socratic-sidecar 0.3.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.
- app/__init__.py +0 -0
- app/__main__.py +115 -0
- app/adapters/__init__.py +39 -0
- app/adapters/base.py +50 -0
- app/adapters/cts.py +190 -0
- app/adapters/http.py +71 -0
- app/adapters/wikisource.py +260 -0
- app/catalog.py +127 -0
- app/citation_policy.py +807 -0
- app/citations.py +81 -0
- app/classifier.py +36 -0
- app/compute.py +45 -0
- app/config.py +270 -0
- app/critic.py +127 -0
- app/curriculum.py +159 -0
- app/editions.py +107 -0
- app/evaluations.py +75 -0
- app/evaluator.py +140 -0
- app/federated.py +236 -0
- app/glossary.json +1066 -0
- app/ingest.py +98 -0
- app/learner.py +196 -0
- app/lexical.py +523 -0
- app/lexicon.py +201 -0
- app/llm.py +144 -0
- app/locators.py +163 -0
- app/main.py +781 -0
- app/pages.py +200 -0
- app/policy.py +59 -0
- app/review.py +339 -0
- app/schema.py +205 -0
- app/search.py +1112 -0
- app/state_machine.py +230 -0
- app/state_store.py +132 -0
- app/textutil.py +117 -0
- app/toc.py +77 -0
- app/translate.py +307 -0
- socratic_sidecar-0.3.0.dist-info/METADATA +174 -0
- socratic_sidecar-0.3.0.dist-info/RECORD +42 -0
- socratic_sidecar-0.3.0.dist-info/WHEEL +5 -0
- socratic_sidecar-0.3.0.dist-info/entry_points.txt +2 -0
- socratic_sidecar-0.3.0.dist-info/top_level.txt +1 -0
app/__init__.py
ADDED
|
File without changes
|
app/__main__.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Command-line entry point for the socratic sidecar.
|
|
2
|
+
|
|
3
|
+
python -m app --port 8765
|
|
4
|
+
socratic-sidecar --data /srv/socratic --port 8765
|
|
5
|
+
|
|
6
|
+
`app.config` reads every setting from the environment *at import time*, so this
|
|
7
|
+
module translates the flags into SOCRATIC_* variables before it imports app or
|
|
8
|
+
uvicorn. That also makes the two invocation styles above exactly equivalent:
|
|
9
|
+
with no arguments, `python -m app` is the same as the console script.
|
|
10
|
+
|
|
11
|
+
The flags mirror the environment variables; explicit flags win over an
|
|
12
|
+
already-exported SOCRATIC_* value because they are applied afterwards.
|
|
13
|
+
"""
|
|
14
|
+
import argparse
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
|
|
18
|
+
DEFAULT_HOST = "127.0.0.1"
|
|
19
|
+
DEFAULT_PORT = 8765
|
|
20
|
+
|
|
21
|
+
#: flag -> environment variable, for the plain string-valued options. Paths are
|
|
22
|
+
#: made absolute so the service keeps resolving them if a later component
|
|
23
|
+
#: changes the working directory.
|
|
24
|
+
_ENV_FLAGS = {
|
|
25
|
+
"data": "SOCRATIC_DATA",
|
|
26
|
+
"db": "SOCRATIC_DB",
|
|
27
|
+
"lexicon_db": "SOCRATIC_LEXICON_DB",
|
|
28
|
+
"root": "SOCRATIC_ROOT",
|
|
29
|
+
"curriculum": "SOCRATIC_CURRICULUM",
|
|
30
|
+
"cache": "SOCRATIC_CACHE",
|
|
31
|
+
"state_db": "SOCRATIC_STATE_DB",
|
|
32
|
+
}
|
|
33
|
+
_PATH_FLAGS = set(_ENV_FLAGS)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def build_parser():
|
|
37
|
+
parser = argparse.ArgumentParser(
|
|
38
|
+
prog="socratic-sidecar",
|
|
39
|
+
description="Minimal Socratic tutor sidecar: search, pages, compute.",
|
|
40
|
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
41
|
+
epilog=(
|
|
42
|
+
"Every option maps to a SOCRATIC_* environment variable and is "
|
|
43
|
+
"applied before the application is imported, so e.g. "
|
|
44
|
+
"`--data DIR` is the same as exporting SOCRATIC_DATA=DIR. "
|
|
45
|
+
"With no arguments this is equivalent to `python -m app`."
|
|
46
|
+
),
|
|
47
|
+
)
|
|
48
|
+
parser.add_argument("--host", default=DEFAULT_HOST,
|
|
49
|
+
help="interface to bind")
|
|
50
|
+
parser.add_argument("--port", type=int, default=DEFAULT_PORT,
|
|
51
|
+
help="TCP port to listen on")
|
|
52
|
+
parser.add_argument("--data", metavar="DIR",
|
|
53
|
+
help="derived data root (indexes, vectors, caches)")
|
|
54
|
+
parser.add_argument("--db", metavar="FILE",
|
|
55
|
+
help="RAG database holding the chunks index")
|
|
56
|
+
parser.add_argument("--lexicon-db", metavar="FILE",
|
|
57
|
+
help="dictionary / grammar database")
|
|
58
|
+
parser.add_argument("--root", metavar="DIR",
|
|
59
|
+
help="directory containing the book library")
|
|
60
|
+
parser.add_argument("--curriculum", metavar="DIR",
|
|
61
|
+
help="directory of curriculum lesson packs")
|
|
62
|
+
parser.add_argument("--cache", metavar="DIR",
|
|
63
|
+
help="page-image cache directory")
|
|
64
|
+
parser.add_argument("--state-db", metavar="FILE",
|
|
65
|
+
help="SQLite file for learner state and the chapter index")
|
|
66
|
+
parser.add_argument("--token", metavar="TOKEN",
|
|
67
|
+
help="shared token required by /v1/* (empty means no auth)")
|
|
68
|
+
parser.add_argument("--bge", action=argparse.BooleanOptionalAction,
|
|
69
|
+
default=None,
|
|
70
|
+
help="enable/disable BGE embeddings; default follows SOCRATIC_BGE")
|
|
71
|
+
parser.add_argument("--version", action="version",
|
|
72
|
+
version="%(prog)s " + _version())
|
|
73
|
+
return parser
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _version():
|
|
77
|
+
try:
|
|
78
|
+
from importlib.metadata import version
|
|
79
|
+
return version("socratic-sidecar")
|
|
80
|
+
except Exception:
|
|
81
|
+
try:
|
|
82
|
+
from . import config
|
|
83
|
+
return config.VERSION
|
|
84
|
+
except Exception:
|
|
85
|
+
return "unknown"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def configure_environment(args):
|
|
89
|
+
"""Apply parsed flags to the process environment (before importing app)."""
|
|
90
|
+
for flag, env_name in _ENV_FLAGS.items():
|
|
91
|
+
value = getattr(args, flag)
|
|
92
|
+
if value:
|
|
93
|
+
if flag in _PATH_FLAGS:
|
|
94
|
+
value = os.path.abspath(os.path.expanduser(value))
|
|
95
|
+
os.environ[env_name] = value
|
|
96
|
+
if args.token is not None:
|
|
97
|
+
os.environ["SOCRATIC_TOKEN"] = args.token
|
|
98
|
+
if args.bge is not None:
|
|
99
|
+
os.environ["SOCRATIC_BGE"] = "1" if args.bge else "0"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def main(argv=None):
|
|
103
|
+
args = build_parser().parse_args(argv)
|
|
104
|
+
configure_environment(args)
|
|
105
|
+
|
|
106
|
+
# Import only after the environment is final: config.py snapshots it.
|
|
107
|
+
import uvicorn
|
|
108
|
+
|
|
109
|
+
uvicorn.run("app.main:app", host=args.host, port=args.port,
|
|
110
|
+
timeout_keep_alive=75)
|
|
111
|
+
return 0
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
if __name__ == "__main__":
|
|
115
|
+
sys.exit(main())
|
app/adapters/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Adapter registry.
|
|
2
|
+
|
|
3
|
+
Adapters are constructed from a source id plus keyword arguments; the registry
|
|
4
|
+
keeps the CLI and the ingest tests from hard-coding classes. Add a new corpus by
|
|
5
|
+
implementing ``fetch()`` and registering it here — the schema does not change.
|
|
6
|
+
"""
|
|
7
|
+
from .base import Document, FetchError, Section, SourceSpec
|
|
8
|
+
from .cts import CtsAdapter, passage, work_urn
|
|
9
|
+
from .wikisource import MediaWikiClient, WikisourceAdapter, extract_sections
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"Document", "FetchError", "Section", "SourceSpec",
|
|
13
|
+
"CtsAdapter", "MediaWikiClient", "WikisourceAdapter",
|
|
14
|
+
"extract_sections", "passage", "work_urn",
|
|
15
|
+
"get", "register", "names",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
_REGISTRY = {
|
|
19
|
+
"wikisource": WikisourceAdapter,
|
|
20
|
+
"mediawiki": WikisourceAdapter,
|
|
21
|
+
"perseus": CtsAdapter,
|
|
22
|
+
"cts": CtsAdapter,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def register(name, cls):
|
|
27
|
+
_REGISTRY[name] = cls
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def names():
|
|
31
|
+
return sorted(_REGISTRY)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def get(name, **kwargs):
|
|
35
|
+
try:
|
|
36
|
+
cls = _REGISTRY[name.lower()]
|
|
37
|
+
except KeyError:
|
|
38
|
+
raise KeyError("unknown adapter %r (known: %s)" % (name, ", ".join(names())))
|
|
39
|
+
return cls(**kwargs)
|
app/adapters/base.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Shared shapes for public-corpus adapters.
|
|
2
|
+
|
|
3
|
+
An adapter turns one external reference (a Wikisource title, a CTS URN, …) into
|
|
4
|
+
a :class:`Document` whose sections already carry a typed locator. Nothing in
|
|
5
|
+
this package writes to the database; ingestion is a separate step so fetching
|
|
6
|
+
and storing can be retried independently.
|
|
7
|
+
"""
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class FetchError(RuntimeError):
|
|
12
|
+
"""The source refused, or returned something the adapter cannot parse."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Section:
|
|
17
|
+
title: str
|
|
18
|
+
text: str
|
|
19
|
+
locator: dict
|
|
20
|
+
ordinal: int = 0
|
|
21
|
+
quality: str | None = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Document:
|
|
26
|
+
document_id: str
|
|
27
|
+
source_id: str
|
|
28
|
+
title: str
|
|
29
|
+
sections: list[Section]
|
|
30
|
+
lang: str = "zh"
|
|
31
|
+
author: str | None = None
|
|
32
|
+
edition: str | None = None
|
|
33
|
+
script: str | None = None
|
|
34
|
+
license: str = "unknown"
|
|
35
|
+
provenance: str = ""
|
|
36
|
+
canonical_url: str = ""
|
|
37
|
+
metadata: dict = field(default_factory=dict)
|
|
38
|
+
source_version: str = ""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class SourceSpec:
|
|
43
|
+
source_id: str
|
|
44
|
+
adapter: str
|
|
45
|
+
base_url: str
|
|
46
|
+
license: str = "unknown"
|
|
47
|
+
redistribution: str = "unknown"
|
|
48
|
+
rate_limit: float | None = 1.0
|
|
49
|
+
auth_env: str | None = None
|
|
50
|
+
config: dict = field(default_factory=dict)
|
app/adapters/cts.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Perseus / CTS adapter.
|
|
2
|
+
|
|
3
|
+
A CTS citation is a URN — a work, a book and a line — not a page. Two endpoints
|
|
4
|
+
exist: Perseus's legacy ``/hopper/CTS`` (reachable and still serving TEI) and
|
|
5
|
+
the newer ``scaife-cts`` host, which some networks cannot reach (TLS SNI is
|
|
6
|
+
rejected). The legacy endpoint does not support passage ranges, so callers pass
|
|
7
|
+
one URN per passage and :meth:`fetch_many` merges them into one document.
|
|
8
|
+
|
|
9
|
+
The locator stores the full URN plus the parsed line window. The document id is
|
|
10
|
+
the edition-level work URN, so every passage of one edition lands in one
|
|
11
|
+
document.
|
|
12
|
+
"""
|
|
13
|
+
import re
|
|
14
|
+
import xml.etree.ElementTree as ET
|
|
15
|
+
|
|
16
|
+
from .. import textutil
|
|
17
|
+
from .base import Document, FetchError, Section, SourceSpec
|
|
18
|
+
from .http import RateLimiter, get, default_user_agent
|
|
19
|
+
|
|
20
|
+
TEI = "{http://www.tei-c.org/ns/1.0}"
|
|
21
|
+
CTS = "{http://chs.harvard.edu/xmlns/cts3}"
|
|
22
|
+
PASSAGE_RE = re.compile(r":(\d+)\.(\d+)(?:-(\d+)\.(\d+))?$")
|
|
23
|
+
LEGACY_API = "https://www.perseus.tufts.edu/hopper/CTS"
|
|
24
|
+
|
|
25
|
+
LANG_MAP = {"grc": "greek", "greek": "greek", "lat": "latin", "la": "latin",
|
|
26
|
+
"eng": "en", "en": "en"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class CtsAdapter:
|
|
30
|
+
def __init__(self, base_url=LEGACY_API, lang="greek", license="CC-BY-SA-4.0",
|
|
31
|
+
redistribution="share-alike", user_agent=None, timeout=40,
|
|
32
|
+
min_interval=1.0, opener=None):
|
|
33
|
+
self.base_url = base_url
|
|
34
|
+
self.lang = lang
|
|
35
|
+
self.license = license
|
|
36
|
+
self.redistribution = redistribution
|
|
37
|
+
self.user_agent = user_agent or default_user_agent()
|
|
38
|
+
self.timeout = timeout
|
|
39
|
+
self._limiter = RateLimiter(min_interval)
|
|
40
|
+
self._opener = opener or get
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def source_id(self):
|
|
44
|
+
return "perseus"
|
|
45
|
+
|
|
46
|
+
def source(self) -> SourceSpec:
|
|
47
|
+
return SourceSpec(
|
|
48
|
+
source_id=self.source_id,
|
|
49
|
+
adapter="cts",
|
|
50
|
+
base_url=self.base_url,
|
|
51
|
+
license=self.license,
|
|
52
|
+
redistribution=self.redistribution,
|
|
53
|
+
rate_limit=self._limiter.min_interval,
|
|
54
|
+
config={"lang": self.lang},
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
def _get_passage(self, urn):
|
|
58
|
+
self._limiter.wait()
|
|
59
|
+
try:
|
|
60
|
+
body, _ctype = self._opener(
|
|
61
|
+
self.base_url, params={"request": "GetPassage", "urn": urn},
|
|
62
|
+
user_agent=self.user_agent, timeout=self.timeout)
|
|
63
|
+
except Exception as e:
|
|
64
|
+
raise FetchError(str(e))
|
|
65
|
+
if isinstance(body, str):
|
|
66
|
+
body = body.encode("utf-8")
|
|
67
|
+
return body
|
|
68
|
+
|
|
69
|
+
def fetch(self, urn, title=None, author=None, edition=None, lang=None,
|
|
70
|
+
license=None):
|
|
71
|
+
urn = urn.strip()
|
|
72
|
+
if not urn.startswith("urn:cts:"):
|
|
73
|
+
raise FetchError("not a CTS URN: %r" % urn)
|
|
74
|
+
body = self._get_passage(urn)
|
|
75
|
+
try:
|
|
76
|
+
root = ET.fromstring(body)
|
|
77
|
+
except ET.ParseError as e:
|
|
78
|
+
raise FetchError("CTS returned non-XML: %s" % e)
|
|
79
|
+
reply = root.find(".//" + CTS + "reply")
|
|
80
|
+
error = (reply is not None and reply.get("name") == "CTSError") or \
|
|
81
|
+
root.find(".//" + CTS + "CTSError") is not None
|
|
82
|
+
if error:
|
|
83
|
+
raise FetchError("CTS error for %s" % urn)
|
|
84
|
+
|
|
85
|
+
work = _text(root.find(".//" + CTS + "workUrn")) or work_urn(urn)
|
|
86
|
+
book, line_start, line_end = passage(urn)
|
|
87
|
+
meta_title = title or _text(root.find(".//" + CTS + "title")) \
|
|
88
|
+
or work.rsplit(":", 1)[-1]
|
|
89
|
+
meta_author = author or _text(root.find(".//" + CTS + "groupname"))
|
|
90
|
+
version = _text(root.find(".//" + CTS + "versionInfo"))
|
|
91
|
+
tei_text = root.find(".//" + TEI + "text")
|
|
92
|
+
xml_lang = tei_text.get("{http://www.w3.org/XML/1998/namespace}lang") \
|
|
93
|
+
if tei_text is not None else None
|
|
94
|
+
|
|
95
|
+
divs = root.findall(".//" + TEI + "div")
|
|
96
|
+
lines = []
|
|
97
|
+
if divs:
|
|
98
|
+
for div in divs:
|
|
99
|
+
t = textutil.clean_text("".join(div.itertext()))
|
|
100
|
+
if t:
|
|
101
|
+
lines.append(t)
|
|
102
|
+
elif tei_text is not None:
|
|
103
|
+
t = textutil.clean_text("".join(tei_text.itertext()))
|
|
104
|
+
if t:
|
|
105
|
+
lines.append(t)
|
|
106
|
+
if not lines:
|
|
107
|
+
raise FetchError("CTS passage %s has no text" % urn)
|
|
108
|
+
|
|
109
|
+
sections = []
|
|
110
|
+
for i, text in enumerate(lines):
|
|
111
|
+
locator = {"scheme": "cts", "urn": urn, "work": work,
|
|
112
|
+
"book": book, "line_start": line_start,
|
|
113
|
+
"line_end": line_end if line_end is not None else line_start}
|
|
114
|
+
sections.append(Section(title=_label(book, line_start, line_end),
|
|
115
|
+
text=text, locator=locator, ordinal=i,
|
|
116
|
+
quality="tei-passage"))
|
|
117
|
+
return Document(
|
|
118
|
+
document_id=work,
|
|
119
|
+
source_id=self.source_id,
|
|
120
|
+
title=meta_title,
|
|
121
|
+
sections=sections,
|
|
122
|
+
lang=LANG_MAP.get((lang or xml_lang or self.lang).lower(), self.lang),
|
|
123
|
+
author=meta_author,
|
|
124
|
+
edition=edition or version or "Perseus Digital Library",
|
|
125
|
+
script=None,
|
|
126
|
+
license=license or self.license,
|
|
127
|
+
provenance="%s %s" % (self.base_url, urn),
|
|
128
|
+
canonical_url="https://scaife.perseus.org/reader/%s" % work,
|
|
129
|
+
metadata={"urn": urn, "work": work, "book": book,
|
|
130
|
+
"base": self.base_url, "version": version},
|
|
131
|
+
source_version=work,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def fetch_many(self, urns, title=None, author=None, skip_errors=False,
|
|
135
|
+
**kwargs):
|
|
136
|
+
"""Fetch several passages of one work into one document.
|
|
137
|
+
|
|
138
|
+
The legacy endpoint refuses some line numbers (and some editions), so
|
|
139
|
+
``skip_errors`` lets a book-level import continue while recording what
|
|
140
|
+
was skipped instead of aborting the whole document.
|
|
141
|
+
"""
|
|
142
|
+
if not urns:
|
|
143
|
+
raise FetchError("no URNs given")
|
|
144
|
+
docs, skipped = [], []
|
|
145
|
+
for urn in urns:
|
|
146
|
+
try:
|
|
147
|
+
docs.append(self.fetch(urn, title=title, author=author, **kwargs))
|
|
148
|
+
except FetchError as e:
|
|
149
|
+
if not skip_errors:
|
|
150
|
+
raise
|
|
151
|
+
skipped.append({"urn": urn, "error": str(e)[:120]})
|
|
152
|
+
if not docs:
|
|
153
|
+
raise FetchError("no passages fetched")
|
|
154
|
+
first = docs[0]
|
|
155
|
+
sections = []
|
|
156
|
+
for doc in docs:
|
|
157
|
+
for sec in doc.sections:
|
|
158
|
+
sec.ordinal = len(sections)
|
|
159
|
+
sections.append(sec)
|
|
160
|
+
first.sections = sections
|
|
161
|
+
first.metadata["skipped"] = skipped
|
|
162
|
+
return first
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _text(el):
|
|
166
|
+
return textutil.clean_text("".join(el.itertext())) if el is not None else ""
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _label(book, start, end):
|
|
170
|
+
if book is None or start is None:
|
|
171
|
+
return "passage"
|
|
172
|
+
if end is None or end == start:
|
|
173
|
+
return "%s.%s" % (book, start)
|
|
174
|
+
return "%s.%s-%s.%s" % (book, start, book, end)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def work_urn(urn: str) -> str:
|
|
178
|
+
"""Drop a trailing passage (``:1.1-1.10``) from a CTS URN."""
|
|
179
|
+
return PASSAGE_RE.sub("", urn)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def passage(urn: str):
|
|
183
|
+
"""Return ``(book, line_start, line_end)`` from a CTS URN, or Nones."""
|
|
184
|
+
m = PASSAGE_RE.search(urn)
|
|
185
|
+
if not m:
|
|
186
|
+
return None, None, None
|
|
187
|
+
book = m.group(1)
|
|
188
|
+
start = int(m.group(2))
|
|
189
|
+
end = int(m.group(4) or m.group(2))
|
|
190
|
+
return book, start, end
|
app/adapters/http.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Minimal HTTP GET with a descriptive User-Agent.
|
|
2
|
+
|
|
3
|
+
Wikimedia requires a UA that identifies the tool and a contact; Python's
|
|
4
|
+
default ``Python-urllib/3.x`` is answered with 403. Callers may inject their own
|
|
5
|
+
opener (tests do) so no test ever needs the network.
|
|
6
|
+
"""
|
|
7
|
+
import json
|
|
8
|
+
import time
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.parse
|
|
11
|
+
import urllib.request
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class HttpError(RuntimeError):
|
|
15
|
+
def __init__(self, status, url, body=""):
|
|
16
|
+
super().__init__("HTTP %s for %s" % (status, url))
|
|
17
|
+
self.status = status
|
|
18
|
+
self.url = url
|
|
19
|
+
self.body = body[:400]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def default_user_agent():
|
|
23
|
+
import os
|
|
24
|
+
return os.environ.get(
|
|
25
|
+
"SOCRATIC_HTTP_UA",
|
|
26
|
+
"socratic-tutor/0.1 (local Socratic tutor; contact: administrator@localhost)",
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def get(url, params=None, user_agent=None, timeout=30, headers=None):
|
|
31
|
+
if params:
|
|
32
|
+
url = url + ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
|
|
33
|
+
hdrs = {"User-Agent": user_agent or default_user_agent(),
|
|
34
|
+
"Accept": "application/json, text/xml;q=0.9, */*;q=0.8"}
|
|
35
|
+
hdrs.update(headers or {})
|
|
36
|
+
req = urllib.request.Request(url, headers=hdrs)
|
|
37
|
+
try:
|
|
38
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
39
|
+
return resp.read(), resp.headers.get("Content-Type", "")
|
|
40
|
+
except urllib.error.HTTPError as e:
|
|
41
|
+
raise HttpError(e.code, url, e.read().decode("utf-8", "replace"))
|
|
42
|
+
except urllib.error.URLError as e:
|
|
43
|
+
raise HttpError(0, url, str(e.reason))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class RateLimiter:
|
|
47
|
+
"""One request per ``min_interval`` seconds; no sleeping when interval is 0."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, min_interval=1.0, clock=time.monotonic, sleep=time.sleep):
|
|
50
|
+
self.min_interval = max(0.0, float(min_interval or 0))
|
|
51
|
+
self._clock = clock
|
|
52
|
+
self._sleep = sleep
|
|
53
|
+
self._last = None
|
|
54
|
+
|
|
55
|
+
def wait(self):
|
|
56
|
+
if not self.min_interval:
|
|
57
|
+
return
|
|
58
|
+
now = self._clock()
|
|
59
|
+
if self._last is not None:
|
|
60
|
+
delta = now - self._last
|
|
61
|
+
if delta < self.min_interval:
|
|
62
|
+
self._sleep(self.min_interval - delta)
|
|
63
|
+
self._last = self._clock()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def get_json(url, params=None, **kwargs):
|
|
67
|
+
body, _ctype = get(url, params=params, **kwargs)
|
|
68
|
+
try:
|
|
69
|
+
return json.loads(body.decode("utf-8"))
|
|
70
|
+
except ValueError as e:
|
|
71
|
+
raise HttpError(0, url, "not JSON: %s" % e)
|