Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

citation-management: fix BibTeX corruption and metadata defects

Timothy Kassisd39264b47c88
diff --git a/skills/citation-management/scripts/_common.py b/skills/citation-management/scripts/_common.py
new file mode 100644
index 00000000..645d6bee
--- /dev/null
+++ b/skills/citation-management/scripts/_common.py
@@ -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
diff --git a/skills/citation-management/scripts/extract_metadata.py b/skills/citation-management/scripts/extract_metadata.py
index 5670bdac..af19dec3 100755
--- a/skills/citation-management/scripts/extract_metadata.py
+++ b/skills/citation-management/scripts/extract_metadata.py
@@ -13,7 +13,16 @@ import re
import json
import xml.etree.ElementTree as ET
from typing import Optional, Dict, List, Tuple
-from urllib.parse import urlparse
+from urllib.parse import urlparse, quote
+
+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."""
@@ -105,30 +114,39 @@ class MetadataExtractor:
Returns:
Metadata dictionary or None
"""
- url = f'https://api.crossref.org/works/{doi}'
-
+ # 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', [''])[0],
+ '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': message.get('container-title', [''])[0] if message.get('container-title') else '',
+ '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)
@@ -191,7 +209,7 @@ class MetadataExtractor:
'type': 'pmid',
'entry_type': 'article',
'pmid': pmid,
- 'title': article_elem.findtext('.//ArticleTitle', ''),
+ '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', ''),
@@ -210,6 +228,20 @@ class MetadataExtractor:
print(f'Error extracting metadata from PMID {pmid}: {e}', 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.
@@ -258,19 +290,26 @@ class MetadataExtractor:
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': 'misc' if not doi else 'article',
+ '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)
@@ -293,57 +332,66 @@ class MetadataExtractor:
"""
if not citation_key:
citation_key = self._generate_citation_key(metadata)
-
+
entry_type = metadata.get('entry_type', 'misc')
-
- # Build BibTeX entry
- lines = [f'@{entry_type}{{{citation_key},']
-
- # Add fields
- if metadata.get('authors'):
- lines.append(f' author = {{{metadata["authors"]}}},')
-
- if metadata.get('title'):
- # Protect capitalization
- title = self._protect_title(metadata['title'])
- lines.append(f' title = {{{title}}},')
-
- if entry_type == 'article' and metadata.get('journal'):
- lines.append(f' journal = {{{metadata["journal"]}}},')
- elif entry_type == 'misc' and metadata.get('type') == 'arxiv':
- lines.append(f' howpublished = {{arXiv}},')
-
- if metadata.get('year'):
- lines.append(f' year = {{{metadata["year"]}}},')
-
- if metadata.get('volume'):
- lines.append(f' volume = {{{metadata["volume"]}}},')
-
- if metadata.get('issue'):
- lines.append(f' number = {{{metadata["issue"]}}},')
-
- if metadata.get('pages'):
- pages = metadata['pages'].replace('-', '--') # En-dash
- lines.append(f' pages = {{{pages}}},')
-
- if metadata.get('doi'):
- lines.append(f' doi = {{{metadata["doi"]}}},')
- elif metadata.get('url'):
- lines.append(f' url = {{{metadata["url"]}}},')
-
+
+ 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'):
- lines.append(f' note = {{PMID: {metadata["pmid"]}}},')
-
- if metadata.get('type') == 'arxiv' and not metadata.get('doi'):
- lines.append(f' note = {{Preprint}},')
-
- # Remove trailing comma from last field
- if lines[-1].endswith(','):
- lines[-1] = lines[-1][:-1]
-
- lines.append('}')
-
- return '\n'.join(lines)
+ 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."""
@@ -412,48 +460,85 @@ class MetadataExtractor:
return year
def _generate_citation_key(self, metadata: Dict) -> str:
- """Generate a citation key from metadata."""
- # Get first author last name
- authors = metadata.get('authors', '')
- if authors:
- first_author = authors.split(' and ')[0]
- if ',' in first_author:
- last_name = first_author.split(',')[0].strip()
- else:
- last_name = first_author.split()[-1] if first_author else 'Unknown'
- else:
- last_name = 'Unknown'
-
- # Get year. It arrives verbatim from the CrossRef/PubMed/arXiv record,
- # so keep only digits — the key is used as a filename and as a shell
- # argument, and a publisher controls the contents of its own record.
- year = re.sub(r'[^0-9]', '', metadata.get('year', ''))
- if not year:
- year = 'XXXX'
-
- # Clean last name (remove special characters)
- last_name = re.sub(r'[^a-zA-Z]', '', last_name)
-
- # Get keyword from title
- title = metadata.get('title', '')
- words = re.findall(r'\b[a-zA-Z]{4,}\b', title)
- keyword = words[0].lower() if words else 'paper'
-
- return f'{last_name}{year}{keyword}'
-
+ """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."""
- # Protect common acronyms and proper nouns
- protected_words = [
- 'DNA', 'RNA', 'CRISPR', 'COVID', 'HIV', 'AIDS', 'AlphaFold',
- 'Python', 'AI', 'ML', 'GPU', 'CPU', 'USA', 'UK', 'EU'
- ]
-
- for word in protected_words:
- title = re.sub(rf'\b{word}\b', f'{{{word}}}', title, flags=re.IGNORECASE)
-
- return title
-
+ 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://www.ncbi.nlm.nih.gov/pmc/utils/idconv/v1.0/'
+ 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 'pmid' not in records[0]:
+ 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(records[0]['pmid'])
+
+ except (requests.exceptions.RequestException, ValueError) as e:
+ print(f'Error resolving PMCID {pmcid}: {e}', 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.
@@ -476,6 +561,10 @@ class MetadataExtractor:
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
@@ -485,6 +574,34 @@ class MetadataExtractor:
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 main():
"""Command-line interface."""
@@ -530,36 +647,38 @@ def main():
# Extract metadata
extractor = MetadataExtractor(email=args.email)
- bibtex_entries = []
-
+ records = []
+
for i, identifier in enumerate(identifiers):
print(f'\nProcessing {i+1}/{len(identifiers)}...', file=sys.stderr)
- bibtex = extractor.extract(identifier)
- if bibtex:
- bibtex_entries.append(bibtex)
-
+ record = extractor.extract_record(identifier)
+ if record:
+ records.append(record)
+
# Rate limiting
if i < len(identifiers) - 1:
time.sleep(0.5)
-
- if not bibtex_entries:
+
+ 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(bibtex_entries),
- 'entries': bibtex_entries
+ '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(bibtex_entries)} entries to {args.output}', file=sys.stderr)
+ print(f"\nSuccessfully wrote {len(records)} entries to {args.output}", file=sys.stderr)
else:
print(output)
diff --git a/skills/citation-management/scripts/format_bibtex.py b/skills/citation-management/scripts/format_bibtex.py
index 31a4d73c..dd05a9f7 100755
--- a/skills/citation-management/scripts/format_bibtex.py
+++ b/skills/citation-management/scripts/format_bibtex.py
@@ -2,155 +2,90 @@
"""
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.
"""
-import sys
-import re
+from __future__ import annotations
+
import argparse
-from typing import List, Dict, Tuple
+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 = [
- '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'
- ]
-
+ 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
"""
- try:
- with open(filepath, 'r', encoding='utf-8') as f:
- content = f.read()
- except Exception as e:
- print(f'Error reading file: {e}', file=sys.stderr)
- return []
-
- entries = []
-
- # Match BibTeX entries
- pattern = r'@(\w+)\s*\{\s*([^,\s]+)\s*,(.*?)\n\}'
- matches = re.finditer(pattern, content, re.DOTALL | re.IGNORECASE)
-
- for match in matches:
- entry_type = match.group(1).lower()
- citation_key = match.group(2).strip()
- fields_text = match.group(3)
-
- # Parse fields
- fields = OrderedDict()
- field_pattern = r'(\w+)\s*=\s*\{([^}]*)\}|(\w+)\s*=\s*"([^"]*)"'
- field_matches = re.finditer(field_pattern, fields_text)
-
- for field_match in field_matches:
- if field_match.group(1):
- field_name = field_match.group(1).lower()
- field_value = field_match.group(2)
- else:
- field_name = field_match.group(3).lower()
- field_value = field_match.group(4)
-
- fields[field_name] = field_value.strip()
-
- entries.append({
- 'type': entry_type,
- 'key': citation_key,
- 'fields': fields
- })
-
- return entries
-
+ 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
"""
- lines = [f'@{entry["type"]}{{{entry["key"]},']
-
- # Order fields according to standard order
- ordered_fields = OrderedDict()
-
- # Add fields in standard order
- for field_name in self.field_order:
- if field_name in entry['fields']:
- ordered_fields[field_name] = entry['fields'][field_name]
-
- # Add any remaining fields
- for field_name, field_value in entry['fields'].items():
- if field_name not in ordered_fields:
- ordered_fields[field_name] = field_value
-
- # Format each field
- max_field_len = max(len(f) for f in ordered_fields.keys()) if ordered_fields else 0
-
- for field_name, field_value in ordered_fields.items():
- # Pad field name for alignment
- padded_field = field_name.ljust(max_field_len)
- lines.append(f' {padded_field} = {{{field_value}}},')
-
- # Remove trailing comma from last field
- if lines[-1].endswith(','):
- lines[-1] = lines[-1][:-1]
-
- lines.append('}')
-
- return '\n'.join(lines)
-
+ 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 = entry.copy()
- fields = fixed['fields'].copy()
-
- # Fix page ranges (single hyphen to double hyphen)
- if 'pages' in fields:
- pages = fields['pages']
- # Replace single hyphen with double hyphen if it's a range
- if re.search(r'\d-\d', pages) and '--' not in pages:
- pages = re.sub(r'(\d)-(\d)', r'\1--\2', pages)
- fields['pages'] = pages
-
- # Remove "pp." from pages
+ 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:
- pages = fields['pages']
- pages = re.sub(r'^pp\.\s*', '', pages, flags=re.IGNORECASE)
- fields['pages'] = pages
-
+ 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
-
+ fields['doi'] = doi.strip()
+
# Fix author separators (semicolon or ampersand to 'and')
if 'author' in fields:
author = fields['author']
@@ -158,106 +93,150 @@ class BibTeXFormatter:
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()
+ 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 == 'key':
- return entry['key'].lower()
- elif sort_by == 'year':
- year = entry['fields'].get('year', '9999')
- return year
- elif sort_by == 'author':
- author = entry['fields'].get('author', 'ZZZ')
- # Get last name of first author
- if ',' in author:
- return author.split(',')[0].lower()
- else:
- return author.split()[0].lower() if author else 'zzz'
- elif sort_by == 'title':
+ 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()
- else:
- return entry['key'].lower()
-
+ return entry['key'].lower()
+
return sorted(entries, key=get_sort_key, reverse=descending)
-
- def format_file(self, filepath: str, output: str = None,
- deduplicate: bool = False, sort_by: str = None,
- descending: bool = False, fix_issues: bool = True) -> None:
+
+ 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 (None for in-place)
+ 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
-
+ 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)
@@ -266,84 +245,112 @@ class BibTeXFormatter:
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]
-
- # Write output
output_content = '\n\n'.join(formatted_entries) + '\n'
-
- output_file = output or filepath
+
+ if output is None:
+ return output_content
+
try:
- with open(output_file, 'w', encoding='utf-8') as f:
+ with open(output, 'w', encoding='utf-8') as f:
f.write(output_content)
- print(f'Successfully wrote {len(entries)} entries to {output_file}', file=sys.stderr)
- except Exception as e:
+ 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 --deduplicate --sort year'
+ 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='Output file (default: overwrite input file)'
+ 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',
+ '--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()
- formatter.format_file(
+ result = formatter.format_file(
args.file,
- output=args.output,
+ output=destination,
deduplicate=args.deduplicate,
sort_by=args.sort,
descending=args.descending,
- fix_issues=not args.no_fix
+ 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()
-
diff --git a/skills/citation-management/scripts/generate_schematic.py b/skills/citation-management/scripts/generate_schematic.py
deleted file mode 100644
index 6392aebf..00000000
--- a/skills/citation-management/scripts/generate_schematic.py
+++ /dev/null
@@ -1,198 +0,0 @@
-#!/usr/bin/env python3
-"""
-Scientific schematic generation using Nano Banana 2.
-
-Generate any scientific diagram by describing it in natural language.
-Nano Banana 2 handles everything automatically with smart iterative refinement.
-
-Smart iteration: Only regenerates if quality is below threshold for your document type.
-Quality review: Uses Gemini 3.6 Flash for professional scientific evaluation.
-
-Usage:
- # Generate for journal paper (highest quality threshold)
- python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal
-
- # Generate for presentation (lower threshold, faster)
- python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation
-
- # Generate for poster
- python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster
-"""
-
-import argparse
-import os
-import subprocess
-import sys
-from pathlib import Path
-
-# Variables forwarded to the generation subprocess. The child needs the
-# OpenRouter credential; the rest keep networking, TLS, and locale working.
-# Copying the whole parent environment instead would hand the child every
-# unrelated secret that happens to be exported in the calling shell.
-FORWARDED_ENV_VARS = (
- "PATH", "HOME", "LANG", "LC_ALL", "TMPDIR", "PYTHONPATH",
- "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY",
- "http_proxy", "https_proxy", "no_proxy",
- "SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE",
- # Windows needs these for sockets, temp files, and interpreter startup.
- "SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT",
- "APPDATA", "LOCALAPPDATA", "USERPROFILE", "TEMP", "TMP",
-)
-
-
-def resolve_api_key(explicit=None):
- """Resolve the OpenRouter key from --api-key, the environment, then any .env file.
-
- The .env scan walks up from the working directory and finally checks the
- script's own directory, so running from anywhere inside a project picks up
- the key at its root. The child process is handed the resolved value through
- build_subprocess_env, so it never has to repeat this search.
- """
- if explicit:
- return explicit
-
- from_env = os.environ.get("OPENROUTER_API_KEY", "").strip()
- if from_env:
- return from_env
-
- cwd = Path.cwd()
- for directory in [cwd, *cwd.parents, Path(__file__).resolve().parent]:
- env_file = directory / ".env"
- if not env_file.is_file():
- continue
- try:
- content = env_file.read_text(encoding="utf-8", errors="replace")
- except OSError:
- continue
- for raw in content.splitlines():
- line = raw.strip()
- if line.startswith("#") or "=" not in line:
- continue
- name, _, value = line.partition("=")
- if name.strip() == "OPENROUTER_API_KEY":
- value = value.strip().strip('"').strip("'")
- if value:
- return value
-
- return None
-
-
-def build_subprocess_env(api_key):
- """Return a minimal environment for the AI generation subprocess."""
- env = {name: os.environ[name] for name in FORWARDED_ENV_VARS if name in os.environ}
- if api_key:
- env["OPENROUTER_API_KEY"] = api_key
- return env
-
-
-def main():
- """Command-line interface."""
- parser = argparse.ArgumentParser(
- description="Generate scientific schematics using AI with smart iterative refinement",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""
-How it works:
- Simply describe your diagram in natural language
- Nano Banana 2 generates it automatically with:
- - Smart iteration (only regenerates if quality is below threshold)
- - Quality review by Gemini 3.6 Flash
- - Document-type aware quality thresholds
- - Publication-ready output
-
-Document Types (quality thresholds):
- journal 8.5/10 - Nature, Science, peer-reviewed journals
- conference 8.0/10 - Conference papers
- thesis 8.0/10 - Dissertations, theses
- grant 8.0/10 - Grant proposals
- preprint 7.5/10 - arXiv, bioRxiv, etc.
- report 7.5/10 - Technical reports
- poster 7.0/10 - Academic posters
- presentation 6.5/10 - Slides, talks
- default 7.5/10 - General purpose
-
-Examples:
- # Generate for journal paper (strict quality)
- python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal
-
- # Generate for poster (moderate quality)
- python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster
-
- # Generate for slides (faster, lower threshold)
- python generate_schematic.py "System diagram" -o system.png --doc-type presentation
-
- # Custom max iterations
- python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2
-
- # Verbose output
- python generate_schematic.py "Circuit diagram" -o circuit.png -v
-
-Environment Variables:
- OPENROUTER_API_KEY Required for AI generation
- """
- )
-
- parser.add_argument("prompt",
- help="Description of the diagram to generate")
- parser.add_argument("-o", "--output", required=True,
- help="Output file path")
- parser.add_argument("--doc-type", default="default",
- choices=["journal", "conference", "poster", "presentation",
- "report", "grant", "thesis", "preprint", "default"],
- help="Document type for quality threshold (default: default)")
- parser.add_argument("--iterations", type=int, default=2,
- help="Maximum refinement iterations (default: 2, max: 2)")
- parser.add_argument("--api-key",
- help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")
- parser.add_argument("-v", "--verbose", action="store_true",
- help="Verbose output")
-
- args = parser.parse_args()
-
- # Validated here rather than clamped silently, and before the credential
- # lookup so an out-of-range value reports itself rather than an absent key.
- if not 1 <= args.iterations <= 2:
- parser.error("--iterations must be 1 or 2")
-
- # Check for API key — resolves --api-key, the environment, then any .env file
- api_key = resolve_api_key(args.api_key)
- if not api_key:
- print("Error: OPENROUTER_API_KEY not found")
- print("\nFor AI generation, you need an OpenRouter API key.")
- print("Get one at: https://openrouter.ai/keys")
- print("\nSet it with:")
- print(" export OPENROUTER_API_KEY='your_api_key'")
- print("\nOr add OPENROUTER_API_KEY=your_api_key to a .env file")
- print("Or use --api-key flag")
- sys.exit(1)
-
- # Find AI generation script
- script_dir = Path(__file__).parent
- ai_script = script_dir / "generate_schematic_ai.py"
-
- if not ai_script.exists():
- print(f"Error: AI generation script not found: {ai_script}")
- sys.exit(1)
-
- # Build command
- cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]
-
- if args.doc_type != "default":
- cmd.extend(["--doc-type", args.doc_type])
-
- cmd.extend(["--iterations", str(args.iterations)])
-
- if args.verbose:
- cmd.append("-v")
-
- # Execute — pass API key via environment to avoid exposure in process listings
- try:
- result = subprocess.run(cmd, check=False, env=build_subprocess_env(api_key))
- sys.exit(result.returncode)
- except Exception as e:
- print(f"Error executing AI generation: {e}")
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
-
diff --git a/skills/citation-management/scripts/generate_schematic_ai.py b/skills/citation-management/scripts/generate_schematic_ai.py
deleted file mode 100644
index 85c4fd29..00000000
--- a/skills/citation-management/scripts/generate_schematic_ai.py
+++ /dev/null
@@ -1,950 +0,0 @@
-#!/usr/bin/env python3
-"""
-AI-powered scientific schematic generation using Nano Banana 2.
-
-This script uses a smart iterative refinement approach:
-1. Generate initial image with Nano Banana 2
-2. AI quality review using Gemini 3.6 Flash for scientific critique
-3. Only regenerate if quality is below threshold for document type
-4. Repeat until quality meets standards (max iterations)
-
-Requirements:
- - OPENROUTER_API_KEY environment variable
- - requests library
-
-Usage:
- python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png
- python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2
- python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster
-"""
-
-import argparse
-import base64
-import json
-import os
-import re
-import sys
-import time
-from pathlib import Path
-from typing import Optional, Dict, Any, List, NamedTuple
-
-try:
- import requests
-except ImportError:
- print("Error: requests library not found. Install with: uv pip install requests")
- sys.exit(1)
-
-
-class ReviewResult(NamedTuple):
- """The outcome of one quality review.
-
- A named tuple rather than a bare tuple because the review has several
- failure modes -- the model returns no choices, the request raises, the
- answer arrives in an unexpected shape -- and each of them used to be a
- chance to return the wrong number of values to the caller.
-
- `score` is None whenever no usable number was parsed, and `reviewed` is
- False whenever the review never produced an answer at all. Neither case
- invents a score: a diagram whose quality was not measured is reported as
- unmeasured, not as passing.
- """
-
- critique: str
- score: Optional[float]
- needs_improvement: bool
- reviewed: bool
- error: Optional[str] = None
-
-
-# Markdown decoration the reviewer routinely wraps its answer in. Gemini writes
-# "**SCORE:** 8.5" far more often than the bare "SCORE: 8.5" the rubric asks
-# for, and a pattern that does not allow for it silently scores every diagram
-# at whatever the default happens to be.
-_MARKUP = re.compile(r"[*_`#]")
-
-_SCORE_PATTERN = re.compile(r"\bSCORE\s*:?\s*(\d+(?:\.\d+)?)", re.IGNORECASE)
-_LOOSE_SCORE_PATTERN = re.compile(
- r"(?:score|rating|quality)\s*[:\s]\s*(\d+(?:\.\d+)?)\s*(?:/\s*10)?", re.IGNORECASE
-)
-# The underscore is optional because normalization strips it out of
-# NEEDS_IMPROVEMENT along with the surrounding markdown.
-_VERDICT_PATTERN = re.compile(
- r"^\s*VERDICT\s*:?\s*(ACCEPTABLE|NEEDS[_ ]?IMPROVEMENT)", re.IGNORECASE | re.MULTILINE
-)
-
-
-def _normalize_review_text(text: str) -> str:
- """Strip markdown decoration so the rubric's fields can be found."""
- return _MARKUP.sub("", text or "")
-
-
-def _parse_score(text: str) -> Optional[float]:
- """Return the reviewer's 0-10 score, or None when there isn't a usable one.
-
- None rather than a default: a fabricated score is indistinguishable from a
- real one once it reaches the review log, and a default near the middle of
- the range quietly passes lenient document types while failing strict ones.
- """
- normalized = _normalize_review_text(text)
- match = _SCORE_PATTERN.search(normalized) or _LOOSE_SCORE_PATTERN.search(normalized)
- if not match:
- return None
- score = float(match.group(1))
- # A number outside the rubric's range means something other than the score
- # was matched -- a figure count, a percentage, an iteration number.
- return score if 0.0 <= score <= 10.0 else None
-
-
-def _parse_verdict(text: str) -> Optional[str]:
- """Return ACCEPTABLE / NEEDS_IMPROVEMENT from the verdict line, or None.
-
- Anchored to the start of a line. The rubric prompt spells out both tokens
- when it explains the response format, so a reviewer that echoes those
- instructions back would fail a perfectly good diagram under a plain
- substring search.
- """
- match = _VERDICT_PATTERN.search(_normalize_review_text(text))
- if not match:
- return None
- verdict = match.group(1).upper().replace(" ", "").replace("_", "")
- return "NEEDS_IMPROVEMENT" if verdict == "NEEDSIMPROVEMENT" else "ACCEPTABLE"
-
-
-def _resolve_api_key(explicit: Optional[str] = None) -> Optional[str]:
- """Resolve the OpenRouter key from --api-key, the environment, then any .env file.
-
- The .env scan walks up from the working directory and finally checks the
- script's own directory, so running from anywhere inside a project picks up
- the key at its root. Only the standard library is used: python-dotenv is a
- common omission, and a missing optional dependency should not read as a
- missing credential.
- """
- if explicit:
- return explicit
-
- from_env = os.environ.get("OPENROUTER_API_KEY", "").strip()
- if from_env:
- return from_env
-
- cwd = Path.cwd()
- for directory in [cwd, *cwd.parents, Path(__file__).resolve().parent]:
- env_file = directory / ".env"
- if not env_file.is_file():
- continue
- try:
- content = env_file.read_text(encoding="utf-8", errors="replace")
- except OSError:
- continue
- for raw in content.splitlines():
- line = raw.strip()
- if line.startswith("#") or "=" not in line:
- continue
- name, _, value = line.partition("=")
- if name.strip() == "OPENROUTER_API_KEY":
- value = value.strip().strip('"').strip("'")
- if value:
- return value
-
- return None
-
-
-class ScientificSchematicGenerator:
- """Generate scientific schematics using AI with smart iterative refinement.
-
- Uses Gemini 3.6 Flash for quality review to determine if regeneration is needed.
- Multiple passes only occur if the generated schematic doesn't meet the
- quality threshold for the target document type.
- """
-
- # Quality thresholds by document type (score out of 10)
- # Higher thresholds for more formal publications
- QUALITY_THRESHOLDS = {
- "journal": 8.5, # Nature, Science, etc. - highest standards
- "conference": 8.0, # Conference papers - high standards
- "poster": 7.0, # Academic posters - good quality
- "presentation": 6.5, # Slides/talks - clear but less formal
- "report": 7.5, # Technical reports - professional
- "grant": 8.0, # Grant proposals - must be compelling
- "thesis": 8.0, # Dissertations - formal academic
- "preprint": 7.5, # arXiv, etc. - good quality
- "default": 7.5, # Default threshold
- }
-
- # Scientific diagram best practices prompt template
- SCIENTIFIC_DIAGRAM_GUIDELINES = """
-Create a high-quality scientific diagram with these requirements:
-
-VISUAL QUALITY:
-- Clean white or light background (no textures or gradients)
-- High contrast for readability and printing
-- Professional, publication-ready appearance
-- Sharp, clear lines and text
-- Adequate spacing between elements to prevent crowding
-
-TYPOGRAPHY:
-- Clear, readable sans-serif fonts (Arial, Helvetica style)
-- Minimum 10pt font size for all labels
-- Consistent font sizes throughout
-- All text horizontal or clearly readable
-- No overlapping text
-
-SCIENTIFIC STANDARDS:
-- Accurate representation of concepts
-- Clear labels for all components
-- Include scale bars, legends, or axes where appropriate
-- Use standard scientific notation and symbols
-- Include units where applicable
-
-ACCESSIBILITY:
-- Colorblind-friendly color palette (use Okabe-Ito colors if using color)
-- High contrast between elements
-- Redundant encoding (shapes + colors, not just colors)
-- Works well in grayscale
-
-LAYOUT:
-- Logical flow (left-to-right or top-to-bottom)
-- Clear visual hierarchy
-- Balanced composition
-- Appropriate use of whitespace
-- No clutter or unnecessary decorative elements
-
-IMPORTANT - NO FIGURE NUMBERS:
-- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image
-- Do NOT add captions or titles like "Figure: ..." at the top or bottom
-- Figure numbers and captions are added separately in the document/LaTeX
-- The diagram should contain only the visual content itself
-"""
-
- def __init__(self, api_key: Optional[str] = None, verbose: bool = False):
- """
- Initialize the generator.
-
- Args:
- api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)
- verbose: Print detailed progress information
- """
- # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file
- self.api_key = _resolve_api_key(api_key)
-
- if not self.api_key:
- raise ValueError(
- "OPENROUTER_API_KEY not found. Please either:\n"
- " 1. Set the OPENROUTER_API_KEY environment variable\n"
- " 2. Add OPENROUTER_API_KEY to your .env file\n"
- " 3. Pass api_key parameter to the constructor\n"
- "Get your API key from: https://openrouter.ai/keys"
- )
-
- self.verbose = verbose
- self._last_error = None # Track last error for better reporting
- self.base_url = "https://openrouter.ai/api/v1"
- # Nano Banana 2 - Google's advanced image generation model. The slug must
- # be an image-output model; a text-only chat model is rejected with
- # "No endpoints found that support the requested output modalities".
- # https://openrouter.ai/google/gemini-3.1-flash-image
- self.image_model = "google/gemini-3.1-flash-image"
- # Gemini 3.6 Flash for quality review - excellent vision and reasoning
- self.review_model = "google/gemini-3.6-flash"
-
- def _log(self, message: str):
- """Log message if verbose mode is enabled."""
- if self.verbose:
- print(f"[{time.strftime('%H:%M:%S')}] {message}")
-
- def _make_request(self, model: str, messages: List[Dict[str, Any]],
- modalities: Optional[List[str]] = None) -> Dict[str, Any]:
- """
- Make a request to OpenRouter API.
-
- Args:
- model: Model identifier
- messages: List of message dictionaries
- modalities: Optional list of modalities (e.g., ["image", "text"])
-
- Returns:
- API response as dictionary
- """
- headers = {
- "Authorization": f"Bearer {self.api_key}",
- "Content-Type": "application/json",
- "HTTP-Referer": "https://github.com/scientific-writer",
- "X-Title": "Scientific Schematic Generator"
- }
-
- payload = {
- "model": model,
- "messages": messages
- }
-
- if modalities:
- payload["modalities"] = modalities
-
- self._log(f"Making request to {model}...")
-
- try:
- response = requests.post(
- f"{self.base_url}/chat/completions",
- headers=headers,
- json=payload,
- timeout=120
- )
-
- # Try to get response body even on error
- try:
- response_json = response.json()
- except json.JSONDecodeError:
- response_json = {"raw_text": response.text[:500]}
-
- # Check for HTTP errors but include response body in error message
- if response.status_code != 200:
- error_detail = response_json.get("error", response_json)
- self._log(f"HTTP {response.status_code}: {error_detail}")
- raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")
-
- return response_json
- except requests.exceptions.Timeout:
- raise RuntimeError("API request timed out after 120 seconds")
- except requests.exceptions.RequestException as e:
- raise RuntimeError(f"API request failed: {str(e)}")
-
- def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:
- """
- Extract base64-encoded image from API response.
-
- For Nano Banana 2, images are returned in the 'images' field of the message,
- not in the 'content' field.
-
- Args:
- response: API response dictionary
-
- Returns:
- Image bytes or None if not found
- """
- try:
- choices = response.get("choices", [])
- if not choices:
- self._log("No choices in response")
- return None
-
- message = choices[0].get("message", {})
-
- # IMPORTANT: Nano Banana 2 returns images in the 'images' field
- images = message.get("images", [])
- if images and len(images) > 0:
- self._log(f"Found {len(images)} image(s) in 'images' field")
-
- # Get first image
- first_image = images[0]
- if isinstance(first_image, dict):
- # Extract image_url
- if first_image.get("type") == "image_url":
- url = first_image.get("image_url", {})
- if isinstance(url, dict):
- url = url.get("url", "")
-
- if url and url.startswith("data:image"):
- # Extract base64 data after comma
- if "," in url:
- base64_str = url.split(",", 1)[1]
- # Clean whitespace
- base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')
- self._log(f"Extracted base64 data (length: {len(base64_str)})")
- return base64.b64decode(base64_str)
-
- # Fallback: check content field (for other models or future changes)
- content = message.get("content", "")
-
- if self.verbose:
- self._log(f"Content type: {type(content)}, length: {len(str(content))}")
-
- # Handle string content
- if isinstance(content, str) and "data:image" in content:
- match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)
- if match:
- base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')
- self._log(f"Found image in content field (length: {len(base64_str)})")
- return base64.b64decode(base64_str)
-
- # Handle list content
- if isinstance(content, list):
- for i, block in enumerate(content):
- if isinstance(block, dict) and block.get("type") == "image_url":
- url = block.get("image_url", {})
- if isinstance(url, dict):
- url = url.get("url", "")
- if url and url.startswith("data:image") and "," in url:
- base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')
- self._log(f"Found image in content block {i}")
- return base64.b64decode(base64_str)
-
- self._log("No image data found in response")
- return None
-
- except Exception as e:
- self._log(f"Error extracting image: {str(e)}")
- import traceback
- if self.verbose:
- traceback.print_exc()
- return None
-
- def _image_to_base64(self, image_path: str) -> str:
- """
- Convert image file to base64 data URL.
-
- Args:
- image_path: Path to image file
-
- Returns:
- Base64 data URL string
- """
- with open(image_path, "rb") as f:
- image_data = f.read()
-
- # Determine image type from extension
- ext = Path(image_path).suffix.lower()
- mime_type = {
- ".png": "image/png",
- ".jpg": "image/jpeg",
- ".jpeg": "image/jpeg",
- ".gif": "image/gif",
- ".webp": "image/webp"
- }.get(ext, "image/png")
-
- base64_data = base64.b64encode(image_data).decode("utf-8")
- return f"data:{mime_type};base64,{base64_data}"
-
- def generate_image(self, prompt: str) -> Optional[bytes]:
- """
- Generate an image using Nano Banana 2.
-
- Args:
- prompt: Description of the diagram to generate
-
- Returns:
- Image bytes or None if generation failed
- """
- self._last_error = None # Reset error
-
- messages = [
- {
- "role": "user",
- "content": prompt
- }
- ]
-
- try:
- response = self._make_request(
- model=self.image_model,
- messages=messages,
- modalities=["image", "text"]
- )
-
- # Debug: print response structure if verbose
- if self.verbose:
- self._log(f"Response keys: {response.keys()}")
- if "error" in response:
- self._log(f"API Error: {response['error']}")
- if "choices" in response and response["choices"]:
- msg = response["choices"][0].get("message", {})
- self._log(f"Message keys: {msg.keys()}")
- # Show content preview without printing huge base64 data
- content = msg.get("content", "")
- if isinstance(content, str):
- preview = content[:200] + "..." if len(content) > 200 else content
- self._log(f"Content preview: {preview}")
- elif isinstance(content, list):
- self._log(f"Content is list with {len(content)} items")
- for i, item in enumerate(content[:3]):
- if isinstance(item, dict):
- self._log(f" Item {i}: type={item.get('type')}")
-
- # Check for API errors in response
- if "error" in response:
- error_msg = response["error"]
- if isinstance(error_msg, dict):
- error_msg = error_msg.get("message", str(error_msg))
- self._last_error = f"API Error: {error_msg}"
- print(f"✗ {self._last_error}")
- return None
-
- image_data = self._extract_image_from_response(response)
- if image_data:
- self._log(f"✓ Generated image ({len(image_data)} bytes)")
- else:
- self._last_error = "No image data in API response - model may not support image generation"
- self._log(f"✗ {self._last_error}")
- # Additional debug info when image extraction fails
- if self.verbose and "choices" in response:
- msg = response["choices"][0].get("message", {})
- self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")
-
- return image_data
- except RuntimeError as e:
- self._last_error = str(e)
- self._log(f"✗ Generation failed: {self._last_error}")
- return None
- except Exception as e:
- self._last_error = f"Unexpected error: {str(e)}"
- self._log(f"✗ Generation failed: {self._last_error}")
- import traceback
- if self.verbose:
- traceback.print_exc()
- return None
-
- def review_image(self, image_path: str, original_prompt: str,
- iteration: int, doc_type: str = "default",
- max_iterations: int = 2) -> ReviewResult:
- """
- Review the generated image for quality, using the vision review model.
-
- Args:
- image_path: Path to the generated image
- original_prompt: Original user prompt
- iteration: Current iteration number
- doc_type: Document type (journal, poster, presentation, etc.)
- max_iterations: Maximum iterations allowed
-
- Returns:
- A ReviewResult. When the review cannot be completed -- the request
- fails, or the model answers with nothing usable -- `reviewed` is
- False and `score` is None rather than a stand-in number, and
- `needs_improvement` is False: the fault is in the reviewer, not in
- the diagram, so regenerating would not help.
- """
- image_data_url = self._image_to_base64(image_path)
-
- # Get quality threshold for this document type
- threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),
- self.QUALITY_THRESHOLDS["default"])
-
- review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.
-
-ORIGINAL REQUEST: {original_prompt}
-
-DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)
-ITERATION: {iteration}/{max_iterations}
-
-Carefully evaluate this diagram on these criteria:
-
-1. **Scientific Accuracy** (0-2 points)
- - Correct representation of concepts
- - Proper notation and symbols
- - Accurate relationships shown
-
-2. **Clarity and Readability** (0-2 points)
- - Easy to understand at a glance
- - Clear visual hierarchy
- - No ambiguous elements
-
-3. **Label Quality** (0-2 points)
- - All important elements labeled
- - Labels are readable (appropriate font size)
- - Consistent labeling style
-
-4. **Layout and Composition** (0-2 points)
- - Logical flow (top-to-bottom or left-to-right)
- - Balanced use of space
- - No overlapping elements
-
-5. **Professional Appearance** (0-2 points)
- - Publication-ready quality
- - Clean, crisp lines and shapes
- - Appropriate colors/contrast
-
-RESPOND IN THIS EXACT FORMAT:
-SCORE: [total score 0-10]
-
-STRENGTHS:
-- [strength 1]
-- [strength 2]
-
-ISSUES:
-- [issue 1 if any]
-- [issue 2 if any]
-
-VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]
-
-If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.
-If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""
-
- messages = [
- {
- "role": "user",
- "content": [
- {
- "type": "text",
- "text": review_prompt
- },
- {
- "type": "image_url",
- "image_url": {
- "url": image_data_url
- }
- }
- ]
- }
- ]
-
- try:
- response = self._make_request(
- model=self.review_model,
- messages=messages
- )
-
- # Extract text response
- choices = response.get("choices", [])
- if not choices:
- # A normal enough outcome -- a rate limit, a content filter, a
- # provider hiccup. The diagram itself is fine; only its review
- # is missing, and saying so beats inventing a score.
- reason = "the review model returned no choices"
- self._log(f"⚠ Review unavailable: {reason}")
- return ReviewResult(
- f"Review unavailable: {reason}.",
- None, False, reviewed=False, error=reason,
- )
-
- message = choices[0].get("message", {})
- content = message.get("content", "")
-
- # Some models put their analysis in a separate reasoning field
- reasoning = message.get("reasoning", "")
- if reasoning and not content:
- content = reasoning
-
- if isinstance(content, list):
- # Extract text from content blocks
- text_parts = []
- for block in content:
- if isinstance(block, dict) and block.get("type") == "text":
- text_parts.append(block.get("text", ""))
- content = "\n".join(text_parts)
-
- score = _parse_score(content)
- verdict = _parse_verdict(content)
-
- if score is None and verdict is None:
- reason = "no score or verdict found in the review"
- self._log(f"⚠ Review unusable: {reason}")
- return ReviewResult(
- content if content else f"Review unusable: {reason}.",
- None, False, reviewed=True, error=reason,
- )
-
- needs_improvement = verdict == "NEEDS_IMPROVEMENT" or (
- score is not None and score < threshold
- )
-
- shown = f"{score}/10" if score is not None else "not stated"
- self._log(f"✓ Review complete (Score: {shown}, Threshold: {threshold}/10)")
- self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")
-
- return ReviewResult(
- content if content else "Review returned no text",
- score,
- needs_improvement,
- reviewed=True,
- error=None if score is not None else "no score found in the review",
- )
- except Exception as e:
- # A failed review must not fail the run -- the image is already
- # generated and saved -- but it must not read as a pass either.
- self._log(f"⚠ Review failed: {str(e)}")
- return ReviewResult(
- f"Review failed: {str(e)}",
- None, False, reviewed=False, error=str(e),
- )
-
- def improve_prompt(self, original_prompt: str, critique: str,
- iteration: int) -> str:
- """
- Improve the generation prompt based on critique.
-
- Args:
- original_prompt: Original user prompt
- critique: Review critique from previous iteration
- iteration: Current iteration number
-
- Returns:
- Improved prompt for next generation
- """
- improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}
-
-USER REQUEST: {original_prompt}
-
-ITERATION {iteration}: Based on previous feedback, address these specific improvements:
-{critique}
-
-Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""
-
- return improved_prompt
-
- def generate_iterative(self, user_prompt: str, output_path: str,
- iterations: int = 2,
- doc_type: str = "default") -> Dict[str, Any]:
- """
- Generate scientific schematic with smart iterative refinement.
-
- Only regenerates if the quality score is below the threshold for the
- specified document type. This saves API calls and time when the first
- generation is already good enough.
-
- Args:
- user_prompt: User's description of desired diagram
- output_path: Path to save final image
- iterations: Maximum refinement iterations (default: 2, max: 2)
- doc_type: Document type for quality threshold (journal, poster, etc.)
-
- Returns:
- Dictionary with generation results and metadata
- """
- output_path = Path(output_path)
- output_dir = output_path.parent
- output_dir.mkdir(parents=True, exist_ok=True)
-
- base_name = output_path.stem
- extension = output_path.suffix or ".png"
-
- # Get quality threshold for this document type
- threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),
- self.QUALITY_THRESHOLDS["default"])
-
- results = {
- "user_prompt": user_prompt,
- "doc_type": doc_type,
- "quality_threshold": threshold,
- "iterations": [],
- "final_image": None,
- # None, not 0.0 -- a run whose review never completed has no score,
- # and a number here would be read as one the reviewer gave.
- "final_score": None,
- "final_reviewed": False,
- "success": False,
- "early_stop": False,
- "early_stop_reason": None
- }
-
- current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}
-
-USER REQUEST: {user_prompt}
-
-Generate a publication-quality scientific diagram that meets all the guidelines above."""
-
- print(f"\n{'='*60}")
- print(f"Generating Scientific Schematic")
- print(f"{'='*60}")
- print(f"Description: {user_prompt}")
- print(f"Document Type: {doc_type}")
- print(f"Quality Threshold: {threshold}/10")
- print(f"Max Iterations: {iterations}")
- print(f"Output: {output_path}")
- print(f"{'='*60}\n")
-
- for i in range(1, iterations + 1):
- print(f"\n[Iteration {i}/{iterations}]")
- print("-" * 40)
-
- # Generate image
- print(f"Generating image...")
- image_data = self.generate_image(current_prompt)
-
- if not image_data:
- error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')
- print(f"✗ Generation failed: {error_msg}")
- results["iterations"].append({
- "iteration": i,
- "success": False,
- "error": error_msg
- })
- continue
-
- # Save iteration image
- iter_path = output_dir / f"{base_name}_v{i}{extension}"
- with open(iter_path, "wb") as f:
- f.write(image_data)
- print(f"✓ Saved: {iter_path}")
-
- # Review the image with the vision review model
- print(f"Reviewing image with {self.review_model}...")
- review = self.review_image(
- str(iter_path), user_prompt, i, doc_type, iterations
- )
- if review.score is not None:
- print(f"✓ Score: {review.score}/10 (threshold: {threshold}/10)")
- else:
- print(f"⚠ Review unavailable — image kept, quality not verified")
- print(f" Reason: {review.error}")
-
- # Save iteration results
- iteration_result = {
- "iteration": i,
- "image_path": str(iter_path),
- "prompt": current_prompt,
- "critique": review.critique,
- "score": review.score,
- "reviewed": review.reviewed,
- "review_error": review.error,
- "needs_improvement": review.needs_improvement,
- "success": True
- }
- results["iterations"].append(iteration_result)
-
- # Check if quality is acceptable - STOP EARLY if so
- if not review.needs_improvement:
- if review.score is not None:
- print(f"\n✓ Quality meets {doc_type} threshold ({review.score} >= {threshold})")
- print(f" No further iterations needed!")
- reason = (f"Quality score {review.score} meets threshold "
- f"{threshold} for {doc_type}")
- else:
- # Regenerating cannot fix a reviewer that did not answer.
- print(f"\n⚠ Stopping without a verified score — review the image yourself")
- reason = f"Review did not produce a score: {review.error}"
- results["final_image"] = str(iter_path)
- results["final_score"] = review.score
- results["final_reviewed"] = review.reviewed and review.score is not None
- results["success"] = True
- results["early_stop"] = True
- results["early_stop_reason"] = reason
- break
-
- # If this is the last iteration, we're done regardless
- if i == iterations:
- print(f"\n⚠ Maximum iterations reached")
- results["final_image"] = str(iter_path)
- results["final_score"] = review.score
- results["final_reviewed"] = review.reviewed and review.score is not None
- results["success"] = True
- break
-
- # Quality below threshold - improve prompt for next iteration
- print(f"\n⚠ Quality below threshold ({review.score} < {threshold})")
- print(f"Improving prompt based on feedback...")
- current_prompt = self.improve_prompt(user_prompt, review.critique, i + 1)
-
- # Copy final version to output path
- if results["success"] and results["final_image"]:
- final_iter_path = Path(results["final_image"])
- if final_iter_path != output_path:
- import shutil
- shutil.copy(final_iter_path, output_path)
- print(f"\n✓ Final image: {output_path}")
-
- # Save review log
- log_path = output_dir / f"{base_name}_review_log.json"
- with open(log_path, "w") as f:
- json.dump(results, f, indent=2)
- print(f"✓ Review log: {log_path}")
-
- print(f"\n{'='*60}")
- print(f"Generation Complete!")
- if results["final_score"] is not None:
- print(f"Final Score: {results['final_score']}/10")
- else:
- print(f"Final Score: unavailable (the review did not produce one)")
- if results["early_stop"]:
- print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")
- print(f"{'='*60}\n")
-
- return results
-
-
-def main():
- """Command-line interface."""
- parser = argparse.ArgumentParser(
- description="Generate scientific schematics using AI with smart iterative refinement",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""
-Examples:
- # Generate a flowchart for a journal paper
- python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal
-
- # Generate neural network architecture for presentation (lower threshold)
- python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation
-
- # Generate with custom max iterations for poster
- python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster
-
- # Verbose output
- python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v
-
-Document Types (quality thresholds):
- journal 8.5/10 - Nature, Science, peer-reviewed journals
- conference 8.0/10 - Conference papers
- thesis 8.0/10 - Dissertations, theses
- grant 8.0/10 - Grant proposals
- preprint 7.5/10 - arXiv, bioRxiv, etc.
- report 7.5/10 - Technical reports
- poster 7.0/10 - Academic posters
- presentation 6.5/10 - Slides, talks
- default 7.5/10 - General purpose
-
-Note: Multiple iterations only occur if quality is BELOW the threshold.
- If the first generation meets the threshold, no extra API calls are made.
-
-Environment:
- OPENROUTER_API_KEY OpenRouter API key (required)
- """
- )
-
- parser.add_argument("prompt", help="Description of the diagram to generate")
- parser.add_argument("-o", "--output", required=True,
- help="Output image path (e.g., diagram.png)")
- parser.add_argument("--iterations", type=int, default=2,
- help="Maximum refinement iterations (default: 2, max: 2)")
- parser.add_argument("--doc-type", default="default",
- choices=["journal", "conference", "poster", "presentation",
- "report", "grant", "thesis", "preprint", "default"],
- help="Document type for quality threshold (default: default)")
- parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")
- parser.add_argument("-v", "--verbose", action="store_true",
- help="Verbose output")
-
- args = parser.parse_args()
-
- # Check for API key — resolves --api-key, the environment, then any .env file
- api_key = _resolve_api_key(args.api_key)
- if not api_key:
- print("Error: OPENROUTER_API_KEY not found")
- print("\nSet it with:")
- print(" export OPENROUTER_API_KEY='your_api_key'")
- print("\nOr add OPENROUTER_API_KEY=your_api_key to a .env file")
- print("Or provide via --api-key flag")
- sys.exit(1)
-
- # Validate iterations - enforce max of 2
- if args.iterations < 1 or args.iterations > 2:
- print("Error: Iterations must be between 1 and 2")
- sys.exit(1)
-
- try:
- generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)
- results = generator.generate_iterative(
- user_prompt=args.prompt,
- output_path=args.output,
- iterations=args.iterations,
- doc_type=args.doc_type
- )
-
- if results["success"]:
- print(f"\n✓ Success! Image saved to: {args.output}")
- used = len([r for r in results['iterations'] if r.get('success')])
- if results.get("final_reviewed"):
- if results.get("early_stop"):
- print(f" (Completed in {used} iteration(s) - quality threshold met)")
- else:
- # The image is real; the quality claim is not. Say which.
- print(f" (Completed in {used} iteration(s) - quality NOT verified,"
- f" the review produced no score. Check the image yourself.)")
- sys.exit(0)
- else:
- print(f"\n✗ Generation failed. Check review log for details.")
- sys.exit(1)
- except Exception as e:
- print(f"\n✗ Error: {str(e)}")
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
-
diff --git a/skills/citation-management/scripts/search_google_scholar.py b/skills/citation-management/scripts/search_google_scholar.py
index 95dc3823..8f797ee9 100755
--- a/skills/citation-management/scripts/search_google_scholar.py
+++ b/skills/citation-management/scripts/search_google_scholar.py
@@ -14,6 +14,14 @@ import time
import random
from typing import List, Dict, Optional
+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
@@ -117,63 +125,41 @@ class GoogleScholarSearcher:
return results
def metadata_to_bibtex(self, metadata: Dict) -> str:
- """Convert metadata to BibTeX format."""
- # Generate citation key
- if metadata.get('authors'):
- first_author = metadata['authors'].split(',')[0].strip()
- last_name = first_author.split()[-1] if first_author else 'Unknown'
- else:
- last_name = 'Unknown'
-
- year = metadata.get('year', 'XXXX')
-
- # Get keyword from title
- import re
- title = metadata.get('title', '')
- words = re.findall(r'\b[a-zA-Z]{4,}\b', title)
- keyword = words[0].lower() if words else 'paper'
-
- citation_key = f'{last_name}{year}{keyword}'
-
+ """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.
+ """
+ # Scholar gives authors as a list; `search` joined it with ', '.
+ authors = ' and '.join(
+ part.strip() for part in metadata.get('authors', '').split(',') if part.strip()
+ )
+
+ 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:
+ 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'
-
- # Build BibTeX
- lines = [f'@{entry_type}{{{citation_key},']
-
- # Convert authors format
- if metadata.get('authors'):
- authors = metadata['authors'].replace(',', ' and')
- lines.append(f' author = {{{authors}}},')
-
- if metadata.get('title'):
- lines.append(f' title = {{{metadata["title"]}}},')
-
- if metadata.get('venue'):
- lines.append(f' {venue_field} = {{{metadata["venue"]}}},')
-
- if metadata.get('year'):
- lines.append(f' year = {{{metadata["year"]}}},')
-
- if metadata.get('url'):
- lines.append(f' url = {{{metadata["url"]}}},')
-
- if metadata.get('citations'):
- lines.append(f' note = {{Cited by: {metadata["citations"]}}},')
-
- # Remove trailing comma
- if lines[-1].endswith(','):
- lines[-1] = lines[-1][:-1]
-
- lines.append('}')
-
- return '\n'.join(lines)
+
+ 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():
diff --git a/skills/citation-management/scripts/search_openalex.py b/skills/citation-management/scripts/search_openalex.py
new file mode 100644
index 00000000..1c607895
--- /dev/null
+++ b/skills/citation-management/scripts/search_openalex.py
@@ -0,0 +1,297 @@
+#!/usr/bin/env python3
+"""
+OpenAlex Search Tool
+Search OpenAlex and export results as JSON or BibTeX.
+
+OpenAlex indexes ~250 million scholarly works across every discipline, needs no
+API key, and has a documented REST API rather than a scraped HTML surface. It
+is the third leg of this skill's coverage: PubMed is authoritative for
+biomedicine, Google Scholar is broad but fragile and rate-limited, and OpenAlex
+is broad, stable, and machine-readable.
+
+Setting OPENALEX_EMAIL (or passing --email) joins OpenAlex's "polite pool",
+which is faster and more reliably available. The address is sent to
+api.openalex.org only, as a query parameter, exactly as OpenAlex documents.
+"""
+
+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', '')
+ self.session = requests.Session()
+ self.session.headers.update({
+ 'User-Agent': 'OpenAlexSearcher/1.0 (Citation Management Tool)'
+ })
+
+ 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
+ """
+ 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(200, 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] = []
+ 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 as e:
+ print(f'Error searching OpenAlex: {e}', file=sys.stderr)
+ break
+ except ValueError as e:
+ print(f'Error: OpenAlex returned invalid JSON: {e}', file=sys.stderr)
+ break
+
+ 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', [])
+ if not works:
+ break
+
+ for work in works:
+ results.append(self._normalise(work))
+ if len(results) >= max_results:
+ break
+
+ next_cursor = payload.get('meta', {}).get('next_cursor')
+ if not next_cursor or len(results) >= max_results:
+ break
+ params['cursor'] = next_cursor
+
+ # OpenAlex asks for courteous pacing even in the polite pool.
+ 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
+ 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 (no API key required)',
+ 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='Contact email for the OpenAlex polite pool (or set OPENALEX_EMAIL)')
+
+ args = parser.parse_args()
+
+ searcher = OpenAlexSearcher(email=args.email)
+ 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,
+ )
+
+ 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()
diff --git a/skills/citation-management/scripts/search_pubmed.py b/skills/citation-management/scripts/search_pubmed.py
index 3b307bc8..f0bc118e 100755
--- a/skills/citation-management/scripts/search_pubmed.py
+++ b/skills/citation-management/scripts/search_pubmed.py
@@ -6,6 +6,7 @@ Search PubMed using E-utilities API and export results.
import sys
import os
+import re
import requests
import argparse
import json
@@ -14,6 +15,15 @@ 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."""
@@ -64,7 +74,18 @@ class PubMedSearcher:
full_query += f' AND ({pub_type_query})'
print(f'Searching PubMed: {full_query}', file=sys.stderr)
-
+
+ # ESearch caps retmax at 10000; asking for more is silently truncated,
+ # so say so rather than letting the caller believe they got everything.
+ if max_results > 10000:
+ print(
+ f'Note: ESearch returns at most 10000 records per request; '
+ 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 = {
@@ -151,6 +172,18 @@ class PubMedSearcher:
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:
@@ -187,22 +220,35 @@ class PubMedSearcher:
if not year:
medline_date = article_elem.findtext('.//Journal/JournalIssue/PubDate/MedlineDate', '')
if medline_date:
- import re
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,
- 'title': article_elem.findtext('.//ArticleTitle', ''),
+ # 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': article_elem.findtext('.//Abstract/AbstractText', '')
+ 'abstract': abstract
}
return metadata
@@ -212,58 +258,33 @@ class PubMedSearcher:
return None
def metadata_to_bibtex(self, metadata: Dict) -> str:
- """Convert metadata to BibTeX format."""
- # Generate citation key
- if metadata.get('authors'):
- first_author = metadata['authors'].split(' and ')[0]
- if ',' in first_author:
- last_name = first_author.split(',')[0].strip()
- else:
- last_name = first_author.split()[0]
- else:
- last_name = 'Unknown'
-
- year = metadata.get('year', 'XXXX')
- citation_key = f'{last_name}{year}pmid{metadata.get("pmid", "")}'
-
- # Build BibTeX entry
- lines = [f'@article{{{citation_key},']
-
- if metadata.get('authors'):
- lines.append(f' author = {{{metadata["authors"]}}},')
-
- if metadata.get('title'):
- lines.append(f' title = {{{metadata["title"]}}},')
-
- if metadata.get('journal'):
- lines.append(f' journal = {{{metadata["journal"]}}},')
-
- if metadata.get('year'):
- lines.append(f' year = {{{metadata["year"]}}},')
-
- if metadata.get('volume'):
- lines.append(f' volume = {{{metadata["volume"]}}},')
-
- if metadata.get('issue'):
- lines.append(f' number = {{{metadata["issue"]}}},')
-
- if metadata.get('pages'):
- pages = metadata['pages'].replace('-', '--')
- lines.append(f' pages = {{{pages}}},')
-
- if metadata.get('doi'):
- lines.append(f' doi = {{{metadata["doi"]}}},')
-
+ """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'):
- lines.append(f' note = {{PMID: {metadata["pmid"]}}},')
-
- # Remove trailing comma
- if lines[-1].endswith(','):
- lines[-1] = lines[-1][:-1]
-
- lines.append('}')
-
- return '\n'.join(lines)
+ fields['note'] = f'PMID: {metadata["pmid"]}'
+
+ return render_entry('article', key, fields)
def main():
diff --git a/skills/citation-management/scripts/validate_citations.py b/skills/citation-management/scripts/validate_citations.py
index ba764faf..b5bd9ef3 100755
--- a/skills/citation-management/scripts/validate_citations.py
+++ b/skills/citation-management/scripts/validate_citations.py
@@ -11,16 +11,49 @@ import argparse
import json
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'],
@@ -50,47 +83,7 @@ class CitationValidator:
Returns:
List of entry dictionaries
"""
- try:
- with open(filepath, 'r', encoding='utf-8') as f:
- content = f.read()
- except Exception as e:
- print(f'Error reading file: {e}', file=sys.stderr)
- return []
-
- entries = []
-
- # Match BibTeX entries
- pattern = r'@(\w+)\s*\{\s*([^,\s]+)\s*,(.*?)\n\}'
- matches = re.finditer(pattern, content, re.DOTALL | re.IGNORECASE)
-
- for match in matches:
- entry_type = match.group(1).lower()
- citation_key = match.group(2).strip()
- fields_text = match.group(3)
-
- # Parse fields
- fields = {}
- field_pattern = r'(\w+)\s*=\s*\{([^}]*)\}|(\w+)\s*=\s*"([^"]*)"'
- field_matches = re.finditer(field_pattern, fields_text)
-
- for field_match in field_matches:
- if field_match.group(1):
- field_name = field_match.group(1).lower()
- field_value = field_match.group(2)
- else:
- field_name = field_match.group(3).lower()
- field_value = field_match.group(4)
-
- fields[field_name] = field_value.strip()
-
- entries.append({
- 'type': entry_type,
- 'key': citation_key,
- 'fields': fields,
- 'raw': match.group(0)
- })
-
- return entries
+ return _parse_bibtex_file(filepath)
def validate_entry(self, entry: Dict) -> Tuple[List[Dict], List[Dict]]:
"""
@@ -208,33 +201,41 @@ class CitationValidator:
Returns:
Tuple of (is_valid, metadata)
"""
+ # 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:
- url = f'https://doi.org/{doi}'
- response = self.session.head(url, timeout=10, allow_redirects=True)
-
- if response.status_code < 400:
- # DOI resolves, now get metadata from CrossRef
- crossref_url = f'https://api.crossref.org/works/{doi}'
- metadata_response = self.session.get(crossref_url, timeout=10)
-
- if metadata_response.status_code == 200:
- data = metadata_response.json()
- message = data.get('message', {})
-
- # Extract key metadata
- metadata = {
- 'title': message.get('title', [''])[0],
- 'year': self._extract_year_crossref(message),
- 'authors': self._format_authors_crossref(message.get('author', [])),
- }
- return True, metadata
- else:
- return True, None # DOI resolves but no CrossRef metadata
- else:
+ 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', {})
+
+ # 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:
+ return True, None
return False, None
-
- except Exception:
- return False, None
+
+ # Any other status is a transport problem on our side, not
+ # evidence that the DOI is bad.
+ return True, None
+
+ except requests.exceptions.RequestException:
+ return True, None
def detect_duplicates(self, entries: List[Dict]) -> List[Dict]:
"""
@@ -418,31 +419,11 @@ class CitationValidator:
# Count and Venue verification logic
count_errors = []
count_warnings = []
-
+
target_min = None
target_max = None
venue_name = None
-
- self.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')
- }
-
+
if venue:
v_lower = venue.lower().strip()
if v_lower in self.venue_standards:
@@ -455,26 +436,25 @@ class CitationValidator:
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:
- # Determine critical threshold (e.g. 70% of target minimum)
- critical_min = int(target_min * 0.7)
- if critical_min < 1:
- critical_min = 1
-
- if total_count < critical_min:
+ if min_count is not None and total_count < min_count:
count_errors.append({
- 'type': 'critically_low_citation_count',
+ 'type': 'below_requested_minimum',
'severity': 'high',
- 'message': f'Total citation entries count ({total_count}) is critically low for {venue_name or "specified standard"}. Expected at least {target_min} citations.'
+ '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 count ({total_count}) is below the recommended standard for {venue_name or "specified standard"}. Expected {target_min}-{target_max or "+"} citations.'
+ '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,
@@ -519,29 +499,35 @@ class CitationValidator:
# Check the count of ACTUALLY used citations
actual_count = len(cited_keys) - len(missing_keys)
if target_min is not None:
- critical_min = int(target_min * 0.7)
- if critical_min < 1:
- critical_min = 1
- if actual_count < critical_min:
+ if min_count is not None and actual_count < min_count:
count_errors.append({
- 'type': 'critically_low_manuscript_citation_count',
+ 'type': 'manuscript_below_requested_minimum',
'severity': 'high',
- 'message': f'The number of cited references in the manuscript ({actual_count}) is critically low for {venue_name or "specified standard"}. Expected at least {target_min} actually cited references.'
+ '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 number of cited references in the manuscript ({actual_count}) is below the recommended standard for {venue_name or "specified standard"}. Expected {target_min}-{target_max or "+"} cited references.'
+ '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([e for e in all_errors if e['severity'] == 'high']),
+ 'valid_entries': len(entries) - len(entries_with_errors & bib_keys_present),
'errors': all_errors,
'warnings': all_warnings,
'duplicates': duplicates,
@@ -596,15 +582,9 @@ def main():
help='Verify DOIs resolve correctly (slow)'
)
- parser.add_argument(
- '--auto-fix',
- action='store_true',
- help='Attempt to auto-fix common issues (not implemented yet)'
- )
-
parser.add_argument(
'--report',
- help='Output file for JSON validation report'
+ help='Output file for the JSON validation report'
)
parser.add_argument(
diff --git a/tests/_contract/office.py b/tests/_contract/office.py
index 2954c0b1..cd4760b2 100644
--- a/tests/_contract/office.py
+++ b/tests/_contract/office.py
@@ -39,7 +39,6 @@ SHARED_FILES: tuple[tuple[str, tuple[str, ...]], ...] = (
"scientific-schematics",
"latex-posters",
"literature-review",
- "citation-management",
"scientific-slides",
),
),
@@ -49,7 +48,6 @@ SHARED_FILES: tuple[tuple[str, tuple[str, ...]], ...] = (
"scientific-schematics",
"latex-posters",
"literature-review",
- "citation-management",
"scientific-slides",
),
),
diff --git a/tests/_contract/schematic.py b/tests/_contract/schematic.py
index 6a7b6862..efc5493a 100644
--- a/tests/_contract/schematic.py
+++ b/tests/_contract/schematic.py
@@ -1,9 +1,9 @@
"""Shared tests for the AI schematic generator bundled by several skills.
-`scientific-schematics`, `latex-posters`, `literature-review`,
-`citation-management`, and `scientific-slides` each ship a byte-identical
+`scientific-schematics`, `latex-posters`, `literature-review`, and
+`scientific-slides` each ship a byte-identical
`scripts/generate_schematic.py` (a thin CLI) and `scripts/generate_schematic_ai.py`
-(the generator). Rather than write the same tests five times, each suite
+(the generator). Rather than write the same tests four times, each suite
instantiates the factories below against its own copy; `tests/_meta` separately
pins the copies together.
diff --git a/tests/citation-management/test_scripts.py b/tests/citation-management/test_scripts.py
index ab77db85..f51157cc 100644
--- a/tests/citation-management/test_scripts.py
+++ b/tests/citation-management/test_scripts.py
@@ -1,13 +1,12 @@
"""Tests for the citation-management BibTeX tooling.
-Two of this skill's scripts reach the network (Crossref, PubMed, Scholar) and
-two are pure text processing. The pure half is where citation errors are
-actually introduced -- a page range silently rewritten, a DOI left with its URL
-prefix so lookups fail, two distinct papers merged because they share a key --
-so that is what the suite drives, end to end through real `.bib` files.
-
-The schematic scripts this skill also ships come from the shared contract;
-five skills carry byte-identical copies.
+Four of this skill's scripts reach the network (Crossref, PubMed, OpenAlex,
+Scholar); the parsing, rendering, and validation layers underneath them are
+pure text processing. The pure half is where citation errors are actually
+introduced -- a page range silently rewritten, a title truncated at a nested
+brace, a DOI left with its URL prefix so lookups fail, two distinct papers
+merged because they share a key -- so that is what the suite drives, end to end
+through real `.bib` files.
"""
from __future__ import annotations
@@ -23,17 +22,20 @@ SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "citation-manageme
SCRIPTS = SKILL_ROOT / "scripts"
sys.path.insert(0, str(SCRIPTS))
+import _common # noqa: E402
import format_bibtex # noqa: E402
import validate_citations # noqa: E402
-SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT)
-ReviewParsingTests = skill_contract.schematic.review_parsing_test_case(
- SCRIPTS, "generate_schematic_ai"
-)
-ReviewFailureTests = skill_contract.schematic.review_failure_test_case(
- SCRIPTS, "generate_schematic_ai", "ScientificSchematicGenerator",
- ("diagram.png", "a prompt", 1, "journal", 2),
-)
+try: # the network-facing scripts need requests; the pure layers do not
+ import extract_metadata # noqa: E402
+ import search_openalex # noqa: E402
+ import search_pubmed # noqa: E402
+
+ REQUESTS_AVAILABLE = True
+except ImportError: # pragma: no cover - exercised only without requests
+ REQUESTS_AVAILABLE = False
+
+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)
BIBLIOGRAPHY = """\
@article{jumper2021,
@@ -92,16 +94,47 @@ class ParsingTests(BibTeXTestCase):
self.assertEqual(len(entries), 1)
self.assertEqual(entries[0]["key"], "a")
- def test_an_entry_closed_on_the_same_line_is_not_recognised(self) -> None:
- # The entry pattern anchors on `\n}`, so the closing brace must start a
- # line. Single-line entries are legal BibTeX but are skipped silently --
- # pinned here so the limitation is visible rather than surprising.
+ def test_an_entry_closed_on_the_same_line_is_recognised(self) -> None:
+ # Single-line entries are legal BibTeX. The brace-depth parser reads
+ # them; the regex it replaced anchored on `\n}` and skipped them.
+ entries = self.formatter.parse_bibtex_file(
+ self.bib("@article{a, title = {T}, year = {2020}}\n")
+ )
+ self.assertEqual(len(entries), 1)
+ self.assertEqual(entries[0]["fields"]["title"], "T")
+
+ def test_a_nested_brace_in_a_title_survives_parsing(self) -> None:
+ # Capitalisation protection puts braces inside a field value. A
+ # `\{([^}]*)\}` field pattern truncates at the inner brace and silently
+ # corrupts the bibliography, which is what this guards.
+ entries = self.formatter.parse_bibtex_file(
+ self.bib(
+ "@article{a,\n"
+ " title = {Prediction with {AlphaFold} and {DNA} data},\n"
+ " year = {2021}\n}\n"
+ )
+ )
self.assertEqual(
- self.formatter.parse_bibtex_file(
- self.bib("@article{a, title = {T}, year = {2020}}\n")
- ),
- [],
+ entries[0]["fields"]["title"],
+ "Prediction with {AlphaFold} and {DNA} data",
+ )
+
+ def test_a_comma_inside_a_field_does_not_split_the_field(self) -> None:
+ entries = self.formatter.parse_bibtex_file(
+ self.bib('@article{a,\n title = {One, two, three},\n year = {2021}\n}\n')
+ )
+ self.assertEqual(entries[0]["fields"]["title"], "One, two, three")
+ self.assertEqual(entries[0]["fields"]["year"], "2021")
+
+ def test_string_and_comment_blocks_are_not_treated_as_entries(self) -> None:
+ entries = self.formatter.parse_bibtex_file(
+ self.bib(
+ '@string{nat = "Nature"}\n'
+ "@comment{not an entry}\n"
+ "@article{a,\n title = {T},\n year = {2021}\n}\n"
+ )
)
+ self.assertEqual([e["key"] for e in entries], ["a"])
def test_quoted_field_values_are_read_as_well_as_braced_ones(self) -> None:
entries = self.formatter.parse_bibtex_file(
@@ -278,6 +311,30 @@ class RenderTests(BibTeXTestCase):
)
self.assertEqual(rendered.count("{"), rendered.count("}"))
+ def test_a_protected_title_round_trips_without_losing_a_brace(self) -> None:
+ # The regression that motivated the parser rewrite: this pipeline
+ # previously emitted `{... with {AlphaFold}` -- one brace short, so the
+ # file no longer compiled and every later entry was swallowed.
+ source = (
+ "@article{a,\n"
+ " title = {Prediction with {AlphaFold}},\n"
+ " author = {Jumper, John},\n"
+ " journal = {Nature},\n"
+ " year = {2021}\n}\n"
+ )
+ rendered = self.formatter.format_entry(
+ self.formatter.parse_bibtex_file(self.bib(source))[0]
+ )
+ self.assertEqual(rendered.count("{"), rendered.count("}"))
+ self.assertIn("{Prediction with {AlphaFold}}", rendered)
+
+ def test_formatting_is_idempotent(self) -> None:
+ first = self.formatter.format_file(self.bib(), output=None)
+ path = self.root / "once.bib"
+ path.write_text(first, encoding="utf-8")
+ second = self.formatter.format_file(str(path), output=None)
+ self.assertEqual(first, second)
+
class EndToEndTests(BibTeXTestCase):
def test_formatting_a_file_applies_every_fix(self) -> None:
@@ -350,6 +407,242 @@ class ValidationTests(BibTeXTestCase):
manuscript.write_text("No citations here.\n", encoding="utf-8")
self.assertEqual(self.validator.parse_manuscript_citations(str(manuscript)), [])
+ def test_the_valid_entry_count_never_goes_negative(self) -> None:
+ # Several errors can land on one entry. Subtracting the error *count*
+ # from the entry count reported `Valid entries: -2` for a one-entry
+ # file, so the figure counts distinct failing entries instead.
+ path = self.bib("@article{a,\n title = {T}\n}\n")
+ report = self.validator.validate_file(path)
+ self.assertEqual(report["total_entries"], 1)
+ self.assertEqual(report["valid_entries"], 0)
+ self.assertGreater(len(report["errors"]), 1)
+
+ def test_a_venue_shortfall_is_a_warning_not_an_error(self) -> None:
+ # Reference-list length is editorial judgement, so falling under a
+ # venue rule of thumb must not fail the run.
+ report = self.validator.validate_file(self.bib(), venue="nature")
+ self.assertTrue(
+ any(w["type"] == "low_citation_count" for w in report["warnings"])
+ )
+ self.assertFalse(
+ any(e.get("type", "").startswith("critically_low") for e in report["errors"])
+ )
+
+ def test_an_explicit_min_count_is_enforced_as_an_error(self) -> None:
+ report = self.validator.validate_file(self.bib(), min_count=10)
+ self.assertTrue(
+ any(e["type"] == "below_requested_minimum" for e in report["errors"])
+ )
+
+ def test_venue_standards_are_available_without_running_a_validation(self) -> None:
+ self.assertIn("nature", validate_citations.CitationValidator().venue_standards)
+
+
+class PageTests(unittest.TestCase):
+ def test_a_single_hyphen_range_becomes_an_en_dash_range(self) -> None:
+ self.assertEqual(_common.format_pages("583-589"), "583--589")
+
+ def test_an_already_correct_range_is_not_doubled(self) -> None:
+ # A blanket `replace('-', '--')` turned this into `583----589`.
+ self.assertEqual(_common.format_pages("583--589"), "583--589")
+
+ def test_an_abbreviated_end_page_is_expanded(self) -> None:
+ # PubMed's MedlinePgn abbreviates the end page; `1123--30` is not a
+ # page range any reader or reference manager can resolve.
+ self.assertEqual(_common.format_pages("1123-30"), "1123--1130")
+ self.assertEqual(_common.format_pages("95-7"), "95--97")
+
+ def test_an_article_number_is_left_alone(self) -> None:
+ for raw in ("e0123456", "e70246", "12", "1,3,5"):
+ with self.subTest(raw=raw):
+ self.assertEqual(_common.format_pages(raw), raw)
+
+ def test_a_pp_prefix_is_stripped(self) -> None:
+ self.assertEqual(_common.format_pages("pp. 5998--6008"), "5998--6008")
+
+ def test_an_en_dash_is_normalised(self) -> None:
+ self.assertEqual(_common.format_pages("583–589"), "583--589")
+
+ def test_an_empty_value_yields_an_empty_string(self) -> None:
+ self.assertEqual(_common.format_pages(None), "")
+
+
+class CitationKeyTests(unittest.TestCase):
+ def test_a_comma_separated_name_uses_the_surname(self) -> None:
+ self.assertEqual(
+ _common.citation_key("Jumper, John", "2021", "Highly accurate prediction"),
+ "Jumper2021highly",
+ )
+
+ def test_a_pubmed_style_name_uses_the_leading_surname(self) -> None:
+ # `Smith JA` is surname-first; taking the last token yields `JA`.
+ self.assertEqual(_common.citation_key("Smith JA", "2021", "A study"), "Smith2021study")
+
+ def test_a_western_style_name_uses_the_trailing_surname(self) -> None:
+ self.assertEqual(_common.citation_key("John Smith", "2021", "A study"), "Smith2021study")
+
+ def test_accents_and_punctuation_are_removed(self) -> None:
+ # A key reaches LaTeX and sometimes a file path, and its source is a
+ # publisher-controlled record.
+ self.assertEqual(_common.citation_key("Müller, Hans", "2021", "A study"), "Muller2021study")
+ self.assertEqual(_common.citation_key("O'Brien, Pat", "2021", "A study"), "OBrien2021study")
+
+ def test_a_key_is_always_safe_to_use(self) -> None:
+ for authors in ("", "$(rm -rf /)", "van der Berg, Jan", "李, 明"):
+ with self.subTest(authors=authors):
+ key = _common.citation_key(authors, "2021", "A study")
+ self.assertRegex(key, r"^[A-Za-z0-9]+$")
+
+ def test_a_missing_year_becomes_a_placeholder(self) -> None:
+ self.assertTrue(_common.citation_key("Smith, J", "", "A study").startswith("SmithXXXX"))
+
+ def test_the_same_paper_from_two_sources_gets_the_same_key(self) -> None:
+ # This is what makes cross-source deduplication possible at all.
+ crossref = _common.citation_key("Jumper, John", "2021", "Highly accurate prediction")
+ pubmed = _common.citation_key("Jumper J", "2021", "Highly accurate prediction")
+ self.assertEqual(crossref, pubmed)
+
+
+class TitleProtectionTests(unittest.TestCase):
+ def test_an_acronym_is_braced(self) -> None:
+ self.assertEqual(
+ _common.protect_title("Prediction with AlphaFold"),
+ "Prediction with {AlphaFold}",
+ )
+
+ def test_protection_is_idempotent(self) -> None:
+ once = _common.protect_title("Editing DNA with CRISPR")
+ self.assertEqual(_common.protect_title(once), once)
+
+ def test_an_acronym_inside_a_longer_word_is_untouched(self) -> None:
+ self.assertEqual(_common.protect_title("Studies of mRNA"), "Studies of {mRNA}")
+ self.assertNotIn("{RNA}", _common.protect_title("Studies of mRNA"))
+
+
+class RekeyTests(BibTeXTestCase):
+ def test_entries_are_rekeyed_to_the_shared_scheme(self) -> None:
+ entries = self.formatter.parse_bibtex_file(self.bib())
+ rekeyed = self.formatter.rekey_entries(entries)
+ self.assertEqual(rekeyed[0]["key"], "Jumper2021highly")
+
+ def test_a_key_collision_gets_a_suffix(self) -> None:
+ entries = [
+ {"key": "x", "type": "article", "fields": {"author": "Smith, J", "year": "2021", "title": "A study"}},
+ {"key": "y", "type": "article", "fields": {"author": "Smith, J", "year": "2021", "title": "A study"}},
+ ]
+ keys = [e["key"] for e in self.formatter.rekey_entries(entries)]
+ self.assertEqual(len(set(keys)), 2)
+ self.assertEqual(keys[0], "Smith2021study")
+
+
[email protected](REQUESTS_AVAILABLE, "requests is not installed")
+class EntryRenderingTests(unittest.TestCase):
+ """The BibTeX each extractor emits, without touching the network."""
+
+ def setUp(self) -> None:
+ self.extractor = extract_metadata.MetadataExtractor()
+
+ def _fields(self, bibtex: str) -> dict:
+ return _common.parse_bibtex(bibtex)[0]["fields"]
+
+ def test_a_book_keeps_its_publisher(self) -> None:
+ # `publisher` was extracted from Crossref and then dropped by the
+ # writer, so every @book failed its own required-field check.
+ bibtex = self.extractor.metadata_to_bibtex({
+ "entry_type": "book", "authors": "Smith, John", "title": "A Book",
+ "year": "2021", "publisher": "Springer",
+ })
+ self.assertEqual(self._fields(bibtex)["publisher"], "Springer")
+
+ def test_a_report_maps_its_publisher_to_institution(self) -> None:
+ bibtex = self.extractor.metadata_to_bibtex({
+ "entry_type": "techreport", "authors": "Smith, John", "title": "A Report",
+ "year": "2021", "publisher": "NIST",
+ })
+ self.assertEqual(self._fields(bibtex)["institution"], "NIST")
+
+ def test_a_chapter_uses_booktitle_rather_than_journal(self) -> None:
+ fields = self._fields(self.extractor.metadata_to_bibtex({
+ "entry_type": "incollection", "authors": "Smith, John", "title": "A Chapter",
+ "year": "2021", "journal": "A Collection", "publisher": "Springer",
+ }))
+ self.assertEqual(fields["booktitle"], "A Collection")
+ self.assertNotIn("journal", fields)
+
+ def test_an_unpublished_preprint_is_misc_not_a_journalless_article(self) -> None:
+ # arXiv mints DOIs for unpublished preprints, so a DOI alone must not
+ # promote an entry to @article -- that yields an article with no
+ # journal, which fails validation every time.
+ fields = self._fields(self.extractor.metadata_to_bibtex({
+ "type": "arxiv", "entry_type": "misc", "arxiv_id": "2103.00020",
+ "authors": "Radford, Alec", "title": "A Preprint", "year": "2021",
+ }))
+ self.assertEqual(fields["note"], "Preprint")
+ self.assertIn("arXiv", fields["howpublished"])
+
+ def test_a_published_preprint_gains_its_journal(self) -> None:
+ journal = self.extractor._journal_from_arxiv_ref("Nature 596, 583-589 (2021)")
+ self.assertEqual(journal, "Nature")
+
+ def test_only_one_note_field_is_emitted(self) -> None:
+ # Two `note` lines in one entry is a BibTeX error.
+ bibtex = self.extractor.metadata_to_bibtex({
+ "type": "arxiv", "entry_type": "misc", "arxiv_id": "2103.1",
+ "pmid": "123", "authors": "Smith, John", "title": "T", "year": "2021",
+ })
+ self.assertEqual(bibtex.count("note "), 1)
+
+ def test_a_pubmed_entry_key_is_shared_scheme_and_pages_expand(self) -> None:
+ bibtex = search_pubmed.PubMedSearcher().metadata_to_bibtex({
+ "authors": "Müller, Hans", "year": "2021", "pmid": "1",
+ "title": "Deep learning methods", "journal": "Nature", "pages": "1123-30",
+ })
+ self.assertIn("@article{Muller2021deep,", bibtex)
+ self.assertEqual(self._fields(bibtex)["pages"], "1123--1130")
+
+
[email protected](REQUESTS_AVAILABLE, "requests is not installed")
+class OpenAlexTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.searcher = search_openalex.OpenAlexSearcher()
+
+ def test_an_abstract_is_rebuilt_from_its_inverted_index(self) -> None:
+ self.assertEqual(
+ self.searcher._abstract({"Deep": [0], "learning": [1], "works": [2]}),
+ "Deep learning works",
+ )
+
+ def test_an_absent_abstract_yields_an_empty_string(self) -> None:
+ self.assertEqual(self.searcher._abstract(None), "")
+
+ def test_a_work_is_flattened_to_the_shared_metadata_shape(self) -> None:
+ record = self.searcher._normalise({
+ "id": "https://openalex.org/W1",
+ "doi": "https://doi.org/10.1/x",
+ "title": "A Paper",
+ "publication_year": 2021,
+ "type": "article",
+ "authorships": [{"author": {"display_name": "Jane Doe"}}],
+ "primary_location": {"source": {"display_name": "Nature"}},
+ "biblio": {"volume": "596", "issue": "7873", "first_page": "583", "last_page": "589"},
+ "cited_by_count": 10,
+ })
+ self.assertEqual(record["doi"], "10.1/x") # the URL prefix is stripped
+ self.assertEqual(record["authors"], "Jane Doe")
+ self.assertEqual(record["journal"], "Nature")
+ self.assertEqual(record["pages"], "583-589")
+
+ def test_a_single_page_work_does_not_become_a_range(self) -> None:
+ record = self.searcher._normalise({"biblio": {"first_page": "7", "last_page": "7"}})
+ self.assertEqual(record["pages"], "7")
+
+ def test_a_preprint_renders_as_misc(self) -> None:
+ bibtex = self.searcher.metadata_to_bibtex({
+ "type": "preprint", "authors": "Jane Doe", "title": "A Preprint",
+ "year": "2021", "doi": "10.1/x",
+ })
+ self.assertTrue(bibtex.startswith("@misc{"))
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/skill-requirements.toml b/tests/skill-requirements.toml
index e5103828..8cf21342 100644
--- a/tests/skill-requirements.toml
+++ b/tests/skill-requirements.toml
@@ -95,15 +95,12 @@ packages = ["matplotlib", "seaborn", "plotly", "pypdf", "pillow", "numpy"]
# --- literature and research workflow -------------------------------------
[skills.citation-management]
+# The BibTeX parsing, rendering, and validation layers are standard library
+# (scripts/_common.py). `requests` covers Crossref, PubMed, OpenAlex, and the
+# DataCite fallback; `scholarly` is needed only by search_google_scholar.py.
packages = [
- "bibtexparser",
- "biopython",
- "crossref-commons",
- "pylatexenc",
- "scholarly",
- "selenium",
"requests",
- "python-dotenv",
+ "scholarly",
]
[skills.pyzotero]