revigil 0.1.0__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.
revigil/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ """Revigil: the always-on dashboard and mail watcher for ReviewerManager.
2
+
3
+ It runs in the background (tray icon on Windows), shows what you have reviewed,
4
+ watches your mailboxes for review e-mails, runs integrity checks on manuscripts,
5
+ and forwards review receipts to Web of Science.
6
+
7
+ Everything it stores lives outside the repository:
8
+ %LOCALAPPDATA%\\Revigil\\ settings, mail events, logs, lookup cache
9
+ articles/<id>/round-N/checks/ per-article check results (gitignored)
10
+ Windows Credential Manager mailbox passwords (service "Revigil")
11
+ """
12
+ __version__ = "0.1.0"
revigil/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """python -m revigil == the `revigil` command (see cli.py)."""
2
+ import sys
3
+
4
+ from revigil.cli import main
5
+
6
+ sys.exit(main())
revigil/ai.py ADDED
@@ -0,0 +1,194 @@
1
+ """Local AI for Revigil: open-weight models running on this computer through Ollama.
2
+
3
+ Nothing in this module talks to a cloud AI service. Manuscript text goes only to the Ollama
4
+ server on 127.0.0.1 (or the OLLAMA_HOST you set yourself). Unpublished manuscripts are
5
+ confidential; see AGREEMENT.md.
6
+
7
+ The catalogue lists light, openly published models (download under 8 GB) that were benchmarked
8
+ on Revigil's own review tasks (benchmarks/). The one marked "recommended" is downloaded on first
9
+ run once the reviewer agrees; the others can be chosen in Settings.
10
+ """
11
+ import json
12
+ import os
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import time
17
+ from pathlib import Path
18
+
19
+ import requests
20
+
21
+ from .config import log
22
+
23
+ HOST = os.environ.get("OLLAMA_HOST", "http://127.0.0.1:11434")
24
+ if not HOST.startswith("http"):
25
+ HOST = "http://" + HOST
26
+
27
+ # size_gb: download size; ram_gb: comfortable memory (RAM or GPU) at the context Revigil uses.
28
+ # score: overall result on benchmarks/ (0-100, higher is better), filled in from benchmarks/results.json.
29
+ CATALOG = [
30
+ {"tag": "qwen3.5:4b", "name": "Qwen 3.5 4B", "size_gb": 3.4, "ram_gb": 6, "license": "Apache-2.0",
31
+ "maker": "Alibaba Qwen", "note": "", "recommended": False},
32
+ {"tag": "qwen3.5:9b", "name": "Qwen 3.5 9B", "size_gb": 6.6, "ram_gb": 10, "license": "Apache-2.0",
33
+ "maker": "Alibaba Qwen", "note": "", "recommended": False},
34
+ {"tag": "gemma4:e4b", "name": "Gemma 4 E4B", "size_gb": 6.6, "ram_gb": 8, "license": "Gemma terms of use",
35
+ "maker": "Google DeepMind", "note": "", "recommended": False},
36
+ {"tag": "gemma3:4b", "name": "Gemma 3 4B", "size_gb": 3.3, "ram_gb": 6, "license": "Gemma terms of use",
37
+ "maker": "Google DeepMind", "note": "", "recommended": False},
38
+ {"tag": "phi4-mini", "name": "Phi-4 mini 3.8B", "size_gb": 2.5, "ram_gb": 5, "license": "MIT",
39
+ "maker": "Microsoft", "note": "", "recommended": False},
40
+ {"tag": "granite4:3b", "name": "Granite 4 3B", "size_gb": 2.1, "ram_gb": 4, "license": "Apache-2.0",
41
+ "maker": "IBM", "note": "", "recommended": False},
42
+ {"tag": "llama3.2:3b", "name": "Llama 3.2 3B", "size_gb": 2.0, "ram_gb": 4, "license": "Llama 3.2 community license",
43
+ "maker": "Meta", "note": "", "recommended": False},
44
+ ]
45
+ _RESULTS = Path(__file__).parent / "data" / "benchmark.json"
46
+
47
+
48
+ def catalog() -> list:
49
+ """The catalogue with benchmark scores merged in (data/benchmark.json, written by benchmarks/run.py)."""
50
+ try:
51
+ bench = json.loads(_RESULTS.read_text(encoding="utf-8"))
52
+ except (OSError, ValueError):
53
+ bench = {}
54
+ out = []
55
+ for m in CATALOG:
56
+ b = bench.get("models", {}).get(m["tag"], {})
57
+ out.append({**m, "score": b.get("score"), "tokens_per_s": b.get("tokens_per_s"),
58
+ "recommended": m["tag"] == bench.get("recommended") or (not bench and m["recommended"]),
59
+ "note": b.get("note") or m["note"], "size_gb": b.get("size_gb") or m["size_gb"]})
60
+ return sorted(out, key=lambda m: (not m["recommended"], -(m["score"] or 0)))
61
+
62
+
63
+ def recommended() -> str:
64
+ c = catalog()
65
+ return next((m["tag"] for m in c if m["recommended"]), c[0]["tag"])
66
+
67
+
68
+ # ---- the Ollama runtime ----
69
+ def ollama_exe() -> str | None:
70
+ found = shutil.which("ollama")
71
+ if found:
72
+ return found
73
+ for p in (Path(os.environ.get("LOCALAPPDATA", "")) / "Programs" / "Ollama" / "ollama.exe",
74
+ Path("/usr/local/bin/ollama"), Path("/Applications/Ollama.app/Contents/Resources/ollama")):
75
+ if p.exists():
76
+ return str(p)
77
+ return None
78
+
79
+
80
+ def running() -> bool:
81
+ try:
82
+ return requests.get(f"{HOST}/api/version", timeout=2).ok
83
+ except requests.RequestException:
84
+ return False
85
+
86
+
87
+ def start() -> bool:
88
+ """Start `ollama serve` in the background when Ollama is installed but not running."""
89
+ if running():
90
+ return True
91
+ exe = ollama_exe()
92
+ if not exe:
93
+ return False
94
+ flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) | getattr(subprocess, "DETACHED_PROCESS", 0)
95
+ subprocess.Popen([exe, "serve"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
96
+ creationflags=flags, close_fds=True)
97
+ for _ in range(30):
98
+ time.sleep(0.5)
99
+ if running():
100
+ return True
101
+ return False
102
+
103
+
104
+ def install_ollama(progress=None) -> str:
105
+ """Install Ollama (the open-source local model runner). Windows: winget; macOS/Linux: show how."""
106
+ if ollama_exe():
107
+ return "Ollama is already installed."
108
+ if sys.platform == "win32" and shutil.which("winget"):
109
+ if progress:
110
+ progress(0, 1)
111
+ r = subprocess.run(["winget", "install", "--id", "Ollama.Ollama", "-e", "--silent",
112
+ "--accept-package-agreements", "--accept-source-agreements"],
113
+ capture_output=True, text=True, timeout=1800,
114
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
115
+ log(f"winget install Ollama: exit {r.returncode}\n{r.stdout[-1500:]}{r.stderr[-800:]}")
116
+ if not ollama_exe():
117
+ raise RuntimeError("Installing Ollama failed. Download it from https://ollama.com/download and run Revigil again.")
118
+ start()
119
+ return "Ollama installed."
120
+ raise RuntimeError("Install Ollama from https://ollama.com/download (macOS/Linux: curl -fsSL https://ollama.com/install.sh | sh), "
121
+ "then come back to this page.")
122
+
123
+
124
+ def installed() -> list:
125
+ try:
126
+ r = requests.get(f"{HOST}/api/tags", timeout=5)
127
+ r.raise_for_status()
128
+ return [{"tag": m["name"], "size_gb": round(m.get("size", 0) / 1e9, 1)} for m in r.json().get("models", [])]
129
+ except requests.RequestException:
130
+ return []
131
+
132
+
133
+ def _has(tag: str, inst: list) -> bool:
134
+ names = {m["tag"] for m in inst}
135
+ return tag in names or (":" not in tag and f"{tag}:latest" in names)
136
+
137
+
138
+ def status(settings: dict) -> dict:
139
+ inst = installed() if running() else []
140
+ chosen = settings.get("ai_model") or ""
141
+ usable = chosen if chosen and _has(chosen, inst) else next((m["tag"] for m in catalog() if _has(m["tag"], inst)), None)
142
+ return {"backend": settings.get("ai_backend", "local"), "ollama_installed": bool(ollama_exe()), "running": running(),
143
+ "host": HOST, "installed": inst, "model": usable, "chosen": chosen, "recommended": recommended(),
144
+ "catalog": [{**m, "installed": _has(m["tag"], inst)} for m in catalog()]}
145
+
146
+
147
+ def pull(tag: str, progress=None) -> str:
148
+ """Download a model (streams Ollama's progress)."""
149
+ if not start():
150
+ raise RuntimeError("Ollama is not installed or does not start.")
151
+ with requests.post(f"{HOST}/api/pull", json={"model": tag, "stream": True}, stream=True, timeout=(10, 3600)) as r:
152
+ r.raise_for_status()
153
+ for line in r.iter_lines():
154
+ if not line:
155
+ continue
156
+ j = json.loads(line)
157
+ if j.get("error"):
158
+ raise RuntimeError(f"download of {tag} failed: {j['error']}")
159
+ if progress and j.get("total"):
160
+ progress(round(100 * j.get("completed", 0) / j["total"]), 100)
161
+ return f"{tag} is ready."
162
+
163
+
164
+ def chat(model: str, system: str, prompt: str, schema: dict | None = None, num_ctx: int = 16384,
165
+ timeout: int = 900) -> dict:
166
+ """One answer from a local model. With a JSON schema the answer is parsed JSON.
167
+
168
+ Returns {"text" or "json", "seconds", "tokens", "tokens_per_s"}. Temperature 0: repeatable."""
169
+ if not start():
170
+ raise RuntimeError("Ollama is not running. Install it in Settings → Local AI.")
171
+ body = {"model": model, "stream": False, "think": False,
172
+ "messages": [{"role": "system", "content": system}, {"role": "user", "content": prompt}],
173
+ # num_predict: a cap on the answer, so a small model that keeps padding its JSON cannot run for minutes
174
+ "options": {"temperature": 0, "num_ctx": num_ctx, "seed": 7, "num_predict": 2500}}
175
+ if schema:
176
+ body["format"] = schema
177
+ t = time.time()
178
+ r = requests.post(f"{HOST}/api/chat", json=body, timeout=timeout)
179
+ if r.status_code == 400 and "think" in r.text: # models without a thinking switch
180
+ body.pop("think")
181
+ r = requests.post(f"{HOST}/api/chat", json=body, timeout=timeout)
182
+ r.raise_for_status()
183
+ j = r.json()
184
+ text = (j.get("message") or {}).get("content", "")
185
+ out = {"seconds": round(time.time() - t, 1), "tokens": j.get("eval_count"),
186
+ "tokens_per_s": round(j["eval_count"] / (j["eval_duration"] / 1e9), 1) if j.get("eval_duration") else None}
187
+ if schema:
188
+ try:
189
+ out["json"] = json.loads(text)
190
+ except ValueError:
191
+ out["json"], out["raw"] = None, text[:2000]
192
+ else:
193
+ out["text"] = text
194
+ return out
revigil/aicheck.py ADDED
@@ -0,0 +1,193 @@
1
+ """AI-assisted reading of a manuscript, with a local model only (see ai.py).
2
+
3
+ The model never writes the review. It points the reviewer at places to check:
4
+ overview aim, design, sample sizes and the main claims, as the authors state them
5
+ consistency numbers or statements in the abstract that the body contradicts
6
+ (a changed n, P value, percentage or direction of effect: careless or fabricated data)
7
+ claims is each main claim backed by a result in the text, only weakly, or not at all?
8
+ citations does the cited paper (Crossref title) plausibly support the sentence that cites it?
9
+ (needs the reference check to have run first)
10
+
11
+ Everything is a signal for the reviewer, never a verdict.
12
+ """
13
+ import json
14
+ import re
15
+ from datetime import datetime
16
+ from pathlib import Path
17
+
18
+ from . import ai
19
+ from .config import load_settings
20
+
21
+ SYSTEM = ("You help a scientific peer reviewer read a confidential manuscript carefully. Report only what the text "
22
+ "itself shows. Quote short exact phrases from the text as evidence. Never invent numbers, claims or "
23
+ "references. If something is not in the text, say so. Answer in the JSON format requested.")
24
+ CHUNK = 18000 # characters per piece of body text (fits a 16k-token context with room to spare)
25
+
26
+
27
+ # ---- text helpers ----
28
+ def abstract_of(text: str) -> str:
29
+ m = re.search(r"(?im)^\s*(abstract|summary)\s*:?\s*$", text[:20000])
30
+ if m:
31
+ rest = text[m.end():m.end() + 6000]
32
+ # the end of the abstract: a "Keywords:" line or a heading alone on its line. Not the labels of a
33
+ # structured abstract ("Background: ...", "Methods: ..."), which have text after them.
34
+ stop = re.search(r"(?im)^\s*(?:key\s?words?\s*[:.]|(?:1\.?\s+)?(?:introduction|background)\s*$)", rest)
35
+ return rest[:stop.start() if stop else 3500].strip()
36
+ return text[:3000].strip()
37
+
38
+
39
+ def without_abstract(text: str) -> str:
40
+ """The text with its abstract taken out, so the body is not compared with the abstract it contains."""
41
+ ab = abstract_of(text)
42
+ return text.replace(ab, " ", 1) if ab and len(ab) < len(text) / 2 else text
43
+
44
+
45
+ def body_chunks(text: str, size: int = CHUNK) -> list:
46
+ """Body text split on paragraph boundaries, the reference list left out."""
47
+ from .refcheck import split_references
48
+ body = split_references(text)[1] or text
49
+ paras, chunks, cur = re.split(r"\n\s*\n|\n(?=[A-Z][^\n]{0,80}\n)", body), [], ""
50
+ for p in paras:
51
+ if len(cur) + len(p) > size and cur:
52
+ chunks.append(cur)
53
+ cur = ""
54
+ cur += p + "\n\n"
55
+ if cur.strip():
56
+ chunks.append(cur)
57
+ return chunks
58
+
59
+
60
+ # ---- tasks (each is one or more calls to the local model) ----
61
+ OVERVIEW_SCHEMA = {"type": "object", "properties": {
62
+ "aim": {"type": "string"}, "design": {"type": "string"},
63
+ "sample_sizes": {"type": "array", "items": {"type": "string"}},
64
+ "main_claims": {"type": "array", "items": {"type": "string"}}},
65
+ "required": ["aim", "design", "sample_sizes", "main_claims"]}
66
+
67
+
68
+ def overview(model: str, text: str) -> dict:
69
+ prompt = ("From the abstract and the start of this manuscript, give: the aim (one sentence), the study design "
70
+ "(one sentence), every sample size stated (e.g. 'n = 120 patients'), and the main claims the authors "
71
+ "make (3 to 6 short sentences, in their words).\n\n=== MANUSCRIPT START ===\n" + text[:14000])
72
+ return ai.chat(model, SYSTEM, prompt, OVERVIEW_SCHEMA)
73
+
74
+
75
+ CONSIST_SCHEMA = {"type": "object", "properties": {"mismatches": {"type": "array", "items": {"type": "object", "properties": {
76
+ "abstract_says": {"type": "string"}, "text_says": {"type": "string"}, "issue": {"type": "string"}},
77
+ "required": ["abstract_says", "text_says", "issue"]}}}, "required": ["mismatches"]}
78
+
79
+
80
+ def consistency(model: str, text: str) -> dict:
81
+ abstract = abstract_of(text)
82
+ found, calls = [], []
83
+ for ch in body_chunks(without_abstract(text)):
84
+ prompt = ("Compare the ABSTRACT with this PART of the manuscript body. List every place where they disagree: "
85
+ "a different number (sample size, percentage, P value, effect size, follow-up time), a different "
86
+ "direction of an effect, or a result in the abstract that this part reports differently. Quote both "
87
+ "sides exactly. Ignore rounding differences and things this part does not mention. If there is no "
88
+ "disagreement, return an empty list.\n\n=== ABSTRACT ===\n" + abstract + "\n\n=== PART OF THE BODY ===\n" + ch)
89
+ r = ai.chat(model, SYSTEM, prompt, CONSIST_SCHEMA)
90
+ calls.append(r)
91
+ found += ((r.get("json") or {}).get("mismatches") or [])
92
+ # the same disagreement reported from two pieces: keep one
93
+ seen, uniq = set(), []
94
+ for x in found:
95
+ k = re.sub(r"\W+", "", (x.get("abstract_says") or "").lower())[:60]
96
+ if k and k not in seen:
97
+ seen.add(k)
98
+ uniq.append(x)
99
+ return {"mismatches": uniq, "calls": calls}
100
+
101
+
102
+ CLAIMS_SCHEMA = {"type": "object", "properties": {"claims": {"type": "array", "items": {"type": "object", "properties": {
103
+ "claim": {"type": "integer"}, "support": {"type": "string", "enum": ["supported", "weak", "contradicted", "not_here"]},
104
+ "evidence": {"type": "string"}}, "required": ["claim", "support", "evidence"]}}}, "required": ["claims"]}
105
+ # "not_here" (this piece does not mention the claim) never replaces anything: a claim no piece backs stays "not_found"
106
+ _RANK = {"contradicted": 3, "supported": 2, "weak": 1, "not_here": 0, "not_found": 0}
107
+
108
+
109
+ def claims(model: str, text: str, main_claims: list) -> dict:
110
+ """Per claim, the strongest verdict over all pieces of the body."""
111
+ if not main_claims:
112
+ return {"claims": []}
113
+ listed = "\n".join(f"{i + 1}. {c}" for i, c in enumerate(main_claims))
114
+ best = {i: {"claim": c, "support": "not_found", "evidence": ""} for i, c in enumerate(main_claims)}
115
+ calls = []
116
+ for ch in body_chunks(text):
117
+ prompt = ("For each numbered CLAIM, judge this PART of the manuscript: 'supported' (a result here, with data, "
118
+ "backs it), 'weak' (only partly: smaller effect, subgroup only, no statistics, or the data show "
119
+ "association while the claim says cause), 'contradicted' (the data here say otherwise) or 'not_here'. "
120
+ "Quote the evidence exactly.\n\n=== CLAIMS ===\n" + listed + "\n\n=== PART OF THE BODY ===\n" + ch)
121
+ r = ai.chat(model, SYSTEM, prompt, CLAIMS_SCHEMA)
122
+ calls.append(r)
123
+ for x in (r.get("json") or {}).get("claims") or []:
124
+ i = (x.get("claim") or 0) - 1
125
+ if i in best and _RANK.get(x.get("support"), 0) > _RANK.get(best[i]["support"], 0):
126
+ best[i].update(support=x["support"], evidence=x.get("evidence", ""))
127
+ return {"claims": list(best.values()), "calls": calls}
128
+
129
+
130
+ CITE_SCHEMA = {"type": "object", "properties": {
131
+ "verdict": {"type": "string", "enum": ["supports", "unrelated", "unclear"]}, "reason": {"type": "string"}},
132
+ "required": ["verdict", "reason"]}
133
+
134
+
135
+ def citation(model: str, sentence: str, title: str) -> dict:
136
+ prompt = ("A manuscript sentence cites a paper. From the paper's TITLE alone, is the paper plausibly a source for "
137
+ "what the sentence states ('supports'), clearly about something else ('unrelated'), or can you not tell "
138
+ "('unclear')? Give a one-sentence reason.\n\nSENTENCE: " + sentence[:600] + "\nCITED PAPER TITLE: " + title[:300])
139
+ return ai.chat(model, SYSTEM, prompt, CITE_SCHEMA, num_ctx=4096)
140
+
141
+
142
+ def citations(model: str, round_dir: Path, limit: int = 40, progress=None) -> list:
143
+ f = round_dir / "checks" / "references.json"
144
+ if not f.exists():
145
+ return []
146
+ refs = [r for r in json.loads(f.read_text(encoding="utf-8")).get("references", [])
147
+ if r.get("found_title") and r.get("cited_in")][:limit]
148
+ out = []
149
+ for i, r in enumerate(refs):
150
+ v = (citation(model, r["cited_in"][0], r["found_title"]).get("json") or {})
151
+ out.append({"n": r["n"], "sentence": r["cited_in"][0], "title": r["found_title"],
152
+ "verdict": v.get("verdict", "unclear"), "reason": v.get("reason", "")})
153
+ if progress:
154
+ progress(i + 1, len(refs))
155
+ return out
156
+
157
+
158
+ # ---- the check, as the dashboard runs it ----
159
+ def run(round_dir: Path, model: str | None = None, progress=None) -> dict:
160
+ settings = load_settings()
161
+ if settings.get("ai_backend", "local") != "local":
162
+ raise RuntimeError("Local AI is switched off in Settings.")
163
+ model = model or ai.status(settings)["model"]
164
+ if not model:
165
+ raise RuntimeError("No local model installed yet: choose one in Settings → Local AI.")
166
+ files = sorted((round_dir / "prepared").glob("*.txt"), key=lambda p: -p.stat().st_size)[:1]
167
+ if not files:
168
+ raise RuntimeError("no prepared text: prepare the manuscript files first")
169
+ text = files[0].read_text(encoding="utf-8", errors="replace")
170
+ step = lambda i: progress and progress(i, 4)
171
+ step(0)
172
+ ov = overview(model, text).get("json") or {}
173
+ step(1)
174
+ cons = consistency(model, text)
175
+ step(2)
176
+ cl = claims(model, text, ov.get("main_claims") or [])
177
+ step(3)
178
+ cites = citations(model, round_dir)
179
+ step(4)
180
+ res = {
181
+ "generated": datetime.now().isoformat(timespec="seconds"), "model": model, "file": files[0].name,
182
+ "overview": ov, "mismatches": cons["mismatches"], "claims": cl["claims"], "citations": cites,
183
+ "summary": {"mismatches": len(cons["mismatches"]),
184
+ "claims_weak": sum(c["support"] in ("weak", "not_found") for c in cl["claims"]),
185
+ "claims_contradicted": sum(c["support"] == "contradicted" for c in cl["claims"]),
186
+ "citations_unrelated": sum(c["verdict"] == "unrelated" for c in cites),
187
+ "model": model},
188
+ "note": "Local model output: signals to check by reading the manuscript, not findings.",
189
+ }
190
+ d = round_dir / "checks"
191
+ d.mkdir(exist_ok=True)
192
+ (d / "ai.json").write_text(json.dumps(res, indent=1, ensure_ascii=False), encoding="utf-8")
193
+ return res
Binary file
Binary file
Binary file
Binary file
Binary file
revigil/authorcheck.py ADDED
@@ -0,0 +1,108 @@
1
+ """Background check of a manuscript's authors with OpenAlex (public, free).
2
+
3
+ Per author: best-matching OpenAlex profile (with how many other people share the name), works,
4
+ citations, h-index, institution, ORCID, main topics, and retracted papers.
5
+ For the manuscript: how many references include one of the authors (self-citation share), and,
6
+ if you set your own OpenAlex ID in Settings, co-authored papers with you (conflict of interest).
7
+ Name matches can be wrong for common names: the "candidates" count says how sure the match is.
8
+ """
9
+ import json
10
+ import re
11
+ import unicodedata
12
+ from datetime import datetime
13
+ from pathlib import Path
14
+
15
+ from .config import load_settings
16
+ from .lookup import get_json
17
+ from .refcheck import split_references
18
+
19
+ OA = "https://api.openalex.org"
20
+
21
+
22
+ def _ascii(s):
23
+ return unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode()
24
+
25
+
26
+ def _surname(name: str) -> str:
27
+ parts = [p for p in re.split(r"\s+", name.strip()) if p]
28
+ return parts[-1] if parts else ""
29
+
30
+
31
+ def lookup_author(name: str, my_id: str | None = None) -> dict:
32
+ j = get_json(f"{OA}/authors", {"search": name, "per-page": 10})
33
+ results = (j or {}).get("results", [])
34
+ # same surname and same first initial; OpenAlex splits one person into several profiles,
35
+ # so take the largest and report how many look-alikes there are
36
+ key = lambda s: (_ascii(_surname(s)).lower(), _ascii(s.strip()[:1]).lower())
37
+ same = [r for r in results if key(r.get("display_name", "")) == key(name)] or results[:1]
38
+ if not same:
39
+ return {"name": name, "found": False}
40
+ best = max(same, key=lambda r: r.get("works_count", 0))
41
+ aid = best["id"].rsplit("/", 1)[-1]
42
+ inst = (best.get("last_known_institutions") or [{}])
43
+ out = {
44
+ "name": name, "found": True, "openalex": best["id"], "display_name": best.get("display_name"),
45
+ "candidates": len(same), "orcid": best.get("orcid"),
46
+ "works": best.get("works_count"), "citations": best.get("cited_by_count"),
47
+ "h_index": (best.get("summary_stats") or {}).get("h_index"),
48
+ "i10_index": (best.get("summary_stats") or {}).get("i10_index"),
49
+ "institution": inst[0].get("display_name") if inst else None,
50
+ "country": inst[0].get("country_code") if inst else None,
51
+ "topics": [t.get("display_name") for t in (best.get("topics") or [])[:4]],
52
+ }
53
+ try:
54
+ r = get_json(f"{OA}/works", {"filter": f"author.id:{aid},is_retracted:true", "per-page": 5,
55
+ "select": "id,display_name,publication_year,doi"})
56
+ out["retracted"] = (r or {}).get("meta", {}).get("count", 0)
57
+ out["retracted_works"] = [{"title": w.get("display_name"), "year": w.get("publication_year"),
58
+ "doi": w.get("doi")} for w in (r or {}).get("results", [])]
59
+ except Exception:
60
+ out["retracted"] = None
61
+ try:
62
+ y = get_json(f"{OA}/works", {"filter": f"author.id:{aid},publication_year:{datetime.now().year - 1}",
63
+ "per-page": 1, "select": "id"})
64
+ out["works_last_year"] = (y or {}).get("meta", {}).get("count")
65
+ except Exception:
66
+ pass
67
+ if my_id:
68
+ try:
69
+ c = get_json(f"{OA}/works", {"filter": f"author.id:{aid},author.id:{my_id}", "per-page": 3,
70
+ "select": "id,display_name,publication_year"})
71
+ out["coauthored_with_me"] = (c or {}).get("meta", {}).get("count", 0)
72
+ except Exception:
73
+ pass
74
+ return out
75
+
76
+
77
+ def run(article: dict, round_dir: Path, text_file: Path | None = None, max_authors: int = 30) -> dict:
78
+ settings = load_settings()
79
+ my_id = (settings.get("my_openalex_id") or "").strip().rsplit("/", 1)[-1] or None
80
+ names = [n for n in article.get("authors", []) if n and len(n) > 3][:max_authors]
81
+ authors = []
82
+ for n in names:
83
+ try:
84
+ authors.append(lookup_author(n, my_id))
85
+ except Exception as e:
86
+ authors.append({"name": n, "found": False, "error": str(e)[:200]})
87
+ prepared = round_dir / "prepared"
88
+ files = [text_file] if text_file else sorted(prepared.glob("*.txt"), key=lambda p: -p.stat().st_size)[:1]
89
+ refs = []
90
+ if files:
91
+ refs, _ = split_references(files[0].read_text(encoding="utf-8", errors="replace"))
92
+ surnames = {_ascii(_surname(n)) for n in names if len(_surname(n)) > 2}
93
+ self_refs = [r[:200] for r in refs if any(re.search(rf"\b{re.escape(s)}\b", _ascii(r[:300])) for s in surnames)]
94
+ summary = {
95
+ "authors": len(names), "found": sum(a.get("found", False) for a in authors),
96
+ "with_retractions": sum(1 for a in authors if a.get("retracted")),
97
+ "ambiguous": sum(1 for a in authors if a.get("candidates", 1) > 1),
98
+ "self_citations": len(self_refs), "references": len(refs),
99
+ "self_citation_pct": round(100 * len(self_refs) / len(refs)) if refs else None,
100
+ "coi": sum(1 for a in authors if a.get("coauthored_with_me")),
101
+ "note": "" if names else "article.json has no author names: add them to run this check",
102
+ }
103
+ res = {"generated": datetime.now().isoformat(timespec="seconds"), "summary": summary, "authors": authors,
104
+ "self_citing_references": self_refs[:60]}
105
+ d = round_dir / "checks"
106
+ d.mkdir(exist_ok=True)
107
+ (d / "authors.json").write_text(json.dumps(res, indent=1, ensure_ascii=False), encoding="utf-8")
108
+ return res