blindlint 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.
- blindlint/__init__.py +3 -0
- blindlint/__main__.py +5 -0
- blindlint/api.py +216 -0
- blindlint/bookmarklet.py +75 -0
- blindlint/citations/__init__.py +10 -0
- blindlint/citations/bibtex.py +168 -0
- blindlint/citations/http.py +155 -0
- blindlint/citations/match.py +176 -0
- blindlint/citations/pipeline.py +148 -0
- blindlint/citations/refs.py +486 -0
- blindlint/citations/related.py +237 -0
- blindlint/citations/retractions.py +74 -0
- blindlint/citations/selfcite.py +145 -0
- blindlint/citations/sources.py +385 -0
- blindlint/citations/venue_names.py +94 -0
- blindlint/citations/verify.py +291 -0
- blindlint/cli.py +472 -0
- blindlint/config.py +147 -0
- blindlint/engine.py +44 -0
- blindlint/loaders.py +222 -0
- blindlint/model.py +122 -0
- blindlint/notation/__init__.py +6 -0
- blindlint/notation/analyze.py +599 -0
- blindlint/notation/meaning.py +442 -0
- blindlint/notation/pdf.py +66 -0
- blindlint/notation/symbols.py +511 -0
- blindlint/notation/table.py +122 -0
- blindlint/notation/tex.py +450 -0
- blindlint/numbers/__init__.py +8 -0
- blindlint/numbers/latex.py +255 -0
- blindlint/numbers/results.py +323 -0
- blindlint/numbers/tfevents.py +144 -0
- blindlint/numbers/values.py +120 -0
- blindlint/registry.py +92 -0
- blindlint/report.py +98 -0
- blindlint/rules/__init__.py +36 -0
- blindlint/rules/anonymity.py +601 -0
- blindlint/rules/citations.py +374 -0
- blindlint/rules/notation.py +462 -0
- blindlint/rules/numbers.py +534 -0
- blindlint/rules/pages.py +154 -0
- blindlint/rules/words.py +229 -0
- blindlint/score.py +221 -0
- blindlint/sources.py +207 -0
- blindlint/text_report.py +100 -0
- blindlint/ui.py +1052 -0
- blindlint/venues/__init__.py +382 -0
- blindlint/venues/data/3dv.toml +9 -0
- blindlint/venues/data/aaai.toml +11 -0
- blindlint/venues/data/aamas.toml +9 -0
- blindlint/venues/data/accv.toml +10 -0
- blindlint/venues/data/acl-short.toml +15 -0
- blindlint/venues/data/acl-workshop.toml +10 -0
- blindlint/venues/data/acl.toml +15 -0
- blindlint/venues/data/acm-mm.toml +12 -0
- blindlint/venues/data/acsac.toml +10 -0
- blindlint/venues/data/aies.toml +9 -0
- blindlint/venues/data/aij.toml +10 -0
- blindlint/venues/data/aistats.toml +10 -0
- blindlint/venues/data/alt.toml +8 -0
- blindlint/venues/data/ase.toml +11 -0
- blindlint/venues/data/asiaccs.toml +12 -0
- blindlint/venues/data/asiacrypt.toml +10 -0
- blindlint/venues/data/asplos.toml +10 -0
- blindlint/venues/data/assets.toml +8 -0
- blindlint/venues/data/atc.toml +10 -0
- blindlint/venues/data/bmvc.toml +9 -0
- blindlint/venues/data/cav.toml +10 -0
- blindlint/venues/data/ccc.toml +8 -0
- blindlint/venues/data/ccs.toml +20 -0
- blindlint/venues/data/chi.toml +10 -0
- blindlint/venues/data/chiir.toml +10 -0
- blindlint/venues/data/cikm.toml +11 -0
- blindlint/venues/data/cl.toml +10 -0
- blindlint/venues/data/coling.toml +16 -0
- blindlint/venues/data/colm.toml +10 -0
- blindlint/venues/data/colt.toml +9 -0
- blindlint/venues/data/conext.toml +9 -0
- blindlint/venues/data/conll.toml +10 -0
- blindlint/venues/data/corl.toml +14 -0
- blindlint/venues/data/crypto.toml +9 -0
- blindlint/venues/data/cscw.toml +8 -0
- blindlint/venues/data/cvpr-workshop.toml +9 -0
- blindlint/venues/data/cvpr.toml +10 -0
- blindlint/venues/data/dac.toml +11 -0
- blindlint/venues/data/dis.toml +9 -0
- blindlint/venues/data/disc.toml +8 -0
- blindlint/venues/data/ec.toml +9 -0
- blindlint/venues/data/eccv.toml +9 -0
- blindlint/venues/data/ecir.toml +10 -0
- blindlint/venues/data/ecml-pkdd.toml +12 -0
- blindlint/venues/data/ecoop.toml +8 -0
- blindlint/venues/data/edbt.toml +11 -0
- blindlint/venues/data/esa.toml +8 -0
- blindlint/venues/data/euro-sp.toml +10 -0
- blindlint/venues/data/eurocrypt.toml +9 -0
- blindlint/venues/data/eurographics.toml +9 -0
- blindlint/venues/data/eurosys.toml +9 -0
- blindlint/venues/data/facct.toml +10 -0
- blindlint/venues/data/fast.toml +9 -0
- blindlint/venues/data/focs.toml +8 -0
- blindlint/venues/data/fse.toml +12 -0
- blindlint/venues/data/hpca.toml +10 -0
- blindlint/venues/data/hri.toml +10 -0
- blindlint/venues/data/icalp.toml +8 -0
- blindlint/venues/data/icaps-short.toml +10 -0
- blindlint/venues/data/icaps.toml +10 -0
- blindlint/venues/data/icassp.toml +11 -0
- blindlint/venues/data/iccad.toml +11 -0
- blindlint/venues/data/iccv.toml +9 -0
- blindlint/venues/data/icdcs.toml +11 -0
- blindlint/venues/data/icde.toml +11 -0
- blindlint/venues/data/icdm.toml +11 -0
- blindlint/venues/data/icdt.toml +9 -0
- blindlint/venues/data/icfp.toml +9 -0
- blindlint/venues/data/icip.toml +11 -0
- blindlint/venues/data/iclr-workshop.toml +8 -0
- blindlint/venues/data/iclr.toml +10 -0
- blindlint/venues/data/icme.toml +12 -0
- blindlint/venues/data/icmi.toml +10 -0
- blindlint/venues/data/icml-workshop.toml +8 -0
- blindlint/venues/data/icml.toml +10 -0
- blindlint/venues/data/iconip.toml +11 -0
- blindlint/venues/data/icpr.toml +11 -0
- blindlint/venues/data/icra.toml +11 -0
- blindlint/venues/data/icse.toml +11 -0
- blindlint/venues/data/icwsm.toml +10 -0
- blindlint/venues/data/ieee-sps.toml +12 -0
- blindlint/venues/data/ieee-vr.toml +12 -0
- blindlint/venues/data/ijcai.toml +12 -0
- blindlint/venues/data/ijcnn.toml +11 -0
- blindlint/venues/data/ijcv.toml +9 -0
- blindlint/venues/data/imc.toml +10 -0
- blindlint/venues/data/imwut.toml +11 -0
- blindlint/venues/data/infocom.toml +11 -0
- blindlint/venues/data/inlg-short.toml +10 -0
- blindlint/venues/data/inlg.toml +10 -0
- blindlint/venues/data/interspeech-long.toml +12 -0
- blindlint/venues/data/interspeech.toml +12 -0
- blindlint/venues/data/ipdps.toml +10 -0
- blindlint/venues/data/iros.toml +11 -0
- blindlint/venues/data/isbi.toml +11 -0
- blindlint/venues/data/isca.toml +10 -0
- blindlint/venues/data/ismar.toml +10 -0
- blindlint/venues/data/ismb.toml +12 -0
- blindlint/venues/data/issta.toml +11 -0
- blindlint/venues/data/itcs.toml +7 -0
- blindlint/venues/data/iui.toml +8 -0
- blindlint/venues/data/jacm.toml +9 -0
- blindlint/venues/data/jair.toml +8 -0
- blindlint/venues/data/jmlr.toml +9 -0
- blindlint/venues/data/kdd.toml +9 -0
- blindlint/venues/data/kr-short.toml +11 -0
- blindlint/venues/data/kr.toml +11 -0
- blindlint/venues/data/lics.toml +9 -0
- blindlint/venues/data/lrec.toml +9 -0
- blindlint/venues/data/media.toml +10 -0
- blindlint/venues/data/miccai.toml +11 -0
- blindlint/venues/data/micro.toml +10 -0
- blindlint/venues/data/midl.toml +10 -0
- blindlint/venues/data/mlhc.toml +11 -0
- blindlint/venues/data/mlsys.toml +9 -0
- blindlint/venues/data/mobicom.toml +9 -0
- blindlint/venues/data/mobisys.toml +9 -0
- blindlint/venues/data/msr.toml +11 -0
- blindlint/venues/data/nature-cs.toml +12 -0
- blindlint/venues/data/nature-methods.toml +12 -0
- blindlint/venues/data/nature-mi.toml +12 -0
- blindlint/venues/data/nature.toml +11 -0
- blindlint/venues/data/ncomms.toml +12 -0
- blindlint/venues/data/ndss.toml +10 -0
- blindlint/venues/data/neural-networks.toml +10 -0
- blindlint/venues/data/neurips-ed.toml +16 -0
- blindlint/venues/data/neurips-workshop.toml +8 -0
- blindlint/venues/data/neurips.toml +16 -0
- blindlint/venues/data/nsdi.toml +9 -0
- blindlint/venues/data/oopsla.toml +11 -0
- blindlint/venues/data/osdi.toml +9 -0
- blindlint/venues/data/pakdd.toml +12 -0
- blindlint/venues/data/pattern-recognition.toml +14 -0
- blindlint/venues/data/percom.toml +11 -0
- blindlint/venues/data/pets.toml +11 -0
- blindlint/venues/data/pldi.toml +10 -0
- blindlint/venues/data/plos-cb.toml +10 -0
- blindlint/venues/data/pnas.toml +12 -0
- blindlint/venues/data/podc.toml +8 -0
- blindlint/venues/data/pods.toml +9 -0
- blindlint/venues/data/popl.toml +9 -0
- blindlint/venues/data/ppopp.toml +10 -0
- blindlint/venues/data/pricai.toml +11 -0
- blindlint/venues/data/ral.toml +12 -0
- blindlint/venues/data/recomb.toml +9 -0
- blindlint/venues/data/recsys-short.toml +10 -0
- blindlint/venues/data/recsys.toml +10 -0
- blindlint/venues/data/rss.toml +11 -0
- blindlint/venues/data/rtss.toml +11 -0
- blindlint/venues/data/sc.toml +12 -0
- blindlint/venues/data/science.toml +12 -0
- blindlint/venues/data/sdm.toml +9 -0
- blindlint/venues/data/sensys.toml +9 -0
- blindlint/venues/data/sigcomm.toml +9 -0
- blindlint/venues/data/sigdial-short.toml +10 -0
- blindlint/venues/data/sigdial.toml +10 -0
- blindlint/venues/data/siggraph-asia.toml +10 -0
- blindlint/venues/data/siggraph.toml +10 -0
- blindlint/venues/data/sigir.toml +10 -0
- blindlint/venues/data/sigmetrics.toml +10 -0
- blindlint/venues/data/sigmod.toml +10 -0
- blindlint/venues/data/socg.toml +8 -0
- blindlint/venues/data/soda.toml +8 -0
- blindlint/venues/data/sosp.toml +9 -0
- blindlint/venues/data/sp.toml +11 -0
- blindlint/venues/data/spaa.toml +9 -0
- blindlint/venues/data/stoc.toml +8 -0
- blindlint/venues/data/tacl.toml +10 -0
- blindlint/venues/data/tkde.toml +11 -0
- blindlint/venues/data/tmi.toml +12 -0
- blindlint/venues/data/tmlr.toml +8 -0
- blindlint/venues/data/tnnls.toml +9 -0
- blindlint/venues/data/tochi.toml +9 -0
- blindlint/venues/data/tog.toml +9 -0
- blindlint/venues/data/tois.toml +10 -0
- blindlint/venues/data/tosem.toml +9 -0
- blindlint/venues/data/tpami.toml +11 -0
- blindlint/venues/data/tse.toml +8 -0
- blindlint/venues/data/uai.toml +9 -0
- blindlint/venues/data/uist.toml +9 -0
- blindlint/venues/data/usenix-security.toml +11 -0
- blindlint/venues/data/vis.toml +13 -0
- blindlint/venues/data/vldb.toml +10 -0
- blindlint/venues/data/wacv.toml +9 -0
- blindlint/venues/data/wsdm-short.toml +11 -0
- blindlint/venues/data/wsdm.toml +11 -0
- blindlint/venues/data/www.toml +11 -0
- blindlint/venues/venue.schema.json +194 -0
- blindlint/web.py +59 -0
- blindlint-0.1.0.dist-info/METADATA +774 -0
- blindlint-0.1.0.dist-info/RECORD +241 -0
- blindlint-0.1.0.dist-info/WHEEL +4 -0
- blindlint-0.1.0.dist-info/entry_points.txt +2 -0
- blindlint-0.1.0.dist-info/licenses/LICENSE +21 -0
blindlint/__init__.py
ADDED
blindlint/__main__.py
ADDED
blindlint/api.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Plain functions behind the web UIs: the local server (`blindlint ui`) and the in-browser Pyodide demo.
|
|
2
|
+
|
|
3
|
+
Nothing here imports server modules, so it runs unchanged inside Pyodide. The network is only used when the
|
|
4
|
+
caller asks for online reference checks: the local server then looks references up from Python, and the browser
|
|
5
|
+
demo drives `CitationSession` from JavaScript, which does the fetching.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
import tempfile
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .citations.pipeline import Progress, pipeline
|
|
17
|
+
from .citations.refs import references_for
|
|
18
|
+
from .citations.sources import Request, Response, settings_from
|
|
19
|
+
from .engine import check_document, skipped_modules
|
|
20
|
+
from .loaders import load
|
|
21
|
+
from .loaders import unpack_zip as _unpack_zip
|
|
22
|
+
from .numbers.results import NumbersSettings, ResultSpec
|
|
23
|
+
from .registry import Context
|
|
24
|
+
from .score import coverage, readiness
|
|
25
|
+
from .text_report import render_markdown
|
|
26
|
+
from .venues import VENUES, custom_venue, get_venue
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def venues() -> list[dict]:
|
|
30
|
+
return [v.to_dict() for v in VENUES.values()]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def run_check(data: bytes, filename: str, options: dict) -> dict:
|
|
34
|
+
suffix = Path(filename).suffix.lower()
|
|
35
|
+
if suffix not in (".pdf", ".tex", ".zip", ".bib"):
|
|
36
|
+
raise ValueError("Drop a .pdf file, a single .tex or .bib file, or a .zip of your LaTeX project.")
|
|
37
|
+
venue = None
|
|
38
|
+
if options.get("max_pages"):
|
|
39
|
+
venue = custom_venue(int(options["max_pages"]))
|
|
40
|
+
elif options.get("venue"):
|
|
41
|
+
venue = get_venue(options["venue"])
|
|
42
|
+
ctx = Context(
|
|
43
|
+
venue=venue,
|
|
44
|
+
identity=[s.strip() for s in options.get("identity", []) if s.strip()],
|
|
45
|
+
allow_urls=[s.strip() for s in options.get("allow_urls", []) if s.strip()],
|
|
46
|
+
)
|
|
47
|
+
# In the browser, Python cannot open sockets; the page runs CitationSession instead.
|
|
48
|
+
if options.get("online") and sys.platform != "emscripten":
|
|
49
|
+
ctx.online = True
|
|
50
|
+
ctx.citations = settings_from()
|
|
51
|
+
notation = None
|
|
52
|
+
with tempfile.TemporaryDirectory(prefix="blindlint-") as tmp:
|
|
53
|
+
if suffix == ".zip":
|
|
54
|
+
path = _unpack_zip(data, Path(tmp))
|
|
55
|
+
else:
|
|
56
|
+
path = Path(tmp) / f"upload{suffix}"
|
|
57
|
+
path.write_bytes(data)
|
|
58
|
+
ctx.numbers = NumbersSettings(results=_write_results(Path(tmp) / "results", options.get("results") or []))
|
|
59
|
+
findings = check_document(path, ctx, set(options.get("ignore", [])))
|
|
60
|
+
if suffix not in (".pdf", ".bib"):
|
|
61
|
+
from .notation.table import notation_rows, render_table
|
|
62
|
+
|
|
63
|
+
rows = notation_rows(load(path))
|
|
64
|
+
notation = {"rows": rows[:500], "latex": render_table(rows, "latex"), "markdown": render_table(rows, "markdown")}
|
|
65
|
+
out = _finding_dicts(findings, filename, f"upload{suffix}:")
|
|
66
|
+
if notation:
|
|
67
|
+
for r in notation["rows"]:
|
|
68
|
+
r["defined_at"] = r["defined_at"].replace(f"upload{suffix}:", f"{filename}:")
|
|
69
|
+
skipped = sorted(skipped_modules(ctx))
|
|
70
|
+
result = {
|
|
71
|
+
"file": filename,
|
|
72
|
+
"venue": venue.label if venue else None,
|
|
73
|
+
"venue_info": venue.to_dict() if venue else None,
|
|
74
|
+
"skipped": skipped,
|
|
75
|
+
"findings": out,
|
|
76
|
+
"readiness": readiness(findings).to_dict(),
|
|
77
|
+
"coverage": coverage("pdf" if suffix == ".pdf" else "tex", venue, bool(ctx.identity), options.get("ignore", []), skipped),
|
|
78
|
+
"notation": notation,
|
|
79
|
+
}
|
|
80
|
+
result["report_markdown"] = render_markdown([result])
|
|
81
|
+
result["report_ai"] = render_markdown([result], for_ai=True)
|
|
82
|
+
return result
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _finding_dicts(findings, filename: str, temp_prefix: str = "") -> list[dict]:
|
|
86
|
+
out = []
|
|
87
|
+
for f in findings:
|
|
88
|
+
d = f.to_dict()
|
|
89
|
+
d["file"] = filename
|
|
90
|
+
d["location"] = str(f.location)
|
|
91
|
+
if temp_prefix:
|
|
92
|
+
d["location"] = d["location"].replace(temp_prefix, f"{filename}:")
|
|
93
|
+
d["message"] = d["message"].replace(temp_prefix, f"{filename}:")
|
|
94
|
+
out.append(d)
|
|
95
|
+
return out
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _write_results(folder: Path, results: list) -> list[ResultSpec]:
|
|
99
|
+
"""Result files sent along with the paper: [{"name": "main.json", "b64": "..."}]. Matched to \\pfresults by name."""
|
|
100
|
+
specs = []
|
|
101
|
+
folder.mkdir(exist_ok=True)
|
|
102
|
+
for i, r in enumerate(results):
|
|
103
|
+
name = Path(str(r.get("name") or f"results{i}.json")).name
|
|
104
|
+
target = folder / str(i)
|
|
105
|
+
target.mkdir()
|
|
106
|
+
f = target / name
|
|
107
|
+
try:
|
|
108
|
+
f.write_bytes(base64.b64decode(r.get("b64") or ""))
|
|
109
|
+
except ValueError as e:
|
|
110
|
+
raise ValueError(f"{name}: could not read the uploaded file") from e
|
|
111
|
+
specs.append(ResultSpec(f, name=name, origin="uploaded results"))
|
|
112
|
+
return specs
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def check_file_json(path: str, filename: str, options_json: str) -> str:
|
|
116
|
+
"""Entry point for the browser demo: the page writes the dropped file to `path` in Pyodide's memory filesystem."""
|
|
117
|
+
p = Path(path)
|
|
118
|
+
try:
|
|
119
|
+
return json.dumps(run_check(p.read_bytes(), filename, json.loads(options_json)), ensure_ascii=False)
|
|
120
|
+
finally:
|
|
121
|
+
p.unlink(missing_ok=True)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class CitationSession:
|
|
125
|
+
"""Online reference checks for the browser demo, one HTTP request at a time.
|
|
126
|
+
|
|
127
|
+
JavaScript calls `next()` for the next request ({"url", "source", "interval", ...}) or the final findings
|
|
128
|
+
({"done": true, "findings": [...]}), fetches the URL itself, and hands the answer back with `feed()`.
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
def __init__(self, path: str, filename: str, ignore: list[str] | None = None):
|
|
132
|
+
suffix = Path(filename).suffix.lower()
|
|
133
|
+
with tempfile.TemporaryDirectory(prefix="blindlint-") as tmp:
|
|
134
|
+
if suffix == ".zip":
|
|
135
|
+
p = _unpack_zip(Path(path).read_bytes(), Path(tmp))
|
|
136
|
+
else:
|
|
137
|
+
p = Path(tmp) / f"upload{suffix}"
|
|
138
|
+
p.write_bytes(Path(path).read_bytes())
|
|
139
|
+
refs = references_for(load(p))
|
|
140
|
+
self.filename = filename
|
|
141
|
+
self.settings = settings_from(browser=True)
|
|
142
|
+
ignore = set(ignore or [])
|
|
143
|
+
self.settings.retractions = not {"CITE006", "CITE007"} <= ignore
|
|
144
|
+
self.settings.related = "CITE008" not in ignore
|
|
145
|
+
self.progress = Progress()
|
|
146
|
+
self.gen = pipeline(refs, self.settings, self.progress)
|
|
147
|
+
self.report = None
|
|
148
|
+
self.pending: Request | None = None
|
|
149
|
+
self._advance(None)
|
|
150
|
+
|
|
151
|
+
def _advance(self, resp: Response | None) -> None:
|
|
152
|
+
try:
|
|
153
|
+
self.pending = self.gen.send(resp)
|
|
154
|
+
except StopIteration as stop:
|
|
155
|
+
self.report, self.pending = stop.value, None
|
|
156
|
+
|
|
157
|
+
def next(self) -> str:
|
|
158
|
+
if self.pending is None:
|
|
159
|
+
from .rules.citations import findings_from_report
|
|
160
|
+
|
|
161
|
+
findings = findings_from_report(self.report, self.filename)
|
|
162
|
+
return json.dumps({"done": True, "findings": _finding_dicts(findings, self.filename)}, ensure_ascii=False)
|
|
163
|
+
req, p = self.pending, self.progress
|
|
164
|
+
return json.dumps(
|
|
165
|
+
{
|
|
166
|
+
"url": req.url,
|
|
167
|
+
"source": req.source,
|
|
168
|
+
"interval": req.interval,
|
|
169
|
+
"headers": req.headers,
|
|
170
|
+
"step": p.step,
|
|
171
|
+
"progress": [p.i, p.n],
|
|
172
|
+
"label": p.label,
|
|
173
|
+
}
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
def feed(self, status: int, body: str) -> None:
|
|
177
|
+
if self.pending is None:
|
|
178
|
+
return
|
|
179
|
+
head = (body or "").lstrip()[:200].lower()
|
|
180
|
+
if status == 200 and (head.startswith("<!doctype html") or head.startswith("<html")):
|
|
181
|
+
status, body = 0, ""
|
|
182
|
+
self._advance(Response(int(status), body or ""))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def citation_session(path: str, filename: str) -> CitationSession:
|
|
186
|
+
return CitationSession(path, filename)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def add_citation_findings(data: dict, extra: list[dict]) -> dict:
|
|
190
|
+
"""Fold the browser's citation findings into a run_check result: findings, score, coverage and reports."""
|
|
191
|
+
from .model import Finding, Location, Severity
|
|
192
|
+
|
|
193
|
+
rank = {"error": 0, "warning": 1, "info": 2}
|
|
194
|
+
data = dict(data)
|
|
195
|
+
data["findings"] = sorted(data["findings"] + extra, key=lambda d: rank.get(d["severity"], 3))
|
|
196
|
+
objs = [
|
|
197
|
+
Finding(
|
|
198
|
+
d["rule"],
|
|
199
|
+
Severity(d["severity"]),
|
|
200
|
+
d["message"],
|
|
201
|
+
Location(d["file"], d.get("page"), d.get("line"), d.get("where")),
|
|
202
|
+
d.get("snippet"),
|
|
203
|
+
d.get("hint"),
|
|
204
|
+
)
|
|
205
|
+
for d in data["findings"]
|
|
206
|
+
]
|
|
207
|
+
data["readiness"] = readiness(objs).to_dict()
|
|
208
|
+
data["skipped"] = [m for m in data.get("skipped", []) if m != "citations"]
|
|
209
|
+
data["coverage"] = [dict(c, status="checked", note="") if c["module"] == "citations" else c for c in data.get("coverage", [])]
|
|
210
|
+
data["report_markdown"] = render_markdown([data])
|
|
211
|
+
data["report_ai"] = render_markdown([data], for_ai=True)
|
|
212
|
+
return data
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def add_citation_findings_json(data_json: str, extra_json: str) -> str:
|
|
216
|
+
return json.dumps(add_citation_findings(json.loads(data_json), json.loads(extra_json)), ensure_ascii=False)
|
blindlint/bookmarklet.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""A bookmarklet that checks the open Overleaf project in the in-browser demo.
|
|
2
|
+
|
|
3
|
+
Overleaf has no plugin API, but a bookmark can run a few lines of JavaScript on the Overleaf page. Clicked in a
|
|
4
|
+
project, the bookmarklet downloads the project's source zip with the user's own Overleaf session (the same request
|
|
5
|
+
as Menu > Download > Source), opens the demo page, and hands the zip to it with window.postMessage, addressed to the
|
|
6
|
+
demo's origin only. The demo checks it with Pyodide inside the browser, so the project never reaches a server other
|
|
7
|
+
than Overleaf. It works on free Overleaf plans and on self-hosted Overleaf, because it needs no Git access.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
import urllib.parse
|
|
14
|
+
|
|
15
|
+
DEMO_URL = "https://longvandt.github.io/blindlint/"
|
|
16
|
+
|
|
17
|
+
# Messages between the Overleaf tab and the demo tab.
|
|
18
|
+
READY = "blindlint:ready"
|
|
19
|
+
FILE = "blindlint:file"
|
|
20
|
+
|
|
21
|
+
_SOURCE = """
|
|
22
|
+
(() => {
|
|
23
|
+
const D = '{{DEMO}}';
|
|
24
|
+
const m = location.pathname.match(/\\/project\\/([0-9a-f]{24})/);
|
|
25
|
+
if (!m) { alert('blindlint: open one of your Overleaf projects first, then click the bookmark again.'); return; }
|
|
26
|
+
const w = window.open(D + '#from=overleaf', '_blank');
|
|
27
|
+
if (!w) { alert('blindlint: allow pop-ups for this site, then click the bookmark again.'); return; }
|
|
28
|
+
const name = (document.title.split(' - ')[0] || 'overleaf-project').trim().replace(/[\\\\/:*?"<>|]/g, '_') + '.zip';
|
|
29
|
+
let zip = null, ready = false;
|
|
30
|
+
const send = () => { if (zip && ready) w.postMessage({type: '{{FILE}}', name, data: zip}, new URL(D).origin); };
|
|
31
|
+
addEventListener('message', e => {
|
|
32
|
+
if (e.source === w && e.data && e.data.type === '{{READY}}') { ready = true; send(); }
|
|
33
|
+
});
|
|
34
|
+
fetch('/project/' + m[1] + '/download/zip', {credentials: 'same-origin'})
|
|
35
|
+
.then(r => { if (!r.ok) throw new Error('Overleaf answered ' + r.status); return r.arrayBuffer(); })
|
|
36
|
+
.then(b => { zip = b; send(); })
|
|
37
|
+
.catch(e => { w.close(); alert('blindlint could not download this project: ' + e.message); });
|
|
38
|
+
})();
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def bookmarklet_source(demo_url: str = DEMO_URL) -> str:
|
|
43
|
+
return _SOURCE.replace("{{DEMO}}", demo_url).replace("{{FILE}}", FILE).replace("{{READY}}", READY).strip()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def bookmarklet(demo_url: str = DEMO_URL) -> str:
|
|
47
|
+
"""The javascript: URL to put in a bookmark."""
|
|
48
|
+
lines = [ln.strip() for ln in bookmarklet_source(demo_url).splitlines()]
|
|
49
|
+
code = re.sub(r"\s+", " ", " ".join(lines))
|
|
50
|
+
# Percent-encode everything but plain punctuation, so "#", "%", quotes and spaces survive bookmark managers.
|
|
51
|
+
return "javascript:" + urllib.parse.quote(code, safe="()[]{}=!;:,.'/+*_~-")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# The demo page's side: tell the opener we are ready, accept one zip from it, then check it like a dropped file.
|
|
55
|
+
RECEIVER = """
|
|
56
|
+
if (window.opener && /^#from=/.test(location.hash)) {
|
|
57
|
+
const from = location.hash.slice(6);
|
|
58
|
+
let got = false;
|
|
59
|
+
const hello = setInterval(() => {
|
|
60
|
+
if (got || window.opener === null) return clearInterval(hello);
|
|
61
|
+
try { window.opener.postMessage({type: '{{READY}}'}, '*'); } catch (e) { clearInterval(hello); }
|
|
62
|
+
}, 300);
|
|
63
|
+
setTimeout(() => clearInterval(hello), 120000);
|
|
64
|
+
addEventListener('message', e => {
|
|
65
|
+
const d = e.data;
|
|
66
|
+
if (got || e.source !== window.opener || !d || d.type !== '{{FILE}}' || !(d.data instanceof ArrayBuffer)) return;
|
|
67
|
+
got = true;
|
|
68
|
+
clearInterval(hello);
|
|
69
|
+
const host = (() => { try { return new URL(e.origin).hostname; } catch (_) { return 'the other tab'; } })();
|
|
70
|
+
pick(new File([d.data], String(d.name || 'project.zip'), {type: 'application/zip'}));
|
|
71
|
+
document.getElementById('dropSub').textContent =
|
|
72
|
+
`Sent from ${from === 'overleaf' ? 'your Overleaf project on ' : ''}${host}; it stays in this browser · click to choose another file`;
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
""".replace("{{READY}}", READY).replace("{{FILE}}", FILE)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Ghost-citation checks: find each reference and confirm that it exists, with these authors and this year.
|
|
2
|
+
|
|
3
|
+
This is the only part of blindlint that uses the network, and only when asked (`--online`).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from .refs import Reference, references_for
|
|
7
|
+
from .sources import Settings
|
|
8
|
+
from .verify import Result, check_references, lookup, run_lookup
|
|
9
|
+
|
|
10
|
+
__all__ = ["Reference", "Result", "Settings", "check_references", "lookup", "references_for", "run_lookup"]
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""A small BibTeX reader: enough to get title, authors, year and identifiers out of real-world .bib files.
|
|
2
|
+
|
|
3
|
+
No dependencies, so it also runs inside Pyodide. It handles nested braces, quoted values, `@string` macros and
|
|
4
|
+
`#` concatenation, and skips `@comment` and `@preamble`. Values are returned with LaTeX markup removed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
_ACCENTS = {
|
|
13
|
+
'"': {"a": "ä", "o": "ö", "u": "ü", "e": "ë", "i": "ï", "A": "Ä", "O": "Ö", "U": "Ü"},
|
|
14
|
+
"'": {"a": "á", "e": "é", "i": "í", "o": "ó", "u": "ú", "y": "ý", "c": "ć", "n": "ń", "s": "ś", "z": "ź", "E": "É"},
|
|
15
|
+
"`": {"a": "à", "e": "è", "i": "ì", "o": "ò", "u": "ù"},
|
|
16
|
+
"^": {"a": "â", "e": "ê", "i": "î", "o": "ô", "u": "û"},
|
|
17
|
+
"~": {"a": "ã", "n": "ñ", "o": "õ", "N": "Ñ"},
|
|
18
|
+
"c": {"c": "ç", "s": "ş", "C": "Ç"},
|
|
19
|
+
"v": {"c": "č", "s": "š", "z": "ž", "r": "ř", "e": "ě", "C": "Č", "S": "Š", "Z": "Ž"},
|
|
20
|
+
}
|
|
21
|
+
_SYMBOLS = {"ss": "ß", "o": "ø", "O": "Ø", "ae": "æ", "AE": "Æ", "aa": "å", "AA": "Å", "l": "ł", "L": "Ł", "i": "ı"}
|
|
22
|
+
_GREEK = ("alpha", "beta", "gamma", "delta", "epsilon", "varepsilon", "zeta", "eta", "theta", "kappa", "lambda", "mu",
|
|
23
|
+
"nu", "xi", "pi", "rho", "sigma", "tau", "phi", "varphi", "chi", "psi", "omega", "Gamma", "Delta", "Theta",
|
|
24
|
+
"Lambda", "Pi", "Sigma", "Phi", "Psi", "Omega") # fmt: skip
|
|
25
|
+
_MONTHS = {m: m for m in ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec")}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class BibEntry:
|
|
30
|
+
type: str
|
|
31
|
+
key: str
|
|
32
|
+
fields: dict[str, str] = field(default_factory=dict)
|
|
33
|
+
line: int = 1 # line of the "@" in the source file
|
|
34
|
+
|
|
35
|
+
def get(self, name: str, default: str = "") -> str:
|
|
36
|
+
return self.fields.get(name, default)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def latex_to_text(s: str) -> str:
|
|
40
|
+
"""Strip common LaTeX markup from a field value: accents, braces, \\emph{}, ~, --."""
|
|
41
|
+
s = re.sub(
|
|
42
|
+
r"\\([\"'`^~])\s*\{?\s*\\[ij](?![A-Za-z])\s*\}?", lambda m: _ACCENTS.get(m.group(1), {}).get("i", "i"), s
|
|
43
|
+
) # \'{\i}
|
|
44
|
+
s = re.sub(r"\\([\"'`^~])\s*\{?\s*([A-Za-z])\s*\}?", lambda m: _ACCENTS.get(m.group(1), {}).get(m.group(2), m.group(2)), s)
|
|
45
|
+
s = re.sub(r"\\([cv])\s*\{\s*([A-Za-z])\s*\}", lambda m: _ACCENTS[m.group(1)].get(m.group(2), m.group(2)), s)
|
|
46
|
+
s = re.sub(r"\\(ss|ae|AE|aa|AA|o|O|l|L|i)(?![A-Za-z])\s*", lambda m: _SYMBOLS[m.group(1)], s)
|
|
47
|
+
s = re.sub(r"\\(" + "|".join(_GREEK) + r")(?![A-Za-z])", lambda m: m.group(1), s) # $\beta$-VAE -> beta-VAE
|
|
48
|
+
s = re.sub(r"\\(?:emph|textit|textbf|textsc|texttt|mathrm|mathcal|mathbf|url|text)\s*\{", "{", s)
|
|
49
|
+
s = re.sub(r"\\&", "&", s)
|
|
50
|
+
s = re.sub(r"\\[%$#_]", lambda m: m.group(0)[1], s)
|
|
51
|
+
s = re.sub(r"\\[A-Za-z]+\s*", "", s) # any other command: drop the name, keep its argument
|
|
52
|
+
s = s.replace("~", " ").replace("---", "—").replace("--", "–")
|
|
53
|
+
s = s.replace("{", "").replace("}", "").replace("$", "")
|
|
54
|
+
return re.sub(r"\s+", " ", s).strip()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def parse_bibtex(src: str) -> list[BibEntry]:
|
|
58
|
+
entries: list[BibEntry] = []
|
|
59
|
+
strings: dict[str, str] = dict(_MONTHS)
|
|
60
|
+
i = 0
|
|
61
|
+
while True:
|
|
62
|
+
at = src.find("@", i)
|
|
63
|
+
if at < 0:
|
|
64
|
+
break
|
|
65
|
+
m = re.match(r"@\s*([A-Za-z]+)\s*([{(])", src[at:])
|
|
66
|
+
if not m:
|
|
67
|
+
i = at + 1
|
|
68
|
+
continue
|
|
69
|
+
etype = m.group(1).lower()
|
|
70
|
+
open_ch = m.group(2)
|
|
71
|
+
close_ch = "}" if open_ch == "{" else ")"
|
|
72
|
+
body_start = at + m.end()
|
|
73
|
+
body_end = _match_close(src, body_start, open_ch, close_ch)
|
|
74
|
+
if body_end < 0:
|
|
75
|
+
break
|
|
76
|
+
body = src[body_start:body_end]
|
|
77
|
+
i = body_end + 1
|
|
78
|
+
if etype in ("comment", "preamble"):
|
|
79
|
+
continue
|
|
80
|
+
if etype == "string":
|
|
81
|
+
for name, value in _parse_fields(body, strings):
|
|
82
|
+
strings[name] = value
|
|
83
|
+
continue
|
|
84
|
+
key, _, rest = body.partition(",")
|
|
85
|
+
fields = {name: latex_to_text(value) for name, value in _parse_fields(rest, strings)}
|
|
86
|
+
line = src.count("\n", 0, at) + 1
|
|
87
|
+
entries.append(BibEntry(etype, key.strip(), fields, line))
|
|
88
|
+
return entries
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _match_close(src: str, start: int, open_ch: str, close_ch: str) -> int:
|
|
92
|
+
depth = 1
|
|
93
|
+
j = start
|
|
94
|
+
while j < len(src):
|
|
95
|
+
c = src[j]
|
|
96
|
+
if c == "\\":
|
|
97
|
+
j += 2 # an escaped brace does not count
|
|
98
|
+
continue
|
|
99
|
+
if c == open_ch:
|
|
100
|
+
depth += 1
|
|
101
|
+
elif c == close_ch:
|
|
102
|
+
depth -= 1
|
|
103
|
+
if depth == 0:
|
|
104
|
+
return j
|
|
105
|
+
j += 1
|
|
106
|
+
return -1
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _parse_fields(body: str, strings: dict[str, str]):
|
|
110
|
+
i, n = 0, len(body)
|
|
111
|
+
while i < n:
|
|
112
|
+
m = re.compile(r"\s*,?\s*([A-Za-z][\w:.+-]*)\s*=\s*").match(body, i)
|
|
113
|
+
if not m:
|
|
114
|
+
break
|
|
115
|
+
name = m.group(1).lower()
|
|
116
|
+
i = m.end()
|
|
117
|
+
parts = []
|
|
118
|
+
while i < n:
|
|
119
|
+
c = body[i]
|
|
120
|
+
if c == "{":
|
|
121
|
+
end = _match_close(body, i + 1, "{", "}")
|
|
122
|
+
if end < 0:
|
|
123
|
+
end = n - 1
|
|
124
|
+
parts.append(body[i + 1 : end])
|
|
125
|
+
i = end + 1
|
|
126
|
+
elif c == '"':
|
|
127
|
+
j = i + 1
|
|
128
|
+
depth = 0
|
|
129
|
+
while j < n and not (body[j] == '"' and depth == 0 and body[j - 1] != "\\"):
|
|
130
|
+
depth += body[j] == "{"
|
|
131
|
+
depth -= body[j] == "}"
|
|
132
|
+
j += 1
|
|
133
|
+
parts.append(body[i + 1 : j])
|
|
134
|
+
i = j + 1
|
|
135
|
+
else:
|
|
136
|
+
w = re.compile(r"[^\s,#}]+").match(body, i)
|
|
137
|
+
if not w:
|
|
138
|
+
break
|
|
139
|
+
token = w.group(0)
|
|
140
|
+
parts.append(strings.get(token.lower(), token))
|
|
141
|
+
i = w.end()
|
|
142
|
+
ws = re.compile(r"\s*#\s*").match(body, i)
|
|
143
|
+
if ws:
|
|
144
|
+
i = ws.end()
|
|
145
|
+
continue
|
|
146
|
+
break
|
|
147
|
+
yield name, "".join(parts)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def split_authors(field_value: str) -> list[str]:
|
|
151
|
+
"""Family names from a BibTeX author field ("Last, First and First Last and {Org}")."""
|
|
152
|
+
out = []
|
|
153
|
+
for name in re.split(r"\s+and\s+", field_value.strip()):
|
|
154
|
+
name = name.strip()
|
|
155
|
+
if not name or name.lower() == "others":
|
|
156
|
+
continue
|
|
157
|
+
if "," in name:
|
|
158
|
+
family = name.split(",")[0]
|
|
159
|
+
else:
|
|
160
|
+
tokens = name.split()
|
|
161
|
+
family = tokens[-1] if tokens else name
|
|
162
|
+
# keep particles: "Ludwig van Beethoven" -> "van Beethoven"
|
|
163
|
+
for k in range(len(tokens) - 1):
|
|
164
|
+
if tokens[k][:1].islower():
|
|
165
|
+
family = " ".join(tokens[k:])
|
|
166
|
+
break
|
|
167
|
+
out.append(family.strip())
|
|
168
|
+
return out
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""HTTP for the command line: a polite user agent, a per-source rate limit, retries on 429, and a disk cache.
|
|
2
|
+
|
|
3
|
+
The user agent names the tool and its homepage and nothing else. An email is only added if the user sets one
|
|
4
|
+
(`contact` in blindlint.toml or BLINDLINT_CONTACT), which is what Crossref asks for to join its faster pool.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import time
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .. import __version__
|
|
17
|
+
from .sources import Request, Response
|
|
18
|
+
|
|
19
|
+
HOMEPAGE = "https://github.com/longvandt/blindlint"
|
|
20
|
+
CACHE_TTL = 30 * 24 * 3600 # a month: references do not change, but a fixed typo should show up eventually
|
|
21
|
+
MAX_RETRY_WAIT = 30.0
|
|
22
|
+
|
|
23
|
+
# fetch(url, headers, timeout) -> (status, headers, body); raises OSError on network failure
|
|
24
|
+
RawFetch = Callable[[str, dict, float], tuple[int, dict, str]]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def user_agent(contact: str | None = None) -> str:
|
|
28
|
+
ua = f"blindlint/{__version__} (+{HOMEPAGE})"
|
|
29
|
+
return f"{ua[:-1]}; mailto:{contact})" if contact else ua
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def default_cache_dir() -> Path:
|
|
33
|
+
base = os.environ.get("XDG_CACHE_HOME") or (Path.home() / ".cache")
|
|
34
|
+
return Path(base) / "blindlint" / "http"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def urllib_fetch(url: str, headers: dict, timeout: float) -> tuple[int, dict, str]:
|
|
38
|
+
import urllib.error
|
|
39
|
+
import urllib.request
|
|
40
|
+
|
|
41
|
+
req = urllib.request.Request(url, headers=headers)
|
|
42
|
+
try:
|
|
43
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
44
|
+
return r.status, dict(r.headers), r.read().decode("utf-8", "replace")
|
|
45
|
+
except urllib.error.HTTPError as e:
|
|
46
|
+
body = ""
|
|
47
|
+
try:
|
|
48
|
+
body = e.read().decode("utf-8", "replace")
|
|
49
|
+
except Exception:
|
|
50
|
+
pass
|
|
51
|
+
return e.code, dict(e.headers or {}), body
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class HttpClient:
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
contact: str | None = None,
|
|
58
|
+
cache_dir: Path | None = None,
|
|
59
|
+
fetch: RawFetch = urllib_fetch,
|
|
60
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
61
|
+
clock: Callable[[], float] = time.monotonic,
|
|
62
|
+
timeout: float = 20.0,
|
|
63
|
+
max_retries: int = 2,
|
|
64
|
+
):
|
|
65
|
+
self.ua = user_agent(contact)
|
|
66
|
+
self.cache_dir = cache_dir
|
|
67
|
+
self.fetch_raw = fetch
|
|
68
|
+
self.sleep = sleep
|
|
69
|
+
self.clock = clock
|
|
70
|
+
self.timeout = timeout
|
|
71
|
+
self.max_retries = max_retries
|
|
72
|
+
self._last: dict[str, float] = {}
|
|
73
|
+
self.requests_sent = 0
|
|
74
|
+
self.cache_hits = 0
|
|
75
|
+
|
|
76
|
+
# -- cache
|
|
77
|
+
def _cache_path(self, url: str) -> Path | None:
|
|
78
|
+
if self.cache_dir is None:
|
|
79
|
+
return None
|
|
80
|
+
return self.cache_dir / (hashlib.sha256(url.encode()).hexdigest()[:32] + ".json")
|
|
81
|
+
|
|
82
|
+
def _cache_get(self, url: str) -> Response | None:
|
|
83
|
+
p = self._cache_path(url)
|
|
84
|
+
if p is None or not p.is_file():
|
|
85
|
+
return None
|
|
86
|
+
try:
|
|
87
|
+
data = json.loads(p.read_text(encoding="utf-8"))
|
|
88
|
+
except (OSError, ValueError):
|
|
89
|
+
return None
|
|
90
|
+
if time.time() - data.get("time", 0) > CACHE_TTL or data.get("url") != url:
|
|
91
|
+
return None
|
|
92
|
+
return Response(data["status"], data["body"])
|
|
93
|
+
|
|
94
|
+
def _cache_put(self, url: str, resp: Response) -> None:
|
|
95
|
+
p = self._cache_path(url)
|
|
96
|
+
if p is None:
|
|
97
|
+
return
|
|
98
|
+
try:
|
|
99
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
100
|
+
tmp = p.with_suffix(".tmp")
|
|
101
|
+
tmp.write_text(
|
|
102
|
+
json.dumps({"url": url, "status": resp.status, "body": resp.body, "time": time.time()}), encoding="utf-8"
|
|
103
|
+
)
|
|
104
|
+
tmp.replace(p)
|
|
105
|
+
except OSError:
|
|
106
|
+
pass # a read-only cache is not a reason to fail
|
|
107
|
+
|
|
108
|
+
# -- rate limit
|
|
109
|
+
def _wait(self, source: str, interval: float) -> None:
|
|
110
|
+
last = self._last.get(source)
|
|
111
|
+
if last is not None:
|
|
112
|
+
delay = last + interval - self.clock()
|
|
113
|
+
if delay > 0:
|
|
114
|
+
self.sleep(delay)
|
|
115
|
+
self._last[source] = self.clock()
|
|
116
|
+
|
|
117
|
+
def get(self, req: Request) -> Response:
|
|
118
|
+
cached = self._cache_get(req.url)
|
|
119
|
+
if cached is not None:
|
|
120
|
+
self.cache_hits += 1
|
|
121
|
+
return cached
|
|
122
|
+
headers = {"User-Agent": self.ua, "Accept": "application/json, application/atom+xml;q=0.9, */*;q=0.1", **req.headers}
|
|
123
|
+
attempt = 0
|
|
124
|
+
while True:
|
|
125
|
+
self._wait(req.source, req.interval)
|
|
126
|
+
self.requests_sent += 1
|
|
127
|
+
try:
|
|
128
|
+
status, rh, body = self.fetch_raw(req.url, headers, self.timeout)
|
|
129
|
+
except (OSError, ValueError) as e: # URLError, timeouts, TLS errors
|
|
130
|
+
return Response(0, "", str(e))
|
|
131
|
+
if status in (429, 500, 502, 503, 504) and attempt < self.max_retries:
|
|
132
|
+
attempt += 1
|
|
133
|
+
self.sleep(min(MAX_RETRY_WAIT, _retry_after(rh) or 2.0 * attempt))
|
|
134
|
+
continue
|
|
135
|
+
if status == 200 and _looks_like_html(body): # bot walls answer 200/202 with an HTML page
|
|
136
|
+
return Response(0, "", "the source answered with a web page instead of data")
|
|
137
|
+
resp = Response(status, body)
|
|
138
|
+
if status in (200, 404):
|
|
139
|
+
self._cache_put(req.url, resp)
|
|
140
|
+
return resp
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _retry_after(headers: dict) -> float | None:
|
|
144
|
+
for k, v in headers.items():
|
|
145
|
+
if k.lower() == "retry-after":
|
|
146
|
+
try:
|
|
147
|
+
return float(v)
|
|
148
|
+
except ValueError:
|
|
149
|
+
return None
|
|
150
|
+
return None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _looks_like_html(body: str) -> bool:
|
|
154
|
+
head = body.lstrip()[:200].lower()
|
|
155
|
+
return head.startswith("<!doctype html") or head.startswith("<html")
|