diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index efa59dc..8e12a3f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,13 +4,6 @@ on: push: tags: ["v*.*.*"] workflow_dispatch: - inputs: - publish: - description: >- - Upload to PyPI. Only takes effect when the run is started from a tag; - from a branch this is a build-and-check rehearsal. - type: boolean - default: false permissions: contents: read @@ -22,7 +15,17 @@ concurrency: cancel-in-progress: false jobs: + container-checks: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - run: make ci-docker + release: + needs: container-checks uses: gojiplus/py-canon/.github/workflows/reusable-release.yml@v1 permissions: contents: write @@ -30,38 +33,3 @@ jobs: # `gh release create` fails when the release already exists, so create it # only on the original tag push — not on a manual re-run of a released tag. github-release: ${{ github.event_name == 'push' }} - - # PyPI trusted publishing rejects reusable workflows (the OIDC claims - # must reference this repo's workflow file), so the publish step lives - # here rather than in py-canon's reusable-release. - publish: - needs: release - # A PyPI upload cannot be withdrawn, so publish only from a tag. The reusable - # build rejects the tag unless it matches the version in pyproject.toml. - if: >- - startsWith(github.ref, 'refs/tags/') && - (github.event_name == 'push' || inputs.publish) - runs-on: ubuntu-latest - timeout-minutes: 15 - environment: pypi - permissions: - id-token: write - steps: - - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: dist - path: dist/ - - name: Publish (trusted publishing, PEP 740 attestations) - uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # release/v1 - with: - attestations: true - # The `if:` above decides *which builds may publish*. This decides what - # happens when one version is published twice, which that guard cannot - # see. The concurrency group serializes a manual dispatch and a tag - # push aimed at the same version, it does not deduplicate them, and - # cancel-in-progress is false -- so the queued run starts once the - # first finishes and uploads identical files. A completed run is not - # covered by concurrency at all, so a plain rerun does the same. PyPI - # answers with a 400 and the release goes red having already - # succeeded, which is the worst of both readings. - skip-existing: true diff --git a/.gitignore b/.gitignore index ad04790..4b1f2ad 100644 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,4 @@ dist/ .coverage docs/_build/ /run/ +/citations.sqlite diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..24ee5b1 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.13 diff --git a/CHANGELOG.md b/CHANGELOG.md index 4390a13..c1f4b4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,9 @@ # Changelog -## Unreleased +## 0.1.0 +- Added SQLite collections for citation results and their source passages. OpenAlex discovery now retains available author, year, and venue metadata. - Renamed Autosum to Anekanta. The Python package and command are both named `anekanta`. - - Added an installable CLI for OpenAlex discovery, PDF acquisition, passage extraction, and importing existing reviewed annotations. - Keyed the PDF text cache by document hash and parser version. Reordering input papers now preserves the attribution of each quotation. - Added the local 16-paper baseline and the Hayes–Lawless endnote example. diff --git a/CITATION.cff b/CITATION.cff index da34e13..1b391e1 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -4,4 +4,5 @@ authors: - family-names: "Sood" given-names: "Gaurav" title: "Anekanta" +version: "0.1.0" url: "https://github.com/recite/anekanta/" diff --git a/README.md b/README.md index 8cfcc52..0d72e49 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Anekanta -What do later authors cite a paper for? One author may borrow its research design, another may report a finding, and a third may challenge its conclusion. Anekanta collects the passages in which later authors cite a work and records where they appear. A reader can then ask what each passage attributes to the source and whether the source supports that attribution. +What do later authors cite a paper for? One author may borrow its research design, another may report a finding, and a third may challenge its conclusion. Anekanta builds a database of citing passages, linking each quotation to the paper, PDF version, and page where it appeared. A reader can then ask what each passage attributes to the source and whether the source supports that attribution. Consider Chattopadhyay and Duflo’s study of women leading village councils in India. Later authors cite it for the design of the quota system, for changes in political participation, and for what happened to roads and water. Those uses call for different checks. Table V reports more drinking-water facilities built or repaired in villages with reserved leadership in both states. The share of roads in good condition was 18 percentage points higher in West Bengal and 8 points lower in Rajasthan. A summary saying that women leaders invested more in water and roads loses the state distinction and changes what was measured. [Original study, Table V](https://doi.org/10.1111/j.1468-0262.2004.00539.x) · [A worked comparison of citing passages](https://www.gojiberries.io/motivated-citations-2/) @@ -16,7 +16,7 @@ cd anekanta uv run anekanta extract testdata/iyengar-2012.json --author Iyengar --year 2012 > passages.jsonl ``` -The extractor finds eight candidate mentions across five of the 16 PDFs. Each line of output describes one PDF, including its identifier, file hash, search method, and outcome. Each match has a quotation, a PDF page, and a review status. A paper with zero matches gets its own record, as does a paper that could not be read. Compare your output with the [saved results](https://github.com/recite/anekanta/blob/master/testout/iyengar-2012.jsonl). +The extractor finds eight candidate mentions across five of the 16 PDFs. Each line of output describes one PDF, including its identifier, file hash, search method, and outcome. Each match has a quotation, a PDF page, and a review status. A paper with zero matches gets its own record, as does a paper that could not be read. Compare your output with the [saved results](https://raw.githubusercontent.com/recite/anekanta/master/testout/iyengar-2012.jsonl). For a two-author work, supply the surnames in publication order, for example `--author Chattopadhyay --coauthor Duflo --year 2004`. This matches both “Chattopadhyay and Duflo (2004)” and “(Chattopadhyay & Duflo, 2004).” Check the bibliography when a year has a suffix such as 2004b. The authors may have published more than one paper that year. @@ -34,7 +34,22 @@ uv run anekanta import-review run/manifest.json schema/examples/hayes-lawless.js 1. **Discover citing works.** OpenAlex supplies the works and their identifiers. Omit `--citing-doi` to request all citing works. Each page saves the works found so far and the cursor for the next request. Set `OPENALEX_API_KEY` to page beyond the first response. Use `--max-pages N` to limit a run and `--resume` to continue it. [OpenAlex authentication](https://help.openalex.org/api/authentication/) 2. **Acquire the PDFs.** The example uses a local catalog and verifies each file’s hash. Online acquisition also tries open-access PDF links from OpenAlex. The resulting manifest records unavailable sources. To process an unfinished discovery run, pass `--allow-partial`. 3. **Extract candidate passages.** The author-and-year search returns `no_match` for Hayes and Lawless. It can miss endnotes, numbered references, and citations split over pages. Use `--cache DIRECTORY` to reuse parsed text when comparing searches. The command writes one result per input and returns exit status 1 if any paper failed. -4. **Import a checked passage.** A reader traced note 40 on printed page 98 (PDF page 4) to the reference on printed page 110 (PDF page 16). The import verifies that the existing annotation identifies the same citing work, cited work, and PDF. Here `source_checked` records that the reader located the passage and its citation. Its accuracy as a description of the cited study is a separate judgment. [Checked annotation](https://github.com/recite/anekanta/blob/master/schema/examples/hayes-lawless.json) +4. **Import a checked passage.** A reader traced note 40 on printed page 98 (PDF page 4) to the reference on printed page 110 (PDF page 16). The import verifies that the existing annotation identifies the same citing work, cited work, and PDF. Here `source_checked` records that the reader located the passage and its citation. Its accuracy as a description of the cited study is a separate judgment. [Checked annotation](https://raw.githubusercontent.com/recite/anekanta/master/schema/examples/hayes-lawless.json) + +## Build a citation database + +Use `anekanta load` to keep a collection of search results in SQLite. The database retains the citing and cited work IDs, the PDF version, the method, the page and quotation for each candidate, and every search that failed or returned no matches. New OpenAlex discovery runs also retain available author names and identifiers, publication year, and venue. Older and local records can omit these fields. + +From the checkout, load the bundled results and count passages by work. Python supplies SQLite. The query below uses the SQLite command-line client. + +```sh +uv run anekanta load testout/iyengar-2012.jsonl --db citations.sqlite --collection iyengar-2012 --source-root . +sqlite3 citations.sqlite "SELECT citing_id, COUNT(*) FROM passages WHERE collection = 'iyengar-2012' GROUP BY citing_id;" +``` + +Each collection preserves a particular export. Loading the same bytes under the same name and source root a second time leaves it unchanged. Give a revised export its own collection name. Use the `results` table to count searched PDFs, the `passages` view to inspect occurrences, and the `work_metadata` view to recover the available attributes on either side of a citation. Counts across exports can include the same paper or passage more than once. + +A study of miscitation can sample these records and attach judgments about what each source supports. A study of selective citation also needs to identify relevant works the author could have cited, including those omitted. Those decisions belong to the study design. ## When several papers are cited together @@ -46,4 +61,4 @@ The package supports Python 3.10 and later. Run `make ci` for tests, lint, and t The wheel includes the discovery, acquisition, and result schemas. Build it with `uv build` and install it with `uv tool install path/to/the-built-wheel.whl`. The sample PDFs and reviewed annotation live in the repository. -The original [Google Scholar and CSV scripts](https://github.com/recite/anekanta/tree/master/scripts) and [arXiv workflow](https://github.com/recite/anekanta/tree/master/arxiv) are available alongside the package. The [original instructions](https://github.com/recite/anekanta/blob/a1dde5b1117fde9cc548b36e04521c4c89100b9f/Readme.md) document their formats. +The original [Google Scholar and CSV scripts](https://github.com/recite/anekanta/tree/master/scripts) and [arXiv workflow](https://github.com/recite/anekanta/tree/master/arxiv) are available alongside the package. The [original instructions](https://raw.githubusercontent.com/recite/anekanta/a1dde5b1117fde9cc548b36e04521c4c89100b9f/Readme.md) document their formats. diff --git a/pyproject.toml b/pyproject.toml index 5b91397..42bf6b6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,12 +1,19 @@ [project] name = "anekanta" version = "0.1.0" -description = "Collect and locate passages in works citing a publication" +description = "Build a database of citation passages with links to their source pages" readme = "README.md" license = "MIT" license-files = ["LICENSE"] authors = [{name = "Gaurav Sood"}] requires-python = ">=3.10" +keywords = ["citation context", "bibliometrics", "metascience", "research software"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Science/Research", + "Programming Language :: Python :: 3 :: Only", + "Topic :: Scientific/Engineering :: Information Analysis", +] dependencies = ["pdfminer.six==20260107", "ftfy==6.3.1", "jsonschema>=4.18,<5", "referencing>=0.30", "httpx>=0.27,<1"] [project.scripts] diff --git a/src/anekanta/cli.py b/src/anekanta/cli.py index 9359eac..6cacf16 100644 --- a/src/anekanta/cli.py +++ b/src/anekanta/cli.py @@ -1,12 +1,13 @@ """Command-line entry point for the citation pipeline.""" import argparse +import sqlite3 from pathlib import Path import httpx from jsonschema import ValidationError -from anekanta import acquire, discover, extract, review +from anekanta import acquire, database, discover, extract, review def main(): @@ -42,6 +43,16 @@ def main(): cmd.add_argument("manifest", type=Path) cmd.add_argument("record", type=Path) cmd.set_defaults(run=review.run) + cmd = stages.add_parser("load", help="load citation results into a SQLite database") + cmd.add_argument( + "results", type=Path, help="JSON Lines from extract or import-review" + ) + cmd.add_argument("--db", type=Path, required=True) + cmd.add_argument("--collection", required=True, help="name for this export") + cmd.add_argument( + "--source-root", type=Path, help="base directory for PDF locations" + ) + cmd.set_defaults(run=database.run) args = parser.parse_args() if args.stage == "extract" and ( not args.author.strip() @@ -52,5 +63,11 @@ def main(): parser.error("Specify a surname and four-digit publication year") try: return args.run(args) - except (OSError, ValueError, ValidationError, httpx.RequestError) as error: + except ( + OSError, + ValueError, + ValidationError, + httpx.RequestError, + sqlite3.Error, + ) as error: parser.exit(2, f"anekanta: {error}\n") diff --git a/src/anekanta/database.py b/src/anekanta/database.py new file mode 100644 index 0000000..89a4e47 --- /dev/null +++ b/src/anekanta/database.py @@ -0,0 +1,100 @@ +"""Store versioned citation-search results and their passages in SQLite.""" + +import hashlib +import json +import sqlite3 +from contextlib import closing + +from jsonschema import ValidationError + +from anekanta.contracts import VALIDATOR + +SCHEMA = """ +BEGIN IMMEDIATE; +CREATE TABLE IF NOT EXISTS collections ( + collection TEXT PRIMARY KEY NOT NULL, + export_sha256 TEXT NOT NULL, + source_root TEXT, + imported_utc TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE TABLE IF NOT EXISTS results ( + collection TEXT NOT NULL REFERENCES collections DEFERRABLE INITIALLY DEFERRED, + cited_id TEXT NOT NULL, + citing_id TEXT NOT NULL, + source_sha256 TEXT NOT NULL, + method TEXT NOT NULL, + outcome TEXT NOT NULL, + record TEXT NOT NULL, + PRIMARY KEY (collection, cited_id, citing_id, source_sha256, method) +); +CREATE INDEX IF NOT EXISTS results_by_target ON results(cited_id); +CREATE INDEX IF NOT EXISTS results_by_citer ON results(citing_id); +CREATE VIEW IF NOT EXISTS passages AS + SELECT collection, cited_id, citing_id, source_sha256, method, + json_extract(p.value, '$.id') AS passage_id, + json_extract(p.value, '$.quote') AS quote, + json_extract(p.value, '$.location.pdf_page') AS pdf_page, + json_extract(p.value, '$.review') AS review, + json_extract(record, '$.source.location') AS source_location, + p.value AS passage + FROM results, json_each(record, '$.passages') AS p; +CREATE VIEW IF NOT EXISTS work_metadata AS + SELECT DISTINCT collection, citing_id AS work_id, + json_extract(record, '$.citing_work') AS metadata FROM results + UNION + SELECT DISTINCT collection, cited_id, json_extract(record, '$.cited_work') + FROM results; +""" + + +def _insert(db, collection, line): + record = json.loads(line) + VALIDATOR.validate(record) + ids = [p["id"] for p in record["passages"]] + if len(ids) != len(set(ids)): + raise ValueError("duplicate passage identifier within a result") + db.execute( + "INSERT INTO results VALUES (?, ?, ?, ?, ?, ?, ?)", + ( + collection, + record["cited_work"]["id"], + record["citing_work"]["id"], + record.get("source", {}).get("sha256", ""), + json.dumps(record["method"], sort_keys=True), + record["outcome"], + json.dumps(record, ensure_ascii=False, sort_keys=True), + ), + ) + + +def run(args): + """Import one immutable, named collection of JSON Lines in one transaction.""" + if not args.collection.strip(): + raise ValueError("Specify a nonempty collection name") + root = str(args.source_root.resolve()) if args.source_root else None + digest = hashlib.sha256() + with args.results.open("rb") as stream, closing(sqlite3.connect(args.db)) as db, db: + db.execute("PRAGMA foreign_keys = ON") + db.executescript(SCHEMA) + previous = db.execute( + "SELECT export_sha256, source_root FROM collections WHERE collection = ?", + (args.collection,), + ).fetchone() + for number, line in enumerate(stream, start=1): + digest.update(line) + if previous is None: + try: + _insert(db, args.collection, line) + except (ValueError, ValidationError, sqlite3.IntegrityError) as error: + raise ValueError( + f"{args.results}, line {number}: {error}" + ) from error + if previous is None: + db.execute( + "INSERT INTO collections (collection, export_sha256, source_root) " + "VALUES (?, ?, ?)", + (args.collection, digest.hexdigest(), root), + ) + elif previous != (digest.hexdigest(), root): + raise ValueError("Collection already exists with different inputs") + return 0 diff --git a/src/anekanta/discover.py b/src/anekanta/discover.py index ffb93d8..08e944f 100644 --- a/src/anekanta/discover.py +++ b/src/anekanta/discover.py @@ -35,12 +35,35 @@ def _get(client, url, params): return response.json() +WORK_FIELDS = "id,doi,display_name,publication_year,authorships,primary_location" + + +def _work_metadata(work, identifier): + metadata = {"id": identifier} + if work.get("display_name"): + metadata["title"] = work["display_name"] + if work.get("publication_year") is not None: + metadata["publication_year"] = work["publication_year"] + venue = (work.get("primary_location") or {}).get("source") or {} + if venue.get("display_name"): + metadata["venue"] = venue["display_name"] + authors = [] + for authorship in work.get("authorships") or []: + author = authorship.get("author") or {} + if author.get("display_name"): + entry = {"name": author["display_name"]} + if author.get("id"): + entry["openalex_id"] = author["id"] + authors.append(entry) + if authors: + metadata["authors"] = authors + return metadata + + def _paper(work): oa = work["id"].rsplit("/", 1)[-1] identifier = doi_id(work["doi"]) if work.get("doi") else "openalex:" + oa - citing = {"id": identifier} - if work.get("display_name"): - citing["title"] = work["display_name"] + citing = _work_metadata(work, identifier) urls = [ location["pdf_url"] for location in work.get("locations", []) @@ -72,13 +95,13 @@ def discover(args, client): "Discovery output exists. Use --resume or choose a new path." ) url = WORKS + "/https://doi.org/" + quote(target[4:], safe="/") - work = _get(client, url, {"select": "id,doi,display_name"}) + work = _get(client, url, {"select": WORK_FIELDS}) if doi_id(work["doi"]) != target: raise ValueError("OpenAlex resolved the query to another DOI") state = { "provider": "openalex", "started_at": datetime.now(timezone.utc).isoformat(), - "cited_work": {"id": target}, + "cited_work": _work_metadata(work, target), "target_openalex_id": work["id"].rsplit("/", 1)[-1], "citing_doi": subset, "reported_count": None, @@ -86,8 +109,6 @@ def discover(args, client): "complete": False, "papers": [], } - if work.get("display_name"): - state["cited_work"]["title"] = work["display_name"] validate("discovery.schema.json", state) save_json(args.output, state) works = {row["citing_work"]["id"]: row for row in state["papers"]} @@ -103,7 +124,7 @@ def discover(args, client): WORKS, { "filter": filters, - "select": "id,doi,display_name,locations", + "select": WORK_FIELDS + ",locations", "cursor": cursor, "per_page": 100, }, diff --git a/src/anekanta/schemas/paper-result.schema.json b/src/anekanta/schemas/paper-result.schema.json index 1549feb..6ee7555 100644 --- a/src/anekanta/schemas/paper-result.schema.json +++ b/src/anekanta/schemas/paper-result.schema.json @@ -75,7 +75,21 @@ "type": "string", "pattern": "^(doi|arxiv|s2|openalex|local):[^\\s]+$" }, - "title": { "$ref": "#/$defs/text" } + "title": { "$ref": "#/$defs/text" }, + "publication_year": { "type": "integer" }, + "venue": { "$ref": "#/$defs/text" }, + "authors": { + "type": "array", + "items": { + "type": "object", + "required": ["name"], + "additionalProperties": false, + "properties": { + "name": { "$ref": "#/$defs/text" }, + "openalex_id": { "$ref": "#/$defs/text" } + } + } + } } }, "location": { diff --git a/tests/test_database.py b/tests/test_database.py new file mode 100644 index 0000000..f1c4210 --- /dev/null +++ b/tests/test_database.py @@ -0,0 +1,68 @@ +import json +import sqlite3 +from contextlib import closing +from types import SimpleNamespace + +import pytest + +from anekanta.database import run +from anekanta.discover import _paper + + +def test_load_preserves_provenance_and_rolls_back_bad_collections(tmp_path): + row = { + "schema_version": "0.1", + "cited_work": {"id": "local:original"}, + "citing_work": _paper( + { + "id": "https://openalex.org/W1", + "publication_year": 2020, + "authorships": [{"author": {"display_name": "Example Author"}}], + "primary_location": {"source": {"display_name": "Example Journal"}}, + } + )["citing_work"], + "method": {"name": "baseline", "version": "1"}, + "source": {"kind": "pdf", "sha256": "a" * 64, "location": "one.pdf"}, + "outcome": "passages_found", + "passages": [ + { + "id": "p3", + "quote": "A citation", + "location": {"pdf_page": 3}, + "review": "unchecked", + } + ], + } + absent = dict( + row, + citing_work={"id": "local:absent"}, + outcome="source_unavailable", + detail="missing", + passages=[], + ) + del absent["source"] + args = SimpleNamespace( + db=tmp_path / "db.sqlite", + collection="pilot", + results=tmp_path / "input.jsonl", + source_root=tmp_path, + ) + export = json.dumps(row) + "\n" + json.dumps(absent) + "\n" + args.results.write_text(export) + assert run(args) == run(args) == 0 + args.results.write_text(export + "invalid\n") + with pytest.raises(ValueError, match="different inputs"): + run(args) + args.collection = "another" + with pytest.raises(ValueError, match="line 3"): + run(args) + with closing(sqlite3.connect(args.db)) as db: + assert db.execute("SELECT count(*) FROM results").fetchone() == (2,) + assert db.execute("SELECT count(*) FROM collections").fetchone() == (1,) + assert db.execute( + "SELECT citing_id, pdf_page, quote FROM passages" + ).fetchall() == [("openalex:W1", 3, "A citation")] + metadata = db.execute( + "SELECT metadata FROM work_metadata WHERE work_id = 'openalex:W1'" + ).fetchone()[0] + assert json.loads(metadata) == row["citing_work"]