cite-analyser 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ """cite-analyser — the Python successor to the cite-sight engine.
2
+
3
+ Ported module-by-module from cite-sight's TypeScript core (frozen at 0.13.x),
4
+ conformance-tested against goldens recorded from the TS engine over its
5
+ demo-corpus. See MIGRATION.md in the cite-sight repo and the status table in
6
+ this package's README.
7
+ """
8
+
9
+ __version__ = "0.1.0"
@@ -0,0 +1,82 @@
1
+ """The analysis pipeline: extract → cross-reference → duplicates → (optional)
2
+ verification — the same order as cite-sight's pipeline.ts."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from .cross_reference import cross_reference_check
7
+ from .duplicates import find_duplicate_references
8
+ from .extractor import extract_references, majority_style
9
+ from .verifier import VerifyOptions, verify_references
10
+
11
+
12
+ def analyze(
13
+ text: str,
14
+ verify: bool = False,
15
+ mailto: str | None = None,
16
+ check_urls: bool = True,
17
+ check_doi: bool = True,
18
+ semantic_scholar_api_key: str | None = None,
19
+ openalex_api_key: str | None = None,
20
+ citation_style: str = "auto",
21
+ check_in_text: bool = True,
22
+ document_type: str | None = None,
23
+ ) -> dict:
24
+ """Run the analysis stages over document text.
25
+
26
+ The output block mirrors cite-sight's ``ReferenceAnalysisResult`` so the
27
+ frozen engine's server can delegate here without an adapter guessing at
28
+ field names. Verification (external lookups) is opt-in."""
29
+ extracted = extract_references(text)
30
+ references = extracted["references"]
31
+ in_text = extracted["inTextCitations"]
32
+ detected_style = majority_style(references)
33
+
34
+ # Source-list heuristic (pipeline.ts): a bibliography with zero in-text
35
+ # citations is likely a collated reference list — the cross-check is
36
+ # meaningless there (and a bare list cannot have orphans).
37
+ source_list_likely = len(references) >= 3 and not in_text
38
+ in_text_check_skipped = (
39
+ not check_in_text or document_type == "reference-list" or source_list_likely
40
+ )
41
+ if in_text_check_skipped:
42
+ cross = {"unmatchedBibliography": [], "unmatchedInText": []}
43
+ else:
44
+ cross = cross_reference_check(references, in_text)
45
+
46
+ verifications = (
47
+ verify_references(
48
+ references,
49
+ VerifyOptions(
50
+ mailto=mailto,
51
+ check_urls=check_urls,
52
+ check_doi=check_doi,
53
+ semantic_scholar_api_key=semantic_scholar_api_key,
54
+ openalex_api_key=openalex_api_key,
55
+ citation_style=citation_style,
56
+ ),
57
+ )
58
+ if verify
59
+ else []
60
+ )
61
+
62
+ def count(statuses: tuple[str, ...]) -> int:
63
+ return sum(1 for v in verifications if v["status"] in statuses)
64
+
65
+ return {
66
+ "references": references,
67
+ "inTextCitations": in_text,
68
+ "crossReference": cross,
69
+ "duplicates": sorted(find_duplicate_references(references)),
70
+ "verifications": verifications,
71
+ "detectedStyle": detected_style,
72
+ "totalReferences": len(references),
73
+ "verifiedCount": count(("verified", "likely_valid")),
74
+ "suspiciousCount": count(("suspicious",)),
75
+ "notFoundCount": count(("not_found",)),
76
+ "unverifiedCount": count(("unverified",)),
77
+ "brokenUrlCount": sum(
78
+ 1 for v in verifications if (v.get("urlCheck") or {}).get("status") == "dead"
79
+ ),
80
+ "sourceListLikely": source_list_likely,
81
+ "inTextCheckSkipped": in_text_check_skipped,
82
+ }
cite_analyser/api.py ADDED
@@ -0,0 +1,71 @@
1
+ """HTTP API — the lens family contract plus POST /analyse."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from fastapi import FastAPI, File, Form, HTTPException, UploadFile
8
+ from lens_contract import add_contract_routes, add_cors
9
+
10
+ from .analysis import analyze
11
+ from .extractors import extract_document
12
+ from .manifest import MANIFEST
13
+
14
+ app = FastAPI(title=MANIFEST["name"], version=MANIFEST["version"])
15
+ add_contract_routes(app, MANIFEST)
16
+ add_cors(app, env_prefix="CITE_ANALYSER")
17
+
18
+
19
+ class AnalyseOptions:
20
+ """Mirror of the cite-sight server's /analyse form options."""
21
+
22
+ def __init__(
23
+ self,
24
+ verify: bool = False,
25
+ mailto: str = "",
26
+ check_urls: bool = True,
27
+ check_doi: bool = True,
28
+ ):
29
+ self.verify = verify
30
+ self.mailto = mailto or None
31
+ self.check_urls = check_urls
32
+ self.check_doi = check_doi
33
+
34
+
35
+ @app.post("/analyse")
36
+ async def analyse(
37
+ file: UploadFile = File(...), # noqa: B008 — FastAPI's declared-parameter idiom
38
+ verify: bool = Form(default=False),
39
+ mailto: str = Form(default=""),
40
+ checkUrls: bool = Form(default=True),
41
+ checkDoi: bool = Form(default=True),
42
+ checkInText: bool = Form(default=True),
43
+ citationStyle: str = Form(default="auto"),
44
+ documentType: str = Form(default=""),
45
+ semanticScholarApiKey: str = Form(default=""),
46
+ openAlexApiKey: str = Form(default=""),
47
+ ) -> dict[str, Any]:
48
+ """Analyse a document: references, in-text citations, cross-reference,
49
+ duplicates, format issues, and (when verify=true) database verdicts.
50
+
51
+ Response keys mirror cite-sight's AnalysisResult.references block plus the
52
+ extracted text, so the frozen engine's server can delegate wholesale."""
53
+ name = file.filename or "document.txt"
54
+ raw = await file.read()
55
+ try:
56
+ text = extract_document(raw, name)
57
+ except ValueError as e:
58
+ raise HTTPException(status_code=400, detail=str(e)) from e
59
+ result = analyze(
60
+ text,
61
+ verify=verify,
62
+ mailto=mailto,
63
+ check_urls=checkUrls,
64
+ check_doi=checkDoi,
65
+ semantic_scholar_api_key=semanticScholarApiKey or None,
66
+ openalex_api_key=openAlexApiKey or None,
67
+ citation_style=citationStyle if citationStyle in ("auto", "apa", "mla", "chicago") else "auto",
68
+ check_in_text=checkInText,
69
+ document_type=documentType or None,
70
+ )
71
+ return {"fileName": name, "extractedText": text, **result}
cite_analyser/cli.py ADDED
@@ -0,0 +1,90 @@
1
+ """CLI: `cite-analyser analyse <file>` plus the family's serve/manifest."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import pathlib
8
+ import sys
9
+
10
+ from .analysis import analyze
11
+ from .extractors import extract_document
12
+ from .manifest import MANIFEST
13
+ from .verifier import verify_references # noqa: F401 — re-exported for library users
14
+
15
+
16
+ def _read_text(path: pathlib.Path) -> str:
17
+ try:
18
+ return extract_document(path.read_bytes(), path.name)
19
+ except ValueError as e:
20
+ print(f"Error: {e}", file=sys.stderr)
21
+ sys.exit(1)
22
+
23
+
24
+ def main(argv: list[str] | None = None) -> int:
25
+ from lens_contract import run_contract_subcommands
26
+
27
+ if run_contract_subcommands(
28
+ MANIFEST,
29
+ app_path="cite_analyser.api:app",
30
+ default_port=8006,
31
+ env_prefix="CITE_ANALYSER",
32
+ argv=argv,
33
+ ):
34
+ return 0
35
+
36
+ parser = argparse.ArgumentParser(
37
+ prog="cite-analyser", description="Citation and reference analysis"
38
+ )
39
+ sub = parser.add_subparsers(dest="command", required=True)
40
+
41
+ p_analyse = sub.add_parser("analyse", help="Extract citations from a document")
42
+ p_analyse.add_argument("file", type=pathlib.Path)
43
+ p_analyse.add_argument("--json", action="store_true", dest="as_json")
44
+ p_analyse.add_argument(
45
+ "--verify", action="store_true", help="Verify references against academic databases"
46
+ )
47
+ p_analyse.add_argument("--email", help="Contact email for the Crossref polite pool (mailto)")
48
+ args = parser.parse_args(argv)
49
+
50
+ if args.command == "analyse":
51
+ result = analyze(_read_text(args.file), verify=args.verify, mailto=args.email)
52
+ if args.as_json:
53
+ print(json.dumps(result, indent=2, ensure_ascii=False))
54
+ else:
55
+ refs = result["references"]
56
+ cross = result["crossReference"]
57
+ print(f"{len(refs)} references, {len(result['inTextCitations'])} in-text citations")
58
+ print(
59
+ f" unmatched: {len(cross['unmatchedBibliography'])} bibliography, "
60
+ f"{len(cross['unmatchedInText'])} in-text"
61
+ + (
62
+ f", {len(cross['nearMatches'])} near matches"
63
+ if cross.get("nearMatches")
64
+ else ""
65
+ )
66
+ )
67
+ if result["duplicates"]:
68
+ print(f" duplicates at positions {result['duplicates']}")
69
+ verdicts = result.get("verifications") or []
70
+ if verdicts:
71
+ counts: dict[str, int] = {}
72
+ for v in verdicts:
73
+ counts[v["status"]] = counts.get(v["status"], 0) + 1
74
+ print(" verdicts: " + ", ".join(f"{k} {v}" for k, v in sorted(counts.items())))
75
+ for v in verdicts:
76
+ if v["status"] in ("verified", "likely_valid"):
77
+ continue
78
+ who = v["reference"]["authors"][0] if v["reference"].get("authors") else "?"
79
+ print(f" {v['status']}: {who} — {', '.join(v['flags'])}")
80
+ for i, r in enumerate(refs):
81
+ year = r.get("year") or "n.d."
82
+ dup = " (duplicate)" if i in result["duplicates"] else ""
83
+ author = r["authors"][0] if r["authors"] else "?"
84
+ print(f" [{r['detectedStyle']}] {author} ({year}){dup}")
85
+ return 0
86
+ return 1
87
+
88
+
89
+ if __name__ == "__main__":
90
+ raise SystemExit(main())
@@ -0,0 +1,163 @@
1
+ """Cross-reference check — port of cite-sight's ``references/crossReference.ts``.
2
+
3
+ Exact author-date identification claims citations first; near matches
4
+ (hand-typing slips: one-edit surnames, transpositions, year off by one,
5
+ second-author citations) only consider what is left, so a suggestion can
6
+ never steal a citation another entry identifies exactly.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import unicodedata
12
+
13
+ import regex
14
+
15
+ from .extractor import InText, ParsedRef # type-aliased dicts, see extractor.py
16
+
17
+
18
+ def author_key(author: str) -> str:
19
+ """Normalised comparison form of one author name."""
20
+ cleaned = regex.sub(r"\s+et\s+al\.?$", "", author, flags=_RE_I)
21
+ cleaned = regex.sub(r"['’]s$", "", cleaned, flags=_RE_I)
22
+ cleaned = unicodedata.normalize("NFC", cleaned).lower()
23
+ return regex.sub(r"[^\p{L}]", "", cleaned)
24
+
25
+
26
+ _RE_I = regex.IGNORECASE
27
+
28
+
29
+ def reference_matches_citation(ref: ParsedRef, cite: InText) -> bool:
30
+ """Exact author-date identification (first author, year, year suffix)."""
31
+ ref_author = author_key((ref["authors"][0] if ref["authors"] else "").split(",")[0])
32
+ cite_author = author_key(cite["authors"][0] if cite["authors"] else "")
33
+ if not ref_author or not cite_author or ref_author != cite_author:
34
+ return False
35
+ if cite["year"] is not None and ref["year"] != cite["year"]:
36
+ return False
37
+ return not (
38
+ cite["year"] is not None and ref.get("yearSuffix", "") != cite.get("yearSuffix", "")
39
+ )
40
+
41
+
42
+ def within_edit_distance(a: str, b: str, max_edits: int) -> bool:
43
+ """Bounded Levenshtein: True when a and b differ by at most `max` edits,
44
+ early-exiting as soon as the bound is provably exceeded."""
45
+ if abs(len(a) - len(b)) > max_edits:
46
+ return False
47
+ if a == b:
48
+ return True
49
+ previous = list(range(len(b) + 1))
50
+ for i in range(1, len(a) + 1):
51
+ row = [i]
52
+ best = i
53
+ for j in range(1, len(b) + 1):
54
+ row.append(
55
+ min(
56
+ row[j - 1] + 1,
57
+ previous[j] + 1,
58
+ previous[j - 1] + (0 if a[i - 1] == b[j - 1] else 1),
59
+ )
60
+ )
61
+ best = min(best, row[j])
62
+ if best > max_edits:
63
+ return False
64
+ previous = row
65
+ return previous[len(b)] <= max_edits
66
+
67
+
68
+ def _cited_surnames(authors: list[str]) -> list[str]:
69
+ """All surnames in an author list, normalised; initials never glue onto a
70
+ surname ("Wilmot, M." must not become "wilmotm")."""
71
+ tokens: list[str] = []
72
+ for author in authors:
73
+ tokens.extend(regex.split(r"\s*(?:\band\b|&|,|;|\s+)\s*", author, flags=_RE_I))
74
+ return [k for k in (author_key(t) for t in tokens) if len(k) >= 3]
75
+
76
+
77
+ def _surname_slip(a: str, b: str) -> bool:
78
+ """One hand-typing slip: a single edit, or an adjacent-letter transposition
79
+ ("Teh" -> "The"). Two plain edits stay a mismatch."""
80
+ if within_edit_distance(a, b, 1):
81
+ return True
82
+ if len(a) != len(b):
83
+ return False
84
+ differing = [i for i, ch in enumerate(a) if ch != b[i]]
85
+ return (
86
+ len(differing) == 2
87
+ and differing[1] == differing[0] + 1
88
+ and a[differing[0]] == b[differing[1]]
89
+ and a[differing[1]] == b[differing[0]]
90
+ )
91
+
92
+
93
+ def near_matches(ref: ParsedRef, cite: InText) -> bool:
94
+ if reference_matches_citation(ref, cite):
95
+ return False
96
+ same_year = (
97
+ cite["year"] is not None
98
+ and ref["year"] == cite["year"]
99
+ and ref.get("yearSuffix", "") == cite.get("yearSuffix", "")
100
+ )
101
+ year_off_by_one = (
102
+ cite["year"] is not None
103
+ and ref["year"] is not None
104
+ and abs(cite["year"] - ref["year"]) == 1
105
+ )
106
+ ref_author = author_key((ref["authors"][0] if ref["authors"] else "").split(",")[0])
107
+ cite_author = author_key(cite["authors"][0] if cite["authors"] else "")
108
+
109
+ # Spelled almost right, same year: "Smth (2020)" for Smith (2020).
110
+ if same_year and len(ref_author) >= 3 and len(cite_author) >= 3:
111
+ ref_surnames = [s for a in ref["authors"] for s in _cited_surnames([a])]
112
+ if _surname_slip(ref_author, cite_author) or any(
113
+ _surname_slip(s, cite_author) for s in ref_surnames
114
+ ):
115
+ return True
116
+ # A cited surname appears in the entry's author list (second/third author).
117
+ if same_year and any(
118
+ s in _cited_surnames(cite["authors"]) for s in _cited_surnames(ref["authors"])
119
+ ):
120
+ return True
121
+ # Surname exactly right, year one off — the classic year slip.
122
+ if (
123
+ year_off_by_one
124
+ and len(ref_author) >= 3
125
+ and len(cite_author) >= 3
126
+ and any(s in _cited_surnames(cite["authors"]) for s in _cited_surnames(ref["authors"]))
127
+ ):
128
+ return True
129
+ return False
130
+
131
+
132
+ def cross_reference_check(references: list[ParsedRef], in_text: list[InText]) -> dict:
133
+ """Match citations against the bibliography; near matches surface as
134
+ suggestions rather than orphans."""
135
+ exact_for_cite: dict[int, int] = {} # cite index -> ref index
136
+ for ci, cite in enumerate(in_text):
137
+ for ri, ref in enumerate(references):
138
+ if reference_matches_citation(ref, cite):
139
+ exact_for_cite[ci] = ri
140
+ break
141
+ matched_refs = {ri for ri in exact_for_cite.values()}
142
+
143
+ pairs: list[dict] = []
144
+ for ci, cite in enumerate(in_text):
145
+ if ci in exact_for_cite:
146
+ continue
147
+ for ri, ref in enumerate(references):
148
+ if ri not in matched_refs and near_matches(ref, cite):
149
+ matched_refs.add(ri)
150
+ pairs.append({"citeIndex": ci, "referenceIndex": ri})
151
+ break
152
+
153
+ result = {
154
+ "unmatchedBibliography": [i for i, _ in enumerate(references) if i not in matched_refs],
155
+ "unmatchedInText": [
156
+ i
157
+ for i in range(len(in_text))
158
+ if i not in exact_for_cite and i not in {p["citeIndex"] for p in pairs}
159
+ ],
160
+ }
161
+ if pairs:
162
+ result["nearMatches"] = pairs
163
+ return result
@@ -0,0 +1,40 @@
1
+ """Title normalisation and duplicate detection — port of cite-sight's
2
+ ``references/matching.ts`` (normalizeTitle) and ``references/duplicates.ts``."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import unicodedata
7
+
8
+ import regex
9
+
10
+ from .cross_reference import author_key
11
+
12
+
13
+ def normalize_title(value: str) -> str:
14
+ """NFKD-folded, marks stripped, punctuation to spaces, collapsed."""
15
+ folded = unicodedata.normalize("NFKD", value.lower())
16
+ folded = regex.sub(r"\p{M}", "", folded)
17
+ folded = regex.sub(r"[^\p{L}\p{N}\s]", " ", folded)
18
+ return regex.sub(r"\s+", " ", folded).strip()
19
+
20
+
21
+ def find_duplicate_references(references: list[dict]) -> set[int]:
22
+ """Indices of entries repeating an earlier entry — same first author,
23
+ year, and first 12 normalised title words. Reported on every occurrence
24
+ after the first (hand-built lists accumulate these across editing
25
+ sessions)."""
26
+ seen: dict[str, int] = {}
27
+ duplicates: set[int] = set()
28
+ for index, ref in enumerate(references):
29
+ key = "|".join(
30
+ (
31
+ author_key((ref["authors"][0] if ref["authors"] else ref["raw"]).split(",")[0]),
32
+ str(ref["year"] if ref["year"] is not None else "nd"),
33
+ " ".join(normalize_title(ref["title"] or ref["raw"]).split(" ")[:12]),
34
+ )
35
+ )
36
+ if key in seen:
37
+ duplicates.add(index)
38
+ else:
39
+ seen[key] = index
40
+ return duplicates