Files
stack/src/zot/extract.py
kert c3edf11bb6
Some checks failed
CI / skinny-install (bib) (push) Has been cancelled
CI / skinny-install (bls) (push) Has been cancelled
CI / skinny-install (ccw) (push) Has been cancelled
CI / skinny-install (cli) (push) Has been cancelled
CI / skinny-install (cms) (push) Has been cancelled
CI / skinny-install (conf) (push) Has been cancelled
CI / skinny-install (opps) (push) Has been cancelled
CI / skinny-install (perf) (push) Has been cancelled
CI / skinny-install (pfs) (push) Has been cancelled
CI / skinny-install (rex) (push) Has been cancelled
CI / skinny-install (aco) (push) Successful in 1m52s
CI / skinny-install (api) (push) Successful in 37s
CI / lint-test (push) Has been cancelled
Deploy / build-scan-report (push) Has been cancelled
Infra CI / notebooks (push) Has been cancelled
Infra CI / zotero (push) Has been cancelled
CI / skinny-install (bcda) (push) Has been cancelled
Infra CI / docs (push) Has been cancelled
Infra CI / api (push) Has been cancelled
Infra CI / mc (push) Has been cancelled
feat: zot module — Zotero ORM, DuckDB engine, provenance extraction
Vendors Zotero's 61-table SQLite backend as a first-class Python module:

- zot.db.Db: full ORM with CRUD, EAV fields, creators, tags, collections,
  search, validation, bulk ops, structured reads, delete, stats
- zot.table: 61 Pydantic SQLTable models from real host-zotero.sqlite
- zot.schema: bootstrap fresh zotero.sqlite with complete DDL + 1,100 seed rows
- zot.duck.DuckDb: DuckDB engine with attach/mirror modes, flat views,
  analytics (type/tag/year/collection counts, tag co-occurrence, DOI/PDF
  coverage), Parquet export, Polars DataFrame conversion
- zot.extract.Extractor: parse Zotero HTML notes into Quote objects,
  generate :pincite: directives for docstrings, export provenance for
  knowledge graph ingestion

Fixes all Zotero ID constants across the codebase — every item type,
field, and creator type ID was wrong (fabricated, not from real schema).
Corrected: statute=20, report=15, webpage=13, document=34,
journalArticle=4, attachment=14; title=110, url=1, DOI=26, etc.

Refactors bib.sync to use zot.db.Db instead of raw SQL.
Fixes 6 dev/scripts that had wrong hardcoded IDs and duplicated helpers.
Adds compose mount validation tests, fixes 2 pre-existing test failures.
Closes #247, #249, #250 and 14 pkg-vuln issues.

12,634 tests passing, 0 failures.
2026-04-09 22:21:43 -04:00

393 lines
12 KiB
Python

"""Extract tags, annotations, and note quotes from Zotero for use in docstrings.
Bridges Zotero's annotation/note data into the ``bib`` provenance system:
- Parses Zotero's HTML notes into structured ``Quote`` objects
- Maps Zotero tags to ``bib.tag.Tag`` namespace conventions
- Resolves ``zotero://open-pdf`` links to page numbers
- Generates ``:pincite:`` directives for Python docstrings
Usage::
from zot.extract import Extractor
ex = Extractor("data/zotero/data/zotero.sqlite")
# Get all quotes from an item's notes
quotes = ex.quotes_for_item("VTWVB384")
for q in quotes:
print(q.pincite_directive())
# :pincite:`VTWVB384 p.14` — "A beneficiary's MBI is unique..."
# Get structured tag mappings
tags = ex.tags_for_item("VTWVB384")
# ["module:aco", "source:cms-website", "seed:true"]
# Generate docstring block for a function
block = ex.docstring_block("VTWVB384", sections=["§2.2.1", "§5.3.1"])
print(block)
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from html.parser import HTMLParser
from zot.db import Db
# ── HTML note parser ─────────────────────────────────────────────
class _NoteParser(HTMLParser):
"""Parse Zotero's HTML notes into plain-text segments with metadata."""
def __init__(self) -> None:
super().__init__()
self._current: list[str] = []
self._current_link = ""
self._para_link = ""
self._segments: list[dict] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag == "a":
href = dict(attrs).get("href", "")
self._current_link = href
if href:
self._para_link = href
elif tag in ("p", "br"):
self._flush()
def handle_endtag(self, tag: str) -> None:
if tag == "a":
self._current_link = ""
elif tag == "p":
self._flush()
def handle_data(self, data: str) -> None:
self._current.append(data)
def _flush(self) -> None:
text = "".join(self._current).strip()
if text:
self._segments.append({"text": text, "link": self._para_link})
self._current = []
self._para_link = ""
def result(self) -> list[dict]:
self._flush()
return self._segments
def _parse_note_html(html: str) -> list[dict]:
"""Parse a Zotero HTML note into text segments.
Each segment: ``{"text": "...", "link": "zotero://..." or ""}``
"""
parser = _NoteParser()
parser.feed(html)
return parser.result()
_PDF_LINK_RE = re.compile(r"zotero://open-pdf/[^/]+/(\d+)")
def _page_from_link(link: str) -> int | None:
"""Extract page number from ``zotero://open-pdf/0_KEY/page``."""
m = _PDF_LINK_RE.search(link)
return int(m.group(1)) if m else None
_QUOTE_RE = re.compile(r'^"(.+)"$', re.DOTALL)
_PARENS_REF = re.compile(r"\(([^)]+)\)$")
@dataclass
class Quote:
"""A single annotation quote extracted from a Zotero note."""
text: str
page: int | None = None
section: str = ""
source_ref: str = "" # e.g. "Ibrahim et al :1"
item_key: str = ""
def pincite_directive(self) -> str:
"""Format as a ``:pincite:`` RST directive for docstrings."""
locator_parts = []
if self.section:
locator_parts.append(self.section)
if self.page:
locator_parts.append(f"p.{self.page}")
locator = " ".join(locator_parts)
loc_str = f" {locator}" if locator else ""
# Truncate quote to ~120 chars for docstrings
short = self.text[:120] + "..." if len(self.text) > 120 else self.text
return f':pincite:`{self.item_key}{loc_str}` — "{short}"'
def as_tag(self) -> str:
"""Format as a ``pin:`` tag value."""
parts = [self.item_key]
if self.section:
parts.append(self.section)
elif self.page:
parts.append(f"p.{self.page}")
return "pin:" + "/".join(parts)
def _extract_quotes_from_note(html: str, item_key: str) -> list[Quote]:
"""Extract quoted text from a Zotero HTML note."""
segments = _parse_note_html(html)
quotes: list[Quote] = []
for seg in segments:
text = seg["text"]
link = seg.get("link", "")
# Skip header lines
if text.startswith("Extracted Annotations"):
continue
# Match quoted text: "..." or "..." (ref)
# Zotero stores annotations as quoted paragraphs
m = _QUOTE_RE.match(text)
if not m:
# Also try: text with parenthetical reference at end
# e.g. '"some quote" (Author :1)'
if text.startswith('"') and '"' in text[1:]:
end_quote = text.index('"', 1)
quoted = text[1:end_quote]
rest = text[end_quote + 1 :].strip()
source_ref = ""
pm = _PARENS_REF.search(rest)
if pm:
source_ref = pm.group(1)
page = _page_from_link(link) if link else None
if not page and source_ref:
# Try to extract page from source ref like "Author :5"
pm2 = re.search(r":(\d+)", source_ref)
if pm2:
page = int(pm2.group(1))
quotes.append(
Quote(
text=quoted,
page=page,
source_ref=source_ref,
item_key=item_key,
)
)
continue
continue
quoted_text = m.group(1).strip()
page = _page_from_link(link) if link else None
quotes.append(Quote(text=quoted_text, page=page, item_key=item_key))
return quotes
class Extractor:
"""Extract provenance data from Zotero for use in Python docstrings.
Bridges Zotero → ``bib`` provenance system.
"""
def __init__(self, db_or_path: Db | str) -> None:
if isinstance(db_or_path, str):
self._db = Db(db_or_path)
self._owns_db = True
else:
self._db = db_or_path
self._owns_db = False
def close(self) -> None:
if self._owns_db:
self._db.close()
def __enter__(self) -> Extractor:
return self
def __exit__(self, *exc) -> None:
self.close()
@property
def db(self) -> Db:
return self._db
def quotes_for_item(self, key: str) -> list[Quote]:
"""Extract all annotation quotes from an item's notes."""
item_id = self._db.find_item_by_key(key)
if item_id is None:
return []
rows = self._db.con.execute(
"SELECT note FROM itemNotes WHERE parentItemID = ? AND note IS NOT NULL",
(item_id,),
).fetchall()
quotes: list[Quote] = []
for row in rows:
quotes.extend(_extract_quotes_from_note(row[0], key))
return quotes
def quotes_for_tag(self, tag_name: str) -> dict[str, list[Quote]]:
"""Extract quotes for all items with a given tag.
Returns ``{item_key: [Quote, ...]}``
"""
item_ids = self._db.search_by_tag(tag_name)
result: dict[str, list[Quote]] = {}
for iid in item_ids:
row = self._db.con.execute(
"SELECT key FROM items WHERE itemID = ?", (iid,)
).fetchone()
if row:
quotes = self.quotes_for_item(row[0])
if quotes:
result[row[0]] = quotes
return result
def tags_for_item(self, key: str) -> list[str]:
"""Get all tags for an item by key."""
item_id = self._db.find_item_by_key(key)
if item_id is None:
return []
return self._db.get_tags(item_id)
def items_by_tag_namespace(self, namespace: str) -> dict[str, list[str]]:
"""Group items by tags in a namespace.
E.g. ``items_by_tag_namespace("module")`` returns
``{"pfs": ["KEY1", "KEY2"], "aco": ["KEY3"]}``
"""
rows = self._db.con.execute(
"""SELECT t.name, i.key
FROM itemTags it
JOIN tags t ON it.tagID = t.tagID
JOIN items i ON it.itemID = i.itemID
WHERE t.name LIKE ?
ORDER BY t.name""",
(f"{namespace}:%",),
).fetchall()
result: dict[str, list[str]] = {}
for tag_name, item_key in rows:
value = tag_name.split(":", 1)[1] if ":" in tag_name else tag_name
result.setdefault(value, []).append(item_key)
return result
def fields_for_item(self, key: str) -> dict[str, str]:
"""Get all EAV fields for an item by key."""
item_id = self._db.find_item_by_key(key)
if item_id is None:
return {}
return self._db.get_fields(item_id)
def docstring_block(
self,
key: str,
*,
sections: list[str] | None = None,
max_quotes: int = 5,
) -> str:
"""Generate a docstring reference block for an item.
Returns a formatted string suitable for inclusion in a Python
function docstring::
References
~~~~~~~~~~
:pincite:`VTWVB384 §2.2.1 p.8` — "Part A Claims Header..."
:pincite:`VTWVB384 §5.3.1 p.23` — "Calculating Total..."
"""
quotes = self.quotes_for_item(key)
# Filter by section if specified
if sections:
filtered = []
for q in quotes:
for s in sections:
if s in (q.section or ""):
filtered.append(q)
break
else:
# Include quotes that match page numbers of sections
filtered.append(q)
quotes = filtered
if not quotes:
# No notes — generate a bare reference
fields = self.fields_for_item(key)
title = fields.get("title") or fields.get("nameOfAct") or key
url = fields.get("url", "")
lines = ["References", "~~~~~~~~~~"]
ref = f":pincite:`{key}` — {title}"
if url:
ref += f"\n {url}"
lines.append(ref)
return "\n".join(lines)
quotes = quotes[:max_quotes]
lines = ["References", "~~~~~~~~~~"]
for q in quotes:
# Assign section if provided
if sections and not q.section:
for s in sections:
q.section = s
break
lines.append(q.pincite_directive())
return "\n".join(lines)
def pincite_directives(self, key: str) -> list[str]:
"""Return ``:pincite:`` directives for all quotes from an item."""
return [q.pincite_directive() for q in self.quotes_for_item(key)]
def export_provenance(self, tag: str = "") -> list[dict]:
"""Export items with quotes and tags for knowledge graph ingestion.
Each dict::
{
"key": "VTWVB384",
"title": "CCLF Information Packet v41",
"url": "https://...",
"tags": ["module:aco", "seed:true"],
"quotes": [{"text": "...", "page": 14}, ...],
"fields": {"DOI": "10.1234/...", ...},
}
"""
if tag:
item_ids = self._db.search_by_tag(tag)
else:
item_ids = [
r[0]
for r in self._db.con.execute(
"SELECT itemID FROM items WHERE itemTypeID NOT IN (1, 14)"
).fetchall()
]
result = []
for iid in item_ids:
item = self._db.get_item(iid)
if not item:
continue
quotes = self.quotes_for_item(item["key"])
result.append(
{
"key": item["key"],
"title": item["fields"].get("title")
or item["fields"].get("nameOfAct")
or "",
"url": item["fields"].get("url", ""),
"item_type": item["itemType"],
"tags": item["tags"],
"quotes": [
{"text": q.text, "page": q.page, "section": q.section}
for q in quotes
],
"fields": item["fields"],
}
)
return result