Skip to content

Commit c7eefac

Browse files
authored
Connect Zotero directory/enrich workflow with local full-text excerpt signing (#180)
* Connect Zotero directory/enrich workflow with local full-text excerpt signing * Address PR #180 review comments on Zotero storage containment, trashed items, and enrich filters
1 parent 95a8645 commit c7eefac

15 files changed

Lines changed: 1005 additions & 48 deletions

‎docs/how-to/export-cache-to-zotero.md‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,19 +86,31 @@ which cached references now have usable Zotero text or PDF attachments. It does
8686
not invoke **Find Full Text** and does not modify Zotero.
8787

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

9194
```bash
9295
uv run linkml-reference-validator cache enrich \
9396
--provider zotero \
97+
--zotero-dir ~/Zotero \
9498
--cache-dir /Users/cjm/repos/dismech/references_cache \
99+
--referenced-in 'kb/disorders/MyDisease.yaml' \
95100
--apply
96101
```
97102

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

103115
## 5. Validate reproducibly
104116

‎docs/how-to/use-signed-excerpts.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,13 +73,19 @@ validation:
7373
```
7474

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

7878
```yaml
7979
validation:
80-
local_full_text_dir: ~/private-papers
80+
local_full_text_dir: ~/private-papers
8181
```
8282

83+
If you used `linkml-reference-validator cache enrich --provider zotero --apply`
84+
(see [Export a Reference Cache to Zotero](export-cache-to-zotero.md)), its
85+
output in `private_cache_dir` (`~/.cache/linkml-reference-validator/private`) is
86+
checked automatically by `excerpts sign` as a fallback for any reference not
87+
already mapped in `local_full_text` or `local_full_text_dir`.
88+
8389
Relative paths, including a relative `local_full_text_dir`, resolve against
8490
`reference_base_dir`, or the working directory if that is unset. Set
8591
`reference_base_dir` so the result does not depend on where you run the

‎src/linkml_reference_validator/cache.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -218,13 +218,23 @@ def _hashed_filename(name: str, reference_id: str) -> str:
218218
return f"{prefix}_{digest}.md"
219219

220220

221-
def _same_reference_id(first: str, second: str) -> bool:
222-
"""Compare stored IDs exactly, except for case-insensitive DOI identity."""
221+
def same_reference_id(first: str, second: str) -> bool:
222+
"""Compare stored IDs exactly, except for case-insensitive DOI identity.
223+
224+
Examples:
225+
>>> same_reference_id("DOI:10.1000/ABC", "doi:10.1000/abc")
226+
True
227+
>>> same_reference_id("PMID:1", "PMID:2")
228+
False
229+
"""
223230
if first.upper().startswith("DOI:"):
224231
return first.casefold() == second.casefold()
225232
return first == second
226233

227234

235+
_same_reference_id = same_reference_id
236+
237+
228238
def _recover_legacy_scalars(metadata: dict) -> dict:
229239
"""Recover scalar text that older writers emitted without YAML quoting.
230240

‎src/linkml_reference_validator/cli/cache.py‎

Lines changed: 80 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import logging
55
import tarfile
66
from pathlib import Path
7-
from typing import Optional
7+
from typing import Iterable, Optional
88

99
import requests # type: ignore
1010
import typer
@@ -17,6 +17,11 @@
1717
)
1818
from linkml_reference_validator.etl.fulltext.base import FullTextProviderRegistry
1919
from linkml_reference_validator.etl.fulltext.bookshelf import LITARCH_URL, download_book
20+
from linkml_reference_validator.models import ReferenceContent
21+
from linkml_reference_validator.signed_excerpts import (
22+
expand_globs,
23+
find_cited_reference_ids,
24+
)
2025
from .shared import (
2126
CacheDirOption,
2227
VerboseOption,
@@ -260,6 +265,32 @@ def enrich_command(
260265
config_file: ConfigFileOption = None,
261266
cache_dir: CacheDirOption = None,
262267
private_cache_dir: PrivateCacheDirOption = None,
268+
zotero_dir: Annotated[
269+
Optional[Path],
270+
typer.Option(
271+
"--zotero-dir",
272+
envvar="ZOTERO_DIR",
273+
help=(
274+
"Local Zotero data directory (e.g. ~/Zotero) containing zotero.sqlite "
275+
"and storage/. Reads Zotero directly without needing Zotero's HTTP API."
276+
),
277+
),
278+
] = None,
279+
reference: Annotated[
280+
Optional[list[str]],
281+
typer.Option(
282+
"--reference",
283+
"-r",
284+
help="Only enrich this reference ID (repeatable)",
285+
),
286+
] = None,
287+
referenced_in: Annotated[
288+
Optional[list[str]],
289+
typer.Option(
290+
"--referenced-in",
291+
help="Glob of data files; only enrich cached references cited there (repeatable)",
292+
),
293+
] = None,
263294
dry_run: DryRunOption = True,
264295
verbose: VerboseOption = False,
265296
):
@@ -274,6 +305,9 @@ def enrich_command(
274305
linkml-reference-validator cache enrich --provider zotero --dry-run
275306
276307
linkml-reference-validator cache enrich --provider zotero --apply
308+
309+
linkml-reference-validator cache enrich --provider zotero \\
310+
--zotero-dir ~/Zotero --referenced-in 'kb/disorders/MyDisease.yaml' --apply
277311
"""
278312
setup_logging(verbose)
279313

@@ -286,24 +320,58 @@ def enrich_command(
286320
config.cache_dir = cache_dir
287321
if private_cache_dir:
288322
config.private_cache_dir = private_cache_dir
323+
if zotero_dir:
324+
config.zotero_dir = zotero_dir
289325
fetcher = ReferenceFetcher(config)
290326

327+
cached_refs: Iterable[ReferenceContent] = fetcher.iter_cached_references()
328+
if reference or referenced_in:
329+
all_cached = list(cached_refs)
330+
331+
def _id_key(ref_id: str) -> str:
332+
norm = fetcher.normalize_reference_id(ref_id)
333+
return norm.casefold() if norm.upper().startswith("DOI:") else norm
334+
335+
cached_keys = {_id_key(r.reference_id) for r in all_cached}
336+
wanted_keys: set[str] = set()
337+
for req in reference or []:
338+
key = _id_key(req)
339+
wanted_keys.add(key)
340+
if key not in cached_keys:
341+
typer.echo(
342+
f"Warning: requested reference not found in cache: {req}",
343+
err=True,
344+
)
345+
if referenced_in:
346+
try:
347+
paths = expand_globs(referenced_in, Path("."))
348+
except ValueError as err:
349+
typer.echo(str(err), err=True)
350+
raise typer.Exit(2)
351+
cited = find_cited_reference_ids(
352+
(r.reference_id for r in all_cached), paths
353+
)
354+
wanted_keys.update(_id_key(r) for r in cited)
355+
cached_refs = [
356+
r for r in all_cached if _id_key(r.reference_id) in wanted_keys
357+
]
358+
291359
found = 0
292360
applied = 0
293361
errors = 0
294362
scanned = 0
295363
consecutive_errors = 0
296-
for reference in fetcher.iter_cached_references():
364+
for ref_item in cached_refs:
297365
scanned += 1
298-
if not fetcher.needs_full_text(reference):
299-
typer.echo(f"{reference.reference_id}\talready_full_text\t-")
366+
if not fetcher.needs_full_text(ref_item):
367+
typer.echo(f"{ref_item.reference_id}\talready_full_text\t-")
300368
continue
301369
try: # provider is an external-system boundary
302-
location = fetcher.locate_full_text(reference, provider)
370+
location = fetcher.locate_full_text(ref_item, provider)
303371
except Exception as exc:
304372
errors += 1
305373
consecutive_errors += 1
306-
typer.echo(f"{reference.reference_id}\terror\t{exc}")
374+
typer.echo(f"{ref_item.reference_id}\terror\t{exc}")
307375
if consecutive_errors >= MAX_CONSECUTIVE_PROVIDER_ERRORS:
308376
typer.echo(
309377
"Stopping after "
@@ -317,30 +385,30 @@ def enrich_command(
317385
consecutive_errors = 0
318386

319387
if location is None:
320-
typer.echo(f"{reference.reference_id}\tnot_found\t-")
388+
typer.echo(f"{ref_item.reference_id}\tnot_found\t-")
321389
continue
322390

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

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

337405
if fetcher.apply_full_text_location(
338-
reference, location, provider, private=True
406+
ref_item, location, provider, private=True
339407
):
340408
applied += 1
341-
typer.echo(f"{reference.reference_id}\tapplied\t{source}")
409+
typer.echo(f"{ref_item.reference_id}\tapplied\t{source}")
342410
else:
343-
typer.echo(f"{reference.reference_id}\tunusable\t{source}")
411+
typer.echo(f"{ref_item.reference_id}\tunusable\t{source}")
344412

345413
typer.echo(f"Scanned: {scanned}")
346414
typer.echo(f"Found: {found}")

‎src/linkml_reference_validator/etl/acquire.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,3 +290,40 @@ def _read_local_file(
290290
)
291291
return None, content_type
292292
return path.read_bytes(), content_type
293+
294+
def read_zotero_storage_file(
295+
self, file_url: str, config: ReferenceValidationConfig
296+
) -> tuple[Optional[bytes], Optional[str]]:
297+
"""Read a local Zotero storage file URI only when inside config.zotero_dir/storage.
298+
299+
Examples:
300+
>>> import tempfile
301+
>>> from linkml_reference_validator.models import ReferenceValidationConfig
302+
>>> d = Path(tempfile.mkdtemp())
303+
>>> (d / "storage" / "K1").mkdir(parents=True)
304+
>>> pdf = d / "storage" / "K1" / "p.pdf"
305+
>>> _ = pdf.write_bytes(b"%PDF-1.4")
306+
>>> outside = d / "outside.pdf"
307+
>>> _ = outside.write_bytes(b"%PDF-1.4")
308+
>>> cfg = ReferenceValidationConfig(zotero_dir=d)
309+
>>> ContentAcquirer().read_zotero_storage_file(pdf.as_uri(), cfg)[0]
310+
b'%PDF-1.4'
311+
>>> ContentAcquirer().read_zotero_storage_file(outside.as_uri(), cfg)
312+
(None, None)
313+
"""
314+
if config.zotero_dir is None:
315+
logger.warning("Refusing file URI without zotero_dir configured")
316+
return None, None
317+
parsed = urlparse(file_url)
318+
if parsed.scheme != "file" or parsed.netloc not in {"", "localhost"}:
319+
logger.warning("Refusing a non-local file URI")
320+
return None, None
321+
zotero_storage = (Path(config.zotero_dir).expanduser() / "storage").resolve()
322+
resolved_path = Path(url2pathname(parsed.path)).resolve()
323+
if not resolved_path.is_relative_to(zotero_storage):
324+
logger.warning(
325+
f"Refusing file URI outside Zotero storage directory: {resolved_path}"
326+
)
327+
return None, None
328+
return self._read_local_file(file_url, config)
329+

0 commit comments

Comments
 (0)