Download code/novelty/litscan.py from bryan7264/lorapop: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/datasets/bryan7264/lorapop/resolve/main/code/novelty/litscan.py
- Command line
-
hf download hf://datasets/bryan7264/lorapop/code/novelty/litscan.py
-
curl -L -o litscan.py https://huggingface.co/datasets/bryan7264/lorapop/resolve/main/code/novelty/litscan.py
18.5 kB
| #!/usr/bin/env python3 | |
| # MIT License, Bryan Cheng, 2026. Part of autonomous-researcher-2. | |
| """litscan: high-recall prior-art search for novelty checks. Standard library only. | |
| search python litscan.py search --proposal P.txt --queries Q.txt --out DIR [--n 25] [--since YEAR] | |
| [--sources arxiv,s2,openreview,europepmc,dblp,openalex,github] [--minutes 8] | |
| cites python litscan.py cites --proposal P.txt --out DIR --seed arXiv:2401.01234 [--seed ...] | |
| (papers citing the seed and papers it cites, via Semantic Scholar; a seed is arXiv:ID, | |
| DOI:..., PMID:..., a Semantic Scholar id, or an exact title) | |
| rank python litscan.py rank --proposal P.txt --out DIR (re-rank DIR/results.jsonl) | |
| Every run merges into DIR/results.jsonl, then rewrites DIR/ranked.md (triage list) and DIR/status.txt. | |
| Optional env keys: S2_API_KEY, OPENALEX_API_KEY (OpenAlex is skipped without one), GITHUB_TOKEN. | |
| """ | |
| import argparse, datetime, html, json, math, os, re, threading, time | |
| import urllib.error, urllib.parse, urllib.request | |
| import xml.etree.ElementTree as ET | |
| from collections import Counter | |
| STOP = set("""a an the of for and or in on to with without by from via using use used based toward towards | |
| we our is are be been as at into than that this these those its it can do does how what when which while | |
| new novel approach approaches method methods study studies paper propose proposed show shows results""".split()) | |
| S2 = "https://api.semanticscholar.org/graph/v1" | |
| S2_FIELDS = "title,abstract,year,venue,externalIds,url" | |
| def fetch(url, headers=None): | |
| hdr = {"User-Agent": "litscan/1.0 (research novelty check)", **(headers or {})} | |
| for i in range(4): | |
| try: | |
| with urllib.request.urlopen(urllib.request.Request(url, headers=hdr), timeout=30) as r: | |
| return r.read().decode("utf-8", "replace") | |
| except urllib.error.HTTPError as e: | |
| if e.code not in (429, 500, 502, 503, 504) or i == 3: | |
| raise | |
| except OSError: # unreachable host or proxy refusal: retry once only | |
| if i >= 1: | |
| raise | |
| time.sleep(3 * 2 ** i) | |
| def clean(s): | |
| return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", str(s or "")))).strip() | |
| def rec(title, abstract, year, venue, url, ids): | |
| try: | |
| year = int(str(year)[:4]) | |
| except ValueError: | |
| year = None | |
| return {"title": clean(title).rstrip("."), "abstract": clean(abstract), "year": year, | |
| "venues": [clean(venue)] if venue else [], "url": url or "", | |
| "ids": {k: v for k, v in (ids or {}).items() if v}, "sources": [], "queries": []} | |
| def terms(q, k): | |
| return [w for w in re.findall(r"[A-Za-z0-9][A-Za-z0-9\-]*", q) if w.lower() not in STOP][:k] | |
| def src_arxiv(q, n, since): | |
| phrases = re.findall(r'"([^"]+)"', q) | |
| parts = [f'all:"{p}"' for p in phrases] + [f"all:{w}" for w in terms(re.sub(r'"[^"]*"', " ", q), 6)] | |
| query, ns, out = " AND ".join(parts[:6]) or q, {"a": "http://www.w3.org/2005/Atom"}, [] | |
| for sort, k in (("relevance", n), ("submittedDate", max(5, n // 2))): # second pass catches new preprints | |
| url = "https://export.arxiv.org/api/query?" + urllib.parse.urlencode( | |
| {"search_query": query, "start": 0, "max_results": k, "sortBy": sort, "sortOrder": "descending"}) | |
| for e in ET.fromstring(fetch(url)).findall("a:entry", ns): | |
| eid = e.findtext("a:id", "", ns) | |
| if "/api/errors" in eid: | |
| continue | |
| aid = re.sub(r"v\d+$", "", eid.split("/abs/")[-1]) | |
| out.append(rec(e.findtext("a:title", "", ns), e.findtext("a:summary", "", ns), | |
| e.findtext("a:published", "", ns)[:4], "arXiv", "https://arxiv.org/abs/" + aid, | |
| {"arxiv": aid})) | |
| time.sleep(3) # arXiv asks for one request every 3 seconds | |
| return out | |
| def s2_headers(): | |
| key = os.environ.get("S2_API_KEY") or os.environ.get("SEMANTIC_SCHOLAR_API_KEY") | |
| return {"x-api-key": key} if key else {} | |
| def s2rec(x): | |
| ids = x.get("externalIds") or {} | |
| url = ("https://arxiv.org/abs/" + ids["ArXiv"] if ids.get("ArXiv") else x.get("url") | |
| or ("https://www.semanticscholar.org/paper/" + x["paperId"] if x.get("paperId") else "")) | |
| return rec(x.get("title"), x.get("abstract"), x.get("year"), x.get("venue"), url, | |
| {"arxiv": ids.get("ArXiv"), "doi": ids.get("DOI"), "s2": x.get("paperId")}) | |
| def src_s2(q, n, since): | |
| p = {"query": re.sub(r'["\-]', " ", q), "limit": min(n, 100), "fields": S2_FIELDS} | |
| if since: | |
| p["year"] = f"{since}-" | |
| d = json.loads(fetch(f"{S2}/paper/search?" + urllib.parse.urlencode(p), s2_headers())) | |
| time.sleep(1.2 if s2_headers() else 3) | |
| return [s2rec(x) for x in d.get("data") or []] | |
| def note_val(c, k): | |
| v = c.get(k) | |
| return v.get("value") if isinstance(v, dict) else v | |
| def src_openreview(q, n, since): # api2 covers newer venues, api (v1) older ones; rejected papers count too | |
| out, errs = [], [] | |
| for base in ("https://api2.openreview.net", "https://api.openreview.net"): | |
| p = {"term": q.replace('"', ""), "type": "terms", "content": "all", "group": "all", | |
| "source": "forum", "limit": n} | |
| try: | |
| notes = json.loads(fetch(base + "/notes/search?" + urllib.parse.urlencode(p))).get("notes") or [] | |
| except Exception as e: | |
| errs.append(e) | |
| continue | |
| for x in notes: | |
| c, ms = x.get("content") or {}, x.get("pdate") or x.get("cdate") or x.get("tcdate") | |
| yr = datetime.datetime.fromtimestamp(ms / 1000, datetime.timezone.utc).year if ms else None | |
| out.append(rec(note_val(c, "title"), note_val(c, "abstract"), yr, note_val(c, "venue") or "OpenReview", | |
| "https://openreview.net/forum?id=" + str(x.get("forum") or x.get("id")), | |
| {"openreview": x.get("id")})) | |
| time.sleep(1) | |
| if len(errs) == 2: | |
| raise errs[0] | |
| return out | |
| def src_europepmc(q, n, since): # PubMed plus bioRxiv/medRxiv preprints | |
| p = {"query": f"({q}) AND PUB_YEAR:[{since} TO 3000]" if since else q, "format": "json", | |
| "resultType": "core", "pageSize": min(n, 1000)} | |
| d = json.loads(fetch("https://www.ebi.ac.uk/europepmc/webservices/rest/search?" + urllib.parse.urlencode(p))) | |
| out = [] | |
| for x in (d.get("resultList") or {}).get("result") or []: | |
| venue = (((x.get("journalInfo") or {}).get("journal") or {}).get("title") | |
| or (x.get("bookOrReportDetails") or {}).get("publisher") or x.get("source")) | |
| url = (f"https://doi.org/{x['doi']}" if x.get("doi") | |
| else f"https://europepmc.org/article/{x.get('source')}/{x.get('id')}") | |
| out.append(rec(x.get("title"), x.get("abstractText"), x.get("pubYear"), venue, url, | |
| {"doi": x.get("doi"), "pmid": x.get("pmid")})) | |
| time.sleep(0.5) | |
| return out | |
| def src_dblp(q, n, since): # CS venues and workshops, titles only | |
| p = {"q": q.replace('"', ""), "format": "json", "h": min(n, 1000)} | |
| d = json.loads(fetch("https://dblp.org/search/publ/api?" + urllib.parse.urlencode(p))) | |
| out = [] | |
| for h in ((d.get("result") or {}).get("hits") or {}).get("hit") or []: | |
| i = h.get("info") or {} | |
| ee, venue = i.get("ee"), i.get("venue") | |
| ee = ee[0] if isinstance(ee, list) else ee | |
| venue = ", ".join(venue) if isinstance(venue, list) else venue | |
| out.append(rec(i.get("title"), "", i.get("year"), venue, ee or i.get("url"), {"doi": i.get("doi")})) | |
| time.sleep(1) | |
| return out | |
| def src_openalex(q, n, since): | |
| p = {"search": q.replace('"', ""), "per_page": min(n, 100), "api_key": os.environ["OPENALEX_API_KEY"]} | |
| if since: | |
| p["filter"] = f"from_publication_date:{since}-01-01" | |
| out = [] | |
| for x in json.loads(fetch("https://api.openalex.org/works?" + urllib.parse.urlencode(p))).get("results") or []: | |
| pos = {i: w for w, idx in (x.get("abstract_inverted_index") or {}).items() for i in idx} | |
| src = ((x.get("primary_location") or {}).get("source") or {}).get("display_name") | |
| out.append(rec(x.get("display_name") or x.get("title"), " ".join(pos[i] for i in sorted(pos)), | |
| x.get("publication_year"), src, x.get("doi") or x.get("id"), | |
| {"doi": (x.get("doi") or "").replace("https://doi.org/", "")})) | |
| time.sleep(0.3) | |
| return out | |
| def src_github(q, n, since): # code that already implements the idea | |
| tok = os.environ.get("GITHUB_TOKEN") | |
| hdr = {"Accept": "application/vnd.github+json", **({"Authorization": f"Bearer {tok}"} if tok else {})} | |
| p = {"q": " ".join(terms(q.replace('"', " "), 4)), "per_page": min(n, 30)} | |
| d = json.loads(fetch("https://api.github.com/search/repositories?" + urllib.parse.urlencode(p), hdr)) | |
| time.sleep(2.5 if tok else 6.5) # search API allows 10 requests/min without a token | |
| return [rec(x.get("full_name"), x.get("description"), (x.get("created_at") or "")[:4], | |
| f"GitHub, {x.get('stargazers_count', 0)} stars", x.get("html_url"), {}) | |
| for x in d.get("items") or []] | |
| SOURCES = {"arxiv": src_arxiv, "s2": src_s2, "openreview": src_openreview, "europepmc": src_europepmc, | |
| "dblp": src_dblp, "openalex": src_openalex, "github": src_github} | |
| def run_source(name, queries, n, since, deadline, sink, status, lock): | |
| got, fails, note = 0, 0, "" | |
| for qi, q in enumerate(queries, 1): | |
| if time.time() > deadline: | |
| note = f"stopped at time limit after {qi - 1} of {len(queries)} queries" | |
| break | |
| try: | |
| recs, fails = SOURCES[name](q, n, since), 0 | |
| except Exception as e: | |
| fails, note = fails + 1, f"{type(e).__name__}: {e}"[:160] | |
| if fails >= (2 if got == 0 else 4): # unreachable or persistently refusing: stop this source | |
| note += f" (gave up at query {qi})" | |
| break | |
| continue | |
| for r in recs: | |
| r["sources"], r["queries"] = [name], [f"q{qi}"] | |
| with lock: | |
| sink.extend(recs) | |
| got += len(recs) | |
| status[name] = f"{got} hits" + (f"; {note}" if note else "") | |
| PREFIX = {"arxiv": "arXiv", "doi": "DOI", "corpusid": "CorpusId", "pmid": "PMID", "pmcid": "PMCID", | |
| "acl": "ACL", "mag": "MAG", "url": "URL"} | |
| def s2_resolve(seed): | |
| m = re.match(r"^(arxiv|doi|corpusid|pmid|pmcid|acl|mag|url):(.+)$", seed.strip(), re.I) | |
| if m: | |
| return f"{PREFIX[m.group(1).lower()]}:{m.group(2).strip()}" | |
| if re.fullmatch(r"[0-9a-f]{40}", seed.strip()): | |
| return seed.strip() | |
| d = json.loads(fetch(f"{S2}/paper/search/match?" + urllib.parse.urlencode({"query": seed, "fields": "title"}), | |
| s2_headers())) | |
| return d["data"][0]["paperId"] | |
| def cites(seed): | |
| pid, out = s2_resolve(seed), [] | |
| for rel, key in (("citations", "citingPaper"), ("references", "citedPaper")): | |
| url = (f"{S2}/paper/{urllib.parse.quote(pid, safe=':/')}/{rel}?" | |
| + urllib.parse.urlencode({"fields": S2_FIELDS, "limit": 1000})) | |
| for x in json.loads(fetch(url, s2_headers())).get("data") or []: | |
| p = x.get(key) or {} | |
| if p.get("title"): | |
| r = s2rec(p) | |
| r["sources"], r["queries"] = [f"s2-{rel}"], [f"{rel} of {seed}"] | |
| out.append(r) | |
| time.sleep(1.2 if s2_headers() else 3) | |
| return out | |
| def norm(t): | |
| return re.sub(r"[^a-z0-9]", "", (t or "").lower())[:150] | |
| def merge(records): | |
| by = {} | |
| for r in records: | |
| k = norm(r["title"]) | |
| if len(k) < 8: | |
| continue | |
| m = by.get(k) | |
| if m is None: | |
| m = by[k] = {**r, "venues": [], "sources": [], "queries": [], "ids": {}} | |
| if len(r["abstract"]) > len(m["abstract"]): | |
| m["abstract"] = r["abstract"] | |
| if r["year"] and (not m["year"] or r["year"] < m["year"]): | |
| m["year"] = r["year"] | |
| if r["url"] and (not m["url"] or ("arxiv.org" in r["url"] and "arxiv.org" not in m["url"])): | |
| m["url"] = r["url"] | |
| for f in ("venues", "sources", "queries"): | |
| m[f] += [x for x in r[f] if x and x not in m[f]] | |
| m["ids"].update({key: v for key, v in r["ids"].items() if v}) | |
| return list(by.values()) | |
| def toks(s): | |
| w = [t for t in re.findall(r"[a-z0-9]+", s.lower()) if t not in STOP and len(t) > 1] | |
| return w + [a + " " + b for a, b in zip(w, w[1:])] | |
| def rank(papers, proposal): # TF-IDF cosine (unigrams + bigrams), title counted twice | |
| docs = [toks(p["title"] + " " + p["title"] + " " + p["abstract"]) for p in papers] | |
| qt = toks(proposal) | |
| df, n = Counter(t for d in docs + [qt] for t in set(d)), len(docs) + 1 | |
| def vec(d): | |
| v = {t: (1 + math.log(c)) * (1 + math.log((n + 1) / (df[t] + 1))) for t, c in Counter(d).items()} | |
| z = math.sqrt(sum(x * x for x in v.values())) or 1.0 | |
| return {t: x / z for t, x in v.items()} | |
| qv = vec(qt) | |
| for p, d in zip(papers, docs): | |
| dv = vec(d) | |
| p["score"] = round(sum(x * dv.get(t, 0.0) for t, x in qv.items()), 4) | |
| papers.sort(key=lambda p: -p["score"]) | |
| return papers | |
| def load(out): | |
| path = os.path.join(out, "results.jsonl") | |
| if not os.path.exists(path): | |
| return [] | |
| with open(path) as f: | |
| return [json.loads(line) for line in f if line.strip()] | |
| def load_status(out): | |
| path = os.path.join(out, "status.txt") | |
| if not os.path.exists(path): | |
| return {} | |
| with open(path) as f: | |
| return dict(line.rstrip("\n").split(": ", 1) for line in f if ": " in line) | |
| def write(out, papers, proposal_path, status): | |
| with open(os.path.join(out, "results.jsonl"), "w") as f: | |
| f.writelines(json.dumps(p, ensure_ascii=False) + "\n" for p in papers) | |
| with open(os.path.join(out, "status.txt"), "w") as f: | |
| f.writelines(f"{k}: {v}\n" for k, v in status.items()) | |
| recent = datetime.date.today().year - 1 | |
| def line(label, p, with_abstract): | |
| s = (f"{label}. [{p['score']:.3f}] {p['title']} ({p['year'] or 'n.d.'}; " | |
| f"{', '.join(p['venues'][:2]) or 'venue n/a'}) {p['url']} " | |
| f"(found by {','.join(p['sources'])}; {', '.join(p['queries'][:6])})") | |
| if with_abstract and p["abstract"]: | |
| s += f"\n {p['abstract'][:700]}{'...' if len(p['abstract']) > 700 else ''}" | |
| return s | |
| newer = [p for p in papers[50:] if (p["year"] or 0) >= recent][:25] | |
| lines = [f"# Prior-art triage: {len(papers)} unique items", "", | |
| f"Ranked by lexical similarity to {proposal_path}.", | |
| "Sources: " + "; ".join(f"{k}: {v}" for k, v in status.items()), "", | |
| "Similarity is a triage aid only. Work that describes the same idea in other words can rank low,", | |
| "so scan every title below and open anything that might be close.", "", | |
| "## Top 50 (read every abstract)"] | |
| lines += [line(str(i), p, True) for i, p in enumerate(papers[:50], 1)] | |
| lines += ["", f"## Published {recent} or later, outside the top 50"] | |
| lines += [line(f"R{i}", p, True) for i, p in enumerate(newer, 1)] | |
| lines += ["", "## Ranks 51 to 250 (titles only)"] | |
| lines += [line(str(i), p, False) for i, p in enumerate(papers[50:250], 51)] | |
| with open(os.path.join(out, "ranked.md"), "w") as f: | |
| f.write("\n".join(lines) + "\n") | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| sub = ap.add_subparsers(dest="cmd", required=True) | |
| for name in ("search", "cites", "rank"): | |
| s = sub.add_parser(name) | |
| s.add_argument("--proposal", required=True, help="text file describing the idea, used for ranking") | |
| s.add_argument("--out", required=True, help="output directory, reused across runs of one iteration") | |
| if name == "search": | |
| s.add_argument("--queries", required=True, help="one query per line; lines starting with # are skipped") | |
| s.add_argument("--n", type=int, default=25, help="results per query per source") | |
| s.add_argument("--since", type=int, help="drop items published before this year") | |
| s.add_argument("--sources", default=",".join(SOURCES)) | |
| s.add_argument("--minutes", type=float, default=8.0, help="stop sending queries after this long") | |
| if name == "cites": | |
| s.add_argument("--seed", required=True, action="append", help="repeat for several seeds") | |
| a = ap.parse_args() | |
| os.makedirs(a.out, exist_ok=True) | |
| with open(a.proposal) as f: | |
| proposal = f.read() | |
| status, new = load_status(a.out), [] | |
| if a.cmd == "search": | |
| with open(a.queries) as f: | |
| queries = [l.strip() for l in f if l.strip() and not l.lstrip().startswith("#")] | |
| names = [s.strip() for s in a.sources.split(",") if s.strip() in SOURCES] | |
| if "openalex" in names and not os.environ.get("OPENALEX_API_KEY"): | |
| names.remove("openalex") | |
| status["openalex"] = "skipped: set OPENALEX_API_KEY (free at openalex.org/settings/api)" | |
| lock, deadline = threading.Lock(), time.time() + 60 * a.minutes | |
| threads = [threading.Thread(target=run_source, args=(nm, queries, a.n, a.since, deadline, new, status, lock)) | |
| for nm in names] | |
| for t in threads: | |
| t.start() | |
| for t in threads: | |
| t.join() | |
| elif a.cmd == "cites": | |
| for seed in a.seed: | |
| try: | |
| got = cites(seed) | |
| new += got | |
| status[f"cites {seed}"] = f"{len(got)} citing or cited items" | |
| except Exception as e: | |
| status[f"cites {seed}"] = f"failed: {type(e).__name__}: {e}"[:200] | |
| papers = merge(load(a.out) + new) | |
| if a.cmd == "search" and a.since: | |
| papers = [p for p in papers if not p["year"] or p["year"] >= a.since] | |
| rank(papers, proposal) | |
| write(a.out, papers, a.proposal, status) | |
| print(f"{len(papers)} unique items -> {a.out}/results.jsonl, triage list -> {a.out}/ranked.md") | |
| for k, v in status.items(): | |
| print(f" {k}: {v}") | |
| if not papers: | |
| print("No results. If every source failed, this shell cannot reach the APIs: use WebSearch and WebFetch.") | |
| for i, p in enumerate(papers[:10], 1): | |
| print(f" {i}. [{p['score']:.3f}] {p['title'][:110]} ({p['year'] or 'n.d.'})") | |
| if __name__ == "__main__": | |
| main() | |