Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 10 additions & 42 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -22,46 +15,21 @@ 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
with:
# `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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,4 @@ dist/
.coverage
docs/_build/
/run/
/citations.sqlite
1 change: 1 addition & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.13
4 changes: 2 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
1 change: 1 addition & 0 deletions CITATION.cff
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ authors:
- family-names: "Sood"
given-names: "Gaurav"
title: "Anekanta"
version: "0.1.0"
url: "https://github.com/recite/anekanta/"
23 changes: 19 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -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/)

Expand All @@ -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.

Expand All @@ -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

Expand All @@ -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.
9 changes: 8 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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]
Expand Down
21 changes: 19 additions & 2 deletions src/anekanta/cli.py
Original file line number Diff line number Diff line change
@@ -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():
Expand Down Expand Up @@ -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()
Expand All @@ -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")
100 changes: 100 additions & 0 deletions src/anekanta/database.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading