Add agent skills under .agents/skills for Codex
Copy of the project skills (.claude/skills is gitignored) so Codex on other machines picks them up; skills-lock.json records their sources. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
331
.agents/skills/citation-management/scripts/_common.py
Normal file
331
.agents/skills/citation-management/scripts/_common.py
Normal file
@@ -0,0 +1,331 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Shared BibTeX parsing and rendering for the citation-management scripts.
|
||||
|
||||
Standard library only.
|
||||
|
||||
The parser here is brace-depth aware. That matters more than it sounds: a
|
||||
regular expression of the form ``\\{([^}]*)\\}`` stops at the first closing
|
||||
brace, so it truncates every title that protects a capitalised term --
|
||||
``{Highly accurate prediction with {AlphaFold}}`` -- and writing the truncated
|
||||
value back out produces a ``.bib`` file with unbalanced braces that no BibTeX
|
||||
engine will read. Capitalisation protection is routine in real bibliographies,
|
||||
and ``extract_metadata.py`` emits it deliberately, so the naive form corrupts
|
||||
this skill's own output.
|
||||
|
||||
Every producer in this skill renders through :func:`render_entry` and keys
|
||||
through :func:`citation_key`, so entries from Crossref, PubMed, OpenAlex, and
|
||||
Scholar are directly comparable and deduplication works across sources.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
import unicodedata
|
||||
from collections import OrderedDict
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
# Field order used when rendering. Anything not listed keeps its input order
|
||||
# and is appended after these.
|
||||
FIELD_ORDER = [
|
||||
'author', 'editor', 'title', 'booktitle', 'journal',
|
||||
'year', 'month', 'volume', 'number', 'pages',
|
||||
'publisher', 'address', 'edition', 'series',
|
||||
'school', 'institution', 'organization',
|
||||
'howpublished', 'doi', 'url', 'isbn', 'issn',
|
||||
'note', 'abstract', 'keywords',
|
||||
]
|
||||
|
||||
# @string, @comment and @preamble are not bibliography entries.
|
||||
_NON_ENTRY_TYPES = {'string', 'comment', 'preamble'}
|
||||
|
||||
_FIELD_NAME = re.compile(r'\s*([A-Za-z][A-Za-z0-9_+:.-]*)\s*=\s*(.*)$', re.DOTALL)
|
||||
|
||||
|
||||
def _is_outer_braced(value: str) -> bool:
|
||||
"""True when the whole value is wrapped in one matched brace pair."""
|
||||
if not (value.startswith('{') and value.endswith('}')):
|
||||
return False
|
||||
depth = 0
|
||||
for index, char in enumerate(value):
|
||||
if char == '{':
|
||||
depth += 1
|
||||
elif char == '}':
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
# Only a wrapper if it closes at the very end; `{a} # {b}`
|
||||
# and `{a}{b}` must be left alone.
|
||||
return index == len(value) - 1
|
||||
return False
|
||||
|
||||
|
||||
def _unwrap(value: str) -> str:
|
||||
"""Strip one layer of delimiters, preserving any nested braces inside."""
|
||||
value = value.strip()
|
||||
if _is_outer_braced(value):
|
||||
return value[1:-1].strip()
|
||||
if len(value) >= 2 and value[0] == '"' and value[-1] == '"':
|
||||
return value[1:-1].strip()
|
||||
return value
|
||||
|
||||
|
||||
def _split_top_level(body: str) -> List[str]:
|
||||
"""Split on commas that sit outside braces and quotes."""
|
||||
parts: List[str] = []
|
||||
buffer: List[str] = []
|
||||
depth = 0
|
||||
in_quote = False
|
||||
|
||||
for char in body:
|
||||
if char == '"' and depth == 0:
|
||||
in_quote = not in_quote
|
||||
elif char == '{':
|
||||
depth += 1
|
||||
elif char == '}':
|
||||
depth -= 1
|
||||
|
||||
if char == ',' and depth == 0 and not in_quote:
|
||||
parts.append(''.join(buffer))
|
||||
buffer = []
|
||||
else:
|
||||
buffer.append(char)
|
||||
|
||||
parts.append(''.join(buffer))
|
||||
return parts
|
||||
|
||||
|
||||
def parse_bibtex(content: str) -> List[Dict]:
|
||||
"""Parse BibTeX source into entry dictionaries.
|
||||
|
||||
Each entry is ``{'type', 'key', 'fields', 'raw'}`` with ``fields`` an
|
||||
``OrderedDict`` of lowercased field names to their unwrapped values.
|
||||
Malformed or unterminated entries are skipped rather than raised on.
|
||||
"""
|
||||
entries: List[Dict] = []
|
||||
length = len(content)
|
||||
position = 0
|
||||
|
||||
while True:
|
||||
at = content.find('@', position)
|
||||
if at < 0:
|
||||
break
|
||||
|
||||
cursor = at + 1
|
||||
while cursor < length and content[cursor].isalpha():
|
||||
cursor += 1
|
||||
entry_type = content[at + 1:cursor].lower()
|
||||
|
||||
if not entry_type:
|
||||
position = at + 1
|
||||
continue
|
||||
|
||||
while cursor < length and content[cursor].isspace():
|
||||
cursor += 1
|
||||
|
||||
if cursor >= length or content[cursor] not in '{(':
|
||||
position = at + 1
|
||||
continue
|
||||
|
||||
opener = content[cursor]
|
||||
closer = '}' if opener == '{' else ')'
|
||||
|
||||
# Walk to the delimiter that matches the opener, counting depth.
|
||||
depth = 0
|
||||
end = -1
|
||||
scan = cursor
|
||||
while scan < length:
|
||||
char = content[scan]
|
||||
if char == opener:
|
||||
depth += 1
|
||||
elif char == closer:
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
end = scan
|
||||
break
|
||||
scan += 1
|
||||
|
||||
if end < 0:
|
||||
# Unterminated entry: nothing reliable left to read.
|
||||
break
|
||||
|
||||
position = end + 1
|
||||
|
||||
if entry_type in _NON_ENTRY_TYPES:
|
||||
continue
|
||||
|
||||
body = content[cursor + 1:end]
|
||||
chunks = _split_top_level(body)
|
||||
if not chunks:
|
||||
continue
|
||||
|
||||
citation_key_text = chunks[0].strip()
|
||||
if not citation_key_text or '=' in citation_key_text:
|
||||
# No citation key -- not an entry we can work with.
|
||||
continue
|
||||
|
||||
fields: "OrderedDict[str, str]" = OrderedDict()
|
||||
for chunk in chunks[1:]:
|
||||
if not chunk.strip():
|
||||
continue
|
||||
match = _FIELD_NAME.match(chunk)
|
||||
if not match:
|
||||
continue
|
||||
fields[match.group(1).lower()] = _unwrap(match.group(2))
|
||||
|
||||
entries.append({
|
||||
'type': entry_type,
|
||||
'key': citation_key_text,
|
||||
'fields': fields,
|
||||
'raw': content[at:end + 1],
|
||||
})
|
||||
|
||||
return entries
|
||||
|
||||
|
||||
def parse_bibtex_file(filepath: str) -> List[Dict]:
|
||||
"""Parse a BibTeX file, reporting read errors rather than raising."""
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8') as handle:
|
||||
return parse_bibtex(handle.read())
|
||||
except OSError as error:
|
||||
print(f'Error reading file: {error}', file=sys.stderr)
|
||||
return []
|
||||
|
||||
|
||||
def render_entry(entry_type: str, key: str, fields: Dict[str, str]) -> str:
|
||||
"""Render one entry with fields in a stable order and aligned values.
|
||||
|
||||
Empty values are dropped, so callers can pass a dictionary built from
|
||||
metadata that may or may not have been populated.
|
||||
"""
|
||||
present = OrderedDict()
|
||||
for name in FIELD_ORDER:
|
||||
value = fields.get(name)
|
||||
if value:
|
||||
present[name] = str(value)
|
||||
for name, value in fields.items():
|
||||
if name not in present and value:
|
||||
present[name] = str(value)
|
||||
|
||||
if not present:
|
||||
return f'@{entry_type}{{{key},\n}}'
|
||||
|
||||
width = max(len(name) for name in present)
|
||||
lines = [f'@{entry_type}{{{key},']
|
||||
rendered = [f' {name.ljust(width)} = {{{value}}}' for name, value in present.items()]
|
||||
lines.append(',\n'.join(rendered))
|
||||
lines.append('}')
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
_PAGE_RANGE = re.compile(r'^(\d+)\s*(?:-{1,3}|–|—)\s*(\d+)$')
|
||||
|
||||
|
||||
def format_pages(raw: Optional[str]) -> str:
|
||||
"""Normalise a page field to a BibTeX en-dash range.
|
||||
|
||||
Handles the two mistakes the previous per-script implementations made:
|
||||
a blanket ``replace('-', '--')`` turned an already-correct ``583--589``
|
||||
into ``583----589``, and PubMed's abbreviated ``MedlinePgn`` ranges
|
||||
(``1123-30``) need their end page expanded to ``1123--1130`` rather than
|
||||
being left as a nonsensical ``1123--30``.
|
||||
|
||||
Values that are not ranges -- article numbers such as ``e0123456``,
|
||||
or discontinuous lists -- are returned unchanged.
|
||||
"""
|
||||
if not raw:
|
||||
return ''
|
||||
|
||||
pages = re.sub(r'^\s*pp?\.\s*', '', str(raw).strip(), flags=re.IGNORECASE)
|
||||
match = _PAGE_RANGE.match(pages)
|
||||
if not match:
|
||||
return pages
|
||||
|
||||
start, end = match.group(1), match.group(2)
|
||||
if len(end) < len(start):
|
||||
end = start[:len(start) - len(end)] + end
|
||||
return f'{start}--{end}'
|
||||
|
||||
|
||||
def _ascii_fold(text: str) -> str:
|
||||
"""Reduce accented Latin characters to ASCII (Muller from Müller)."""
|
||||
decomposed = unicodedata.normalize('NFKD', text)
|
||||
return ''.join(char for char in decomposed if not unicodedata.combining(char))
|
||||
|
||||
|
||||
def sanitize_key(text: str) -> str:
|
||||
"""Reduce a string to characters that are safe in a BibTeX citation key.
|
||||
|
||||
Keys reach both LaTeX and, in some workflows, the filesystem, and their
|
||||
source is a publisher-controlled metadata record. Restricting them to
|
||||
ASCII letters and digits keeps `O'Brien` and `Müller` from producing an
|
||||
entry that LaTeX rejects.
|
||||
"""
|
||||
return re.sub(r'[^A-Za-z0-9]', '', _ascii_fold(text or ''))
|
||||
|
||||
|
||||
def _looks_like_initials(word: str) -> bool:
|
||||
"""True for `J`, `JA`, `J.A.` -- the initials half of a PubMed author."""
|
||||
stripped = word.replace('.', '')
|
||||
return bool(stripped) and len(stripped) <= 3 and stripped.isupper()
|
||||
|
||||
|
||||
def citation_key(authors: str, year: str, title: str) -> str:
|
||||
"""Build the citation key used by every producer in this skill.
|
||||
|
||||
``<FirstAuthorSurname><Year><FirstSubstantiveTitleWord>``, ASCII-folded and
|
||||
stripped of anything outside ``[A-Za-z0-9]``. Sharing one scheme across
|
||||
Crossref, PubMed, OpenAlex, and Scholar output is what makes the
|
||||
deduplication in ``format_bibtex.py`` and ``validate_citations.py`` able to
|
||||
see the same paper twice.
|
||||
"""
|
||||
surname = ''
|
||||
if authors:
|
||||
first = authors.split(' and ')[0].strip()
|
||||
if ',' in first:
|
||||
surname = first.split(',')[0]
|
||||
else:
|
||||
words = first.split()
|
||||
if not words:
|
||||
surname = ''
|
||||
elif len(words) > 1 and _looks_like_initials(words[-1]):
|
||||
# PubMed's comma-less form puts the surname first: `Smith JA`.
|
||||
surname = words[0]
|
||||
else:
|
||||
# Western given-name-first order: `John Smith`.
|
||||
surname = words[-1]
|
||||
|
||||
surname = sanitize_key(surname) or 'unknown'
|
||||
|
||||
digits = re.sub(r'[^0-9]', '', str(year or ''))
|
||||
year_part = digits[:4] if digits else 'XXXX'
|
||||
|
||||
words = re.findall(r'[A-Za-z]{4,}', _ascii_fold(title or ''))
|
||||
keyword = words[0].lower() if words else 'paper'
|
||||
|
||||
return f'{surname}{year_part}{keyword}'
|
||||
|
||||
|
||||
# Terms whose capitalisation BibTeX would otherwise flatten in a title.
|
||||
PROTECTED_TERMS = [
|
||||
'AlphaFold', 'CRISPR', 'COVID', 'SARS', 'DNA', 'RNA', 'mRNA', 'HIV',
|
||||
'AIDS', 'MRI', 'PCR', 'USA', 'UK', 'EU', 'GPU', 'CPU', 'AI', 'ML',
|
||||
]
|
||||
|
||||
|
||||
def protect_title(title: str) -> str:
|
||||
"""Brace terms whose capitalisation must survive BibTeX style processing.
|
||||
|
||||
Terms already inside braces are left alone, so running this twice is safe.
|
||||
"""
|
||||
if not title:
|
||||
return ''
|
||||
|
||||
for term in PROTECTED_TERMS:
|
||||
# Skip occurrences already wrapped, so the function is idempotent.
|
||||
title = re.sub(
|
||||
rf'(?<!\{{)\b{re.escape(term)}\b(?!\}})',
|
||||
f'{{{term}}}',
|
||||
title,
|
||||
)
|
||||
return title
|
||||
212
.agents/skills/citation-management/scripts/doi_to_bibtex.py
Normal file
212
.agents/skills/citation-management/scripts/doi_to_bibtex.py
Normal file
@@ -0,0 +1,212 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
DOI to BibTeX Converter
|
||||
Convert DOIs to BibTeX through DOI content negotiation (Crossref/DataCite/mEDRA).
|
||||
"""
|
||||
|
||||
import sys
|
||||
import requests
|
||||
import argparse
|
||||
import time
|
||||
import json
|
||||
import re
|
||||
from typing import Optional, List
|
||||
from urllib.parse import quote, unquote
|
||||
|
||||
from _common import citation_key, parse_bibtex, render_entry
|
||||
|
||||
class DOIConverter:
|
||||
"""Convert DOIs to BibTeX through their registration agency."""
|
||||
|
||||
def __init__(self):
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update({
|
||||
'User-Agent': 'DOIConverter/1.0 (Citation Management Tool)'
|
||||
})
|
||||
|
||||
def doi_to_bibtex(self, doi: str) -> Optional[str]:
|
||||
"""
|
||||
Convert a single DOI to BibTeX format.
|
||||
|
||||
Args:
|
||||
doi: Digital Object Identifier
|
||||
|
||||
Returns:
|
||||
BibTeX string or None if conversion fails
|
||||
"""
|
||||
# Clean DOI (remove URL prefix if present)
|
||||
doi = doi.strip()
|
||||
if re.match(r'^https?://(?:dx\.)?doi\.org/', doi, re.IGNORECASE):
|
||||
doi = unquote(re.sub(r'^https?://(?:dx\.)?doi\.org/', '', doi, flags=re.IGNORECASE))
|
||||
doi = re.sub(r'^doi:\s*', '', doi, flags=re.IGNORECASE)
|
||||
|
||||
# Request BibTeX from CrossRef content negotiation
|
||||
url = f'https://doi.org/{quote(doi, safe="/")}'
|
||||
headers = {
|
||||
'Accept': 'application/x-bibtex',
|
||||
'User-Agent': 'DOIConverter/1.0 (Citation Management Tool)'
|
||||
}
|
||||
|
||||
try:
|
||||
response = self.session.get(url, headers=headers, timeout=15)
|
||||
|
||||
if response.status_code == 200:
|
||||
bibtex = response.text.strip()
|
||||
entries = parse_bibtex(bibtex)
|
||||
if len(entries) != 1:
|
||||
print(f'Error: DOI service returned no single BibTeX entry for {doi}', file=sys.stderr)
|
||||
return None
|
||||
entry = entries[0]
|
||||
fields = entry['fields']
|
||||
key = citation_key(fields.get('author', ''), fields.get('year', ''), fields.get('title', ''))
|
||||
entry_type = 'misc' if entry['type'] in ('data', 'dataset') else entry['type']
|
||||
return render_entry(entry_type, key, fields)
|
||||
elif response.status_code == 404:
|
||||
print(f'Error: DOI not found: {doi}', file=sys.stderr)
|
||||
return None
|
||||
else:
|
||||
print(f'Error: Failed to retrieve BibTeX for {doi} (status {response.status_code})', file=sys.stderr)
|
||||
return None
|
||||
|
||||
except requests.exceptions.Timeout:
|
||||
print(f'Error: Request timeout for DOI: {doi}', file=sys.stderr)
|
||||
return None
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f'Error: Request failed for {doi}: {e}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
def convert_multiple(self, dois: List[str], delay: float = 0.5) -> List[str]:
|
||||
"""
|
||||
Convert multiple DOIs to BibTeX.
|
||||
|
||||
Args:
|
||||
dois: List of DOIs
|
||||
delay: Delay between requests (seconds) for rate limiting
|
||||
|
||||
Returns:
|
||||
List of BibTeX entries (excludes failed conversions)
|
||||
"""
|
||||
bibtex_entries = []
|
||||
|
||||
for i, doi in enumerate(dois):
|
||||
print(f'Converting DOI {i+1}/{len(dois)}: {doi}', file=sys.stderr)
|
||||
bibtex = self.doi_to_bibtex(doi)
|
||||
|
||||
if bibtex:
|
||||
bibtex_entries.append(bibtex)
|
||||
|
||||
# Rate limiting
|
||||
if i < len(dois) - 1: # Don't delay after last request
|
||||
time.sleep(delay)
|
||||
|
||||
return bibtex_entries
|
||||
|
||||
|
||||
def main():
|
||||
"""Command-line interface."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Convert DOIs to BibTeX using DOI content negotiation',
|
||||
epilog='Example: python doi_to_bibtex.py 10.1038/s41586-021-03819-2'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'dois',
|
||||
nargs='*',
|
||||
help='DOI(s) to convert (can provide multiple)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'-i', '--input',
|
||||
help='Input file with DOIs (one per line)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'-o', '--output',
|
||||
help='Output file for BibTeX (default: stdout)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--delay',
|
||||
type=float,
|
||||
default=0.5,
|
||||
help='Delay between requests in seconds (default: 0.5)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--format',
|
||||
choices=['bibtex', 'json'],
|
||||
default='bibtex',
|
||||
help='Output format (default: bibtex)'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Collect DOIs from command line and/or file
|
||||
dois = []
|
||||
|
||||
if args.dois:
|
||||
dois.extend(args.dois)
|
||||
|
||||
if args.input:
|
||||
try:
|
||||
with open(args.input, 'r', encoding='utf-8') as f:
|
||||
file_dois = [line.strip() for line in f if line.strip()]
|
||||
dois.extend(file_dois)
|
||||
except FileNotFoundError:
|
||||
print(f'Error: Input file not found: {args.input}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f'Error reading input file: {e}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if not dois:
|
||||
parser.print_help()
|
||||
sys.exit(1)
|
||||
|
||||
# Convert DOIs
|
||||
converter = DOIConverter()
|
||||
|
||||
if len(dois) == 1:
|
||||
bibtex = converter.doi_to_bibtex(dois[0])
|
||||
if bibtex:
|
||||
bibtex_entries = [bibtex]
|
||||
else:
|
||||
sys.exit(1)
|
||||
else:
|
||||
bibtex_entries = converter.convert_multiple(dois, delay=args.delay)
|
||||
|
||||
if not bibtex_entries:
|
||||
print('Error: No successful conversions', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Format output
|
||||
if args.format == 'bibtex':
|
||||
output = '\n\n'.join(bibtex_entries) + '\n'
|
||||
else: # json
|
||||
output = json.dumps({
|
||||
'count': len(bibtex_entries),
|
||||
'entries': bibtex_entries
|
||||
}, indent=2)
|
||||
|
||||
# Write output
|
||||
if args.output:
|
||||
try:
|
||||
with open(args.output, 'w', encoding='utf-8') as f:
|
||||
f.write(output)
|
||||
print(f'Successfully wrote {len(bibtex_entries)} entries to {args.output}', file=sys.stderr)
|
||||
except Exception as e:
|
||||
print(f'Error writing output file: {e}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
else:
|
||||
print(output)
|
||||
|
||||
# Summary
|
||||
if len(dois) > 1:
|
||||
success_rate = len(bibtex_entries) / len(dois) * 100
|
||||
print(f'\nConverted {len(bibtex_entries)}/{len(dois)} DOIs ({success_rate:.1f}%)', file=sys.stderr)
|
||||
if len(bibtex_entries) < len(dois):
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
744
.agents/skills/citation-management/scripts/extract_metadata.py
Executable file
744
.agents/skills/citation-management/scripts/extract_metadata.py
Executable file
@@ -0,0 +1,744 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Metadata Extraction Tool
|
||||
Extract citation metadata from DOI, PMID, arXiv ID, or URL using various APIs.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import requests
|
||||
import argparse
|
||||
import time
|
||||
import re
|
||||
import json
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import Optional, Dict, List, Tuple
|
||||
from urllib.parse import urlparse, quote, unquote
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent))
|
||||
|
||||
from _common import ( # noqa: E402
|
||||
citation_key,
|
||||
format_pages,
|
||||
protect_title,
|
||||
render_entry,
|
||||
)
|
||||
|
||||
class MetadataExtractor:
|
||||
"""Extract metadata from various sources and generate BibTeX."""
|
||||
|
||||
def __init__(self, email: Optional[str] = None):
|
||||
"""
|
||||
Initialize extractor.
|
||||
|
||||
Args:
|
||||
email: Email for Entrez API (recommended for PubMed)
|
||||
"""
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update({
|
||||
'User-Agent': 'MetadataExtractor/1.0 (Citation Management Tool)'
|
||||
})
|
||||
self.email = email or os.getenv('NCBI_EMAIL', '')
|
||||
self._last_arxiv_request = None
|
||||
|
||||
def identify_type(self, identifier: str) -> Tuple[str, str]:
|
||||
"""
|
||||
Identify the type of identifier.
|
||||
|
||||
Args:
|
||||
identifier: DOI, PMID, arXiv ID, or URL
|
||||
|
||||
Returns:
|
||||
Tuple of (type, cleaned_identifier)
|
||||
"""
|
||||
identifier = identifier.strip()
|
||||
|
||||
# Check if URL
|
||||
if identifier.startswith('http://') or identifier.startswith('https://'):
|
||||
return self._parse_url(identifier)
|
||||
|
||||
# Check for DOI
|
||||
identifier = re.sub(r'^doi:\s*', '', identifier, flags=re.IGNORECASE)
|
||||
if identifier.startswith('10.'):
|
||||
return ('doi', identifier)
|
||||
|
||||
# Check for arXiv ID
|
||||
if re.match(r'^\d{4}\.\d{4,5}(v\d+)?$', identifier):
|
||||
return ('arxiv', identifier)
|
||||
if identifier.startswith('arXiv:'):
|
||||
return ('arxiv', identifier.replace('arXiv:', ''))
|
||||
if re.fullmatch(r'[a-z-]+(?:\.[A-Z]{2})?/\d{7}(?:v\d+)?', identifier):
|
||||
return ('arxiv', identifier)
|
||||
|
||||
# Check for PMID (8-digit number typically)
|
||||
if identifier.isdigit() and int(identifier) > 0:
|
||||
return ('pmid', identifier)
|
||||
|
||||
# Check for PMCID
|
||||
if identifier.upper().startswith('PMC') and identifier[3:].isdigit():
|
||||
return ('pmcid', identifier.upper())
|
||||
|
||||
return ('unknown', identifier)
|
||||
|
||||
def _parse_url(self, url: str) -> Tuple[str, str]:
|
||||
"""Parse URL to extract identifier type and value."""
|
||||
parsed = urlparse(url)
|
||||
|
||||
# DOI URLs
|
||||
if parsed.hostname in ('doi.org', 'dx.doi.org'):
|
||||
doi = unquote(parsed.path.lstrip('/'))
|
||||
return ('doi', doi)
|
||||
|
||||
# PubMed URLs
|
||||
if parsed.hostname == 'pubmed.ncbi.nlm.nih.gov' or (
|
||||
parsed.hostname == 'www.ncbi.nlm.nih.gov' and parsed.path.startswith('/pubmed/')
|
||||
):
|
||||
pmid = re.search(r'/(\d+)', parsed.path)
|
||||
if pmid:
|
||||
return ('pmid', pmid.group(1))
|
||||
|
||||
# arXiv URLs
|
||||
if parsed.hostname in ('arxiv.org', 'www.arxiv.org', 'export.arxiv.org'):
|
||||
arxiv_path = re.sub(r'^/(?:abs|pdf)/', '', parsed.path)
|
||||
arxiv_path = re.sub(r'\.pdf$', '', arxiv_path)
|
||||
kind, value = self.identify_type(arxiv_path)
|
||||
if kind == 'arxiv':
|
||||
return (kind, value)
|
||||
|
||||
if parsed.hostname in ('pmc.ncbi.nlm.nih.gov', 'www.ncbi.nlm.nih.gov'):
|
||||
pmcid = re.search(r'/articles/(PMC\d+)', parsed.path, re.IGNORECASE)
|
||||
if pmcid:
|
||||
return ('pmcid', pmcid.group(1).upper())
|
||||
|
||||
# Nature, Science, Cell, etc. - try to extract DOI from URL
|
||||
doi_match = re.search(r'10\.\d{4,}/[^\s]+', unquote(parsed.path))
|
||||
if doi_match:
|
||||
return ('doi', doi_match.group())
|
||||
|
||||
return ('url', url)
|
||||
|
||||
def extract_from_doi(self, doi: str) -> Optional[Dict]:
|
||||
"""
|
||||
Extract metadata from DOI using CrossRef API.
|
||||
|
||||
Args:
|
||||
doi: Digital Object Identifier
|
||||
|
||||
Returns:
|
||||
Metadata dictionary or None
|
||||
"""
|
||||
# A DOI is publisher-controlled text and may legitimately contain
|
||||
# `#`, `?`, `<` or `>`, so it cannot be interpolated into a URL raw.
|
||||
url = f'https://api.crossref.org/works/{quote(doi, safe="")}'
|
||||
|
||||
try:
|
||||
response = self.session.get(url, timeout=15)
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
message = data.get('message', {})
|
||||
|
||||
container = message.get('container-title') or ['']
|
||||
isbns = message.get('ISBN') or []
|
||||
issns = message.get('ISSN') or []
|
||||
|
||||
metadata = {
|
||||
'type': 'doi',
|
||||
'entry_type': self._crossref_type_to_bibtex(message.get('type')),
|
||||
'doi': doi,
|
||||
'title': (message.get('title') or [''])[0],
|
||||
'authors': self._format_authors_crossref(message.get('author', [])),
|
||||
'editors': self._format_authors_crossref(message.get('editor', [])),
|
||||
'year': self._extract_year_crossref(message),
|
||||
'journal': container[0] if container else '',
|
||||
'volume': str(message.get('volume', '')) if message.get('volume') else '',
|
||||
'issue': str(message.get('issue', '')) if message.get('issue') else '',
|
||||
'pages': message.get('page', ''),
|
||||
'publisher': message.get('publisher', ''),
|
||||
'isbn': isbns[0] if isbns else '',
|
||||
'issn': issns[0] if issns else '',
|
||||
'url': f'https://doi.org/{doi}'
|
||||
}
|
||||
|
||||
return metadata
|
||||
else:
|
||||
print(f'Error: CrossRef API returned status {response.status_code} for DOI: {doi}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
print(f'Error extracting metadata from DOI {doi}: {e}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
def extract_from_pmid(self, pmid: str) -> Optional[Dict]:
|
||||
"""
|
||||
Extract metadata from PMID using PubMed E-utilities.
|
||||
|
||||
Args:
|
||||
pmid: PubMed ID
|
||||
|
||||
Returns:
|
||||
Metadata dictionary or None
|
||||
"""
|
||||
url = f'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi'
|
||||
params = {
|
||||
'db': 'pubmed',
|
||||
'id': pmid,
|
||||
'retmode': 'xml',
|
||||
'tool': 'citation-management',
|
||||
}
|
||||
|
||||
if self.email:
|
||||
params['email'] = self.email
|
||||
|
||||
api_key = os.getenv('NCBI_API_KEY')
|
||||
if api_key:
|
||||
params['api_key'] = api_key
|
||||
|
||||
try:
|
||||
response = self.session.get(url, params=params, timeout=15)
|
||||
|
||||
if response.status_code == 200:
|
||||
root = ET.fromstring(response.content)
|
||||
article = root.find('.//PubmedArticle')
|
||||
|
||||
if article is None:
|
||||
print(f'Error: No article found for PMID: {pmid}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
# Extract metadata from XML
|
||||
medline_citation = article.find('.//MedlineCitation')
|
||||
article_elem = medline_citation.find('.//Article')
|
||||
journal = article_elem.find('.//Journal')
|
||||
|
||||
# Get DOI if available
|
||||
doi = None
|
||||
article_ids = article.findall('.//ArticleId')
|
||||
for article_id in article_ids:
|
||||
if article_id.get('IdType') == 'doi':
|
||||
doi = article_id.text
|
||||
break
|
||||
|
||||
metadata = {
|
||||
'type': 'pmid',
|
||||
'entry_type': 'article',
|
||||
'pmid': pmid,
|
||||
'title': self._pubmed_title(article_elem.find('.//ArticleTitle')),
|
||||
'authors': self._format_authors_pubmed(article_elem.findall('.//Author')),
|
||||
'year': self._extract_year_pubmed(article_elem),
|
||||
'journal': journal.findtext('.//Title', ''),
|
||||
'volume': journal.findtext('.//JournalIssue/Volume', ''),
|
||||
'issue': journal.findtext('.//JournalIssue/Issue', ''),
|
||||
'pages': article_elem.findtext('.//Pagination/MedlinePgn', ''),
|
||||
'doi': doi
|
||||
}
|
||||
|
||||
return metadata
|
||||
else:
|
||||
print(f'Error: PubMed API returned status {response.status_code} for PMID: {pmid}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
print(f'Error extracting metadata from PMID {pmid} ({type(e).__name__}); request details omitted', file=sys.stderr)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _pubmed_title(element) -> str:
|
||||
"""Read a PubMed ArticleTitle as a citation title.
|
||||
|
||||
`itertext`, not `findtext`, because titles carry inline markup such as
|
||||
<i> and <sup> and findtext returns only the leading run. PubMed also
|
||||
terminates titles with a full stop that is not part of the title; a
|
||||
trailing `?` or `!` is, so only the period is dropped.
|
||||
"""
|
||||
if element is None:
|
||||
return ''
|
||||
text = ' '.join(''.join(element.itertext()).split())
|
||||
return text[:-1] if text.endswith('.') else text
|
||||
|
||||
def extract_from_arxiv(self, arxiv_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Extract metadata from arXiv ID using arXiv API.
|
||||
|
||||
Args:
|
||||
arxiv_id: arXiv identifier
|
||||
|
||||
Returns:
|
||||
Metadata dictionary or None
|
||||
"""
|
||||
url = 'https://export.arxiv.org/api/query'
|
||||
params = {
|
||||
'id_list': arxiv_id,
|
||||
'max_results': 1
|
||||
}
|
||||
|
||||
try:
|
||||
# arXiv requests must be at least three seconds apart, including
|
||||
# callers using this class directly rather than the batch CLI.
|
||||
if self._last_arxiv_request is not None:
|
||||
time.sleep(max(0, 3.0 - (time.monotonic() - self._last_arxiv_request)))
|
||||
self._last_arxiv_request = time.monotonic()
|
||||
response = self.session.get(url, params=params, timeout=15)
|
||||
|
||||
if response.status_code == 200:
|
||||
# Parse Atom XML
|
||||
root = ET.fromstring(response.content)
|
||||
ns = {'atom': 'http://www.w3.org/2005/Atom', 'arxiv': 'http://arxiv.org/schemas/atom'}
|
||||
|
||||
entry = root.find('atom:entry', ns)
|
||||
if entry is None:
|
||||
print(f'Error: No entry found for arXiv ID: {arxiv_id}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
if '/api/errors' in entry.findtext('atom:id', '', ns):
|
||||
print(f'Error: arXiv returned an error entry for {arxiv_id}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
# Extract DOI if published
|
||||
doi_elem = entry.find('arxiv:doi', ns)
|
||||
doi = doi_elem.text if doi_elem is not None else None
|
||||
|
||||
# Extract journal reference if published
|
||||
journal_ref_elem = entry.find('arxiv:journal_ref', ns)
|
||||
journal_ref = journal_ref_elem.text if journal_ref_elem is not None else None
|
||||
|
||||
# Get publication date
|
||||
published = entry.findtext('atom:published', '', ns)
|
||||
year = published[:4] if published else ''
|
||||
|
||||
# Get authors
|
||||
authors = []
|
||||
for author in entry.findall('atom:author', ns):
|
||||
name = author.findtext('atom:name', '', ns)
|
||||
if name:
|
||||
authors.append(name)
|
||||
|
||||
# Only call it an @article when there is a journal to name.
|
||||
# A DOI alone is not enough -- arXiv mints DataCite DOIs for
|
||||
# unpublished preprints -- and an @article without a `journal`
|
||||
# fails the required-field check in validate_citations.py.
|
||||
journal = self._journal_from_arxiv_ref(journal_ref)
|
||||
|
||||
metadata = {
|
||||
'type': 'arxiv',
|
||||
'entry_type': 'article' if journal else 'misc',
|
||||
'arxiv_id': arxiv_id,
|
||||
'title': entry.findtext('atom:title', '', ns).strip().replace('\n', ' '),
|
||||
'authors': ' and '.join(authors),
|
||||
'year': year,
|
||||
'doi': doi,
|
||||
'journal': journal,
|
||||
'journal_ref': journal_ref,
|
||||
'abstract': entry.findtext('atom:summary', '', ns).strip().replace('\n', ' '),
|
||||
'url': f'https://arxiv.org/abs/{arxiv_id}'
|
||||
}
|
||||
|
||||
return metadata
|
||||
else:
|
||||
print(f'Error: arXiv API returned status {response.status_code} for ID: {arxiv_id}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
print(f'Error extracting metadata from arXiv {arxiv_id}: {e}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
def metadata_to_bibtex(self, metadata: Dict, citation_key: Optional[str] = None) -> str:
|
||||
"""
|
||||
Convert metadata dictionary to BibTeX format.
|
||||
|
||||
Args:
|
||||
metadata: Metadata dictionary
|
||||
citation_key: Optional custom citation key
|
||||
|
||||
Returns:
|
||||
BibTeX string
|
||||
"""
|
||||
if not citation_key:
|
||||
citation_key = self._generate_citation_key(metadata)
|
||||
|
||||
entry_type = metadata.get('entry_type', 'misc')
|
||||
|
||||
fields = {
|
||||
'author': metadata.get('authors', ''),
|
||||
'editor': metadata.get('editors', ''),
|
||||
'title': protect_title(metadata.get('title', '')),
|
||||
'year': metadata.get('year', ''),
|
||||
'volume': metadata.get('volume', ''),
|
||||
'number': metadata.get('issue', ''),
|
||||
'pages': format_pages(metadata.get('pages')),
|
||||
'doi': metadata.get('doi') or '',
|
||||
'isbn': metadata.get('isbn', ''),
|
||||
'issn': metadata.get('issn', ''),
|
||||
}
|
||||
|
||||
# The venue field's name depends on the entry type, and a book or
|
||||
# report needs its publisher/institution or it fails validation.
|
||||
if entry_type in ('inproceedings', 'incollection'):
|
||||
fields['booktitle'] = metadata.get('journal', '')
|
||||
elif entry_type != 'misc':
|
||||
fields['journal'] = metadata.get('journal', '')
|
||||
|
||||
if entry_type in ('book', 'incollection', 'inproceedings'):
|
||||
fields['publisher'] = metadata.get('publisher', '')
|
||||
elif entry_type == 'techreport':
|
||||
fields['institution'] = metadata.get('publisher', '')
|
||||
|
||||
if entry_type == 'misc' and metadata.get('type') == 'arxiv':
|
||||
arxiv_id = metadata.get('arxiv_id', '')
|
||||
fields['howpublished'] = f'arXiv:{arxiv_id}' if arxiv_id else 'arXiv'
|
||||
|
||||
# A DOI is the stable locator; only fall back to a URL without one.
|
||||
if not fields['doi'] and metadata.get('url'):
|
||||
fields['url'] = metadata['url']
|
||||
|
||||
# BibTeX takes one `note` per entry, so build it from all the parts
|
||||
# that would otherwise each claim the field.
|
||||
notes = []
|
||||
if metadata.get('pmid'):
|
||||
notes.append(f'PMID: {metadata["pmid"]}')
|
||||
if metadata.get('type') == 'arxiv' and entry_type == 'misc':
|
||||
notes.append('Preprint')
|
||||
if notes:
|
||||
fields['note'] = '. '.join(notes)
|
||||
|
||||
return render_entry(entry_type, citation_key, fields)
|
||||
|
||||
@staticmethod
|
||||
def _journal_from_arxiv_ref(journal_ref: Optional[str]) -> str:
|
||||
"""Pull a journal name out of arXiv's free-text `journal_ref`.
|
||||
|
||||
The field has no schema -- `Nature 596, 583-589 (2021)` is typical --
|
||||
so take the leading run of non-numeric text and leave the rest for the
|
||||
enrichment pass rather than guessing at volume and pages.
|
||||
"""
|
||||
if not journal_ref:
|
||||
return ''
|
||||
head = re.split(r'[,;]|\s\d', journal_ref.strip(), maxsplit=1)[0]
|
||||
return head.strip(' .')
|
||||
|
||||
def _crossref_type_to_bibtex(self, crossref_type: str) -> str:
|
||||
"""Map CrossRef type to BibTeX entry type."""
|
||||
type_map = {
|
||||
'journal-article': 'article',
|
||||
'book': 'book',
|
||||
'book-chapter': 'incollection',
|
||||
'proceedings-article': 'inproceedings',
|
||||
'posted-content': 'misc',
|
||||
'dataset': 'misc',
|
||||
'report': 'techreport'
|
||||
}
|
||||
return type_map.get(crossref_type, 'misc')
|
||||
|
||||
def _format_authors_crossref(self, authors: List[Dict]) -> str:
|
||||
"""Format author list from CrossRef data."""
|
||||
if not authors:
|
||||
return ''
|
||||
|
||||
formatted = []
|
||||
for author in authors:
|
||||
given = author.get('given', '')
|
||||
family = author.get('family', '')
|
||||
if family:
|
||||
if given:
|
||||
formatted.append(f'{family}, {given}')
|
||||
else:
|
||||
formatted.append(family)
|
||||
|
||||
return ' and '.join(formatted)
|
||||
|
||||
def _format_authors_pubmed(self, authors: List) -> str:
|
||||
"""Format author list from PubMed XML."""
|
||||
formatted = []
|
||||
for author in authors:
|
||||
last_name = author.findtext('.//LastName', '')
|
||||
fore_name = author.findtext('.//ForeName', '')
|
||||
if last_name:
|
||||
if fore_name:
|
||||
formatted.append(f'{last_name}, {fore_name}')
|
||||
else:
|
||||
formatted.append(last_name)
|
||||
|
||||
return ' and '.join(formatted)
|
||||
|
||||
def _extract_year_crossref(self, message: Dict) -> str:
|
||||
"""Extract year from CrossRef message."""
|
||||
# Try published-print first, then published-online
|
||||
date_parts = message.get('published-print', {}).get('date-parts', [[]])
|
||||
if not date_parts or not date_parts[0]:
|
||||
date_parts = message.get('published-online', {}).get('date-parts', [[]])
|
||||
if not date_parts or not date_parts[0]:
|
||||
date_parts = message.get('published', {}).get('date-parts', [[]])
|
||||
if not date_parts or not date_parts[0]:
|
||||
date_parts = message.get('issued', {}).get('date-parts', [[]])
|
||||
|
||||
if date_parts and date_parts[0]:
|
||||
return str(date_parts[0][0])
|
||||
return ''
|
||||
|
||||
def _extract_year_pubmed(self, article: ET.Element) -> str:
|
||||
"""Extract year from PubMed XML."""
|
||||
year = article.findtext('.//Journal/JournalIssue/PubDate/Year', '')
|
||||
if not year:
|
||||
medline_date = article.findtext('.//Journal/JournalIssue/PubDate/MedlineDate', '')
|
||||
if medline_date:
|
||||
year_match = re.search(r'\d{4}', medline_date)
|
||||
if year_match:
|
||||
year = year_match.group()
|
||||
return year
|
||||
|
||||
def _generate_citation_key(self, metadata: Dict) -> str:
|
||||
"""Generate a citation key from metadata.
|
||||
|
||||
Shared with every other producer in this skill so that entries from
|
||||
different sources collide when -- and only when -- they are the same
|
||||
paper. Values arrive verbatim from a publisher-controlled record, and
|
||||
the key reaches both LaTeX and, in some workflows, a file path, so the
|
||||
shared helper restricts it to ASCII letters and digits.
|
||||
"""
|
||||
return citation_key(
|
||||
metadata.get('authors', ''),
|
||||
metadata.get('year', ''),
|
||||
metadata.get('title', ''),
|
||||
)
|
||||
|
||||
def _protect_title(self, title: str) -> str:
|
||||
"""Protect capitalization in title for BibTeX."""
|
||||
return protect_title(title)
|
||||
|
||||
def extract_from_pmcid(self, pmcid: str) -> Optional[Dict]:
|
||||
"""Resolve a PMCID to a PMID via the NCBI ID converter, then extract."""
|
||||
url = 'https://pmc.ncbi.nlm.nih.gov/tools/idconv/api/v1/articles/'
|
||||
params = {'ids': pmcid, 'format': 'json', 'tool': 'citation-management'}
|
||||
if self.email:
|
||||
params['email'] = self.email
|
||||
|
||||
try:
|
||||
response = self.session.get(url, params=params, timeout=15)
|
||||
if response.status_code != 200:
|
||||
print(f'Error: ID converter returned status {response.status_code} for {pmcid}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
records = response.json().get('records', [])
|
||||
if not records or not records[0].get('pmid'):
|
||||
if records and records[0].get('doi'):
|
||||
return self.extract_from_doi(records[0]['doi'])
|
||||
print(f'Error: Could not resolve {pmcid} to a PMID or DOI', file=sys.stderr)
|
||||
return None
|
||||
|
||||
return self.extract_from_pmid(str(records[0]['pmid']))
|
||||
|
||||
except (requests.exceptions.RequestException, ValueError) as e:
|
||||
print(f'Error resolving PMCID {pmcid} ({type(e).__name__}); request details omitted', file=sys.stderr)
|
||||
return None
|
||||
|
||||
def extract_from_url(self, url: str) -> Optional[Dict]:
|
||||
"""Extract via a DOI advertised in the page's citation metadata.
|
||||
|
||||
Publishers embed `citation_doi` / `DC.Identifier` meta tags on article
|
||||
pages. Reading the DOI and handing off to Crossref is far more reliable
|
||||
than scraping the page itself, and it fails honestly when absent.
|
||||
"""
|
||||
try:
|
||||
response = self.session.get(url, timeout=15)
|
||||
if response.status_code != 200:
|
||||
print(f'Error: URL returned status {response.status_code}: {url}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
head = response.text[:200000]
|
||||
patterns = [
|
||||
r'<meta[^>]+name=["\'](?:citation_doi|DC\.Identifier|dc\.identifier)["\'][^>]+content=["\']([^"\']+)["\']',
|
||||
r'<meta[^>]+content=["\']([^"\']+)["\'][^>]+name=["\'](?:citation_doi|DC\.Identifier|dc\.identifier)["\']',
|
||||
]
|
||||
for pattern in patterns:
|
||||
match = re.search(pattern, head, re.IGNORECASE)
|
||||
if match:
|
||||
doi = match.group(1).strip()
|
||||
doi = re.sub(r'^(?:https?://(?:dx\.)?doi\.org/|doi:)', '', doi, flags=re.IGNORECASE)
|
||||
if doi.startswith('10.'):
|
||||
print(f'Found DOI in page metadata: {doi}', file=sys.stderr)
|
||||
return self.extract_from_doi(doi)
|
||||
|
||||
print(f'Error: No DOI found in page metadata for {url}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f'Error fetching {url}: {e}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def extract(self, identifier: str) -> Optional[str]:
|
||||
"""
|
||||
Extract metadata and return BibTeX.
|
||||
|
||||
Args:
|
||||
identifier: DOI, PMID, arXiv ID, or URL
|
||||
|
||||
Returns:
|
||||
BibTeX string or None
|
||||
"""
|
||||
id_type, clean_id = self.identify_type(identifier)
|
||||
|
||||
print(f'Identified as {id_type}: {clean_id}', file=sys.stderr)
|
||||
|
||||
metadata = None
|
||||
|
||||
if id_type == 'doi':
|
||||
metadata = self.extract_from_doi(clean_id)
|
||||
elif id_type == 'pmid':
|
||||
metadata = self.extract_from_pmid(clean_id)
|
||||
elif id_type == 'arxiv':
|
||||
metadata = self.extract_from_arxiv(clean_id)
|
||||
elif id_type == 'pmcid':
|
||||
metadata = self.extract_from_pmcid(clean_id)
|
||||
elif id_type == 'url':
|
||||
metadata = self.extract_from_url(clean_id)
|
||||
else:
|
||||
print(f'Error: Unknown identifier type: {identifier}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
if metadata:
|
||||
return self.metadata_to_bibtex(metadata)
|
||||
else:
|
||||
return None
|
||||
|
||||
def extract_record(self, identifier: str) -> Optional[Dict]:
|
||||
"""Extract metadata and return it with its rendered BibTeX attached."""
|
||||
id_type, clean_id = self.identify_type(identifier)
|
||||
|
||||
print(f'Identified as {id_type}: {clean_id}', file=sys.stderr)
|
||||
|
||||
handlers = {
|
||||
'doi': self.extract_from_doi,
|
||||
'pmid': self.extract_from_pmid,
|
||||
'arxiv': self.extract_from_arxiv,
|
||||
'pmcid': self.extract_from_pmcid,
|
||||
'url': self.extract_from_url,
|
||||
}
|
||||
|
||||
handler = handlers.get(id_type)
|
||||
if handler is None:
|
||||
print(f'Error: Unknown identifier type: {identifier}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
metadata = handler(clean_id)
|
||||
if not metadata:
|
||||
return None
|
||||
|
||||
record = dict(metadata)
|
||||
record['citation_key'] = self._generate_citation_key(metadata)
|
||||
record['bibtex'] = self.metadata_to_bibtex(metadata, record['citation_key'])
|
||||
return record
|
||||
|
||||
|
||||
def read_identifiers(filepath: str) -> List[str]:
|
||||
"""Read newline identifiers or the JSON results emitted by search scripts."""
|
||||
with open(filepath, encoding='utf-8') as handle:
|
||||
content = handle.read()
|
||||
if not content.lstrip().startswith(('{', '[')):
|
||||
return [line.strip() for line in content.splitlines() if line.strip()]
|
||||
payload = json.loads(content)
|
||||
rows = payload.get('results', payload.get('entries')) if isinstance(payload, dict) else payload
|
||||
if not isinstance(rows, list):
|
||||
raise ValueError('JSON input must be an array or contain results/entries array')
|
||||
identifiers = []
|
||||
for index, row in enumerate(rows, start=1):
|
||||
if isinstance(row, str):
|
||||
identifier = row.strip()
|
||||
elif isinstance(row, dict):
|
||||
identifier = next((str(row[key]).strip() for key in
|
||||
('doi', 'pmid', 'pmcid', 'arxiv_id', 'url') if row.get(key)), '')
|
||||
else:
|
||||
identifier = ''
|
||||
if not identifier:
|
||||
raise ValueError(f'JSON record {index} has no DOI, PMID, PMCID, arXiv ID, or URL')
|
||||
identifiers.append(identifier)
|
||||
return identifiers
|
||||
|
||||
|
||||
def main():
|
||||
"""Command-line interface."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Extract citation metadata from DOI, PMID, arXiv ID, or URL',
|
||||
epilog='Example: python extract_metadata.py --doi 10.1038/s41586-021-03819-2'
|
||||
)
|
||||
|
||||
parser.add_argument('--doi', action='append', help='Digital Object Identifier (repeatable)')
|
||||
parser.add_argument('--pmid', action='append', help='PubMed ID (repeatable)')
|
||||
parser.add_argument('--pmcid', action='append', help='PubMed Central ID (repeatable)')
|
||||
parser.add_argument('--arxiv', action='append', help='arXiv ID (repeatable)')
|
||||
parser.add_argument('--url', action='append', help='URL to article (repeatable)')
|
||||
parser.add_argument('-i', '--input', help='Newline identifiers or search-results JSON file')
|
||||
parser.add_argument('-o', '--output', help='Output file for BibTeX (default: stdout)')
|
||||
parser.add_argument('--format', choices=['bibtex', 'json'], default='bibtex', help='Output format')
|
||||
parser.add_argument('--email', help='Email for NCBI E-utilities (recommended)')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Collect identifiers
|
||||
identifiers = []
|
||||
if args.doi:
|
||||
identifiers.extend(args.doi)
|
||||
if args.pmid:
|
||||
identifiers.extend(args.pmid)
|
||||
if args.pmcid:
|
||||
identifiers.extend(args.pmcid)
|
||||
if args.arxiv:
|
||||
identifiers.extend(args.arxiv)
|
||||
if args.url:
|
||||
identifiers.extend(args.url)
|
||||
|
||||
if args.input:
|
||||
try:
|
||||
identifiers.extend(read_identifiers(args.input))
|
||||
except Exception as e:
|
||||
print(f'Error reading input file: {e}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if not identifiers:
|
||||
parser.print_help()
|
||||
sys.exit(1)
|
||||
|
||||
# Extract metadata
|
||||
extractor = MetadataExtractor(email=args.email)
|
||||
records = []
|
||||
|
||||
for i, identifier in enumerate(identifiers):
|
||||
print(f'\nProcessing {i+1}/{len(identifiers)}...', file=sys.stderr)
|
||||
record = extractor.extract_record(identifier)
|
||||
if record:
|
||||
records.append(record)
|
||||
|
||||
# Rate limiting
|
||||
if i < len(identifiers) - 1:
|
||||
time.sleep(0.5)
|
||||
|
||||
if not records:
|
||||
print('Error: No successful extractions', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
bibtex_entries = [record['bibtex'] for record in records]
|
||||
|
||||
# Format output
|
||||
if args.format == 'bibtex':
|
||||
output = '\n\n'.join(bibtex_entries) + '\n'
|
||||
else: # json
|
||||
output = json.dumps({
|
||||
'count': len(records),
|
||||
'entries': records
|
||||
}, indent=2)
|
||||
|
||||
# Write output
|
||||
if args.output:
|
||||
with open(args.output, 'w', encoding='utf-8') as f:
|
||||
f.write(output)
|
||||
print(f"\nSuccessfully wrote {len(records)} entries to {args.output}", file=sys.stderr)
|
||||
else:
|
||||
print(output)
|
||||
|
||||
print(f'\nExtracted {len(bibtex_entries)}/{len(identifiers)} entries', file=sys.stderr)
|
||||
if len(records) < len(identifiers):
|
||||
print('Error: partial extraction; review failed identifiers before using output', file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
356
.agents/skills/citation-management/scripts/format_bibtex.py
Executable file
356
.agents/skills/citation-management/scripts/format_bibtex.py
Executable file
@@ -0,0 +1,356 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
BibTeX Formatter and Cleaner
|
||||
Format, clean, sort, and deduplicate BibTeX files.
|
||||
|
||||
Writing is opt-in: pass --output to write elsewhere, or --in-place to
|
||||
overwrite the input. Neither flag prints the result to stdout and leaves the
|
||||
input untouched.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
from collections import OrderedDict
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent))
|
||||
|
||||
from _common import ( # noqa: E402
|
||||
FIELD_ORDER,
|
||||
citation_key,
|
||||
format_pages,
|
||||
parse_bibtex_file,
|
||||
render_entry,
|
||||
)
|
||||
|
||||
|
||||
class BibTeXFormatter:
|
||||
"""Format and clean BibTeX entries."""
|
||||
|
||||
def __init__(self):
|
||||
# Standard field order for readability
|
||||
self.field_order = list(FIELD_ORDER)
|
||||
|
||||
def parse_bibtex_file(self, filepath: str) -> List[Dict]:
|
||||
"""
|
||||
Parse BibTeX file and extract entries.
|
||||
|
||||
Args:
|
||||
filepath: Path to BibTeX file
|
||||
|
||||
Returns:
|
||||
List of entry dictionaries
|
||||
"""
|
||||
return parse_bibtex_file(filepath)
|
||||
|
||||
def format_entry(self, entry: Dict) -> str:
|
||||
"""
|
||||
Format a single BibTeX entry.
|
||||
|
||||
Args:
|
||||
entry: Entry dictionary
|
||||
|
||||
Returns:
|
||||
Formatted BibTeX string
|
||||
"""
|
||||
return render_entry(entry['type'], entry['key'], entry['fields'])
|
||||
|
||||
def fix_common_issues(self, entry: Dict) -> Dict:
|
||||
"""
|
||||
Fix common formatting issues in entry.
|
||||
|
||||
Args:
|
||||
entry: Entry dictionary
|
||||
|
||||
Returns:
|
||||
Fixed entry dictionary
|
||||
"""
|
||||
fixed = dict(entry)
|
||||
fields = OrderedDict(entry['fields'])
|
||||
|
||||
# Normalise page ranges: strip `pp.`, use an en-dash range, and expand
|
||||
# abbreviated end pages. Idempotent, unlike a blanket hyphen replace.
|
||||
if 'pages' in fields:
|
||||
fields['pages'] = format_pages(fields['pages'])
|
||||
|
||||
# Fix DOI (remove URL prefix if present)
|
||||
if 'doi' in fields:
|
||||
doi = fields['doi']
|
||||
doi = doi.replace('https://doi.org/', '')
|
||||
doi = doi.replace('http://doi.org/', '')
|
||||
doi = doi.replace('https://dx.doi.org/', '')
|
||||
doi = doi.replace('http://dx.doi.org/', '')
|
||||
doi = doi.replace('doi:', '')
|
||||
fields['doi'] = doi.strip()
|
||||
|
||||
# Fix author separators (semicolon or ampersand to 'and')
|
||||
if 'author' in fields:
|
||||
author = fields['author']
|
||||
author = author.replace(';', ' and')
|
||||
author = author.replace(' & ', ' and ')
|
||||
# Clean up multiple 'and's
|
||||
author = re.sub(r'\s+and\s+and\s+', ' and ', author)
|
||||
author = re.sub(r'\s+', ' ', author).strip()
|
||||
fields['author'] = author
|
||||
|
||||
fixed['fields'] = fields
|
||||
return fixed
|
||||
|
||||
def deduplicate_entries(self, entries: List[Dict]) -> List[Dict]:
|
||||
"""
|
||||
Remove duplicate entries based on DOI or citation key.
|
||||
|
||||
Args:
|
||||
entries: List of entry dictionaries
|
||||
|
||||
Returns:
|
||||
List of unique entries
|
||||
"""
|
||||
seen_dois = set()
|
||||
seen_keys = set()
|
||||
unique_entries = []
|
||||
|
||||
for entry in entries:
|
||||
doi = entry['fields'].get('doi', '').strip().lower()
|
||||
key = entry['key']
|
||||
|
||||
# Check DOI first (more reliable)
|
||||
if doi:
|
||||
if doi in seen_dois:
|
||||
print(f'Duplicate DOI found: {doi} (skipping {key})', file=sys.stderr)
|
||||
continue
|
||||
seen_dois.add(doi)
|
||||
|
||||
# Check citation key
|
||||
if key in seen_keys:
|
||||
print(f'Duplicate citation key found: {key} (skipping)', file=sys.stderr)
|
||||
continue
|
||||
seen_keys.add(key)
|
||||
|
||||
unique_entries.append(entry)
|
||||
|
||||
return unique_entries
|
||||
|
||||
def rekey_entries(self, entries: List[Dict]) -> List[Dict]:
|
||||
"""Rewrite citation keys to this skill's shared scheme.
|
||||
|
||||
Entries pulled from different sources arrive with different key
|
||||
conventions, which hides duplicates. Collisions between genuinely
|
||||
distinct papers get a letter suffix.
|
||||
"""
|
||||
rekeyed = []
|
||||
used = {}
|
||||
|
||||
for entry in entries:
|
||||
fields = entry['fields']
|
||||
base = citation_key(
|
||||
fields.get('author', ''),
|
||||
fields.get('year', ''),
|
||||
fields.get('title', ''),
|
||||
)
|
||||
if base in used:
|
||||
used[base] += 1
|
||||
# 'a' is the original, so the second occurrence becomes 'b'.
|
||||
new_key = f'{base}{chr(ord("a") + used[base])}'
|
||||
else:
|
||||
used[base] = 0
|
||||
new_key = base
|
||||
|
||||
updated = dict(entry)
|
||||
updated['key'] = new_key
|
||||
rekeyed.append(updated)
|
||||
|
||||
return rekeyed
|
||||
|
||||
def sort_entries(self, entries: List[Dict], sort_by: str = 'key', descending: bool = False) -> List[Dict]:
|
||||
"""
|
||||
Sort entries by specified field.
|
||||
|
||||
Args:
|
||||
entries: List of entry dictionaries
|
||||
sort_by: Field to sort by ('key', 'year', 'author', 'title')
|
||||
descending: Sort in descending order
|
||||
|
||||
Returns:
|
||||
Sorted list of entries
|
||||
"""
|
||||
def get_sort_key(entry: Dict) -> str:
|
||||
if sort_by == 'year':
|
||||
# Zero-pad so string comparison orders numerically, and push
|
||||
# undated entries to the end.
|
||||
year = entry['fields'].get('year', '')
|
||||
digits = re.sub(r'[^0-9]', '', year)
|
||||
return digits.zfill(4) if digits else '9999'
|
||||
if sort_by == 'author':
|
||||
author = entry['fields'].get('author', '')
|
||||
if not author:
|
||||
return 'zzz'
|
||||
first = author.split(' and ')[0]
|
||||
if ',' in first:
|
||||
return first.split(',')[0].strip().lower()
|
||||
words = first.split()
|
||||
return words[-1].lower() if words else 'zzz'
|
||||
if sort_by == 'title':
|
||||
return entry['fields'].get('title', '').lower()
|
||||
return entry['key'].lower()
|
||||
|
||||
return sorted(entries, key=get_sort_key, reverse=descending)
|
||||
|
||||
def format_file(self, filepath: str, output: Optional[str] = None,
|
||||
deduplicate: bool = False, sort_by: Optional[str] = None,
|
||||
descending: bool = False, fix_issues: bool = True,
|
||||
rekey: bool = False) -> Optional[str]:
|
||||
"""
|
||||
Format entire BibTeX file.
|
||||
|
||||
Args:
|
||||
filepath: Input BibTeX file
|
||||
output: Output file, or None to return the formatted text
|
||||
deduplicate: Remove duplicates
|
||||
sort_by: Field to sort by
|
||||
descending: Sort in descending order
|
||||
fix_issues: Fix common formatting issues
|
||||
rekey: Rewrite citation keys to the shared scheme
|
||||
|
||||
Returns:
|
||||
The formatted BibTeX text, or None when nothing was parsed.
|
||||
"""
|
||||
print(f'Parsing {filepath}...', file=sys.stderr)
|
||||
entries = self.parse_bibtex_file(filepath)
|
||||
|
||||
if not entries:
|
||||
print('No entries found', file=sys.stderr)
|
||||
return None
|
||||
|
||||
print(f'Found {len(entries)} entries', file=sys.stderr)
|
||||
|
||||
# Fix common issues
|
||||
if fix_issues:
|
||||
print('Fixing common issues...', file=sys.stderr)
|
||||
entries = [self.fix_common_issues(e) for e in entries]
|
||||
|
||||
# Rekey before deduplicating, so cross-source duplicates collapse.
|
||||
if rekey:
|
||||
print('Rewriting citation keys...', file=sys.stderr)
|
||||
entries = self.rekey_entries(entries)
|
||||
|
||||
# Deduplicate
|
||||
if deduplicate:
|
||||
print('Removing duplicates...', file=sys.stderr)
|
||||
original_count = len(entries)
|
||||
entries = self.deduplicate_entries(entries)
|
||||
removed = original_count - len(entries)
|
||||
if removed > 0:
|
||||
print(f'Removed {removed} duplicate(s)', file=sys.stderr)
|
||||
|
||||
# Sort
|
||||
if sort_by:
|
||||
print(f'Sorting by {sort_by}...', file=sys.stderr)
|
||||
entries = self.sort_entries(entries, sort_by, descending)
|
||||
|
||||
# Format entries
|
||||
print('Formatting entries...', file=sys.stderr)
|
||||
formatted_entries = [self.format_entry(e) for e in entries]
|
||||
output_content = '\n\n'.join(formatted_entries) + '\n'
|
||||
|
||||
if output is None:
|
||||
return output_content
|
||||
|
||||
try:
|
||||
with open(output, 'w', encoding='utf-8') as f:
|
||||
f.write(output_content)
|
||||
print(f'Successfully wrote {len(entries)} entries to {output}', file=sys.stderr)
|
||||
except OSError as e:
|
||||
print(f'Error writing file: {e}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
return output_content
|
||||
|
||||
|
||||
def main():
|
||||
"""Command-line interface."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Format, clean, sort, and deduplicate BibTeX files',
|
||||
epilog='Example: python format_bibtex.py references.bib -o clean.bib --deduplicate --sort year'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'file',
|
||||
help='BibTeX file to format'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'-o', '--output',
|
||||
help='Write the result to this file'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--in-place',
|
||||
action='store_true',
|
||||
help='Overwrite the input file (mutually exclusive with --output)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--deduplicate', '--remove-duplicates',
|
||||
dest='deduplicate',
|
||||
action='store_true',
|
||||
help='Remove duplicate entries'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--rekey',
|
||||
action='store_true',
|
||||
help="Rewrite citation keys to this skill's shared scheme before deduplicating"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--sort',
|
||||
choices=['key', 'year', 'author', 'title'],
|
||||
help='Sort entries by field'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--descending',
|
||||
action='store_true',
|
||||
help='Sort in descending order'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--no-fix',
|
||||
action='store_true',
|
||||
help='Do not fix common issues'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.output and args.in_place:
|
||||
parser.error('--output and --in-place are mutually exclusive')
|
||||
|
||||
destination = args.file if args.in_place else args.output
|
||||
|
||||
# Format file
|
||||
formatter = BibTeXFormatter()
|
||||
result = formatter.format_file(
|
||||
args.file,
|
||||
output=destination,
|
||||
deduplicate=args.deduplicate,
|
||||
sort_by=args.sort,
|
||||
descending=args.descending,
|
||||
fix_issues=not args.no_fix,
|
||||
rekey=args.rekey,
|
||||
)
|
||||
|
||||
if result is None:
|
||||
sys.exit(1)
|
||||
|
||||
# Without a destination the input is left alone and the result goes to
|
||||
# stdout, so a mistaken invocation cannot destroy a bibliography.
|
||||
if destination is None:
|
||||
print(result, end='')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
266
.agents/skills/citation-management/scripts/search_google_scholar.py
Executable file
266
.agents/skills/citation-management/scripts/search_google_scholar.py
Executable file
@@ -0,0 +1,266 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Google Scholar Search Tool
|
||||
Search Google Scholar and export results.
|
||||
|
||||
Note: This script requires the 'scholarly' library.
|
||||
Install with: uv pip install scholarly
|
||||
"""
|
||||
|
||||
import sys
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
from typing import List, Dict, Optional
|
||||
from itertools import islice
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent))
|
||||
|
||||
from _common import ( # noqa: E402
|
||||
citation_key,
|
||||
protect_title,
|
||||
render_entry,
|
||||
)
|
||||
|
||||
try:
|
||||
from scholarly import scholarly, ProxyGenerator
|
||||
SCHOLARLY_AVAILABLE = True
|
||||
except ImportError:
|
||||
SCHOLARLY_AVAILABLE = False
|
||||
print('Warning: scholarly library not installed. Install with: uv pip install scholarly', file=sys.stderr)
|
||||
|
||||
class GoogleScholarSearcher:
|
||||
"""Search Google Scholar using scholarly library."""
|
||||
|
||||
def __init__(self, use_proxy: bool = False):
|
||||
"""
|
||||
Initialize searcher.
|
||||
|
||||
Args:
|
||||
use_proxy: Use an optional scholarly proxy provider (does not authorize bypassing blocks)
|
||||
"""
|
||||
if not SCHOLARLY_AVAILABLE:
|
||||
raise ImportError('scholarly library required. Install with: uv pip install scholarly')
|
||||
|
||||
# Setup proxy if requested
|
||||
if use_proxy:
|
||||
try:
|
||||
pg = ProxyGenerator()
|
||||
pg.FreeProxies()
|
||||
scholarly.use_proxy(pg)
|
||||
print('Using free proxy', file=sys.stderr)
|
||||
except Exception as e:
|
||||
print(f'Warning: Could not setup proxy: {e}', file=sys.stderr)
|
||||
|
||||
def search(self, query: str, max_results: int = 50,
|
||||
year_start: Optional[int] = None, year_end: Optional[int] = None,
|
||||
sort_by: str = 'relevance') -> List[Dict]:
|
||||
"""
|
||||
Search Google Scholar.
|
||||
|
||||
Args:
|
||||
query: Search query
|
||||
max_results: Maximum number of results
|
||||
year_start: Start year filter
|
||||
year_end: End year filter
|
||||
sort_by: Sort order ('relevance' or 'citations')
|
||||
|
||||
Returns:
|
||||
List of result dictionaries
|
||||
"""
|
||||
if not SCHOLARLY_AVAILABLE:
|
||||
print('Error: scholarly library not installed', file=sys.stderr)
|
||||
return []
|
||||
|
||||
print(f'Searching Google Scholar: {query}', file=sys.stderr)
|
||||
print(f'Max results: {max_results}', file=sys.stderr)
|
||||
|
||||
results = []
|
||||
|
||||
try:
|
||||
# Perform search
|
||||
search_query = scholarly.search_pubs(query, year_low=year_start, year_high=year_end)
|
||||
|
||||
for i, result in enumerate(islice(search_query, max_results)):
|
||||
|
||||
print(f'Retrieved {i+1}/{max_results}', file=sys.stderr)
|
||||
|
||||
# Extract metadata
|
||||
metadata = {
|
||||
'title': result.get('bib', {}).get('title', ''),
|
||||
'authors': ' and '.join(result.get('bib', {}).get('author', [])),
|
||||
'year': result.get('bib', {}).get('pub_year', ''),
|
||||
'venue': result.get('bib', {}).get('venue', ''),
|
||||
'abstract': result.get('bib', {}).get('abstract', ''),
|
||||
'citations': result.get('num_citations', 0),
|
||||
'url': result.get('pub_url', ''),
|
||||
'eprint_url': result.get('eprint_url', ''),
|
||||
}
|
||||
|
||||
# Filter by year
|
||||
if year_start or year_end:
|
||||
try:
|
||||
pub_year = int(metadata['year']) if metadata['year'] else 0
|
||||
if year_start and pub_year < year_start:
|
||||
continue
|
||||
if year_end and pub_year > year_end:
|
||||
continue
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
results.append(metadata)
|
||||
|
||||
# Rate limiting to avoid blocking
|
||||
time.sleep(random.uniform(2, 5))
|
||||
|
||||
except Exception as e:
|
||||
print(f'Error during search: {e}', file=sys.stderr)
|
||||
return [] # A blocked or failed iterator is not a complete search.
|
||||
|
||||
# Sort if requested
|
||||
if sort_by == 'citations' and results:
|
||||
results.sort(key=lambda x: x.get('citations', 0), reverse=True)
|
||||
|
||||
return results
|
||||
|
||||
def metadata_to_bibtex(self, metadata: Dict) -> str:
|
||||
"""Convert metadata to BibTeX format.
|
||||
|
||||
Scholar records carry no DOI and an unstructured venue string, so an
|
||||
entry built from one is a starting point: run it through the metadata
|
||||
enrichment pass before citing it.
|
||||
"""
|
||||
authors = metadata.get('authors', '')
|
||||
|
||||
key = citation_key(authors, metadata.get('year', ''), metadata.get('title', ''))
|
||||
|
||||
# Determine entry type (guess based on venue)
|
||||
venue = metadata.get('venue', '').lower()
|
||||
if 'proceedings' in venue or 'conference' in venue or 'symposium' in venue:
|
||||
entry_type = 'inproceedings'
|
||||
venue_field = 'booktitle'
|
||||
else:
|
||||
entry_type = 'article'
|
||||
venue_field = 'journal'
|
||||
|
||||
fields = {
|
||||
'author': authors,
|
||||
'title': protect_title(metadata.get('title', '')),
|
||||
venue_field: metadata.get('venue', ''),
|
||||
'year': metadata.get('year', ''),
|
||||
'url': metadata.get('url', ''),
|
||||
}
|
||||
|
||||
# The citation count deliberately does not go in the `.bib`: it changes
|
||||
# every week, and baking it into a bibliography makes the file wrong
|
||||
# the moment it is written. It stays in the JSON output instead.
|
||||
|
||||
return render_entry(entry_type, key, fields)
|
||||
|
||||
|
||||
def main():
|
||||
"""Command-line interface."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Search Google Scholar (requires scholarly library)',
|
||||
epilog='Example: python search_google_scholar.py "machine learning" --limit 50'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'query',
|
||||
help='Search query'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--limit',
|
||||
type=int,
|
||||
default=50,
|
||||
help='Maximum number of results (default: 50)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--year-start',
|
||||
type=int,
|
||||
help='Start year for filtering'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--year-end',
|
||||
type=int,
|
||||
help='End year for filtering'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--sort-by',
|
||||
choices=['relevance', 'citations'],
|
||||
default='relevance',
|
||||
help='Order within retrieved results; citations is a local sort (default: relevance)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--use-proxy',
|
||||
action='store_true',
|
||||
help='Use scholarly free-proxy support; respect upstream access restrictions'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'-o', '--output',
|
||||
help='Output file (default: stdout)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--format',
|
||||
choices=['json', 'bibtex'],
|
||||
default='json',
|
||||
help='Output format (default: json)'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
if args.limit < 1:
|
||||
parser.error('--limit must be positive')
|
||||
|
||||
if not SCHOLARLY_AVAILABLE:
|
||||
print('\nError: scholarly library not installed', file=sys.stderr)
|
||||
print('Install with: uv pip install scholarly', file=sys.stderr)
|
||||
print('\nAlternatively, use PubMed search for biomedical literature:', file=sys.stderr)
|
||||
print(' python search_pubmed.py "your query"', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Search
|
||||
searcher = GoogleScholarSearcher(use_proxy=args.use_proxy)
|
||||
results = searcher.search(
|
||||
args.query,
|
||||
max_results=args.limit,
|
||||
year_start=args.year_start,
|
||||
year_end=args.year_end,
|
||||
sort_by=args.sort_by
|
||||
)
|
||||
|
||||
if not results:
|
||||
print('No results found', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Format output
|
||||
if args.format == 'json':
|
||||
output = json.dumps({
|
||||
'query': args.query,
|
||||
'count': len(results),
|
||||
'results': results
|
||||
}, indent=2)
|
||||
else: # bibtex
|
||||
bibtex_entries = [searcher.metadata_to_bibtex(r) for r in results]
|
||||
output = '\n\n'.join(bibtex_entries) + '\n'
|
||||
|
||||
# Write output
|
||||
if args.output:
|
||||
with open(args.output, 'w', encoding='utf-8') as f:
|
||||
f.write(output)
|
||||
print(f'Wrote {len(results)} results to {args.output}', file=sys.stderr)
|
||||
else:
|
||||
print(output)
|
||||
|
||||
print(f'\nRetrieved {len(results)} results', file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
325
.agents/skills/citation-management/scripts/search_openalex.py
Normal file
325
.agents/skills/citation-management/scripts/search_openalex.py
Normal file
@@ -0,0 +1,325 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
OpenAlex Search Tool
|
||||
Search OpenAlex and export results as JSON or BibTeX.
|
||||
|
||||
OpenAlex provides a documented REST API. Casual keyless requests are supported;
|
||||
set OPENALEX_API_KEY for an account budget. The key is sent only in the OpenAlex
|
||||
Authorization header. OPENALEX_EMAIL / --email remains an optional contact
|
||||
identifier; it does not establish a higher API quota.
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
import requests
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent))
|
||||
|
||||
from _common import ( # noqa: E402
|
||||
citation_key,
|
||||
format_pages,
|
||||
protect_title,
|
||||
render_entry,
|
||||
)
|
||||
|
||||
API_URL = 'https://api.openalex.org/works'
|
||||
|
||||
# OpenAlex work types -> BibTeX entry types.
|
||||
TYPE_MAP = {
|
||||
'article': 'article',
|
||||
'journal-article': 'article',
|
||||
'review': 'article',
|
||||
'book': 'book',
|
||||
'book-chapter': 'incollection',
|
||||
'monograph': 'book',
|
||||
'proceedings-article': 'inproceedings',
|
||||
'proceedings': 'inproceedings',
|
||||
'dissertation': 'phdthesis',
|
||||
'report': 'techreport',
|
||||
'preprint': 'misc',
|
||||
'posted-content': 'misc',
|
||||
'dataset': 'misc',
|
||||
}
|
||||
|
||||
|
||||
class OpenAlexSearcher:
|
||||
"""Search OpenAlex via its public REST API."""
|
||||
|
||||
def __init__(self, email: Optional[str] = None):
|
||||
self.email = email or os.getenv('OPENALEX_EMAIL', '')
|
||||
api_key = os.getenv('OPENALEX_API_KEY', '')
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update({
|
||||
'User-Agent': 'OpenAlexSearcher/1.0 (Citation Management Tool)'
|
||||
})
|
||||
if api_key:
|
||||
self.session.headers['Authorization'] = f'Bearer {api_key}'
|
||||
|
||||
def search(self, query: str, max_results: int = 50,
|
||||
year_start: Optional[int] = None, year_end: Optional[int] = None,
|
||||
work_type: Optional[str] = None,
|
||||
sort_by: str = 'relevance') -> List[Dict]:
|
||||
"""
|
||||
Search OpenAlex and return normalised metadata records.
|
||||
|
||||
Args:
|
||||
query: Free-text search query
|
||||
max_results: Maximum number of works to return
|
||||
year_start: Earliest publication year, inclusive
|
||||
year_end: Latest publication year, inclusive
|
||||
work_type: OpenAlex work type filter (e.g. 'article', 'review')
|
||||
sort_by: 'relevance' or 'citations'
|
||||
|
||||
Returns:
|
||||
List of metadata dictionaries
|
||||
"""
|
||||
if max_results < 1:
|
||||
raise ValueError("max_results must be positive")
|
||||
filters = []
|
||||
if year_start:
|
||||
filters.append(f'from_publication_date:{year_start}-01-01')
|
||||
if year_end:
|
||||
filters.append(f'to_publication_date:{year_end}-12-31')
|
||||
if work_type:
|
||||
filters.append(f'type:{work_type}')
|
||||
|
||||
params = {
|
||||
'search': query,
|
||||
'per-page': str(min(100, max_results)),
|
||||
'cursor': '*',
|
||||
}
|
||||
if filters:
|
||||
params['filter'] = ','.join(filters)
|
||||
if sort_by == 'citations':
|
||||
params['sort'] = 'cited_by_count:desc'
|
||||
if self.email:
|
||||
params['mailto'] = self.email
|
||||
|
||||
print(f'Searching OpenAlex: {query}', file=sys.stderr)
|
||||
|
||||
results: List[Dict] = []
|
||||
seen_cursors = {'*'}
|
||||
seen_work_ids = set()
|
||||
reported_total = False
|
||||
|
||||
while len(results) < max_results:
|
||||
try:
|
||||
response = self.session.get(API_URL, params=params, timeout=30)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
except (requests.exceptions.RequestException, ValueError) as error:
|
||||
# Partial bibliographies must not look like a completed search.
|
||||
# Avoid printing request URLs or headers in diagnostics.
|
||||
raise RuntimeError(
|
||||
f'OpenAlex search failed after {len(results)} records '
|
||||
f'({type(error).__name__}); retry or narrow the query'
|
||||
) from None
|
||||
|
||||
if not reported_total:
|
||||
total = payload.get('meta', {}).get('count', 0)
|
||||
print(f'Found {total} results, retrieving up to {max_results}', file=sys.stderr)
|
||||
reported_total = True
|
||||
|
||||
works = payload.get('results', [])
|
||||
next_cursor = payload.get('meta', {}).get('next_cursor')
|
||||
if next_cursor is not None and (
|
||||
not isinstance(next_cursor, str) or next_cursor in seen_cursors
|
||||
):
|
||||
raise RuntimeError(
|
||||
f'OpenAlex search failed after {len(results)} records '
|
||||
'(invalid or repeated cursor); retry or narrow the query'
|
||||
)
|
||||
if not works:
|
||||
if next_cursor is not None:
|
||||
raise RuntimeError(
|
||||
f'OpenAlex search failed after {len(results)} records '
|
||||
'(empty nonterminal page); retry or narrow the query'
|
||||
)
|
||||
break
|
||||
for work in works:
|
||||
work_id = work.get('id')
|
||||
if not isinstance(work_id, str) or not work_id or work_id in seen_work_ids:
|
||||
raise RuntimeError(
|
||||
f'OpenAlex search failed after {len(results)} records '
|
||||
'(missing or duplicate work ID); retry or narrow the query'
|
||||
)
|
||||
seen_work_ids.add(work_id)
|
||||
results.append(self._normalise(work))
|
||||
if len(results) >= max_results:
|
||||
break
|
||||
|
||||
if next_cursor is None or len(results) >= max_results:
|
||||
break
|
||||
seen_cursors.add(next_cursor)
|
||||
params['cursor'] = next_cursor
|
||||
|
||||
# Pace requests; quota exhaustion remains an explicit error.
|
||||
time.sleep(0.1)
|
||||
|
||||
print(f'Retrieved {len(results)} results', file=sys.stderr)
|
||||
return results
|
||||
|
||||
def _normalise(self, work: Dict) -> Dict:
|
||||
"""Flatten one OpenAlex work into this skill's metadata shape."""
|
||||
authors = [
|
||||
authorship.get('author', {}).get('display_name', '')
|
||||
for authorship in work.get('authorships', [])
|
||||
]
|
||||
authors = [name for name in authors if name]
|
||||
|
||||
location = work.get('primary_location') or {}
|
||||
source = location.get('source') or {}
|
||||
biblio = work.get('biblio') or {}
|
||||
|
||||
first_page = biblio.get('first_page') or ''
|
||||
last_page = biblio.get('last_page') or ''
|
||||
if first_page and last_page and first_page != last_page:
|
||||
pages = f'{first_page}-{last_page}'
|
||||
else:
|
||||
pages = first_page or ''
|
||||
|
||||
doi = work.get('doi') or ''
|
||||
if doi.startswith('https://doi.org/'):
|
||||
doi = doi[len('https://doi.org/'):]
|
||||
|
||||
return {
|
||||
'openalex_id': work.get('id', ''),
|
||||
'doi': doi,
|
||||
'title': work.get('title') or work.get('display_name') or '',
|
||||
'authors': ' and '.join(authors),
|
||||
'journal': source.get('display_name', '') or '',
|
||||
'publisher': source.get('host_organization_name', '') or '',
|
||||
'year': str(work.get('publication_year') or ''),
|
||||
'volume': biblio.get('volume') or '',
|
||||
'issue': biblio.get('issue') or '',
|
||||
'pages': pages,
|
||||
'type': work.get('type') or '',
|
||||
'citations': work.get('cited_by_count', 0),
|
||||
'is_open_access': (work.get('open_access') or {}).get('is_oa', False),
|
||||
'abstract': self._abstract(work.get('abstract_inverted_index')),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _abstract(inverted_index: Optional[Dict]) -> str:
|
||||
"""Rebuild the abstract from OpenAlex's inverted index."""
|
||||
if not inverted_index:
|
||||
return ''
|
||||
positions = []
|
||||
for word, indices in inverted_index.items():
|
||||
for index in indices:
|
||||
positions.append((index, word))
|
||||
positions.sort()
|
||||
return ' '.join(word for _, word in positions)
|
||||
|
||||
def metadata_to_bibtex(self, metadata: Dict) -> str:
|
||||
"""Convert a normalised record to a BibTeX entry."""
|
||||
entry_type = TYPE_MAP.get(metadata.get('type', ''), 'misc')
|
||||
|
||||
key = citation_key(
|
||||
metadata.get('authors', ''),
|
||||
metadata.get('year', ''),
|
||||
metadata.get('title', ''),
|
||||
)
|
||||
|
||||
fields = {
|
||||
'author': metadata.get('authors', ''),
|
||||
'title': protect_title(metadata.get('title', '')),
|
||||
'year': metadata.get('year', ''),
|
||||
'volume': metadata.get('volume', ''),
|
||||
'number': metadata.get('issue', ''),
|
||||
'pages': format_pages(metadata.get('pages')),
|
||||
'doi': metadata.get('doi', ''),
|
||||
}
|
||||
|
||||
venue = metadata.get('journal', '')
|
||||
if entry_type in ('inproceedings', 'incollection'):
|
||||
fields['booktitle'] = venue
|
||||
elif entry_type != 'misc':
|
||||
fields['journal'] = venue
|
||||
|
||||
if entry_type in ('book', 'incollection', 'inproceedings'):
|
||||
fields['publisher'] = metadata.get('publisher', '')
|
||||
elif entry_type == 'techreport':
|
||||
fields['institution'] = metadata.get('publisher', '')
|
||||
|
||||
if entry_type == 'misc':
|
||||
if venue:
|
||||
fields['howpublished'] = venue
|
||||
if metadata.get('type') in ('preprint', 'posted-content'):
|
||||
fields['note'] = 'Preprint'
|
||||
|
||||
if not fields['doi'] and metadata.get('openalex_id'):
|
||||
fields['url'] = metadata['openalex_id']
|
||||
|
||||
return render_entry(entry_type, key, fields)
|
||||
|
||||
|
||||
def main():
|
||||
"""Command-line interface."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Search OpenAlex (optional OPENALEX_API_KEY for account quota)',
|
||||
epilog='Example: python search_openalex.py "CRISPR gene editing" --limit 50 --format bibtex'
|
||||
)
|
||||
|
||||
parser.add_argument('query', help='Search query')
|
||||
parser.add_argument('--limit', type=int, default=50,
|
||||
help='Maximum number of results (default: 50)')
|
||||
parser.add_argument('--year-start', type=int, help='Earliest publication year')
|
||||
parser.add_argument('--year-end', type=int, help='Latest publication year')
|
||||
parser.add_argument('--type', dest='work_type',
|
||||
help='OpenAlex work type filter (e.g. article, review, preprint)')
|
||||
parser.add_argument('--sort-by', choices=['relevance', 'citations'], default='relevance',
|
||||
help='Sort order (default: relevance)')
|
||||
parser.add_argument('-o', '--output', help='Output file (default: stdout)')
|
||||
parser.add_argument('--format', choices=['json', 'bibtex'], default='json',
|
||||
help='Output format (default: json)')
|
||||
parser.add_argument('--email',
|
||||
help='Optional contact email (or set OPENALEX_EMAIL)')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
searcher = OpenAlexSearcher(email=args.email)
|
||||
try:
|
||||
results = searcher.search(
|
||||
args.query,
|
||||
max_results=args.limit,
|
||||
year_start=args.year_start,
|
||||
year_end=args.year_end,
|
||||
work_type=args.work_type,
|
||||
sort_by=args.sort_by,
|
||||
)
|
||||
except (RuntimeError, ValueError) as error:
|
||||
print(f'Error: {error}', file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
if not results:
|
||||
print('No results found', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if args.format == 'json':
|
||||
output = json.dumps({
|
||||
'query': args.query,
|
||||
'count': len(results),
|
||||
'results': results,
|
||||
}, indent=2)
|
||||
else:
|
||||
output = '\n\n'.join(searcher.metadata_to_bibtex(r) for r in results) + '\n'
|
||||
|
||||
if args.output:
|
||||
with open(args.output, 'w', encoding='utf-8') as f:
|
||||
f.write(output)
|
||||
print(f'Wrote {len(results)} results to {args.output}', file=sys.stderr)
|
||||
else:
|
||||
print(output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
434
.agents/skills/citation-management/scripts/search_pubmed.py
Executable file
434
.agents/skills/citation-management/scripts/search_pubmed.py
Executable file
@@ -0,0 +1,434 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
PubMed Search Tool
|
||||
Search PubMed using E-utilities API and export results.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
import requests
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import List, Dict, Optional
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent))
|
||||
|
||||
from _common import ( # noqa: E402
|
||||
citation_key,
|
||||
format_pages,
|
||||
protect_title,
|
||||
render_entry,
|
||||
)
|
||||
|
||||
class PubMedSearcher:
|
||||
"""Search PubMed using NCBI E-utilities API."""
|
||||
|
||||
def __init__(self, api_key: Optional[str] = None, email: Optional[str] = None):
|
||||
"""
|
||||
Initialize searcher.
|
||||
|
||||
Args:
|
||||
api_key: NCBI API key (optional but recommended)
|
||||
email: Email for Entrez (optional but recommended)
|
||||
"""
|
||||
self.api_key = api_key or os.getenv('NCBI_API_KEY', '')
|
||||
self.email = email or os.getenv('NCBI_EMAIL', '')
|
||||
self.base_url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/'
|
||||
self.session = requests.Session()
|
||||
|
||||
# Rate limiting
|
||||
self.delay = 0.11 if self.api_key else 0.34 # 10/sec with key, 3/sec without
|
||||
|
||||
def search(self, query: str, max_results: int = 100,
|
||||
date_start: Optional[str] = None, date_end: Optional[str] = None,
|
||||
publication_types: Optional[List[str]] = None) -> List[str]:
|
||||
"""
|
||||
Search PubMed and return PMIDs.
|
||||
|
||||
Args:
|
||||
query: Search query
|
||||
max_results: Maximum number of results
|
||||
date_start: Start date (YYYY/MM/DD or YYYY)
|
||||
date_end: End date (YYYY/MM/DD or YYYY)
|
||||
publication_types: List of publication types to filter
|
||||
|
||||
Returns:
|
||||
List of PMIDs
|
||||
"""
|
||||
# Build query with filters
|
||||
if max_results < 1:
|
||||
raise ValueError('max_results must be positive')
|
||||
full_query = f'({query})'
|
||||
|
||||
# Add date range
|
||||
if date_start or date_end:
|
||||
start = (date_start or '1900').replace('-', '/')
|
||||
end = (date_end or datetime.now().strftime('%Y')).replace('-', '/')
|
||||
full_query += f' AND {start}:{end}[Publication Date]'
|
||||
|
||||
# Add publication types
|
||||
if publication_types:
|
||||
pub_type_query = ' OR '.join([f'"{pt}"[Publication Type]' for pt in publication_types])
|
||||
full_query += f' AND ({pub_type_query})'
|
||||
|
||||
print(f'Searching PubMed: {full_query}', file=sys.stderr)
|
||||
|
||||
# PubMed ESearch exposes only the first 10000 matches in total,
|
||||
# so say so rather than letting the caller believe they got everything.
|
||||
if max_results > 10000:
|
||||
print(
|
||||
f'Note: PubMed ESearch exposes only the first 10000 matches; '
|
||||
f'requesting 10000 rather than {max_results}. Narrow the query '
|
||||
f'or split it by date range for a larger set.',
|
||||
file=sys.stderr,
|
||||
)
|
||||
max_results = 10000
|
||||
|
||||
# ESearch to get PMIDs
|
||||
esearch_url = self.base_url + 'esearch.fcgi'
|
||||
params = {
|
||||
'db': 'pubmed',
|
||||
'term': full_query,
|
||||
'retmax': max_results,
|
||||
'retmode': 'json',
|
||||
'tool': 'citation-management',
|
||||
}
|
||||
|
||||
if self.email:
|
||||
params['email'] = self.email
|
||||
if self.api_key:
|
||||
params['api_key'] = self.api_key
|
||||
|
||||
try:
|
||||
response = self.session.get(esearch_url, params=params, timeout=30)
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
if data.get('error') or data.get('esearchresult', {}).get('errorlist'):
|
||||
raise ValueError('ESearch returned a query error')
|
||||
pmids = data['esearchresult']['idlist']
|
||||
count = int(data['esearchresult']['count'])
|
||||
|
||||
print(f'Found {count} results, retrieving {len(pmids)}', file=sys.stderr)
|
||||
|
||||
return pmids
|
||||
|
||||
except Exception as e:
|
||||
print(f'Error searching PubMed ({type(e).__name__}); request details omitted', file=sys.stderr)
|
||||
return []
|
||||
|
||||
def fetch_metadata(self, pmids: List[str]) -> List[Dict]:
|
||||
"""
|
||||
Fetch metadata for PMIDs.
|
||||
|
||||
Args:
|
||||
pmids: List of PubMed IDs
|
||||
|
||||
Returns:
|
||||
List of metadata dictionaries
|
||||
"""
|
||||
if not pmids:
|
||||
return []
|
||||
|
||||
metadata_list = []
|
||||
|
||||
# Fetch in batches of 200
|
||||
batch_size = 200
|
||||
for i in range(0, len(pmids), batch_size):
|
||||
batch = pmids[i:i+batch_size]
|
||||
print(f'Fetching metadata for PMIDs {i+1}-{min(i+batch_size, len(pmids))}...', file=sys.stderr)
|
||||
|
||||
efetch_url = self.base_url + 'efetch.fcgi'
|
||||
params = {
|
||||
'db': 'pubmed',
|
||||
'id': ','.join(batch),
|
||||
'retmode': 'xml',
|
||||
'tool': 'citation-management',
|
||||
}
|
||||
|
||||
if self.email:
|
||||
params['email'] = self.email
|
||||
if self.api_key:
|
||||
params['api_key'] = self.api_key
|
||||
|
||||
try:
|
||||
time.sleep(self.delay)
|
||||
response = self.session.get(efetch_url, params=params, timeout=60)
|
||||
response.raise_for_status()
|
||||
|
||||
# Parse XML
|
||||
root = ET.fromstring(response.content)
|
||||
if root.find('.//ERROR') is not None:
|
||||
raise ValueError('EFetch returned an error')
|
||||
articles = root.findall('.//PubmedArticle')
|
||||
batch_metadata = []
|
||||
|
||||
for article in articles:
|
||||
metadata = self._extract_metadata_from_xml(article)
|
||||
if metadata:
|
||||
batch_metadata.append(metadata)
|
||||
if {record['pmid'] for record in batch_metadata} != set(batch):
|
||||
print('Error: EFetch omitted requested records or returned unsupported book records', file=sys.stderr)
|
||||
raise ValueError('Incomplete EFetch batch')
|
||||
metadata_list.extend(batch_metadata)
|
||||
|
||||
except Exception as e:
|
||||
print(f'Error fetching metadata for batch ({type(e).__name__}); request details omitted', file=sys.stderr)
|
||||
# Never export a failed batch as a complete bibliography.
|
||||
return []
|
||||
|
||||
return metadata_list
|
||||
|
||||
@staticmethod
|
||||
def _element_text(element: Optional[ET.Element]) -> str:
|
||||
"""Flatten an element's text, including any inline markup children.
|
||||
|
||||
PubMed terminates titles with a full stop that is not part of the
|
||||
title; a trailing `?` or `!` is, so only the period is dropped.
|
||||
"""
|
||||
if element is None:
|
||||
return ''
|
||||
text = ' '.join(''.join(element.itertext()).split())
|
||||
return text[:-1] if text.endswith('.') else text
|
||||
|
||||
def _extract_metadata_from_xml(self, article: ET.Element) -> Optional[Dict]:
|
||||
"""Extract metadata from PubmedArticle XML element."""
|
||||
try:
|
||||
medline_citation = article.find('.//MedlineCitation')
|
||||
article_elem = medline_citation.find('.//Article')
|
||||
journal = article_elem.find('.//Journal')
|
||||
|
||||
# Get PMID
|
||||
pmid = medline_citation.findtext('.//PMID', '')
|
||||
|
||||
# Get DOI
|
||||
doi = None
|
||||
article_ids = article.findall('.//ArticleId')
|
||||
for article_id in article_ids:
|
||||
if article_id.get('IdType') == 'doi':
|
||||
doi = article_id.text
|
||||
break
|
||||
|
||||
# Get authors
|
||||
authors = []
|
||||
author_list = article_elem.find('.//AuthorList')
|
||||
if author_list is not None:
|
||||
for author in author_list.findall('.//Author'):
|
||||
last_name = author.findtext('.//LastName', '')
|
||||
fore_name = author.findtext('.//ForeName', '')
|
||||
if last_name:
|
||||
if fore_name:
|
||||
authors.append(f'{last_name}, {fore_name}')
|
||||
else:
|
||||
authors.append(last_name)
|
||||
|
||||
# Get year
|
||||
year = article_elem.findtext('.//Journal/JournalIssue/PubDate/Year', '')
|
||||
if not year:
|
||||
medline_date = article_elem.findtext('.//Journal/JournalIssue/PubDate/MedlineDate', '')
|
||||
if medline_date:
|
||||
year_match = re.search(r'\d{4}', medline_date)
|
||||
if year_match:
|
||||
year = year_match.group()
|
||||
|
||||
# Structured abstracts split into several labelled AbstractText
|
||||
# elements; taking only the first drops most of the abstract.
|
||||
sections = []
|
||||
for chunk in article_elem.findall('.//Abstract/AbstractText'):
|
||||
text = ''.join(chunk.itertext()).strip()
|
||||
if not text:
|
||||
continue
|
||||
label = chunk.get('Label')
|
||||
sections.append(f'{label}: {text}' if label else text)
|
||||
abstract = ' '.join(sections)
|
||||
|
||||
|
||||
metadata = {
|
||||
'pmid': pmid,
|
||||
'doi': doi,
|
||||
# itertext, not findtext: titles carry inline markup such as
|
||||
# <i> and <sup>, and findtext returns only the leading run.
|
||||
'title': self._element_text(article_elem.find('.//ArticleTitle')),
|
||||
'authors': ' and '.join(authors),
|
||||
'journal': journal.findtext('.//Title', ''),
|
||||
'year': year,
|
||||
'volume': journal.findtext('.//JournalIssue/Volume', ''),
|
||||
'issue': journal.findtext('.//JournalIssue/Issue', ''),
|
||||
'pages': article_elem.findtext('.//Pagination/MedlinePgn', ''),
|
||||
'abstract': abstract
|
||||
}
|
||||
|
||||
return metadata
|
||||
|
||||
except Exception as e:
|
||||
print(f'Error extracting metadata: {e}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
def metadata_to_bibtex(self, metadata: Dict) -> str:
|
||||
"""Convert metadata to BibTeX format.
|
||||
|
||||
Uses the shared key scheme rather than appending the PMID, so an entry
|
||||
found here and the same paper found via Crossref or OpenAlex collide
|
||||
and can be deduplicated.
|
||||
"""
|
||||
key = citation_key(
|
||||
metadata.get('authors', ''),
|
||||
metadata.get('year', ''),
|
||||
metadata.get('title', ''),
|
||||
)
|
||||
|
||||
fields = {
|
||||
'author': metadata.get('authors', ''),
|
||||
'title': protect_title(metadata.get('title', '')),
|
||||
'journal': metadata.get('journal', ''),
|
||||
'year': metadata.get('year', ''),
|
||||
'volume': metadata.get('volume', ''),
|
||||
'number': metadata.get('issue', ''),
|
||||
'pages': format_pages(metadata.get('pages')),
|
||||
'doi': metadata.get('doi') or '',
|
||||
}
|
||||
|
||||
if metadata.get('pmid'):
|
||||
fields['note'] = f'PMID: {metadata["pmid"]}'
|
||||
|
||||
return render_entry('article', key, fields)
|
||||
|
||||
|
||||
def main():
|
||||
"""Command-line interface."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Search PubMed using E-utilities API',
|
||||
epilog='Example: python search_pubmed.py "CRISPR gene editing" --limit 100'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'query',
|
||||
nargs='?',
|
||||
help='Search query (PubMed syntax)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--query',
|
||||
dest='query_arg',
|
||||
help='Search query (alternative to positional argument)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--query-file',
|
||||
help='File containing search query'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--limit',
|
||||
type=int,
|
||||
default=100,
|
||||
help='Maximum number of results (default: 100)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--date-start',
|
||||
help='Start date (YYYY/MM/DD or YYYY)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--date-end',
|
||||
help='End date (YYYY/MM/DD or YYYY)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--publication-types',
|
||||
help='Comma-separated publication types (e.g., "Review,Clinical Trial")'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'-o', '--output',
|
||||
help='Output file (default: stdout)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--format',
|
||||
choices=['json', 'bibtex'],
|
||||
default='json',
|
||||
help='Output format (default: json)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--api-key',
|
||||
help='NCBI API key (or set NCBI_API_KEY env var)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--email',
|
||||
help='Email for Entrez (or set NCBI_EMAIL env var)'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Get query
|
||||
query = args.query or args.query_arg
|
||||
|
||||
if args.query_file:
|
||||
try:
|
||||
with open(args.query_file, 'r', encoding='utf-8') as f:
|
||||
query = f.read().strip()
|
||||
except Exception as e:
|
||||
print(f'Error reading query file: {e}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if not query:
|
||||
parser.print_help()
|
||||
sys.exit(1)
|
||||
if args.limit < 1:
|
||||
parser.error('--limit must be positive')
|
||||
|
||||
# Parse publication types
|
||||
pub_types = None
|
||||
if args.publication_types:
|
||||
pub_types = [pt.strip() for pt in args.publication_types.split(',')]
|
||||
|
||||
# Search PubMed
|
||||
searcher = PubMedSearcher(api_key=args.api_key, email=args.email)
|
||||
pmids = searcher.search(
|
||||
query,
|
||||
max_results=args.limit,
|
||||
date_start=args.date_start,
|
||||
date_end=args.date_end,
|
||||
publication_types=pub_types
|
||||
)
|
||||
|
||||
if not pmids:
|
||||
print('No results found', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Fetch metadata
|
||||
metadata_list = searcher.fetch_metadata(pmids)
|
||||
if not metadata_list:
|
||||
print('Error: incomplete PubMed metadata retrieval; no output written', file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
# Format output
|
||||
if args.format == 'json':
|
||||
output = json.dumps({
|
||||
'query': query,
|
||||
'count': len(metadata_list),
|
||||
'results': metadata_list
|
||||
}, indent=2)
|
||||
else: # bibtex
|
||||
bibtex_entries = [searcher.metadata_to_bibtex(m) for m in metadata_list]
|
||||
output = '\n\n'.join(bibtex_entries) + '\n'
|
||||
|
||||
# Write output
|
||||
if args.output:
|
||||
with open(args.output, 'w', encoding='utf-8') as f:
|
||||
f.write(output)
|
||||
print(f'Wrote {len(metadata_list)} results to {args.output}', file=sys.stderr)
|
||||
else:
|
||||
print(output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
713
.agents/skills/citation-management/scripts/validate_citations.py
Executable file
713
.agents/skills/citation-management/scripts/validate_citations.py
Executable file
@@ -0,0 +1,713 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Citation Validation Tool
|
||||
Validate BibTeX files for accuracy, completeness, and format compliance.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import re
|
||||
import requests
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
from typing import Dict, List, Tuple, Optional
|
||||
from collections import defaultdict
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent))
|
||||
|
||||
from _common import parse_bibtex_file as _parse_bibtex_file # noqa: E402
|
||||
|
||||
# Typical reference-list lengths, as (minimum, typical maximum, display name).
|
||||
#
|
||||
# These are editorial rules of thumb drawn from what published papers at these
|
||||
# venues tend to carry -- not sourced submission requirements, most of which do
|
||||
# not cap references at all. They drive warnings only; a bibliography is never
|
||||
# wrong merely for being short.
|
||||
VENUE_STANDARDS = {
|
||||
'nature': (35, 50, 'Nature'),
|
||||
'science': (35, 50, 'Science'),
|
||||
'cell': (35, 50, 'Cell'),
|
||||
'multidisciplinary': (35, 50, 'High-impact Multidisciplinary Journal'),
|
||||
'neurips': (30, 45, 'NeurIPS'),
|
||||
'icml': (30, 45, 'ICML'),
|
||||
'iclr': (30, 45, 'ICLR'),
|
||||
'cvpr': (30, 45, 'CVPR'),
|
||||
'acl': (30, 45, 'ACL'),
|
||||
'ml_cs_conf': (30, 45, 'ML/CS Conference'),
|
||||
'review': (40, 65, 'Comprehensive Literature Review'),
|
||||
'market_research': (40, 65, 'Market Research Report'),
|
||||
'literature_review': (40, 65, 'Literature Review / Market Research'),
|
||||
'nejm': (30, 45, 'NEJM'),
|
||||
'lancet': (30, 45, 'The Lancet'),
|
||||
'jama': (30, 45, 'JAMA'),
|
||||
'medical': (30, 45, 'Medical Journal'),
|
||||
}
|
||||
|
||||
|
||||
class CitationValidator:
|
||||
"""Validate BibTeX entries for errors and inconsistencies."""
|
||||
|
||||
def __init__(self):
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update({
|
||||
'User-Agent': 'CitationValidator/1.0 (Citation Management Tool)'
|
||||
})
|
||||
self.venue_standards = VENUE_STANDARDS
|
||||
|
||||
# Required fields by entry type
|
||||
self.required_fields = {
|
||||
'article': ['author', 'title', 'journal', 'year'],
|
||||
'book': ['title', 'publisher', 'year'], # author OR editor
|
||||
'inproceedings': ['author', 'title', 'booktitle', 'year'],
|
||||
'incollection': ['author', 'title', 'booktitle', 'publisher', 'year'],
|
||||
'phdthesis': ['author', 'title', 'school', 'year'],
|
||||
'mastersthesis': ['author', 'title', 'school', 'year'],
|
||||
'techreport': ['author', 'title', 'institution', 'year'],
|
||||
'misc': ['title', 'year']
|
||||
}
|
||||
|
||||
# Recommended fields
|
||||
self.recommended_fields = {
|
||||
'article': ['volume', 'pages', 'doi'],
|
||||
'book': ['isbn'],
|
||||
'inproceedings': ['pages'],
|
||||
}
|
||||
|
||||
def parse_bibtex_file(self, filepath: str) -> List[Dict]:
|
||||
"""
|
||||
Parse BibTeX file and extract entries.
|
||||
|
||||
Args:
|
||||
filepath: Path to BibTeX file
|
||||
|
||||
Returns:
|
||||
List of entry dictionaries
|
||||
"""
|
||||
return _parse_bibtex_file(filepath)
|
||||
|
||||
def validate_entry(self, entry: Dict) -> Tuple[List[Dict], List[Dict]]:
|
||||
"""
|
||||
Validate a single BibTeX entry.
|
||||
|
||||
Args:
|
||||
entry: Entry dictionary
|
||||
|
||||
Returns:
|
||||
Tuple of (errors, warnings)
|
||||
"""
|
||||
errors = []
|
||||
warnings = []
|
||||
|
||||
entry_type = entry['type']
|
||||
key = entry['key']
|
||||
fields = entry['fields']
|
||||
|
||||
# Check required fields
|
||||
if entry_type in self.required_fields:
|
||||
for req_field in self.required_fields[entry_type]:
|
||||
if req_field not in fields or not fields[req_field]:
|
||||
# Special case: book can have author OR editor
|
||||
if entry_type == 'book' and req_field == 'author':
|
||||
if 'editor' not in fields or not fields['editor']:
|
||||
errors.append({
|
||||
'type': 'missing_required_field',
|
||||
'field': 'author or editor',
|
||||
'severity': 'high',
|
||||
'message': f'Entry {key}: Missing required field "author" or "editor"'
|
||||
})
|
||||
else:
|
||||
errors.append({
|
||||
'type': 'missing_required_field',
|
||||
'field': req_field,
|
||||
'severity': 'high',
|
||||
'message': f'Entry {key}: Missing required field "{req_field}"'
|
||||
})
|
||||
|
||||
# Check recommended fields
|
||||
if entry_type in self.recommended_fields:
|
||||
for rec_field in self.recommended_fields[entry_type]:
|
||||
if rec_field not in fields or not fields[rec_field]:
|
||||
warnings.append({
|
||||
'type': 'missing_recommended_field',
|
||||
'field': rec_field,
|
||||
'severity': 'medium',
|
||||
'message': f'Entry {key}: Missing recommended field "{rec_field}"'
|
||||
})
|
||||
|
||||
# Validate year
|
||||
if 'year' in fields:
|
||||
year = fields['year']
|
||||
if not re.match(r'^\d{4}$', year):
|
||||
errors.append({
|
||||
'type': 'invalid_year',
|
||||
'field': 'year',
|
||||
'value': year,
|
||||
'severity': 'high',
|
||||
'message': f'Entry {key}: Invalid year format "{year}" (should be 4 digits)'
|
||||
})
|
||||
elif int(year) < 1600 or int(year) > 2030:
|
||||
warnings.append({
|
||||
'type': 'suspicious_year',
|
||||
'field': 'year',
|
||||
'value': year,
|
||||
'severity': 'medium',
|
||||
'message': f'Entry {key}: Suspicious year "{year}" (outside reasonable range)'
|
||||
})
|
||||
|
||||
# Validate DOI format
|
||||
if 'doi' in fields:
|
||||
doi = fields['doi']
|
||||
if not re.match(r'^10\.\d{4,}/[^\s]+$', doi):
|
||||
warnings.append({
|
||||
'type': 'invalid_doi_format',
|
||||
'field': 'doi',
|
||||
'value': doi,
|
||||
'severity': 'medium',
|
||||
'message': f'Entry {key}: Invalid DOI format "{doi}"'
|
||||
})
|
||||
|
||||
# Check for single hyphen in pages (should be --)
|
||||
if 'pages' in fields:
|
||||
pages = fields['pages']
|
||||
if re.search(r'\d-\d', pages) and '--' not in pages:
|
||||
warnings.append({
|
||||
'type': 'page_range_format',
|
||||
'field': 'pages',
|
||||
'value': pages,
|
||||
'severity': 'low',
|
||||
'message': f'Entry {key}: Page range uses single hyphen, should use -- (en-dash)'
|
||||
})
|
||||
|
||||
# Check author format
|
||||
if 'author' in fields:
|
||||
author = fields['author']
|
||||
if ';' in author or '&' in author:
|
||||
errors.append({
|
||||
'type': 'invalid_author_format',
|
||||
'field': 'author',
|
||||
'severity': 'high',
|
||||
'message': f'Entry {key}: Authors should be separated by " and ", not ";" or "&"'
|
||||
})
|
||||
|
||||
return errors, warnings
|
||||
|
||||
def verify_doi(self, doi: str) -> Tuple[Optional[bool], Optional[Dict]]:
|
||||
"""
|
||||
Verify DOI resolves correctly and get metadata.
|
||||
|
||||
Args:
|
||||
doi: Digital Object Identifier
|
||||
|
||||
Returns:
|
||||
(True, metadata) when registered, (False, None) on resolver 404,
|
||||
or (None, None) when the lookup could not be completed.
|
||||
"""
|
||||
# Ask the registration agency, not the publisher. A HEAD request to
|
||||
# doi.org follows the redirect to the publisher, and several publishers
|
||||
# answer HEAD with 403 or 405 behind a bot check -- which made a
|
||||
# perfectly good DOI look unresolvable.
|
||||
try:
|
||||
time.sleep(0.21) # Stay below Crossref's public single-record limit.
|
||||
crossref_url = f'https://api.crossref.org/works/{quote(doi, safe="")}'
|
||||
metadata_response = self.session.get(crossref_url, timeout=10)
|
||||
|
||||
if metadata_response.status_code == 200:
|
||||
data = metadata_response.json()
|
||||
message = data.get('message', {})
|
||||
if not isinstance(message, dict) or str(message.get('DOI', '')).lower() != doi.lower():
|
||||
return None, None
|
||||
|
||||
# Extract key metadata
|
||||
metadata = {
|
||||
'title': (message.get('title') or [''])[0],
|
||||
'year': self._extract_year_crossref(message),
|
||||
'authors': self._format_authors_crossref(message.get('author', [])),
|
||||
}
|
||||
return True, metadata
|
||||
|
||||
if metadata_response.status_code == 404:
|
||||
# Not a Crossref DOI. DataCite registers datasets and many
|
||||
# preprints, so check there before calling it broken.
|
||||
datacite_url = f'https://api.datacite.org/dois/{quote(doi, safe="")}'
|
||||
datacite_response = self.session.get(datacite_url, timeout=10)
|
||||
if datacite_response.status_code == 200:
|
||||
record = datacite_response.json().get('data', {})
|
||||
if str(record.get('id', '')).lower() == doi.lower():
|
||||
return True, None
|
||||
return None, None
|
||||
if datacite_response.status_code != 404:
|
||||
return None, None
|
||||
# Other agencies mint DOIs too. Check the resolver itself,
|
||||
# without following publishers' bot-blocked landing pages.
|
||||
resolver = self.session.get(f'https://doi.org/{quote(doi, safe="/")}',
|
||||
allow_redirects=False, timeout=10)
|
||||
if resolver.status_code == 404:
|
||||
return False, None
|
||||
if resolver.status_code in (301, 302, 303, 307, 308) and resolver.headers.get('Location'):
|
||||
return True, None
|
||||
return None, None
|
||||
|
||||
# Any other status is a transport problem on our side, not
|
||||
# evidence that the DOI is bad.
|
||||
return None, None
|
||||
|
||||
except (requests.exceptions.RequestException, ValueError, TypeError, AttributeError):
|
||||
return None, None
|
||||
|
||||
def detect_duplicates(self, entries: List[Dict]) -> List[Dict]:
|
||||
"""
|
||||
Detect duplicate entries.
|
||||
|
||||
Args:
|
||||
entries: List of entry dictionaries
|
||||
|
||||
Returns:
|
||||
List of duplicate groups
|
||||
"""
|
||||
duplicates = []
|
||||
|
||||
# Check for duplicate DOIs
|
||||
doi_map = defaultdict(list)
|
||||
for entry in entries:
|
||||
doi = entry['fields'].get('doi', '').strip()
|
||||
if doi:
|
||||
doi_map[doi].append(entry['key'])
|
||||
|
||||
for doi, keys in doi_map.items():
|
||||
if len(keys) > 1:
|
||||
duplicates.append({
|
||||
'type': 'duplicate_doi',
|
||||
'doi': doi,
|
||||
'entries': keys,
|
||||
'severity': 'high',
|
||||
'message': f'Duplicate DOI {doi} found in entries: {", ".join(keys)}'
|
||||
})
|
||||
|
||||
# Check for duplicate citation keys
|
||||
key_counts = defaultdict(int)
|
||||
for entry in entries:
|
||||
key_counts[entry['key']] += 1
|
||||
|
||||
for key, count in key_counts.items():
|
||||
if count > 1:
|
||||
duplicates.append({
|
||||
'type': 'duplicate_key',
|
||||
'key': key,
|
||||
'count': count,
|
||||
'severity': 'high',
|
||||
'message': f'Citation key "{key}" appears {count} times'
|
||||
})
|
||||
|
||||
# Check for similar titles (possible duplicates)
|
||||
titles = {}
|
||||
for entry in entries:
|
||||
title = entry['fields'].get('title', '').lower()
|
||||
title = re.sub(r'[^\w\s]', '', title) # Remove punctuation
|
||||
title = ' '.join(title.split()) # Normalize whitespace
|
||||
|
||||
if title:
|
||||
if title in titles:
|
||||
duplicates.append({
|
||||
'type': 'similar_title',
|
||||
'entries': [titles[title], entry['key']],
|
||||
'severity': 'medium',
|
||||
'message': f'Possible duplicate: "{titles[title]}" and "{entry["key"]}" have identical titles'
|
||||
})
|
||||
else:
|
||||
titles[title] = entry['key']
|
||||
|
||||
return duplicates
|
||||
|
||||
def parse_manuscript_citations(self, filepath: str) -> List[str]:
|
||||
"""
|
||||
Parse a manuscript file (Markdown or LaTeX) and extract all cited keys.
|
||||
|
||||
Args:
|
||||
filepath: Path to manuscript file
|
||||
|
||||
Returns:
|
||||
List of cited citation keys
|
||||
"""
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
except Exception as e:
|
||||
print(f'Error reading manuscript file {filepath}: {e}', file=sys.stderr)
|
||||
return []
|
||||
|
||||
cited_keys = set()
|
||||
|
||||
# 1. LaTeX citations: \cite{key1, key2}, \citep{key}, \citet{key}, etc.
|
||||
latex_matches = re.findall(r'\\cite[a-z]*\*?\{([^}]+)\}', content)
|
||||
for match in latex_matches:
|
||||
keys = [k.strip() for k in match.split(',')]
|
||||
for key in keys:
|
||||
if key:
|
||||
cited_keys.add(key)
|
||||
|
||||
# 2. Markdown / Pandoc citations: @key or [@key1; @key2]
|
||||
# Match @ followed by valid citation key chars (alphanumeric, -, _, :, .)
|
||||
# Avoid email addresses, twitter handles, etc. by requiring that @ is not preceded by alphanumeric/dot/dash/underscore
|
||||
md_matches = re.findall(r'(?<![a-zA-Z0-9_.-])@([a-zA-Z0-9_\-:]+)', content)
|
||||
for key in md_matches:
|
||||
# Exclude common false positives
|
||||
if key and not key.isdigit():
|
||||
cited_keys.add(key)
|
||||
|
||||
return list(cited_keys)
|
||||
|
||||
def validate_file(self, filepath: str, check_dois: bool = False, min_count: Optional[int] = None, venue: Optional[str] = None, manuscript_filepath: Optional[str] = None) -> Dict:
|
||||
"""
|
||||
Validate entire BibTeX file.
|
||||
|
||||
Args:
|
||||
filepath: Path to BibTeX file
|
||||
check_dois: Whether to verify DOIs (slow)
|
||||
min_count: Optional minimum citation count to enforce
|
||||
venue: Optional venue type to check against standards
|
||||
manuscript_filepath: Optional path to manuscript to cross-check citations
|
||||
|
||||
Returns:
|
||||
Validation report dictionary
|
||||
"""
|
||||
print(f'Parsing {filepath}...', file=sys.stderr)
|
||||
entries = self.parse_bibtex_file(filepath)
|
||||
|
||||
if not entries:
|
||||
return {
|
||||
'filepath': filepath,
|
||||
'total_entries': 0,
|
||||
'valid_entries': 0,
|
||||
'errors': [{
|
||||
'type': 'empty_bibtex_file',
|
||||
'severity': 'high',
|
||||
'message': f'BibTeX file {filepath} has no valid entries.'
|
||||
}],
|
||||
'warnings': [],
|
||||
'duplicates': [],
|
||||
'venue_standard_checked': venue,
|
||||
'min_count_checked': min_count,
|
||||
'manuscript_results': {'checked': False}
|
||||
}
|
||||
|
||||
print(f'Found {len(entries)} entries', file=sys.stderr)
|
||||
|
||||
all_errors = []
|
||||
all_warnings = []
|
||||
|
||||
# Validate each entry
|
||||
for i, entry in enumerate(entries):
|
||||
print(f'Validating entry {i+1}/{len(entries)}: {entry["key"]}', file=sys.stderr)
|
||||
errors, warnings = self.validate_entry(entry)
|
||||
|
||||
for error in errors:
|
||||
error['entry'] = entry['key']
|
||||
all_errors.append(error)
|
||||
|
||||
for warning in warnings:
|
||||
warning['entry'] = entry['key']
|
||||
all_warnings.append(warning)
|
||||
|
||||
# Check for duplicates
|
||||
print('Checking for duplicates...', file=sys.stderr)
|
||||
duplicates = self.detect_duplicates(entries)
|
||||
|
||||
# Verify DOIs if requested
|
||||
doi_errors = []
|
||||
if check_dois:
|
||||
print('Verifying DOIs...', file=sys.stderr)
|
||||
for i, entry in enumerate(entries):
|
||||
doi = entry['fields'].get('doi', '')
|
||||
if doi:
|
||||
print(f'Verifying DOI {i+1}: {doi}', file=sys.stderr)
|
||||
is_valid, metadata = self.verify_doi(doi)
|
||||
|
||||
if is_valid is None:
|
||||
all_warnings.append({
|
||||
'type': 'doi_unverified',
|
||||
'entry': entry['key'],
|
||||
'doi': doi,
|
||||
'severity': 'medium',
|
||||
'message': f'Entry {entry["key"]}: DOI lookup inconclusive; retry or verify manually: {doi}'
|
||||
})
|
||||
elif is_valid is False:
|
||||
doi_errors.append({
|
||||
'type': 'invalid_doi',
|
||||
'entry': entry['key'],
|
||||
'doi': doi,
|
||||
'severity': 'high',
|
||||
'message': f'Entry {entry["key"]}: DOI does not resolve: {doi}'
|
||||
})
|
||||
|
||||
all_errors.extend(doi_errors)
|
||||
|
||||
# Count and Venue verification logic
|
||||
count_errors = []
|
||||
count_warnings = []
|
||||
|
||||
target_min = None
|
||||
target_max = None
|
||||
venue_name = None
|
||||
|
||||
if venue:
|
||||
v_lower = venue.lower().strip()
|
||||
if v_lower in self.venue_standards:
|
||||
target_min, target_max, venue_name = self.venue_standards[v_lower]
|
||||
else:
|
||||
print(f"Warning: Unknown venue '{venue}'. Supported venues are: {', '.join(self.venue_standards.keys())}", file=sys.stderr)
|
||||
|
||||
if min_count is not None:
|
||||
target_min = min_count
|
||||
venue_name = f"Custom threshold (min: {min_count})"
|
||||
target_max = None
|
||||
|
||||
# A reference list is never *wrong* for being short -- the right length
|
||||
# is whatever the argument needs -- so a shortfall is reported as a
|
||||
# warning. `--min-count` is the exception: an explicit floor the caller
|
||||
# asked to have enforced, so falling under it is an error.
|
||||
total_count = len(entries)
|
||||
if target_min is not None:
|
||||
if min_count is not None and total_count < min_count:
|
||||
count_errors.append({
|
||||
'type': 'below_requested_minimum',
|
||||
'severity': 'high',
|
||||
'message': f'Total citation entries ({total_count}) is below the requested minimum of {min_count}.'
|
||||
})
|
||||
elif total_count < target_min:
|
||||
count_warnings.append({
|
||||
'type': 'low_citation_count',
|
||||
'severity': 'medium',
|
||||
'message': f'Total citation entries ({total_count}) is below the {venue_name or "specified standard"} rule of thumb of {target_min}-{target_max or "+"}. This is a heuristic, not a submission requirement.'
|
||||
})
|
||||
|
||||
# Manuscript checking logic
|
||||
manuscript_results = {
|
||||
'checked': False,
|
||||
'manuscript_filepath': None,
|
||||
'cited_keys': [],
|
||||
'missing_keys': [],
|
||||
'unused_keys': []
|
||||
}
|
||||
|
||||
if manuscript_filepath:
|
||||
manuscript_results['checked'] = True
|
||||
manuscript_results['manuscript_filepath'] = manuscript_filepath
|
||||
|
||||
# Parse cited keys
|
||||
cited_keys = self.parse_manuscript_citations(manuscript_filepath)
|
||||
manuscript_results['cited_keys'] = cited_keys
|
||||
|
||||
bib_keys = {entry['key'] for entry in entries}
|
||||
|
||||
# Missing references: cited in manuscript but not defined in BibTeX
|
||||
missing_keys = [key for key in cited_keys if key not in bib_keys]
|
||||
manuscript_results['missing_keys'] = missing_keys
|
||||
for key in missing_keys:
|
||||
all_errors.append({
|
||||
'type': 'unresolved_citation',
|
||||
'entry': key,
|
||||
'severity': 'high',
|
||||
'message': f'Unresolved citation: Key "@{key}" is cited in manuscript "{manuscript_filepath}" but not defined in the BibTeX file.'
|
||||
})
|
||||
|
||||
# Unused references: defined in BibTeX but not cited in manuscript
|
||||
unused_keys = [key for key in bib_keys if key not in cited_keys]
|
||||
manuscript_results['unused_keys'] = unused_keys
|
||||
for key in unused_keys:
|
||||
all_warnings.append({
|
||||
'type': 'unused_citation',
|
||||
'entry': key,
|
||||
'severity': 'medium',
|
||||
'message': f'Unused citation: Reference "{key}" is defined in the BibTeX file but not cited in the manuscript.'
|
||||
})
|
||||
|
||||
# Check the count of ACTUALLY used citations
|
||||
actual_count = len(cited_keys) - len(missing_keys)
|
||||
if target_min is not None:
|
||||
if min_count is not None and actual_count < min_count:
|
||||
count_errors.append({
|
||||
'type': 'manuscript_below_requested_minimum',
|
||||
'severity': 'high',
|
||||
'message': f'The manuscript cites {actual_count} references, below the requested minimum of {min_count}.'
|
||||
})
|
||||
elif actual_count < target_min:
|
||||
count_warnings.append({
|
||||
'type': 'low_manuscript_citation_count',
|
||||
'severity': 'medium',
|
||||
'message': f'The manuscript cites {actual_count} references, below the {venue_name or "specified standard"} rule of thumb of {target_min}-{target_max or "+"}. This is a heuristic, not a submission requirement.'
|
||||
})
|
||||
|
||||
all_errors.extend(count_errors)
|
||||
all_warnings.extend(count_warnings)
|
||||
|
||||
# Count entries carrying at least one high-severity error, rather than
|
||||
# subtracting the error count -- several errors can land on one entry,
|
||||
# which previously drove this figure negative.
|
||||
entries_with_errors = {
|
||||
error['entry'] for error in all_errors
|
||||
if error.get('severity') == 'high' and error.get('entry')
|
||||
}
|
||||
bib_keys_present = {entry['key'] for entry in entries}
|
||||
|
||||
return {
|
||||
'filepath': filepath,
|
||||
'total_entries': len(entries),
|
||||
'valid_entries': len(entries) - len(entries_with_errors & bib_keys_present),
|
||||
'errors': all_errors,
|
||||
'warnings': all_warnings,
|
||||
'duplicates': duplicates,
|
||||
'venue_standard_checked': venue,
|
||||
'min_count_checked': min_count,
|
||||
'manuscript_results': manuscript_results
|
||||
}
|
||||
|
||||
def _extract_year_crossref(self, message: Dict) -> str:
|
||||
"""Extract year from CrossRef message."""
|
||||
date_parts = message.get('published-print', {}).get('date-parts', [[]])
|
||||
if not date_parts or not date_parts[0]:
|
||||
date_parts = message.get('published-online', {}).get('date-parts', [[]])
|
||||
|
||||
if date_parts and date_parts[0]:
|
||||
return str(date_parts[0][0])
|
||||
return ''
|
||||
|
||||
def _format_authors_crossref(self, authors: List[Dict]) -> str:
|
||||
"""Format author list from CrossRef."""
|
||||
if not authors:
|
||||
return ''
|
||||
|
||||
formatted = []
|
||||
for author in authors[:3]: # First 3 authors
|
||||
given = author.get('given', '')
|
||||
family = author.get('family', '')
|
||||
if family:
|
||||
formatted.append(f'{family}, {given}' if given else family)
|
||||
|
||||
if len(authors) > 3:
|
||||
formatted.append('et al.')
|
||||
|
||||
return ', '.join(formatted)
|
||||
|
||||
|
||||
def main():
|
||||
"""Command-line interface."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Validate BibTeX files for errors and inconsistencies',
|
||||
epilog='Example: python validate_citations.py references.bib'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'file',
|
||||
help='BibTeX file to validate'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--check-dois',
|
||||
action='store_true',
|
||||
help='Verify DOIs resolve correctly (slow)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--report',
|
||||
help='Output file for the JSON validation report'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--verbose',
|
||||
action='store_true',
|
||||
help='Show detailed output'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--min-count',
|
||||
type=int,
|
||||
help='Enforce a minimum number of citation entries'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--venue',
|
||||
help='Enforce citation standards for a specific venue (e.g. nature, neurips, review)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--manuscript',
|
||||
help='Path to manuscript file (Markdown or LaTeX) to check for unresolved or unused citations'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Validate file
|
||||
validator = CitationValidator()
|
||||
report = validator.validate_file(
|
||||
args.file,
|
||||
check_dois=args.check_dois,
|
||||
min_count=args.min_count,
|
||||
venue=args.venue,
|
||||
manuscript_filepath=args.manuscript
|
||||
)
|
||||
|
||||
# Print summary
|
||||
print('\n' + '='*60)
|
||||
print('CITATION VALIDATION REPORT')
|
||||
print('='*60)
|
||||
print(f'\nFile: {args.file}')
|
||||
if report.get('venue_standard_checked'):
|
||||
print(f'Venue Standard: {report["venue_standard_checked"]}')
|
||||
if report.get('min_count_checked') is not None:
|
||||
print(f'Required Min Count: {report["min_count_checked"]}')
|
||||
print(f'Total entries in BibTeX: {report["total_entries"]}')
|
||||
|
||||
m_res = report.get('manuscript_results', {})
|
||||
if m_res.get('checked'):
|
||||
print(f'Manuscript checked: {m_res["manuscript_filepath"]}')
|
||||
print(f' Actual unique citations in manuscript: {len(m_res["cited_keys"])}')
|
||||
print(f' Missing/unresolved: {len(m_res["missing_keys"])}')
|
||||
print(f' Unused in bib file: {len(m_res["unused_keys"])}')
|
||||
|
||||
print(f'Valid entries: {report["valid_entries"]}')
|
||||
print(f'Errors: {len(report["errors"])}')
|
||||
print(f'Warnings: {len(report["warnings"])}')
|
||||
print(f'Duplicates: {len(report["duplicates"])}')
|
||||
|
||||
# Print errors
|
||||
if report['errors']:
|
||||
print('\n' + '-'*60)
|
||||
print('ERRORS (must fix):')
|
||||
print('-'*60)
|
||||
for error in report['errors']:
|
||||
print(f'\n{error["message"]}')
|
||||
if args.verbose:
|
||||
print(f' Type: {error["type"]}')
|
||||
print(f' Severity: {error["severity"]}')
|
||||
|
||||
# Print warnings
|
||||
if report['warnings'] and (args.verbose or report.get('venue_standard_checked') or report.get('min_count_checked') is not None or m_res.get('checked')):
|
||||
print('\n' + '-'*60)
|
||||
print('WARNINGS (should fix):')
|
||||
print('-'*60)
|
||||
for warning in report['warnings']:
|
||||
print(f'\n{warning["message"]}')
|
||||
|
||||
# Print duplicates
|
||||
if report['duplicates']:
|
||||
print('\n' + '-'*60)
|
||||
print('DUPLICATES:')
|
||||
print('-'*60)
|
||||
for dup in report['duplicates']:
|
||||
print(f'\n{dup["message"]}')
|
||||
|
||||
# Save report
|
||||
if args.report:
|
||||
with open(args.report, 'w', encoding='utf-8') as f:
|
||||
json.dump(report, f, indent=2)
|
||||
print(f'\nDetailed report saved to: {args.report}')
|
||||
|
||||
# Exit with error code if there are high-severity errors
|
||||
has_high_errors = any(e.get('severity') == 'high' for e in report['errors'])
|
||||
if has_high_errors:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user