From 1d00d17e8a0388ed654495460b11ffcd9c702365 Mon Sep 17 00:00:00 2001 From: Chris Mungall Date: Mon, 26 Jan 2026 18:42:21 -0800 Subject: [PATCH] feat: add DOI DataCite fallback, supplementary files, and URL normalization --- .claude/settings.json | 12 - .devcontainer/devcontainer.json | 27 ++ .devcontainer/post_create.sh | 6 + .goosehints | 1 + AGENTS.md | 1 + BUG_GEO_ACCESSION_TO_UID.md | 137 +++++++ BUG_ZENODO_DOI_AND_URL_HANDLING.md | 258 ++++++++++++ CLI-ISSUES.md | 31 ++ FEATURE_REQUEST_REPAIR.md | 255 ++++++++++++ copilot-instructions.md | 1 + docs/concepts/content-types.md | 63 ++- docs/how-to/repair-validation-errors.md | 2 +- docs/how-to/use-local-files-and-urls.md | 8 +- docs/how-to/validate-dois.md | 102 ++++- docs/how-to/validate-urls.md | 20 +- docs/notebooks/01_getting_started.ipynb | 5 +- docs/notebooks/02_advanced_usage.ipynb | 5 +- docs/notebooks/04_obo_validation.ipynb | 7 +- docs/notebooks/05_geo_validation.ipynb | 9 +- docs/reference/cli.md | 264 +++++++++++- src/linkml_reference_validator/cli/lookup.py | 39 +- .../etl/reference_fetcher.py | 99 ++++- .../etl/sources/doi.py | 300 +++++++++++++- .../etl/sources/pmid.py | 58 ++- src/linkml_reference_validator/models.py | 57 +++ tests/test_reference_fetcher.py | 382 ++++++++++++++++++ 26 files changed, 2074 insertions(+), 75 deletions(-) create mode 100644 .devcontainer/devcontainer.json create mode 100644 .devcontainer/post_create.sh create mode 120000 .goosehints create mode 120000 AGENTS.md create mode 100644 BUG_GEO_ACCESSION_TO_UID.md create mode 100644 BUG_ZENODO_DOI_AND_URL_HANDLING.md create mode 100644 CLI-ISSUES.md create mode 100644 FEATURE_REQUEST_REPAIR.md create mode 120000 copilot-instructions.md diff --git a/.claude/settings.json b/.claude/settings.json index 29f0ffc..2c63c08 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,14 +1,2 @@ { - "permissions": { - "allow": [ - "Bash(*)", - "Edit", - "MultiEdit", - "NotebookEdit", - "FileEdit", - "WebFetch", - "WebSearch", - "Write" - ] - } } diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..01136a1 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,27 @@ +{ + "name": "odkfull-codespace", + // consider also: Codespaces Prebuilds + "image": "obolibrary/odkfull:latest", + + // Mount your repo where ODK expects it + "workspaceMount": "source=${localWorkspaceFolder},target=/work,type=bind,consistency=cached", + "workspaceFolder": "/work", + + // Keep VS Code in control of the container command (safer than using image ENTRYPOINT) + "overrideCommand": true, + + // Be root so you can add small tools if you need them + "remoteUser": "root", + //"features": { + // "ghcr.io/devcontainers/features/node:1": { "version": "lts" } + //}, + "extensions": [ + "anthropic.claude-code", + "ms-python.python", + "ms-azuretools.vscode-docker" + ], + "remoteEnv": { + "TEST_ENV": "123" + }, + "postCreateCommand": "bash .devcontainer/post_create.sh" +} diff --git a/.devcontainer/post_create.sh b/.devcontainer/post_create.sh new file mode 100644 index 0000000..dd6d4d6 --- /dev/null +++ b/.devcontainer/post_create.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -e +odk --help || true +#curl -LsSf https://astral.sh/uv/install.sh | sh +#uv pip install oaklib +npm install -g @anthropic-ai/claude-code diff --git a/.goosehints b/.goosehints new file mode 120000 index 0000000..47dc3e3 --- /dev/null +++ b/.goosehints @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 120000 index 0000000..681311e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1 @@ +CLAUDE.md \ No newline at end of file diff --git a/BUG_GEO_ACCESSION_TO_UID.md b/BUG_GEO_ACCESSION_TO_UID.md new file mode 100644 index 0000000..7a25115 --- /dev/null +++ b/BUG_GEO_ACCESSION_TO_UID.md @@ -0,0 +1,137 @@ +# Bug: GEOSource fails to fetch GEO datasets + +## Summary + +The `GEOSource` class in `linkml_reference_validator/etl/sources/entrez.py` cannot fetch GEO dataset metadata because it passes GSE accessions directly to `esummary`, but the GDS Entrez database requires numeric UIDs. + +## Error Observed + +``` +WARNING:linkml_reference_validator.etl.sources.entrez:Failed to fetch Entrez summary for GEO:GSE67472: Invalid uid GSE67472 at position= 0 +``` + +## Root Cause + +The `EntrezSummarySource.fetch()` method calls: + +```python +handle = Entrez.esummary(db=self.ENTREZ_DB, id=identifier) +``` + +For GEO, this becomes `esummary(db='gds', id='GSE67472')`, but the GDS database doesn't accept accession numbers as IDs - it requires numeric UIDs like `200067472`. + +## Proof of Concept + +```python +from Bio import Entrez +Entrez.email = 'test@example.com' + +# This FAILS - accession not accepted as UID +handle = Entrez.esummary(db='gds', id='GSE67472') +# Error: Invalid uid GSE67472 at position=0 + +# This WORKS - use esearch first to get UID +handle = Entrez.esearch(db='gds', term='GSE67472[Accession]') +result = Entrez.read(handle) +handle.close() +# result['IdList'] = ['200067472', ...] + +uid = result['IdList'][0] # '200067472' + +handle = Entrez.esummary(db='gds', id=uid) +summary = Entrez.read(handle) +handle.close() +print(summary[0].get('title')) +# Output: "Airway epithelial gene expression in asthma versus healthy controls" +``` + +## Proposed Fix + +Override `fetch()` in `GEOSource` to add an `esearch` step that converts accessions to UIDs: + +```python +@ReferenceSourceRegistry.register +class GEOSource(EntrezSummarySource): + """Fetch GEO series and dataset summaries from Entrez.""" + + PREFIX = "GEO" + ENTREZ_DB = "gds" + TITLE_FIELDS = ("title", "description", "summary") + CONTENT_FIELDS = ("summary", "description", "title") + ID_PATTERNS = (r"^GSE\d+$", r"^GDS\d+$") + + def fetch( + self, identifier: str, config: ReferenceValidationConfig + ) -> Optional[ReferenceContent]: + """Fetch GEO dataset metadata, converting accession to UID first.""" + Entrez.email = config.email + time.sleep(config.rate_limit_delay) + + # Convert accession to UID via esearch + uid = self._accession_to_uid(identifier) + if not uid: + logger.warning(f"Could not find GDS UID for {identifier}") + return None + + # Now fetch summary with numeric UID + handle = None + try: + handle = Entrez.esummary(db=self.ENTREZ_DB, id=uid) + records = Entrez.read(handle) + except Exception as exc: + logger.warning(f"Failed to fetch Entrez summary for {self.prefix()}:{identifier}: {exc}") + return None + finally: + if handle is not None: + handle.close() + + record = self._extract_record(records) + if not record: + logger.warning(f"No Entrez summary found for {self.prefix()}:{identifier}") + return None + + title = self._get_first_field_value(record, self.TITLE_FIELDS) + content = self._get_first_field_value(record, self.CONTENT_FIELDS) + content_type = "summary" if content else "unavailable" + + return ReferenceContent( + reference_id=f"{self.prefix()}:{identifier}", + title=title, + content=content, + content_type=content_type, + metadata={"entrez_db": self.ENTREZ_DB, "entrez_uid": uid}, + ) + + def _accession_to_uid(self, accession: str) -> Optional[str]: + """Convert a GEO accession (GSE/GDS) to its Entrez UID.""" + handle = None + try: + handle = Entrez.esearch(db=self.ENTREZ_DB, term=f"{accession}[Accession]") + result = Entrez.read(handle) + if result.get("IdList"): + return result["IdList"][0] + except Exception as exc: + logger.warning(f"esearch failed for {accession}: {exc}") + finally: + if handle is not None: + handle.close() + return None +``` + +## Testing + +After the fix, validation should catch title mismatches like: + +```yaml +# In kb/disorders/Asthma.yaml +datasets: + - accession: geo:GSE67472 + title: xxxAirway epithelial gene expression in asthma versus healthy controls # Wrong! +``` + +Expected validation error: +``` +[ERROR] Title mismatch for geo:GSE67472 + Expected: "Airway epithelial gene expression in asthma versus healthy controls" + Found: "xxxAirway epithelial gene expression in asthma versus healthy controls" +``` diff --git a/BUG_ZENODO_DOI_AND_URL_HANDLING.md b/BUG_ZENODO_DOI_AND_URL_HANDLING.md new file mode 100644 index 0000000..6cd6a39 --- /dev/null +++ b/BUG_ZENODO_DOI_AND_URL_HANDLING.md @@ -0,0 +1,258 @@ +# Bug Report: Zenodo DOIs and bare HTTPS URLs not handled + +## Summary + +Two related bugs prevent fetching Zenodo DOIs and bare HTTPS URLs: + +1. **Zenodo DOIs return 404**: DOIs like `DOI:10.5281/zenodo.17993529` fail because the DOI source only queries Crossref, but Zenodo DOIs are registered with DataCite. + +2. **Bare HTTPS URLs not recognized**: URLs like `https://doi.org/10.5281/zenodo.17993529` fail because the prefix parser extracts `https` as the prefix, which gets uppercased to `HTTPS` and doesn't match any source. + +## Reproduction + +```bash +# Both of these fail: +linkml-reference-validator lookup --no-cache https://doi.org/10.5281/zenodo.17993529 +# Output: No source found for reference type: HTTPS://doi.org/10.5281/zenodo.17993529 + +linkml-reference-validator lookup --no-cache DOI:10.5281/zenodo.17993529 +# Output: Failed to fetch DOI:10.5281/zenodo.17993529 - status 404 +``` + +## Root Cause Analysis + +### Bug 1: URL Prefix Handling + +In `src/linkml_reference_validator/etl/reference_fetcher.py`: + +```python +# Line 141 - regex parses https://example.com as: +# prefix = "https" +# identifier = "//example.com" +match = re.match(r"^([A-Za-z_]+)[:\s]+(.+)$", stripped) + +# Lines 174-178 - prefix normalization uppercases non-file/url prefixes: +def _normalize_prefix(self, prefix: str) -> str: + if prefix.lower() in ("file", "url"): + return prefix.lower() + return prefix.upper() # "https" becomes "HTTPS" +``` + +No source is registered for `HTTPS:`, so lookup fails. + +### Bug 2: Crossref-only DOI Resolution + +In `src/linkml_reference_validator/etl/sources/doi.py`: + +```python +# Line 72 - only queries Crossref API +url = f"https://api.crossref.org/works/{doi}" +``` + +Zenodo DOIs (prefix `10.5281/zenodo.*`) are registered with **DataCite**, not Crossref. Crossref returns 404 for these DOIs. + +## Solution + +### Fix 1: Handle bare HTTP/HTTPS URLs + +In `reference_fetcher.py`, add detection for bare URLs before the prefix regex matching: + +```python +def _parse_reference_id(self, reference_id: str) -> tuple[str, str]: + stripped = reference_id.strip() + + # NEW: Handle bare URLs (http:// or https://) + if stripped.lower().startswith(("http://", "https://")): + return "url", stripped + + # Existing prefix:identifier parsing... + match = re.match(r"^([A-Za-z_]+)[:\s]+(.+)$", stripped) + # ... rest of method +``` + +### Fix 2: Add DataCite fallback for DOIs + +In `doi.py`, try Crossref first, then fall back to DataCite if 404: + +```python +def fetch( + self, identifier: str, config: ReferenceValidationConfig +) -> Optional[ReferenceContent]: + doi = identifier.strip() + time.sleep(config.rate_limit_delay) + + # Try Crossref first + result = self._fetch_from_crossref(doi, config) + if result: + return result + + # Fall back to DataCite (handles Zenodo, Figshare, etc.) + return self._fetch_from_datacite(doi, config) + +def _fetch_from_crossref(self, doi: str, config: ReferenceValidationConfig) -> Optional[ReferenceContent]: + """Fetch from Crossref API.""" + url = f"https://api.crossref.org/works/{doi}" + headers = { + "User-Agent": f"linkml-reference-validator/1.0 (mailto:{config.email})", + } + + response = requests.get(url, headers=headers, timeout=30) + if response.status_code != 200: + logger.debug(f"Crossref returned {response.status_code} for DOI:{doi}, will try DataCite") + return None + + data = response.json() + if data.get("status") != "ok": + return None + + message = data.get("message", {}) + return self._parse_crossref_response(doi, message) + +def _fetch_from_datacite(self, doi: str, config: ReferenceValidationConfig) -> Optional[ReferenceContent]: + """Fetch from DataCite API (handles Zenodo, Figshare, Dryad, etc.).""" + url = f"https://api.datacite.org/dois/{doi}" + headers = { + "User-Agent": f"linkml-reference-validator/1.0 (mailto:{config.email})", + "Accept": "application/json", + } + + response = requests.get(url, headers=headers, timeout=30) + if response.status_code != 200: + logger.warning(f"Failed to fetch DOI:{doi} from both Crossref and DataCite") + return None + + data = response.json() + attributes = data.get("data", {}).get("attributes", {}) + + # Extract title + titles = attributes.get("titles", []) + title = titles[0].get("title", "") if titles else "" + + # Extract authors + authors = self._parse_datacite_creators(attributes.get("creators", [])) + + # Extract year + year = str(attributes.get("publicationYear", "")) + + # Extract abstract from descriptions + abstract = "" + for desc in attributes.get("descriptions", []): + if desc.get("descriptionType") == "Abstract": + abstract = desc.get("description", "") + break + + # Publisher as journal equivalent + publisher = attributes.get("publisher", "") + + return ReferenceContent( + reference_id=f"DOI:{doi}", + title=title, + content=abstract if abstract else None, + content_type="abstract_only" if abstract else "unavailable", + authors=authors, + journal=publisher, + year=year, + doi=doi, + ) + +def _parse_datacite_creators(self, creators: list) -> list[str]: + """Parse creator list from DataCite response.""" + result = [] + for creator in creators: + # DataCite may have full name or given/family + name = creator.get("name") + if not name: + given = creator.get("givenName", "") + family = creator.get("familyName", "") + if given and family: + name = f"{given} {family}" + elif family: + name = family + elif given: + name = given + if name: + result.append(name) + return result +``` + +## DataCite API Response Structure + +The DataCite API at `https://api.datacite.org/dois/{doi}` returns: + +```json +{ + "data": { + "attributes": { + "doi": "10.5281/zenodo.17993529", + "titles": [{"title": "Gene Ontology Curators AI Workshop (Part 1)"}], + "creators": [ + { + "name": "Mungall, Christopher", + "givenName": "Christopher", + "familyName": "Mungall", + "affiliation": [{"name": "Lawrence Berkeley National Laboratory"}] + } + ], + "publicationYear": 2025, + "publisher": "Zenodo", + "descriptions": [ + { + "description": "Workshop aims to equip curators with...", + "descriptionType": "Abstract" + } + ] + } + } +} +``` + +## Test Cases + +Add tests for both fixes: + +```python +@pytest.mark.integration +def test_zenodo_doi(): + """Test that Zenodo DOIs are fetched via DataCite.""" + config = ReferenceValidationConfig() + fetcher = ReferenceFetcher(config) + ref = fetcher.fetch("DOI:10.5281/zenodo.17993529", force_refresh=True) + assert ref is not None + assert "Gene Ontology" in ref.title + assert ref.year == "2025" + +@pytest.mark.integration +def test_bare_https_url(): + """Test that bare HTTPS URLs are handled.""" + config = ReferenceValidationConfig() + fetcher = ReferenceFetcher(config) + ref = fetcher.fetch("https://example.com", force_refresh=True) + assert ref is not None + assert ref.reference_id == "url:https://example.com" + +def test_parse_bare_url(): + """Test URL parsing for bare HTTP/HTTPS URLs.""" + config = ReferenceValidationConfig() + fetcher = ReferenceFetcher(config) + + assert fetcher._parse_reference_id("https://example.com") == ("url", "https://example.com") + assert fetcher._parse_reference_id("http://example.com/path") == ("url", "http://example.com/path") + assert fetcher._parse_reference_id("url:https://example.com") == ("url", "https://example.com") +``` + +## Files to Modify + +1. `src/linkml_reference_validator/etl/reference_fetcher.py` - Add bare URL detection +2. `src/linkml_reference_validator/etl/sources/doi.py` - Add DataCite fallback +3. `tests/test_reference_fetcher.py` - Add unit tests +4. `tests/test_doi_source.py` or similar - Add integration tests + +## Verification + +After fixes, these should work: + +```bash +linkml-reference-validator lookup DOI:10.5281/zenodo.17993529 +linkml-reference-validator lookup https://doi.org/10.5281/zenodo.17993529 +linkml-reference-validator lookup https://zenodo.org/records/17993529 +``` diff --git a/CLI-ISSUES.md b/CLI-ISSUES.md new file mode 100644 index 0000000..7fa5f2f --- /dev/null +++ b/CLI-ISSUES.md @@ -0,0 +1,31 @@ +# CLI Issues + +## 1) `validate data` summary label is misleading + +**Current behavior** +The CLI prints: +``` +Validation Summary: + Total checks: +``` +where `` is the **number of issues** (`len(all_results)`), not the number of checks performed. This makes successful runs look like they performed zero checks (e.g., “Total checks: 0”), which is confusing. + +**Where** +`linkml_reference_validator/cli/validate.py` (near the end of `validate data` command). + +**Repro** +Run with a file that has valid evidence/snippets and get: +``` +Validation Summary: + Total checks: 0 + All validations passed! +``` + +**Suggested fix** +Either: +- Rename the label to **“Total issues”**, or +- Add two counters: + - **Checks performed** (number of excerpt/reference pairs found) + - **Issues found** (`len(all_results)`) + +This would make the summary accurate and less surprising. diff --git a/FEATURE_REQUEST_REPAIR.md b/FEATURE_REQUEST_REPAIR.md new file mode 100644 index 0000000..873af0a --- /dev/null +++ b/FEATURE_REQUEST_REPAIR.md @@ -0,0 +1,255 @@ +# Feature Request: Automated Repair Function for Reference Validation + +## Summary + +Add a `--repair` mode to `linkml-reference-validator` that can automatically fix or flag snippet validation errors based on configurable confidence thresholds. + +## Background + +After manually fixing ~40 validation errors across 11 disease YAML files, clear patterns emerged in the types of errors and their appropriate fixes: + +### Error Categories (from real-world experience) + +1. **Minor Text Differences (~30% of errors)** + - Special character mismatches: `+/-` vs `±`, `Δ` vs `∆`, `CO2` vs `CO₂` + - Parentheses variations: `(131)I` vs `131I`, `FBN1(T7498C)` vs `FBN1T7498C` + - Abbreviation differences: `Haemophilus influenzae type b` vs `H. influenzae type b` + - Minor spacing/punctuation issues + +2. **Missing Ellipsis Connectors (~20% of errors)** + - Non-contiguous text portions quoted without `...` separator + - Text spans across abstract sections without indicator + +3. **Completely Fabricated Snippets (~35% of errors)** + - Text that appears nowhere in the referenced abstract + - Often AI-hallucinated plausible-sounding but incorrect quotes + - Meta-commentary like "No abstract provided" or "No environmental factors mentioned" + +4. **No Abstract Available (~15% of errors)** + - Reference exists but PubMed has no abstract (older papers, certain journals) + - Cannot be validated - must be flagged or removed + +## Proposed Solution + +### Command-Line Interface + +```bash +# Dry run - show what would be changed +uv run linkml-reference-validator repair data file.yaml \ + --schema schema.yaml \ + --target-class Disease \ + --dry-run + +# Auto-fix with confidence threshold +uv run linkml-reference-validator repair data file.yaml \ + --schema schema.yaml \ + --target-class Disease \ + --auto-fix-threshold 0.95 \ + --output repaired.yaml + +# Interactive mode for ambiguous cases +uv run linkml-reference-validator repair data file.yaml \ + --schema schema.yaml \ + --target-class Disease \ + --interactive +``` + +### Confidence Thresholds + +| Threshold | Action | Use Case | +|-----------|--------|----------| +| 0.95-1.00 | Auto-fix | Minor character substitutions (±, subscripts) | +| 0.80-0.95 | Suggest fix | Abbreviation changes, minor rewording | +| 0.50-0.80 | Flag for review | Partial matches, possible ellipsis insertion points | +| 0.00-0.50 | Recommend removal | Likely fabricated or wrong reference | +| N/A | Flag as unverifiable | No abstract available for reference | + +### Repair Strategies + +#### 1. Character Normalization (High Confidence) +```yaml +# Before (fails validation) +snippet: "CO2 levels were measured" + +# After (auto-fixed) +snippet: "CO₂ levels were measured" +``` + +Implement character mapping table: +- `+/-` → `±` +- `Δ` ↔ `∆` (Unicode normalization) +- `(X)Y` → `XY` where X is a number (isotope notation) +- ASCII approximations → proper Unicode + +#### 2. Ellipsis Insertion (Medium Confidence) +```yaml +# Before (fails - non-contiguous text) +snippet: "Disease X affects children. Treatment involves medication Y." + +# After (suggested fix) +snippet: "Disease X affects children. ... Treatment involves medication Y." +``` + +Algorithm: +1. Split snippet on sentence boundaries +2. Find each sentence in abstract +3. If gap between matched sentences > threshold, insert `...` +4. Recalculate similarity score + +#### 3. Fuzzy Match Correction (Medium Confidence) +```yaml +# Before (fails - abbreviation mismatch) +snippet: "Haemophilus influenzae type b causes meningitis" + +# After (suggested from abstract) +snippet: "H. influenzae type b causes meningitis" +``` + +Use sequence alignment to find best-matching substring in abstract. + +#### 4. Removal Recommendation (Low Confidence) +```yaml +# Before (fabricated - not in abstract) +- reference: PMID:12345678 + supports: SUPPORT + snippet: "This completely made up text that doesn't exist anywhere" + explanation: "..." + +# After (flagged for removal) +# REMOVED: Evidence item for PMID:12345678 - snippet not found in abstract (similarity: 0.12) +``` + +### Output Modes + +#### 1. Report Mode (Default) +``` +=== Repair Report for disease.yaml === + +HIGH CONFIDENCE FIXES (auto-applicable): + Line 45: Changed "CO2" → "CO₂" (PMID:12345678) + Line 89: Changed "+/-" → "±" (PMID:23456789) + +SUGGESTED FIXES (review recommended): + Line 123: Insert "..." between sentences (similarity: 0.85) + Before: "Sentence A. Sentence B." + After: "Sentence A. ... Sentence B." + +RECOMMENDED REMOVALS (low confidence): + Line 234: PMID:34567890 - snippet similarity 0.08 + Snippet appears to be fabricated or from wrong reference + +UNVERIFIABLE (no abstract available): + Line 345: PMID:45678901 - no abstract in PubMed + Consider finding alternative reference or removing + +Summary: 4 auto-fixes, 2 suggestions, 3 removals, 1 unverifiable +``` + +#### 2. YAML Output Mode +Write repaired YAML with comments for manual review items: + +```yaml +evidence: + - reference: PMID:12345678 + supports: SUPPORT + snippet: "CO₂ levels were measured" # AUTO-FIXED: CO2 → CO₂ + explanation: "..." + # REVIEW: Consider inserting "..." - similarity 0.85 + - reference: PMID:23456789 + supports: SUPPORT + snippet: "Sentence A. Sentence B." + explanation: "..." + # FLAGGED FOR REMOVAL: snippet not found (similarity: 0.08) + # - reference: PMID:34567890 + # supports: SUPPORT + # snippet: "Fabricated text..." +``` + +### Configuration File + +Allow project-specific repair settings: + +```yaml +# .linkml-reference-validator.yaml +repair: + auto_fix_threshold: 0.95 + suggest_threshold: 0.80 + removal_threshold: 0.50 + + character_mappings: + "+/-": "±" + "Δ": "∆" + + abbreviation_patterns: + - pattern: "Haemophilus influenzae" + alternatives: ["H. influenzae", "H influenzae"] + + skip_references: + - "PMID:12345678" # Known to have no abstract + + trusted_low_similarity: + - "PMID:98765432" # Manually verified despite low similarity +``` + +## Implementation Notes + +### Similarity Metrics + +Recommend using multiple metrics and combining: + +1. **Levenshtein distance** - catches typos and minor edits +2. **Token overlap (Jaccard)** - catches reordering +3. **Longest common subsequence** - catches insertions/deletions +4. **Semantic similarity (optional)** - using sentence embeddings for paraphrase detection + +Weighted combination: +```python +confidence = 0.4 * levenshtein_sim + 0.3 * jaccard_sim + 0.3 * lcs_sim +``` + +### Safety Considerations + +1. **Never auto-remove evidence** - only flag for removal +2. **Preserve original in comments** when auto-fixing +3. **Git-friendly output** - changes should be reviewable in diffs +4. **Backup original file** before in-place repair +5. **Audit log** - record all changes made and why + +### Edge Cases to Handle + +1. **Multiple evidence items for same claim** - safer to remove one bad item if others support +2. **Only evidence item for claim** - require higher confidence or manual review +3. **Snippet matches but different reference** - flag as possible wrong PMID +4. **Abstract has been updated** - note that cached vs live abstracts may differ + +## Acceptance Criteria + +- [ ] `--repair` command with `--dry-run` mode +- [ ] Configurable confidence thresholds +- [ ] Character normalization auto-fix +- [ ] Ellipsis insertion suggestions +- [ ] Fuzzy match suggestions from actual abstract text +- [ ] Removal recommendations with similarity scores +- [ ] Detection of references without abstracts +- [ ] Report output format +- [ ] Repaired YAML output format +- [ ] Configuration file support +- [ ] Audit logging of all changes + +## Related Work + +- [linkml-runtime](https://github.com/linkml/linkml-runtime) - core LinkML functionality +- [rapidfuzz](https://github.com/maxbachmann/RapidFuzz) - fast fuzzy string matching +- [textdistance](https://github.com/life4/textdistance) - comprehensive text similarity metrics + +## Notes from Manual Repair Experience + +After fixing ~40 errors manually, key observations: + +1. **Most fabricated snippets are obvious** - they often contain meta-commentary or suspiciously perfect phrasing +2. **Character issues are mechanical** - a fixed mapping table handles 90% of cases +3. **Ellipsis insertion is usually correct** - when text is in abstract but non-contiguous +4. **Removal is safe when multiple evidence exists** - claims typically have 2-5 supporting references +5. **Human review is essential for edge cases** - especially single-evidence claims + +The 0.95 threshold for auto-fix is conservative and appropriate - it catches the obvious mechanical fixes while requiring human review for anything ambiguous. diff --git a/copilot-instructions.md b/copilot-instructions.md new file mode 120000 index 0000000..be77ac8 --- /dev/null +++ b/copilot-instructions.md @@ -0,0 +1 @@ +../AGENTS.md \ No newline at end of file diff --git a/docs/concepts/content-types.md b/docs/concepts/content-types.md index bdebaef..c52b708 100644 --- a/docs/concepts/content-types.md +++ b/docs/concepts/content-types.md @@ -92,12 +92,12 @@ content_type: abstract_only ### Via CLI ```bash -linkml-reference-validator cache show PMID:16888623 +linkml-reference-validator cache lookup PMID:16888623 --content ``` Output includes: ``` -Content type: abstract_only +content_type: abstract_only ``` ### In Validation Results @@ -124,3 +124,62 @@ If validation fails due to abstract-only content: 5. **Accept the limitation**: Document that certain excerpts couldn't be verified due to access limitations See [Using Local Files and URLs](../how-to/use-local-files-and-urls.md) for detailed guidance on alternatives. + +## Reference Metadata + +Beyond the main content, the validator extracts additional metadata from references: + +### Keywords + +The `keywords` field contains subject terms or tags from the source: + +| Source | Keyword Type | Example | +|--------|--------------|---------| +| PMID | MeSH terms | `Adaptor Proteins, Signal Transducing/metabolism` | +| DOI (Crossref) | Subjects | `General Chemistry`, `Biochemistry` | +| DOI (DataCite) | Subjects | `Climate Change`, `Bioinformatics` | + +MeSH (Medical Subject Headings) terms from PubMed are particularly valuable for biomedical literature, providing standardized vocabulary with qualifier subheadings (e.g., `/metabolism`, `/genetics`). + +**Example cache file with keywords:** +```yaml +--- +reference_id: PMID:33505029 +title: Genomic mechanisms of climate adaptation... +keywords: +- Acclimatization/genetics +- Biofuels +- Genetic Introgression +- Genome, Plant/genetics +content_type: abstract_only +--- +``` + +**Viewing keywords via CLI:** +```bash +linkml-reference-validator lookup PMID:33505029 --format text +``` + +Output: +``` +Reference: PMID:33505029 +Title: Genomic mechanisms of climate adaptation... +Keywords: Acclimatization/genetics, Biofuels, Genetic Introgression, ... +``` + +### Supplementary Files + +For repository DOIs (Zenodo, etc.), the `supplementary_files` field lists associated files: + +```yaml +--- +reference_id: DOI:10.5281/zenodo.7961621 +supplementary_files: + - filename: data_analysis.xlsx + download_url: https://zenodo.org/api/records/7961621/files/data_analysis.xlsx/content + size_bytes: 123456 + checksum: md5:88c66d378d886fea4969949c5877802f +--- +``` + +See [Validating DOIs](../how-to/validate-dois.md#supported-repository-dois) for details on supplementary files. diff --git a/docs/how-to/repair-validation-errors.md b/docs/how-to/repair-validation-errors.md index d5610fd..c9ce960 100644 --- a/docs/how-to/repair-validation-errors.md +++ b/docs/how-to/repair-validation-errors.md @@ -389,7 +389,7 @@ The `content_type` field in cached references tells you what content was retriev Check content type with: ```bash -linkml-reference-validator cache show PMID:16888623 +linkml-reference-validator cache lookup PMID:16888623 --content ``` See [Content Types](../concepts/content-types.md) for full documentation. diff --git a/docs/how-to/use-local-files-and-urls.md b/docs/how-to/use-local-files-and-urls.md index 385f271..09dab78 100644 --- a/docs/how-to/use-local-files-and-urls.md +++ b/docs/how-to/use-local-files-and-urls.md @@ -31,6 +31,9 @@ file:/Users/me/research/notes.md 1. If `reference_base_dir` is configured, paths resolve relative to it 2. Otherwise, paths resolve relative to the current working directory +Note: cached references use the resolved absolute path in the reference ID, so +the cache file name reflects the full path. + ### Configuring a Base Directory Set a base directory for all relative file references: @@ -67,7 +70,8 @@ linkml-reference-validator validate text \ ## URL References -Use the `url:` prefix to reference web pages: +Use the `url:` prefix to reference web pages (the prefix is optional for bare +HTTP/HTTPS URLs and will be normalized to `url:` internally): ```bash linkml-reference-validator validate text \ @@ -81,7 +85,7 @@ URLs are cached the same way as PMID and DOI references: - First fetch downloads and caches the content - Subsequent validations use the cached version -- Use `--force-refresh` to re-fetch +- Use `linkml-reference-validator cache reference url:https://... --force` to re-fetch ### Title Extraction diff --git a/docs/how-to/validate-dois.md b/docs/how-to/validate-dois.md index 773079c..ae7d547 100644 --- a/docs/how-to/validate-dois.md +++ b/docs/how-to/validate-dois.md @@ -4,7 +4,12 @@ This guide shows how to validate supporting text against publications using Digi ## Overview -DOIs are persistent identifiers for digital objects, commonly used for journal articles. The validator fetches publication metadata from the [Crossref API](https://www.crossref.org/documentation/retrieve-metadata/rest-api/) when you provide a DOI reference. +DOIs are persistent identifiers for digital objects, commonly used for journal articles and data repositories. The validator fetches publication metadata from: + +1. **Crossref API** - Primary source for journal articles +2. **DataCite API** - Fallback for repository DOIs (Zenodo, Figshare, Dryad, OSTI) + +This dual-source approach ensures broad coverage across both scholarly publications and data repositories. ## Basic Usage @@ -38,6 +43,79 @@ DOI:10.1016/j.cell.2023.01.001 The DOI itself follows the standard format: `10.prefix/suffix` +## Supported Repository DOIs + +The validator supports DOIs from data repositories via the DataCite API: + +| Repository | DOI Prefix | Example | +|------------|------------|---------| +| Zenodo | `10.5281/zenodo.*` | `DOI:10.5281/zenodo.7961621` | +| Figshare | `10.6084/m9.figshare.*` | `DOI:10.6084/m9.figshare.123456` | +| Dryad | `10.5061/dryad.*` | `DOI:10.5061/dryad.abc123` | +| OSTI | `10.2172/*` | `DOI:10.2172/1234567` | + +### Looking Up Repository DOIs + +```bash +linkml-reference-validator lookup DOI:10.5281/zenodo.7961621 +``` + +For Zenodo DOIs, the output includes supplementary file metadata: + +``` +Reference: DOI:10.5281/zenodo.7961621 +Title: Gene Ontology Curators AI Workshop +Authors: Dickinson R, Carbon S, Mungall CJ +... +Content type: abstract_only + +--- Supplementary Files (3) --- + - Dickinson_Varenna2022.pdf (1,975,995 bytes) + - workshop_slides.pptx (2,345,678 bytes) + - data_analysis.xlsx (123,456 bytes) +``` + +### Downloading Supplementary Files + +By default, only metadata about supplementary files is captured. To download the actual files: + +```bash +linkml-reference-validator lookup -D DOI:10.5281/zenodo.7961621 +``` + +Downloaded files are stored in: +``` +references_cache/ + files/ + DOI_10.5281_zenodo.7961621/ + Dickinson_Varenna2022.pdf + workshop_slides.pptx + data_analysis.xlsx +``` + +### Publisher DOIs vs Repository DOIs + +**Important:** Supplementary file support only works for **repository DOIs** (Zenodo, Figshare, Dryad), not for publisher DOIs (Elsevier, Springer, Nature, etc.). + +| DOI Type | Example | Supplementary Files | +|----------|---------|---------------------| +| **Repository** (Zenodo) | `10.5281/zenodo.7961621` | ✅ File metadata + download | +| **Repository** (Figshare) | `10.6084/m9.figshare.123456` | ✅ File metadata + download | +| **Publisher** (Elsevier) | `10.1016/j.neuron.2011.05.021` | ❌ Not available | +| **Publisher** (Nature) | `10.1038/nature12373` | ❌ Not available | + +**Why the difference?** + +- **Repository APIs** (Zenodo, Figshare) are designed for data sharing and provide open, documented file APIs +- **Publisher APIs** (Elsevier, Springer) require paid institutional access or text-mining agreements +- Even when articles are in PMC, supplementary files are often not available via the OA API + +**Workarounds for publisher supplementary files:** + +1. **Manual download**: Download supplementary files from the publisher website and use `file:` references +2. **Data repository**: Check if the authors deposited data separately in Zenodo/Figshare/Dryad +3. **PubMed Central**: For some OA articles, supplementary files may be available via PMC + ## Pre-caching DOIs For offline validation or to speed up repeated validations: @@ -115,20 +193,24 @@ linkml-reference-validator repair text \ | Feature | PMID | DOI | |---------|------|-----| -| Source | NCBI PubMed | Crossref | -| Coverage | Biomedical literature | All scholarly content | +| Source | NCBI PubMed | Crossref + DataCite | +| Coverage | Biomedical literature | All scholarly content + data repos | | Full text | Via PMC when available | Metadata only | -| Abstract | Usually available | Depends on publisher | +| Abstract | Usually available | Depends on publisher/repo | +| Keywords | MeSH terms | Subjects (if available) | +| Supplementary files | No | Yes (Zenodo, etc.) | **Use PMID when:** - Working with biomedical/life science literature - Full text access is important - The article is indexed in PubMed +- You need MeSH term keywords **Use DOI when:** - The article is not in PubMed - Working with non-biomedical journals -- The DOI is more readily available +- Working with data repositories (Zenodo, Figshare, Dryad) +- You need supplementary file metadata ## Content Availability @@ -151,12 +233,18 @@ This means Crossref returned metadata but no abstract. The DOI was fetched succe ### "Failed to fetch DOI" -The DOI may be invalid or the Crossref API may be temporarily unavailable. +The DOI may be invalid or both APIs (Crossref and DataCite) may have failed. + +**How DOI resolution works:** +1. First, the validator tries Crossref API +2. If Crossref returns 404, it falls back to DataCite API +3. If both fail, the error is reported **Check:** 1. Verify the DOI format (should be `10.prefix/suffix`) 2. Test the DOI at https://doi.org/YOUR_DOI -3. Try again later if Crossref is rate-limiting +3. Try again later if APIs are rate-limiting +4. For repository DOIs (Zenodo, etc.), ensure the record is public ### Rate Limiting diff --git a/docs/how-to/validate-urls.md b/docs/how-to/validate-urls.md index 77426e9..2fb3ccc 100644 --- a/docs/how-to/validate-urls.md +++ b/docs/how-to/validate-urls.md @@ -21,7 +21,8 @@ When a reference field contains a URL, the validator: ## URL Format -Use the `url:` prefix to specify URL references: +Use the `url:` prefix to specify URL references (the prefix is optional for bare +HTTP/HTTPS URLs and will be normalized to `url:` internally): ```yaml my_field: @@ -82,7 +83,10 @@ The fetcher stores: - **Content**: The raw page content as received - **Content type**: Marked as `url` to distinguish from other reference types -Note: Unlike some tools, the validator stores the raw page content without HTML-to-text conversion. This preserves the original content, though HTML tags will be present in the cached file. +Note: The validator stores raw page content without HTML-to-text conversion. +HTML tags remain in the cached file, and tag names can surface during +normalization. If validation fails because tags interrupt the text, consider +extracting plain text and validating against a local `file:` reference instead. ### 3. Caching @@ -171,7 +175,7 @@ After adding a URL reference, verify the extracted content: ```bash # Check what was extracted -cat references_cache/url_https___example.com_page.md +linkml-reference-validator cache lookup url:https://example.com/page --content ``` Ensure the cached content contains the text you're referencing. @@ -179,7 +183,7 @@ Ensure the cached content contains the text you're referencing. ### 3. Cache Management - Commit cache files to version control for reproducibility -- Use `--force-refresh` to update cached content when pages change +- Use `linkml-reference-validator cache reference url:https://... --force` to update cached content when pages change - Periodically review cached URLs to ensure they're still accessible ### 4. Mix Reference Types @@ -217,13 +221,15 @@ If validation fails for URL references: ### Force Refresh -To re-fetch content for a URL that may have changed: +To re-fetch content for a URL that may have changed, refresh the cache before +validating: ```bash +linkml-reference-validator cache reference url:https://example.com/page --force + linkml-reference-validator validate text \ "Updated content" \ - url:https://example.com/page \ - --force-refresh + url:https://example.com/page ``` ## Comparison with Other Reference Types diff --git a/docs/notebooks/01_getting_started.ipynb b/docs/notebooks/01_getting_started.ipynb index 85e553e..8ee60b5 100644 --- a/docs/notebooks/01_getting_started.ipynb +++ b/docs/notebooks/01_getting_started.ipynb @@ -1061,7 +1061,8 @@ "source": [ "%%bash\n", "# Peek at a cached reference\n", - "head -20 references_cache/PMID_16888623.md" + "cache_path=$(linkml-reference-validator cache lookup PMID:16888623)\n", + "head -20 \"$cache_path\"" ] }, { @@ -2083,4 +2084,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} \ No newline at end of file +} diff --git a/docs/notebooks/02_advanced_usage.ipynb b/docs/notebooks/02_advanced_usage.ipynb index b9da950..fb3cf4e 100644 --- a/docs/notebooks/02_advanced_usage.ipynb +++ b/docs/notebooks/02_advanced_usage.ipynb @@ -1189,7 +1189,8 @@ "%%bash\n", "# Show structure of a cached reference\n", "echo \"Structure of cached reference PMID:16888623:\"\n", - "head -25 references_cache/PMID_16888623.md" + "cache_path=$(linkml-reference-validator cache lookup PMID:16888623)\n", + "head -25 \"$cache_path\"" ] }, { @@ -1622,4 +1623,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} \ No newline at end of file +} diff --git a/docs/notebooks/04_obo_validation.ipynb b/docs/notebooks/04_obo_validation.ipynb index 76e8c06..4f42cd1 100644 --- a/docs/notebooks/04_obo_validation.ipynb +++ b/docs/notebooks/04_obo_validation.ipynb @@ -249,13 +249,14 @@ "source": [ "%%bash\n", "# View the cached reference\n", + "cache_path=$(linkml-reference-validator cache lookup PMID:11601609)\n", "echo \"Cached reference metadata:\"\n", - "head -20 references_cache/PMID_11601609.md\n", + "head -20 \"$cache_path\"\n", "echo \"\"\n", "echo \"...\"\n", "echo \"\"\n", "echo \"Abstract excerpt:\"\n", - "tail -10 references_cache/PMID_11601609.md" + "tail -10 \"$cache_path\"" ] }, { @@ -531,4 +532,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} diff --git a/docs/notebooks/05_geo_validation.ipynb b/docs/notebooks/05_geo_validation.ipynb index 32cb095..bb78182 100644 --- a/docs/notebooks/05_geo_validation.ipynb +++ b/docs/notebooks/05_geo_validation.ipynb @@ -282,10 +282,11 @@ "source": [ "%%bash\n", "# View a cached GEO reference (if it exists)\n", - "if [ -f references_cache/GEO_GSE67472.md ]; then\n", - " head -30 references_cache/GEO_GSE67472.md\n", + "cache_path=$(linkml-reference-validator cache lookup GEO:GSE67472 2>/dev/null || true)\n", + "if [ -n \"$cache_path\" ] && [ -f \"$cache_path\" ]; then\n", + " head -30 \"$cache_path\"\n", "else\n", - " echo \"GEO_GSE67472.md not found in cache\"\n", + " echo \"GEO:GSE67472 not found in cache\"\n", "fi" ] }, @@ -332,4 +333,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} \ No newline at end of file +} diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 91e0c24..bc3ff24 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -14,10 +14,146 @@ linkml-reference-validator [OPTIONS] COMMAND [ARGS]... ### Commands +- `lookup` - Look up reference metadata (quick lookups) - `validate` - Validate supporting text against references - `repair` - Repair supporting text validation errors - `cache` - Manage reference cache +--- + +## lookup + +Look up reference metadata and content. Useful for quick "what is this PMID?" lookups. + +### Usage + +```bash +linkml-reference-validator lookup [OPTIONS] REFERENCE_ID [REFERENCE_ID...] +``` + +### Arguments + +- **REFERENCE_ID** (required) - One or more reference IDs (e.g., PMID:12345678, DOI:10.1234/example) + +### Options + +- `--format, -f [md|json|yaml|text]` - Output format (default: md) +- `--no-cache` - Bypass disk cache and fetch fresh from source +- `--download-files, -D` - Download supplementary files from repositories (e.g., Zenodo) +- `--cache-dir PATH, -c PATH` - Directory for caching references (default: `references_cache`) +- `--config PATH` - Path to validation configuration file (.yaml) +- `--verbose, -v` - Verbose output with detailed logging +- `--help` - Show help message + +### Examples + +**Basic lookup:** +```bash +linkml-reference-validator lookup PMID:16888623 +``` + +**Multiple references:** +```bash +linkml-reference-validator lookup PMID:16888623 PMID:33505029 +``` + +**JSON output:** +```bash +linkml-reference-validator lookup PMID:16888623 --format json +``` + +**YAML output:** +```bash +linkml-reference-validator lookup PMID:16888623 --format yaml +``` + +**Text output (human-readable):** +```bash +linkml-reference-validator lookup PMID:16888623 --format text +``` + +**Force fresh fetch (bypass cache):** +```bash +linkml-reference-validator lookup PMID:16888623 --no-cache +``` + +**Zenodo DOI with supplementary files:** +```bash +linkml-reference-validator lookup DOI:10.5281/zenodo.7961621 +``` + +**Download supplementary files:** +```bash +linkml-reference-validator lookup -D DOI:10.5281/zenodo.7961621 +``` + +### Output Format + +**Markdown (default):** +```markdown +--- +reference_id: PMID:16888623 +title: MUC1 oncoprotein blocks nuclear targeting... +authors: +- Raina D +- Ahmad R +journal: Cancer Research +year: '2006' +doi: 10.1158/0008-5472.CAN-06-0205 +keywords: +- Adaptor Proteins, Signal Transducing/metabolism +- Cell Line, Tumor +content_type: abstract_only +--- + +# MUC1 oncoprotein blocks nuclear targeting... +**Authors:** Raina D, Ahmad R, ... +**Journal:** Cancer Research (2006) +**DOI:** [10.1158/...](https://doi.org/10.1158/...) + +## Content + +1. Cancer Res. 2006 Jul 1;66(13):6715-21... +``` + +**Text format:** +``` +Reference: PMID:16888623 +Title: MUC1 oncoprotein blocks nuclear targeting... +Authors: Raina D, Ahmad R, ... +Journal: Cancer Research (2006) +DOI: 10.1158/0008-5472.CAN-06-0205 +Keywords: Adaptor Proteins, Signal Transducing/metabolism, Cell Line, Tumor, ... +Content type: abstract_only + +--- Content --- +1. Cancer Res. 2006 Jul 1;66(13):6715-21... +``` + +**With supplementary files (Zenodo):** +``` +Reference: DOI:10.5281/zenodo.7961621 +Title: Gene Ontology Curators AI Workshop +Authors: Dickinson R, Carbon S, Mungall CJ +... +Content type: abstract_only + +--- Supplementary Files (3) --- + - Dickinson_Varenna2022.pdf (1,975,995 bytes) + - workshop_slides.pptx (2,345,678 bytes) + - data_analysis.xlsx (123,456 bytes) + +--- Content --- +... +``` + +### Exit Codes + +- `0` - At least one reference fetched successfully +- `1` - All references failed to fetch + +--- + ## validate Validate supporting text against references. @@ -29,6 +165,7 @@ linkml-reference-validator validate COMMAND [ARGS]... ### Subcommands - `text` - Validate a single text quote +- `text-file` - Validate supporting text extracted from a text file via regex - `data` - Validate supporting text in data files --- @@ -50,6 +187,7 @@ linkml-reference-validator validate text [OPTIONS] TEXT REFERENCE_ID ### Options +- `--title, -t TEXT` - Expected title to validate against the reference title - `--cache-dir PATH` - Directory for caching references (default: `references_cache`) - `--config PATH` - Path to validation configuration file (.yaml) - `--verbose, -v` - Verbose output with detailed logging @@ -80,6 +218,14 @@ linkml-reference-validator validate text \ --verbose ``` +**With title check:** +```bash +linkml-reference-validator validate text \ + "Airway epithelial brushings" \ + GEO:GSE67472 \ + --title "Airway epithelial gene expression in asthma versus healthy controls" +``` + **With editorial notes:** ```bash linkml-reference-validator validate text \ @@ -120,6 +266,55 @@ Result: --- +## validate text-file + +Validate supporting text in a text file by extracting quotes and references with a regex. + +### Usage + +```bash +linkml-reference-validator validate text-file [OPTIONS] FILE_PATH +``` + +### Arguments + +- **FILE_PATH** (required) - Path to a text file (e.g., OBO, plain text) + +### Options + +- `--regex, -r TEXT` (required) - Regular expression with capture groups for text and reference ID +- `--text-group, -t INTEGER` - Capture group number for supporting text (default: 1) +- `--ref-group, -R INTEGER` - Capture group number for reference ID (default: 2) +- `--summary, -s` - Show only summary statistics (skip per-line output) +- `--cache-dir PATH, -c PATH` - Directory for caching references (default: `references_cache`) +- `--config PATH` - Path to validation configuration file (.yaml) +- `--verbose, -v` - Verbose output with detailed logging +- `--help` - Show help message + +### Examples + +**Validate OBO axiom annotations:** +```bash +linkml-reference-validator validate text-file my_ontology.obo \ + --regex 'ex:supporting_text="([^"]*)\[(\S+:\S+)\]"' \ + --text-group 1 \ + --ref-group 2 +``` + +**Summary only:** +```bash +linkml-reference-validator validate text-file my_ontology.obo \ + --regex 'ex:supporting_text="([^"]*)\[(\S+:\S+)\]"' \ + --summary +``` + +### Exit Codes + +- `0` - Validation successful +- `1` - Validation failed + +--- + ## validate data Validate supporting text in data files against their cited references. @@ -461,6 +656,7 @@ linkml-reference-validator cache COMMAND [ARGS]... ### Subcommands - `reference` - Cache a reference for offline use +- `lookup` - Show the cache path for a reference (or print file contents) --- @@ -525,6 +721,48 @@ Successfully cached PMID:16888623 --- +## cache lookup + +Show the cached file path for a reference, or print the cached file contents. + +### Usage + +```bash +linkml-reference-validator cache lookup [OPTIONS] REFERENCE_ID +``` + +### Arguments + +- **REFERENCE_ID** (required) - Reference ID (e.g., PMID:12345678) + +### Options + +- `--content` - Show file contents instead of just the path +- `--no-cache` - Bypass disk cache and fetch fresh from source +- `--cache-dir PATH, -c PATH` - Directory for caching references (default: `references_cache`) +- `--config PATH` - Path to validation configuration file (.yaml) +- `--verbose, -v` - Verbose output with detailed logging +- `--help` - Show help message + +### Examples + +**Show cache path:** +```bash +linkml-reference-validator cache lookup PMID:16888623 +``` + +**Print cached content:** +```bash +linkml-reference-validator cache lookup PMID:16888623 --content +``` + +**Refresh then show path:** +```bash +linkml-reference-validator cache lookup PMID:16888623 --no-cache +``` + +--- + ## Reference ID Formats ### PubMed (PMID) @@ -560,27 +798,11 @@ DOI:10.1126/science.1234567 --- -## Environment Variables - -### LINKML_REFERENCE_VALIDATOR_CACHE_DIR - -Override default cache directory: - -```bash -export LINKML_REFERENCE_VALIDATOR_CACHE_DIR=/custom/cache -linkml-reference-validator validate text "..." PMID:12345678 -``` - -### NCBI_API_KEY - -Set NCBI API key for higher rate limits: - -```bash -export NCBI_API_KEY=your_api_key_here -linkml-reference-validator validate text "..." PMID:12345678 -``` +## Configuration Notes -Request an API key: https://www.ncbi.nlm.nih.gov/account/settings/ +- The CLI currently does not read environment variables for cache dir or NCBI API keys. +- Use `--cache-dir` or set `cache_dir` in `.linkml-reference-validator.yaml`. +- Set `email` in `.linkml-reference-validator.yaml` for NCBI requests. --- @@ -650,4 +872,4 @@ The old commands are hidden from `--help` but continue to function. - [Quickstart](../quickstart.md) - Get started quickly - [Tutorial 1](../notebooks/01_getting_started.ipynb) - CLI examples -- [Python API Reference](python-api.md) - Programmatic usage +- [Python API](../notebooks/03_python_api.ipynb) - Programmatic usage diff --git a/src/linkml_reference_validator/cli/lookup.py b/src/linkml_reference_validator/cli/lookup.py index 0b2293e..a0e1d14 100644 --- a/src/linkml_reference_validator/cli/lookup.py +++ b/src/linkml_reference_validator/cli/lookup.py @@ -50,19 +50,43 @@ class OutputFormat(str, Enum): ), ] +# Option for downloading supplementary files +DownloadFilesOption = Annotated[ + bool, + typer.Option( + "--download-files", + "-D", + help="Download supplementary files from repositories (e.g., Zenodo). By default, only metadata is captured.", + ), +] + def _reference_to_dict(reference: ReferenceContent) -> dict: """Convert ReferenceContent to a dictionary.""" - return { + result: dict = { "reference_id": reference.reference_id, "title": reference.title, "authors": reference.authors, "journal": reference.journal, "year": reference.year, "doi": reference.doi, + "keywords": reference.keywords, "content_type": reference.content_type, "content": reference.content, } + if reference.supplementary_files: + result["supplementary_files"] = [ + { + "filename": sf.filename, + "download_url": sf.download_url, + "content_type": sf.content_type, + "size_bytes": sf.size_bytes, + "checksum": sf.checksum, + "local_path": sf.local_path, + } + for sf in reference.supplementary_files + ] + return result def _format_as_markdown(reference: ReferenceContent, fetcher: ReferenceFetcher) -> str: @@ -159,7 +183,15 @@ def _format_as_text(reference: ReferenceContent) -> str: lines.append(f"Journal: {journal_info}") if reference.doi: lines.append(f"DOI: {reference.doi}") + if reference.keywords: + lines.append(f"Keywords: {', '.join(reference.keywords)}") lines.append(f"Content type: {reference.content_type}") + if reference.supplementary_files: + lines.append("") + lines.append(f"--- Supplementary Files ({len(reference.supplementary_files)}) ---") + for sf in reference.supplementary_files: + size_str = f" ({sf.size_bytes:,} bytes)" if sf.size_bytes else "" + lines.append(f" - {sf.filename}{size_str}") if reference.content: lines.append("") lines.append("--- Content ---") @@ -176,6 +208,7 @@ def lookup_command( cache_dir: CacheDirOption = None, format: FormatOption = OutputFormat.md, no_cache: NoCacheOption = False, + download_files: DownloadFilesOption = False, verbose: VerboseOption = False, ): """Look up reference(s) and display their information. @@ -194,12 +227,16 @@ def lookup_command( linkml-reference-validator lookup PMID:12345678 --format yaml linkml-reference-validator lookup PMID:12345678 --no-cache + + linkml-reference-validator lookup -D DOI:10.5281/zenodo.7961621 """ setup_logging(verbose) config = load_validation_config(config_file) if cache_dir: config.cache_dir = cache_dir + if download_files: + config.download_supplementary_files = True fetcher = ReferenceFetcher(config) diff --git a/src/linkml_reference_validator/etl/reference_fetcher.py b/src/linkml_reference_validator/etl/reference_fetcher.py index d282be9..ae2d724 100644 --- a/src/linkml_reference_validator/etl/reference_fetcher.py +++ b/src/linkml_reference_validator/etl/reference_fetcher.py @@ -11,7 +11,11 @@ from ruamel.yaml import YAML # type: ignore -from linkml_reference_validator.models import ReferenceContent, ReferenceValidationConfig +from linkml_reference_validator.models import ( + ReferenceContent, + ReferenceValidationConfig, + SupplementaryFile, +) from linkml_reference_validator.etl.sources import ReferenceSourceRegistry logger = logging.getLogger(__name__) @@ -131,12 +135,20 @@ def _parse_reference_id(self, reference_id: str) -> tuple[str, str]: ('file', './test.md') >>> fetcher._parse_reference_id("url:https://example.com/page") ('url', 'https://example.com/page') + >>> fetcher._parse_reference_id("https://example.com/page") + ('url', 'https://example.com/page') + >>> fetcher._parse_reference_id("http://example.com") + ('url', 'http://example.com') >>> config = ReferenceValidationConfig(reference_prefix_map={"geo": "GEO"}) >>> ReferenceFetcher(config)._parse_reference_id("geo:GSE12345") ('GEO', 'GSE12345') """ stripped = reference_id.strip() + # Handle bare HTTP/HTTPS URLs (before the prefix:identifier parsing) + if stripped.lower().startswith(("http://", "https://")): + return "url", stripped + # Standard prefix:identifier format match = re.match(r"^([A-Za-z_]+)[:\s]+(.+)$", stripped) if match: @@ -285,7 +297,27 @@ def _save_to_disk(self, reference: ReferenceContent) -> None: lines.append(f"year: '{reference.year}'") if reference.doi: lines.append(f"doi: {reference.doi}") + if reference.keywords: + lines.append("keywords:") + for keyword in reference.keywords: + lines.append(f"- {self._quote_yaml_value(keyword)}") lines.append(f"content_type: {reference.content_type}") + if reference.supplementary_files: + lines.append("supplementary_files:") + for sf in reference.supplementary_files: + lines.append(f" - filename: {self._quote_yaml_value(sf.filename)}") + if sf.download_url: + lines.append(f" download_url: {self._quote_yaml_value(sf.download_url)}") + if sf.content_type: + lines.append(f" content_type: {sf.content_type}") + if sf.size_bytes is not None: + lines.append(f" size_bytes: {sf.size_bytes}") + if sf.checksum: + lines.append(f" checksum: {sf.checksum}") + if sf.description: + lines.append(f" description: {self._quote_yaml_value(sf.description)}") + if sf.local_path: + lines.append(f" local_path: {self._quote_yaml_value(sf.local_path)}") lines.append("---") lines.append("") @@ -370,6 +402,19 @@ def _load_markdown_format( else: authors = None + keywords = frontmatter.get("keywords") + if keywords and isinstance(keywords, list): + keywords = keywords + elif keywords: + keywords = [keywords] + else: + keywords = None + + # Parse supplementary files + supplementary_files = self._parse_supplementary_files( + frontmatter.get("supplementary_files") + ) + return ReferenceContent( reference_id=frontmatter.get("reference_id", reference_id), title=frontmatter.get("title"), @@ -379,6 +424,8 @@ def _load_markdown_format( journal=frontmatter.get("journal"), year=str(frontmatter.get("year")) if frontmatter.get("year") else None, doi=frontmatter.get("doi"), + keywords=keywords, + supplementary_files=supplementary_files, ) def _extract_content_from_markdown(self, body: str) -> str: @@ -408,6 +455,56 @@ def _extract_content_from_markdown(self, body: str) -> str: return body + def _parse_supplementary_files( + self, files_data: Optional[list] + ) -> Optional[list[SupplementaryFile]]: + """Parse supplementary files from YAML frontmatter data. + + Args: + files_data: List of file dicts from YAML frontmatter + + Returns: + List of SupplementaryFile objects, or None if no files + + Examples: + >>> config = ReferenceValidationConfig() + >>> fetcher = ReferenceFetcher(config) + >>> fetcher._parse_supplementary_files(None) is None + True + >>> fetcher._parse_supplementary_files([]) is None + True + >>> files = fetcher._parse_supplementary_files([ + ... {"filename": "test.pdf", "size_bytes": 1000} + ... ]) + >>> len(files) + 1 + >>> files[0].filename + 'test.pdf' + """ + if not files_data: + return None + + files = [] + for f in files_data: + if not isinstance(f, dict): + continue + filename = f.get("filename") + if not filename: + continue + files.append( + SupplementaryFile( + filename=filename, + download_url=f.get("download_url"), + content_type=f.get("content_type"), + size_bytes=f.get("size_bytes"), + checksum=f.get("checksum"), + description=f.get("description"), + local_path=f.get("local_path"), + ) + ) + + return files if files else None + def _load_legacy_format( self, content_text: str, reference_id: str ) -> Optional[ReferenceContent]: diff --git a/src/linkml_reference_validator/etl/sources/doi.py b/src/linkml_reference_validator/etl/sources/doi.py index be52ab8..e38a428 100644 --- a/src/linkml_reference_validator/etl/sources/doi.py +++ b/src/linkml_reference_validator/etl/sources/doi.py @@ -1,6 +1,7 @@ """DOI (Digital Object Identifier) reference source. -Fetches publication metadata from Crossref API. +Fetches publication metadata from Crossref API, with fallback to DataCite +for DOIs not found in Crossref (e.g., Zenodo, Figshare, Dryad). Examples: >>> from linkml_reference_validator.etl.sources.doi import DOISource @@ -17,7 +18,11 @@ from bs4 import BeautifulSoup # type: ignore import requests # type: ignore -from linkml_reference_validator.models import ReferenceContent, ReferenceValidationConfig +from linkml_reference_validator.models import ( + ReferenceContent, + ReferenceValidationConfig, + SupplementaryFile, +) from linkml_reference_validator.etl.sources.base import ReferenceSource, ReferenceSourceRegistry logger = logging.getLogger(__name__) @@ -25,9 +30,11 @@ @ReferenceSourceRegistry.register class DOISource(ReferenceSource): - """Fetch references from Crossref using DOI. + """Fetch references from Crossref using DOI, with DataCite fallback. Uses the Crossref API (https://api.crossref.org) to fetch publication metadata. + Falls back to DataCite API (https://api.datacite.org) for DOIs not found in + Crossref (e.g., Zenodo, Figshare, Dryad DOIs). Examples: >>> source = DOISource() @@ -50,7 +57,7 @@ def prefix(cls) -> str: def fetch( self, identifier: str, config: ReferenceValidationConfig ) -> Optional[ReferenceContent]: - """Fetch a publication from Crossref by DOI. + """Fetch a publication by DOI from Crossref, falling back to DataCite. Args: identifier: DOI (without prefix) @@ -69,6 +76,26 @@ def fetch( doi = identifier.strip() time.sleep(config.rate_limit_delay) + # Try Crossref first + result = self._fetch_from_crossref(doi, config) + if result: + return result + + # Fall back to DataCite (handles Zenodo, Figshare, Dryad, etc.) + return self._fetch_from_datacite(doi, config) + + def _fetch_from_crossref( + self, doi: str, config: ReferenceValidationConfig + ) -> Optional[ReferenceContent]: + """Fetch from Crossref API. + + Args: + doi: DOI string (without prefix) + config: Configuration including rate limiting and email + + Returns: + ReferenceContent if successful, None otherwise + """ url = f"https://api.crossref.org/works/{doi}" headers = { "User-Agent": f"linkml-reference-validator/1.0 (mailto:{config.email})", @@ -76,12 +103,12 @@ def fetch( response = requests.get(url, headers=headers, timeout=30) if response.status_code != 200: - logger.warning(f"Failed to fetch DOI:{doi} - status {response.status_code}") + logger.debug(f"Crossref returned {response.status_code} for DOI:{doi}, will try DataCite") return None data = response.json() if data.get("status") != "ok": - logger.warning(f"Crossref API error for DOI:{doi}") + logger.debug(f"Crossref API error for DOI:{doi}, will try DataCite") return None message = data.get("message", {}) @@ -98,6 +125,9 @@ def fetch( abstract = self._clean_abstract(message.get("abstract", "")) + # Extract keywords/subjects from Crossref + keywords = self._parse_crossref_subjects(message.get("subject", [])) + return ReferenceContent( reference_id=f"DOI:{doi}", title=title, @@ -107,8 +137,245 @@ def fetch( journal=journal, year=year, doi=doi, + keywords=keywords, + ) + + def _fetch_from_datacite( + self, doi: str, config: ReferenceValidationConfig + ) -> Optional[ReferenceContent]: + """Fetch from DataCite API (handles Zenodo, Figshare, Dryad, etc.). + + Also fetches supplementary file metadata from repository-specific APIs + when available (e.g., Zenodo API for Zenodo DOIs). + + Args: + doi: DOI string (without prefix) + config: Configuration including rate limiting and email + + Returns: + ReferenceContent if successful, None otherwise + """ + url = f"https://api.datacite.org/dois/{doi}" + headers = { + "User-Agent": f"linkml-reference-validator/1.0 (mailto:{config.email})", + "Accept": "application/json", + } + + response = requests.get(url, headers=headers, timeout=30) + if response.status_code != 200: + logger.warning(f"Failed to fetch DOI:{doi} from both Crossref and DataCite") + return None + + data = response.json() + attributes = data.get("data", {}).get("attributes", {}) + + # Extract title + titles = attributes.get("titles", []) + title = titles[0].get("title", "") if titles else "" + + # Extract authors + authors = self._parse_datacite_creators(attributes.get("creators", [])) + + # Extract year + year = str(attributes.get("publicationYear", "")) + + # Extract abstract from descriptions + abstract = "" + for desc in attributes.get("descriptions", []): + if desc.get("descriptionType") == "Abstract": + abstract = desc.get("description", "") + break + + # Publisher as journal equivalent + publisher = attributes.get("publisher", "") + + # Extract keywords/subjects + keywords = self._parse_datacite_subjects(attributes.get("subjects", [])) + + # Fetch supplementary files from repository-specific APIs + supplementary_files = self._fetch_repository_files(doi, config) + + return ReferenceContent( + reference_id=f"DOI:{doi}", + title=title, + content=abstract if abstract else None, + content_type="abstract_only" if abstract else "unavailable", + authors=authors, + journal=publisher, + year=year, + doi=doi, + keywords=keywords, + supplementary_files=supplementary_files, ) + def _detect_repository(self, doi: str) -> Optional[str]: + """Detect repository from DOI prefix. + + Args: + doi: DOI string (without prefix) + + Returns: + Repository name if detected, None otherwise + + Examples: + >>> source = DOISource() + >>> source._detect_repository("10.5281/zenodo.7961621") + 'zenodo' + >>> source._detect_repository("10.1038/s41586-024-12345") is None + True + """ + # Zenodo DOIs: 10.5281/zenodo.{record_id} + if doi.startswith("10.5281/zenodo."): + return "zenodo" + # Can add more repositories here: + # Figshare: 10.6084/m9.figshare.{id} + # Dryad: 10.5061/dryad.{id} + return None + + def _extract_zenodo_record_id(self, doi: str) -> Optional[str]: + """Extract Zenodo record ID from DOI. + + Args: + doi: DOI string (without prefix) + + Returns: + Record ID if Zenodo DOI, None otherwise + + Examples: + >>> source = DOISource() + >>> source._extract_zenodo_record_id("10.5281/zenodo.7961621") + '7961621' + >>> source._extract_zenodo_record_id("10.1038/s41586-024-12345") is None + True + """ + if doi.startswith("10.5281/zenodo."): + return doi.split("zenodo.")[1] + return None + + def _fetch_repository_files( + self, doi: str, config: ReferenceValidationConfig + ) -> Optional[list[SupplementaryFile]]: + """Fetch supplementary file metadata from repository-specific APIs. + + Args: + doi: DOI string (without prefix) + config: Configuration + + Returns: + List of SupplementaryFile objects, or None if no files or unsupported repo + """ + repository = self._detect_repository(doi) + if repository == "zenodo": + record_id = self._extract_zenodo_record_id(doi) + if record_id: + return self._fetch_zenodo_files(record_id, config) + # Add more repository handlers here as needed + return None + + def _fetch_zenodo_files( + self, record_id: str, config: ReferenceValidationConfig + ) -> Optional[list[SupplementaryFile]]: + """Fetch file metadata from Zenodo API. + + Args: + record_id: Zenodo record ID + config: Configuration + + Returns: + List of SupplementaryFile objects, or None if fetch fails + """ + url = f"https://zenodo.org/api/records/{record_id}" + headers = { + "User-Agent": f"linkml-reference-validator/1.0 (mailto:{config.email})", + "Accept": "application/json", + } + + response = requests.get(url, headers=headers, timeout=30) + if response.status_code != 200: + logger.debug(f"Failed to fetch Zenodo files for record {record_id}") + return None + + data = response.json() + files_data = data.get("files", []) + + if not files_data: + return None + + files = [] + for f in files_data: + download_url = f.get("links", {}).get("self") + files.append( + SupplementaryFile( + filename=f.get("key", ""), + download_url=download_url, + size_bytes=f.get("size"), + checksum=f.get("checksum"), + ) + ) + + return files if files else None + + def _parse_datacite_creators(self, creators: list) -> list[str]: + """Parse creator list from DataCite response. + + Args: + creators: List of creator dicts from DataCite + + Returns: + List of formatted author names + + Examples: + >>> source = DOISource() + >>> source._parse_datacite_creators([{"name": "Mungall, Christopher"}]) + ['Mungall, Christopher'] + >>> source._parse_datacite_creators([{"givenName": "John", "familyName": "Smith"}]) + ['John Smith'] + """ + result = [] + for creator in creators: + # DataCite may have full name or given/family + name = creator.get("name") + if not name: + given = creator.get("givenName", "") + family = creator.get("familyName", "") + if given and family: + name = f"{given} {family}" + elif family: + name = family + elif given: + name = given + if name: + result.append(name) + return result + + def _parse_datacite_subjects(self, subjects: list) -> Optional[list[str]]: + """Parse subjects/keywords from DataCite response. + + Args: + subjects: List of subject dicts from DataCite + + Returns: + List of subject strings, or None if empty + + Examples: + >>> source = DOISource() + >>> source._parse_datacite_subjects([{"subject": "Climate Change"}]) + ['Climate Change'] + >>> source._parse_datacite_subjects([]) is None + True + """ + if not subjects: + return None + result = [] + for subj in subjects: + if isinstance(subj, dict): + text = subj.get("subject") + if text: + result.append(text) + elif isinstance(subj, str): + result.append(subj) + return result if result else None + def _parse_crossref_authors(self, authors: list) -> list[str]: """Parse author list from Crossref response. @@ -137,6 +404,27 @@ def _parse_crossref_authors(self, authors: list) -> list[str]: result.append(given) return result + def _parse_crossref_subjects(self, subjects: list) -> Optional[list[str]]: + """Parse subjects/keywords from Crossref response. + + Args: + subjects: List of subject strings from Crossref + + Returns: + List of subject strings, or None if empty + + Examples: + >>> source = DOISource() + >>> source._parse_crossref_subjects(["General Chemistry", "Biochemistry"]) + ['General Chemistry', 'Biochemistry'] + >>> source._parse_crossref_subjects([]) is None + True + """ + if not subjects: + return None + result = [str(s) for s in subjects if s] + return result if result else None + def _extract_crossref_year(self, message: dict) -> str: """Extract publication year from Crossref message. diff --git a/src/linkml_reference_validator/etl/sources/pmid.py b/src/linkml_reference_validator/etl/sources/pmid.py index 6dca297..fe1d7d5 100644 --- a/src/linkml_reference_validator/etl/sources/pmid.py +++ b/src/linkml_reference_validator/etl/sources/pmid.py @@ -118,14 +118,17 @@ def fetch( record = records[0] if isinstance(records, list) else records - title = record.get("Title", "") + # Convert Entrez StringElement objects to plain strings + title = str(record.get("Title", "")) authors = self._parse_authors(record.get("AuthorList", [])) - journal = record.get("Source", "") - year = record.get("PubDate", "")[:4] if record.get("PubDate") else "" - doi = record.get("DOI", "") + journal = str(record.get("Source", "")) + pub_date = record.get("PubDate", "") + year = str(pub_date)[:4] if pub_date else "" + doi = str(record.get("DOI", "")) if record.get("DOI") else "" abstract = self._fetch_abstract(pmid, config) full_text, content_type = self._fetch_pmc_fulltext(pmid, config) + keywords = self._fetch_mesh_terms(pmid, config) if full_text: content: Optional[str] = f"{abstract}\n\n{full_text}" if abstract else full_text @@ -142,6 +145,7 @@ def fetch( journal=journal, year=year, doi=doi, + keywords=keywords, ) def _parse_authors(self, author_list: list) -> list[str]: @@ -183,6 +187,52 @@ def _fetch_abstract( return None + def _fetch_mesh_terms( + self, pmid: str, config: ReferenceValidationConfig + ) -> Optional[list[str]]: + """Fetch MeSH terms for a PMID from PubMed XML. + + Args: + pmid: PubMed ID + config: Configuration for rate limiting + + Returns: + List of MeSH terms if available + + Examples: + >>> source = PMIDSource() + >>> # Would return MeSH terms like: + >>> # ['Adaptation, Physiological/genetics', 'Climate Change', ...] + """ + time.sleep(config.rate_limit_delay) + + handle = Entrez.efetch(db="pubmed", id=pmid, rettype="xml", retmode="xml") + xml_content = handle.read() + handle.close() + + if isinstance(xml_content, bytes): + xml_content = xml_content.decode("utf-8") + + soup = BeautifulSoup(xml_content, "xml") + mesh_list = soup.find("MeshHeadingList") + + if not mesh_list: + return None + + terms = [] + for heading in mesh_list.find_all("MeshHeading"): + descriptor = heading.find("DescriptorName") + if descriptor: + term = descriptor.get_text() + # Include qualifiers if present (e.g., "genetics", "metabolism") + qualifiers = heading.find_all("QualifierName") + if qualifiers: + qualifier_texts = [q.get_text() for q in qualifiers] + term = f"{term}/{', '.join(qualifier_texts)}" + terms.append(term) + + return terms if terms else None + def _fetch_pmc_fulltext( self, pmid: str, config: ReferenceValidationConfig ) -> tuple[Optional[str], str]: diff --git a/src/linkml_reference_validator/models.py b/src/linkml_reference_validator/models.py index c16ea3e..677f6b0 100644 --- a/src/linkml_reference_validator/models.py +++ b/src/linkml_reference_validator/models.py @@ -410,6 +410,22 @@ class ReferenceValidationConfig(BaseModel): "Does not apply to prefixes in skip_prefixes list." ), ) + download_supplementary_files: bool = Field( + default=False, + description=( + "If True, download supplementary files from repositories like Zenodo. " + "By default, only metadata is captured without downloading." + ), + ) + max_supplementary_file_size: int = Field( + default=50 * 1024 * 1024, # 50MB + ge=0, + description=( + "Maximum size in bytes for downloading individual supplementary files. " + "Files larger than this limit will have metadata captured but not downloaded. " + "Default is 50MB (50 * 1024 * 1024 bytes)." + ), + ) def get_cache_dir(self) -> Path: """Create and return the cache directory. @@ -468,6 +484,36 @@ class JSONAPISourceConfig: store_raw_response: bool = False # Store full response in metadata['raw_response'] +@dataclass +class SupplementaryFile: + """Metadata for a supplementary file associated with a reference. + + Captures file information from repository APIs (Zenodo, Figshare, etc.) + without necessarily downloading the file. + + Examples: + >>> sf = SupplementaryFile( + ... filename="Table_S1.xlsx", + ... download_url="https://zenodo.org/api/records/123/files/Table_S1.xlsx/content", + ... content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ... size_bytes=12345, + ... checksum="md5:88c66d378d886fea4969949c5877802f" + ... ) + >>> sf.filename + 'Table_S1.xlsx' + >>> sf.size_bytes + 12345 + """ + + filename: str + download_url: Optional[str] = None + content_type: Optional[str] = None # MIME type: "application/pdf", "text/csv" + size_bytes: Optional[int] = None + checksum: Optional[str] = None # e.g., "md5:88c66d378d886fea4969949c5877802f" + description: Optional[str] = None + local_path: Optional[str] = None # Relative path if downloaded + + @dataclass class ReferenceContent: """Content retrieved from a reference. @@ -481,6 +527,15 @@ class ReferenceContent: ... ) >>> ref.reference_id 'PMID:12345678' + >>> ref = ReferenceContent( + ... reference_id="DOI:10.5281/zenodo.123", + ... title="Dataset", + ... supplementary_files=[ + ... SupplementaryFile(filename="data.csv", size_bytes=1000) + ... ] + ... ) + >>> len(ref.supplementary_files) + 1 """ reference_id: str @@ -491,6 +546,8 @@ class ReferenceContent: journal: Optional[str] = None year: Optional[str] = None doi: Optional[str] = None + keywords: Optional[list[str]] = None # MeSH terms, subjects, tags + supplementary_files: Optional[list[SupplementaryFile]] = None metadata: dict = field(default_factory=dict) diff --git a/tests/test_reference_fetcher.py b/tests/test_reference_fetcher.py index 1c3da80..3d017d3 100644 --- a/tests/test_reference_fetcher.py +++ b/tests/test_reference_fetcher.py @@ -310,3 +310,385 @@ def test_save_and_load_url_from_disk(mock_get, fetcher, tmp_path): assert result2.reference_id == "url:https://example.com/cached" assert result2.title == "Cached URL Content" assert "This content should be cached" in result2.content + + +def test_parse_bare_https_url(fetcher): + """Test that bare HTTPS URLs are correctly parsed as url: prefix. + + Bug fix: Previously https://example.com was parsed as prefix='HTTPS' + with identifier='//example.com', which failed to match any source. + """ + # Bare HTTPS URL should be parsed as url: prefix + prefix, identifier = fetcher._parse_reference_id("https://example.com") + assert prefix == "url" + assert identifier == "https://example.com" + + # Bare HTTP URL should also work + prefix, identifier = fetcher._parse_reference_id("http://example.com/path") + assert prefix == "url" + assert identifier == "http://example.com/path" + + # doi.org URL should also be treated as url: + prefix, identifier = fetcher._parse_reference_id("https://doi.org/10.5281/zenodo.123") + assert prefix == "url" + assert identifier == "https://doi.org/10.5281/zenodo.123" + + # Explicit url: prefix should still work + prefix, identifier = fetcher._parse_reference_id("url:https://example.com") + assert prefix == "url" + assert identifier == "https://example.com" + + +def test_normalize_bare_https_url(fetcher): + """Test that normalize_reference_id handles bare HTTPS URLs.""" + assert fetcher.normalize_reference_id("https://example.com") == "url:https://example.com" + assert fetcher.normalize_reference_id("http://example.com/path") == "url:http://example.com/path" + assert fetcher.normalize_reference_id("https://doi.org/10.5281/zenodo.123") == "url:https://doi.org/10.5281/zenodo.123" + + +@patch("linkml_reference_validator.etl.sources.url.requests.get") +def test_fetch_bare_https_url(mock_get, fetcher): + """Test that bare HTTPS URLs are fetched correctly.""" + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.text = "Bare URL TestContent from bare URL." + mock_response.headers = {"content-type": "text/html"} + mock_get.return_value = mock_response + + # Fetch using bare URL (no url: prefix) + result = fetcher.fetch("https://example.com/page") + + assert result is not None + assert result.title == "Bare URL Test" + assert "Content from bare URL" in result.content + assert result.reference_id == "url:https://example.com/page" + + +@patch("linkml_reference_validator.etl.sources.doi.requests.get") +def test_fetch_zenodo_doi_via_datacite(mock_get, fetcher): + """Test that Zenodo DOIs are fetched via DataCite when Crossref returns 404. + + Zenodo DOIs (10.5281/zenodo.*) are registered with DataCite, not Crossref. + The DOI source should fall back to DataCite when Crossref returns 404. + """ + # Set up mock responses: Crossref 404, then DataCite success, then Zenodo files + crossref_response = MagicMock() + crossref_response.status_code = 404 + + datacite_response = MagicMock() + datacite_response.status_code = 200 + datacite_response.json.return_value = { + "data": { + "attributes": { + "doi": "10.5281/zenodo.17993529", + "titles": [{"title": "Gene Ontology Curators AI Workshop (Part 1)"}], + "creators": [ + { + "name": "Mungall, Christopher", + "givenName": "Christopher", + "familyName": "Mungall", + } + ], + "publicationYear": 2025, + "publisher": "Zenodo", + "descriptions": [ + { + "description": "Workshop aims to equip curators with AI skills.", + "descriptionType": "Abstract", + } + ], + } + } + } + + # Zenodo API returns file metadata (or 404 if no files) + zenodo_response = MagicMock() + zenodo_response.status_code = 200 + zenodo_response.json.return_value = {"files": []} # Empty files list + + # Order: Crossref (404), DataCite (success), Zenodo (success) + mock_get.side_effect = [crossref_response, datacite_response, zenodo_response] + + result = fetcher.fetch("DOI:10.5281/zenodo.17993529") + + assert result is not None + assert result.reference_id == "DOI:10.5281/zenodo.17993529" + assert "Gene Ontology" in result.title + assert result.year == "2025" + assert result.journal == "Zenodo" + assert "Christopher" in result.authors[0] or "Mungall" in result.authors[0] + assert "AI skills" in result.content or "Workshop" in result.content + + +@patch("linkml_reference_validator.etl.sources.doi.requests.get") +def test_fetch_doi_crossref_success_no_datacite_call(mock_get, fetcher): + """Test that when Crossref succeeds, DataCite is not called.""" + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.json.return_value = { + "status": "ok", + "message": { + "title": ["Regular Crossref Article"], + "author": [{"given": "Jane", "family": "Doe"}], + "container-title": ["Nature"], + "published-print": {"date-parts": [[2024]]}, + }, + } + mock_get.return_value = mock_response + + result = fetcher.fetch("DOI:10.1038/s41586-024-12345") + + assert result is not None + assert result.title == "Regular Crossref Article" + # Crossref should only be called once + assert mock_get.call_count == 1 + assert "crossref.org" in mock_get.call_args[0][0] + + +@patch("linkml_reference_validator.etl.sources.doi.requests.get") +def test_fetch_doi_both_fail(mock_get, fetcher): + """Test that when both Crossref and DataCite fail, None is returned.""" + crossref_response = MagicMock() + crossref_response.status_code = 404 + + datacite_response = MagicMock() + datacite_response.status_code = 404 + + mock_get.side_effect = [crossref_response, datacite_response] + + result = fetcher.fetch("DOI:10.9999/nonexistent.doi") + + assert result is None + # Both APIs should be called + assert mock_get.call_count == 2 + + +# === Supplementary Files Tests === + + +@patch("linkml_reference_validator.etl.sources.doi.requests.get") +def test_fetch_zenodo_doi_with_supplementary_files(mock_get, fetcher): + """Test that Zenodo DOIs include supplementary file metadata. + + Zenodo DOIs (10.5281/zenodo.*) should fetch file metadata from + the Zenodo API and populate supplementary_files. + """ + # Crossref returns 404 (Zenodo DOIs aren't in Crossref) + crossref_response = MagicMock() + crossref_response.status_code = 404 + + # DataCite returns basic metadata + datacite_response = MagicMock() + datacite_response.status_code = 200 + datacite_response.json.return_value = { + "data": { + "attributes": { + "doi": "10.5281/zenodo.7961621", + "titles": [{"title": "Workshop Presentation"}], + "creators": [{"name": "Mungall, Christopher"}], + "publicationYear": 2023, + "publisher": "Zenodo", + "descriptions": [], + } + } + } + + # Zenodo API returns file metadata + zenodo_response = MagicMock() + zenodo_response.status_code = 200 + zenodo_response.json.return_value = { + "files": [ + { + "key": "Dickinson_Varenna2022.pdf", + "size": 1975995, + "checksum": "md5:88c66d378d886fea4969949c5877802f", + "links": { + "self": "https://zenodo.org/api/records/7961621/files/Dickinson_Varenna2022.pdf/content" + }, + }, + { + "key": "supplementary_data.csv", + "size": 12345, + "checksum": "md5:abc123def456", + "links": { + "self": "https://zenodo.org/api/records/7961621/files/supplementary_data.csv/content" + }, + }, + ] + } + + # Order: Crossref (404), DataCite (success), Zenodo (success) + mock_get.side_effect = [crossref_response, datacite_response, zenodo_response] + + result = fetcher.fetch("DOI:10.5281/zenodo.7961621") + + assert result is not None + assert result.reference_id == "DOI:10.5281/zenodo.7961621" + assert result.title == "Workshop Presentation" + + # Check supplementary files + assert result.supplementary_files is not None + assert len(result.supplementary_files) == 2 + + # Check first file + pdf_file = result.supplementary_files[0] + assert pdf_file.filename == "Dickinson_Varenna2022.pdf" + assert pdf_file.size_bytes == 1975995 + assert pdf_file.checksum == "md5:88c66d378d886fea4969949c5877802f" + assert "zenodo.org" in pdf_file.download_url + assert pdf_file.local_path is None # Not downloaded by default + + # Check second file + csv_file = result.supplementary_files[1] + assert csv_file.filename == "supplementary_data.csv" + assert csv_file.size_bytes == 12345 + + +@patch("linkml_reference_validator.etl.sources.doi.requests.get") +def test_fetch_non_zenodo_doi_no_supplementary_files(mock_get, fetcher): + """Test that non-Zenodo DOIs (regular Crossref) don't have supplementary files.""" + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.json.return_value = { + "status": "ok", + "message": { + "title": ["Regular Journal Article"], + "author": [{"given": "Jane", "family": "Doe"}], + "container-title": ["Nature"], + "published-print": {"date-parts": [[2024]]}, + }, + } + mock_get.return_value = mock_response + + result = fetcher.fetch("DOI:10.1038/s41586-024-12345") + + assert result is not None + assert result.title == "Regular Journal Article" + # Regular DOIs don't have supplementary files from Crossref + assert result.supplementary_files is None + + +def test_detect_repository(): + """Test repository detection from DOI prefix.""" + from linkml_reference_validator.etl.sources.doi import DOISource + + source = DOISource() + + # Zenodo DOIs + assert source._detect_repository("10.5281/zenodo.7961621") == "zenodo" + assert source._detect_repository("10.5281/zenodo.123") == "zenodo" + + # Non-Zenodo DOIs + assert source._detect_repository("10.1038/s41586-024-12345") is None + assert source._detect_repository("10.1234/test") is None + + # Edge cases + assert source._detect_repository("10.5281/other.123") is None # 10.5281 but not zenodo + + +def test_extract_zenodo_record_id(): + """Test extracting Zenodo record ID from DOI.""" + from linkml_reference_validator.etl.sources.doi import DOISource + + source = DOISource() + + assert source._extract_zenodo_record_id("10.5281/zenodo.7961621") == "7961621" + assert source._extract_zenodo_record_id("10.5281/zenodo.123") == "123" + assert source._extract_zenodo_record_id("10.1038/s41586-024-12345") is None + + +# === Supplementary Files Cache Serialization Tests === + + +def test_save_and_load_supplementary_files(fetcher, tmp_path): + """Test saving and loading reference with supplementary files to/from cache.""" + from linkml_reference_validator.models import SupplementaryFile + + ref = ReferenceContent( + reference_id="DOI:10.5281/zenodo.7961621", + title="Workshop Presentation", + content="Abstract text here.", + content_type="abstract_only", + authors=["Mungall, Christopher"], + journal="Zenodo", + year="2023", + doi="10.5281/zenodo.7961621", + supplementary_files=[ + SupplementaryFile( + filename="Dickinson_Varenna2022.pdf", + download_url="https://zenodo.org/api/records/7961621/files/Dickinson_Varenna2022.pdf/content", + content_type="application/pdf", + size_bytes=1975995, + checksum="md5:88c66d378d886fea4969949c5877802f", + ), + SupplementaryFile( + filename="data.csv", + download_url="https://zenodo.org/api/records/7961621/files/data.csv/content", + size_bytes=12345, + ), + ], + ) + + # Save to disk + fetcher._save_to_disk(ref) + + # Clear memory cache + fetcher._cache.clear() + + # Load from disk + loaded = fetcher._load_from_disk("DOI:10.5281/zenodo.7961621") + + assert loaded is not None + assert loaded.reference_id == "DOI:10.5281/zenodo.7961621" + assert loaded.title == "Workshop Presentation" + + # Check supplementary files were preserved + assert loaded.supplementary_files is not None + assert len(loaded.supplementary_files) == 2 + + pdf_file = loaded.supplementary_files[0] + assert pdf_file.filename == "Dickinson_Varenna2022.pdf" + assert pdf_file.size_bytes == 1975995 + assert pdf_file.checksum == "md5:88c66d378d886fea4969949c5877802f" + assert "zenodo.org" in pdf_file.download_url + + csv_file = loaded.supplementary_files[1] + assert csv_file.filename == "data.csv" + assert csv_file.size_bytes == 12345 + + +def test_save_and_load_no_supplementary_files(fetcher, tmp_path): + """Test that references without supplementary files serialize correctly.""" + ref = ReferenceContent( + reference_id="PMID:12345678", + title="Regular Article", + content="Abstract text.", + content_type="abstract_only", + supplementary_files=None, + ) + + fetcher._save_to_disk(ref) + fetcher._cache.clear() + + loaded = fetcher._load_from_disk("PMID:12345678") + + assert loaded is not None + assert loaded.supplementary_files is None + + +def test_save_and_load_empty_supplementary_files(fetcher, tmp_path): + """Test that empty supplementary files list serializes correctly.""" + ref = ReferenceContent( + reference_id="DOI:10.1234/test", + title="Article", + supplementary_files=[], # Empty list + ) + + fetcher._save_to_disk(ref) + fetcher._cache.clear() + + loaded = fetcher._load_from_disk("DOI:10.1234/test") + + assert loaded is not None + # Empty list should be treated as None or empty + assert loaded.supplementary_files is None or loaded.supplementary_files == []