Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions docs/how-to/export-cache-to-zotero.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,19 +86,31 @@ which cached references now have usable Zotero text or PDF attachments. It does
not invoke **Find Full Text** and does not modify Zotero.

After reviewing the matches, materialize them into the separate private research
cache:
cache (you can also pass `--zotero-dir ~/Zotero` to read your local Zotero SQLite
database and `storage/` folder directly without needing the Zotero desktop HTTP
API running, and `--referenced-in` or `--reference` to scope to specific data
files):

```bash
uv run linkml-reference-validator cache enrich \
--provider zotero \
--zotero-dir ~/Zotero \
--cache-dir /Users/cjm/repos/dismech/references_cache \
--referenced-in 'kb/disorders/MyDisease.yaml' \
--apply
```

Apply mode leaves `references_cache` unchanged. Private content goes to
`~/.cache/linkml-reference-validator/private` by default with owner-only
permissions. Agents may inspect it for context, but validation cannot use it as
evidence.
permissions (or to a private full-text repository such as `claimstore` when
`--private-cache-dir /path/to/claimstore/references_cache` is passed). When
`download_pdfs: true` is configured, `--zotero-dir` also copies the source PDF
into `<private_cache_dir>/files/` even when Zotero has already pre-indexed the
full text (whereas the HTTP API backend only downloads the PDF when Zotero has
not indexed the text). Ordinary validation never reads `private_cache_dir`
directly, but `linkml-reference-validator excerpts sign` can verify quotes
against it and write fair-use bundles to `signed_excerpts/` (see
[Using Signed Excerpts](use-signed-excerpts.md)).

## 5. Validate reproducibly

Expand Down
10 changes: 8 additions & 2 deletions docs/how-to/use-signed-excerpts.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,19 @@ validation:
```

or with a directory of files named like cache files
(`DOI_10.1016_j.ajodo.2025.11.017.md` or `.txt`):
(`DOI_10.1016_j.ajodo.2025.11.017.md`, `.txt`, or `.pdf`):

```yaml
validation:
local_full_text_dir: ~/private-papers
local_full_text_dir: ~/private-papers
```

If you used `linkml-reference-validator cache enrich --provider zotero --apply`
(see [Export a Reference Cache to Zotero](export-cache-to-zotero.md)), its
output in `private_cache_dir` (`~/.cache/linkml-reference-validator/private`) is
checked automatically by `excerpts sign` as a fallback for any reference not
already mapped in `local_full_text` or `local_full_text_dir`.

Relative paths, including a relative `local_full_text_dir`, resolve against
`reference_base_dir`, or the working directory if that is unset. Set
`reference_base_dir` so the result does not depend on where you run the
Expand Down
14 changes: 12 additions & 2 deletions src/linkml_reference_validator/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,13 +218,23 @@ def _hashed_filename(name: str, reference_id: str) -> str:
return f"{prefix}_{digest}.md"


def _same_reference_id(first: str, second: str) -> bool:
"""Compare stored IDs exactly, except for case-insensitive DOI identity."""
def same_reference_id(first: str, second: str) -> bool:
"""Compare stored IDs exactly, except for case-insensitive DOI identity.

Examples:
>>> same_reference_id("DOI:10.1000/ABC", "doi:10.1000/abc")
True
>>> same_reference_id("PMID:1", "PMID:2")
False
"""
if first.upper().startswith("DOI:"):
return first.casefold() == second.casefold()
return first == second


_same_reference_id = same_reference_id


def _recover_legacy_scalars(metadata: dict) -> dict:
"""Recover scalar text that older writers emitted without YAML quoting.

Expand Down
92 changes: 80 additions & 12 deletions src/linkml_reference_validator/cli/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import logging
import tarfile
from pathlib import Path
from typing import Optional
from typing import Iterable, Optional

import requests # type: ignore
import typer
Expand All @@ -17,6 +17,11 @@
)
from linkml_reference_validator.etl.fulltext.base import FullTextProviderRegistry
from linkml_reference_validator.etl.fulltext.bookshelf import LITARCH_URL, download_book
from linkml_reference_validator.models import ReferenceContent
from linkml_reference_validator.signed_excerpts import (
expand_globs,
find_cited_reference_ids,
)
from .shared import (
CacheDirOption,
VerboseOption,
Expand Down Expand Up @@ -260,6 +265,32 @@ def enrich_command(
config_file: ConfigFileOption = None,
cache_dir: CacheDirOption = None,
private_cache_dir: PrivateCacheDirOption = None,
zotero_dir: Annotated[
Optional[Path],
typer.Option(
"--zotero-dir",
envvar="ZOTERO_DIR",
help=(
"Local Zotero data directory (e.g. ~/Zotero) containing zotero.sqlite "
"and storage/. Reads Zotero directly without needing Zotero's HTTP API."
),
),
] = None,
reference: Annotated[
Optional[list[str]],
typer.Option(
"--reference",
"-r",
help="Only enrich this reference ID (repeatable)",
),
] = None,
referenced_in: Annotated[
Optional[list[str]],
typer.Option(
"--referenced-in",
help="Glob of data files; only enrich cached references cited there (repeatable)",
),
] = None,
dry_run: DryRunOption = True,
verbose: VerboseOption = False,
):
Expand All @@ -274,6 +305,9 @@ def enrich_command(
linkml-reference-validator cache enrich --provider zotero --dry-run

linkml-reference-validator cache enrich --provider zotero --apply

linkml-reference-validator cache enrich --provider zotero \\
--zotero-dir ~/Zotero --referenced-in 'kb/disorders/MyDisease.yaml' --apply
"""
setup_logging(verbose)

Expand All @@ -286,24 +320,58 @@ def enrich_command(
config.cache_dir = cache_dir
if private_cache_dir:
config.private_cache_dir = private_cache_dir
if zotero_dir:
config.zotero_dir = zotero_dir
fetcher = ReferenceFetcher(config)

cached_refs: Iterable[ReferenceContent] = fetcher.iter_cached_references()
if reference or referenced_in:
all_cached = list(cached_refs)

def _id_key(ref_id: str) -> str:
norm = fetcher.normalize_reference_id(ref_id)
return norm.casefold() if norm.upper().startswith("DOI:") else norm

cached_keys = {_id_key(r.reference_id) for r in all_cached}
wanted_keys: set[str] = set()
for req in reference or []:
key = _id_key(req)
wanted_keys.add(key)
if key not in cached_keys:
typer.echo(
f"Warning: requested reference not found in cache: {req}",
err=True,
)
if referenced_in:
try:
paths = expand_globs(referenced_in, Path("."))
except ValueError as err:
typer.echo(str(err), err=True)
raise typer.Exit(2)
cited = find_cited_reference_ids(
(r.reference_id for r in all_cached), paths
)
wanted_keys.update(_id_key(r) for r in cited)
cached_refs = [
r for r in all_cached if _id_key(r.reference_id) in wanted_keys
]

found = 0
applied = 0
errors = 0
scanned = 0
consecutive_errors = 0
for reference in fetcher.iter_cached_references():
for ref_item in cached_refs:
scanned += 1
if not fetcher.needs_full_text(reference):
typer.echo(f"{reference.reference_id}\talready_full_text\t-")
if not fetcher.needs_full_text(ref_item):
typer.echo(f"{ref_item.reference_id}\talready_full_text\t-")
continue
try: # provider is an external-system boundary
location = fetcher.locate_full_text(reference, provider)
location = fetcher.locate_full_text(ref_item, provider)
except Exception as exc:
errors += 1
consecutive_errors += 1
typer.echo(f"{reference.reference_id}\terror\t{exc}")
typer.echo(f"{ref_item.reference_id}\terror\t{exc}")
if consecutive_errors >= MAX_CONSECUTIVE_PROVIDER_ERRORS:
typer.echo(
"Stopping after "
Expand All @@ -317,30 +385,30 @@ def enrich_command(
consecutive_errors = 0

if location is None:
typer.echo(f"{reference.reference_id}\tnot_found\t-")
typer.echo(f"{ref_item.reference_id}\tnot_found\t-")
continue

if location.declined:
# Reported as its own outcome, not as a find and not as an absence.
# A declined location carries no url and no text, so counting it
# would inflate `Found:` by exactly the references the provider
# refused -- and this command's whole output is an inventory.
typer.echo(f"{reference.reference_id}\tdeclined\t{location.declined}")
typer.echo(f"{ref_item.reference_id}\tdeclined\t{location.declined}")
continue

found += 1
source = f"{location.provider or provider}:{location.source_item_id or '-'}"
if dry_run:
typer.echo(f"{reference.reference_id}\tfound\t{source}")
typer.echo(f"{ref_item.reference_id}\tfound\t{source}")
continue

if fetcher.apply_full_text_location(
reference, location, provider, private=True
ref_item, location, provider, private=True
):
applied += 1
typer.echo(f"{reference.reference_id}\tapplied\t{source}")
typer.echo(f"{ref_item.reference_id}\tapplied\t{source}")
else:
typer.echo(f"{reference.reference_id}\tunusable\t{source}")
typer.echo(f"{ref_item.reference_id}\tunusable\t{source}")

typer.echo(f"Scanned: {scanned}")
typer.echo(f"Found: {found}")
Expand Down
37 changes: 37 additions & 0 deletions src/linkml_reference_validator/etl/acquire.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,3 +290,40 @@ def _read_local_file(
)
return None, content_type
return path.read_bytes(), content_type

def read_zotero_storage_file(
self, file_url: str, config: ReferenceValidationConfig
) -> tuple[Optional[bytes], Optional[str]]:
"""Read a local Zotero storage file URI only when inside config.zotero_dir/storage.

Examples:
>>> import tempfile
>>> from linkml_reference_validator.models import ReferenceValidationConfig
>>> d = Path(tempfile.mkdtemp())
>>> (d / "storage" / "K1").mkdir(parents=True)
>>> pdf = d / "storage" / "K1" / "p.pdf"
>>> _ = pdf.write_bytes(b"%PDF-1.4")
>>> outside = d / "outside.pdf"
>>> _ = outside.write_bytes(b"%PDF-1.4")
>>> cfg = ReferenceValidationConfig(zotero_dir=d)
>>> ContentAcquirer().read_zotero_storage_file(pdf.as_uri(), cfg)[0]
b'%PDF-1.4'
>>> ContentAcquirer().read_zotero_storage_file(outside.as_uri(), cfg)
(None, None)
"""
if config.zotero_dir is None:
logger.warning("Refusing file URI without zotero_dir configured")
return None, None
parsed = urlparse(file_url)
if parsed.scheme != "file" or parsed.netloc not in {"", "localhost"}:
logger.warning("Refusing a non-local file URI")
return None, None
zotero_storage = (Path(config.zotero_dir).expanduser() / "storage").resolve()
resolved_path = Path(url2pathname(parsed.path)).resolve()
if not resolved_path.is_relative_to(zotero_storage):
logger.warning(
f"Refusing file URI outside Zotero storage directory: {resolved_path}"
)
return None, None
return self._read_local_file(file_url, config)

Loading