ragpages 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.
- ragpages/__init__.py +16 -0
- ragpages/chapter.py +68 -0
- ragpages/cli.py +513 -0
- ragpages/config.py +103 -0
- ragpages/ingest.py +312 -0
- ragpages/meta.py +80 -0
- ragpages/ocr/__init__.py +1 -0
- ragpages/ocr/base.py +63 -0
- ragpages/ocr/kraken_engine.py +59 -0
- ragpages/ocr/rapidocr_engine.py +56 -0
- ragpages/ocr/registry.py +25 -0
- ragpages/parser.py +122 -0
- ragpages/parser_compare.py +142 -0
- ragpages/pipeline.yaml +37 -0
- ragpages/toc_store.py +59 -0
- ragpages-0.1.0.dist-info/METADATA +197 -0
- ragpages-0.1.0.dist-info/RECORD +21 -0
- ragpages-0.1.0.dist-info/WHEEL +5 -0
- ragpages-0.1.0.dist-info/entry_points.txt +2 -0
- ragpages-0.1.0.dist-info/licenses/LICENSE +21 -0
- ragpages-0.1.0.dist-info/top_level.txt +1 -0
ragpages/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""ragpages: PDF (+ OCR) -> data contract -> database for agents.
|
|
2
|
+
|
|
3
|
+
A lightweight, single-machine producer pipeline. It consumes PDFs (with a text
|
|
4
|
+
layer, or via an OCR stage) and emits SQLite artifacts that follow a classic
|
|
5
|
+
RAG database contract:
|
|
6
|
+
|
|
7
|
+
<data>/indexes/<source>.db documents + chunks + chunks_fts (per source)
|
|
8
|
+
<data>/indexes/search.db fused chunks (with `source` column) + chunks_fts
|
|
9
|
+
<data>/indexes/*-manifest.json
|
|
10
|
+
<data>/ocr/<book_id>/pages.jsonl OCR stage output (optional)
|
|
11
|
+
|
|
12
|
+
Everything is driven by `pipeline.yaml` profiles; no code path names a corpus
|
|
13
|
+
directory. See README.md.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
__version__ = "0.1.0"
|
ragpages/chapter.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Chapter stage: header / 回 OCR -> `toc` rows, via `classics-index` only.
|
|
2
|
+
|
|
3
|
+
No runtime import: the pure logic is the published package `classics-index`
|
|
4
|
+
(PyPI, >= 0.1), the storage is `ragpages.toc_store`. A downstream RAG runtime
|
|
5
|
+
keeps reading the same `toc` table.
|
|
6
|
+
|
|
7
|
+
Inputs (JSONL, one record per page):
|
|
8
|
+
headers: {"page": 12, "vol": 3} or {"page": 12, "lines": [{"text": ...}]}
|
|
9
|
+
hui: {"page": 12, "texts": ["第五十九回", "唐三藏路阻火焰山"]}
|
|
10
|
+
"""
|
|
11
|
+
import json
|
|
12
|
+
|
|
13
|
+
from classics_index import core, hui
|
|
14
|
+
|
|
15
|
+
from . import toc_store
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _vol(rec):
|
|
19
|
+
vol = rec.get("vol")
|
|
20
|
+
if vol is not None:
|
|
21
|
+
return core.cn2int(vol) if isinstance(vol, str) else int(vol)
|
|
22
|
+
lines = rec.get("lines") or ([{"text": rec["text"]}] if rec.get("text") else [])
|
|
23
|
+
return core.volume_of(lines)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _lines(rec):
|
|
27
|
+
return rec.get("lines") or ([{"text": rec["text"]}] if rec.get("text") else [])
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def rows_from_headers(records, min_run=5):
|
|
31
|
+
"""卷/篇 rows: contiguous page ranges, 篇 names attached where a page has one."""
|
|
32
|
+
records = [r for r in records if r.get("page")]
|
|
33
|
+
pages = {int(r["page"]): _lines(r) for r in records}
|
|
34
|
+
vols = {int(r["page"]): _vol(r) for r in records}
|
|
35
|
+
chapters = core.build_from_volumes(core.clean_volumes(vols, min_run=min_run))
|
|
36
|
+
chapters = core.enrich(chapters, pages)
|
|
37
|
+
return chapters, {"pages": len(records), "min_run": min_run}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def rows_from_hui(records, names=None):
|
|
41
|
+
"""回 rows for one or more novels; `names` maps book number -> title."""
|
|
42
|
+
books = hui.build(records, names=names or {})
|
|
43
|
+
rows = []
|
|
44
|
+
for book_no, part in enumerate(books, 1):
|
|
45
|
+
for r in part:
|
|
46
|
+
rows.append({
|
|
47
|
+
"ord": len(rows), "level": 2,
|
|
48
|
+
"title": r.get("title_text") or r.get("title") or "回%d" % r["num"],
|
|
49
|
+
"page_start": r["page_start"], "page_end": r["page_end"],
|
|
50
|
+
"volume": None, "pages": r["page_end"] - r["page_start"] + 1,
|
|
51
|
+
"book": book_no, "num": r["num"],
|
|
52
|
+
})
|
|
53
|
+
return rows, {"pages": len(records), "books": len(books), "replies": len(rows)}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def rows_from_toc(data):
|
|
57
|
+
"""Import an already-built toc JSON ({"chapters": [...]} or a list)."""
|
|
58
|
+
rows = data.get("chapters") if isinstance(data, dict) else data
|
|
59
|
+
rows = list(rows or [])
|
|
60
|
+
for i, row in enumerate(rows):
|
|
61
|
+
row.setdefault("ord", i)
|
|
62
|
+
row.setdefault("level", 1)
|
|
63
|
+
row.setdefault("pages", row["page_end"] - row["page_start"] + 1)
|
|
64
|
+
return rows, {"rows": len(rows)}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def write(db, source, book, rows, meta=None):
|
|
68
|
+
return toc_store.save(source, book, rows, meta=meta, path=db)
|
ragpages/cli.py
ADDED
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
"""ragpages CLI: PDF directory (+ OCR) -> RAG database.
|
|
2
|
+
|
|
3
|
+
ragpages build --profiles books --out data/
|
|
4
|
+
ragpages extract --profile books --out data/ [--limit 1]
|
|
5
|
+
ragpages search --out data/ --sources books
|
|
6
|
+
ragpages validate --out data/
|
|
7
|
+
ragpages ocr --profile books-scan --out data/ --books-from books.jsonl
|
|
8
|
+
ragpages chapter --source books --book a.pdf --toc toc.json
|
|
9
|
+
ragpages meta --in book_meta.json --out data/
|
|
10
|
+
ragpages selftest
|
|
11
|
+
|
|
12
|
+
`build` is extract per profile followed by search. Everything takes a profile,
|
|
13
|
+
so no code path names a corpus directory.
|
|
14
|
+
"""
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import shutil
|
|
19
|
+
import sqlite3
|
|
20
|
+
import tempfile
|
|
21
|
+
|
|
22
|
+
from . import config as pcfg
|
|
23
|
+
from . import ingest
|
|
24
|
+
from .parser import get_parser
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _writable_tmp():
|
|
28
|
+
"""A fresh scratch dir in the system temp; best-effort removal by callers."""
|
|
29
|
+
return tempfile.mkdtemp(prefix="ragpages-")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _db_path(out_dir, source):
|
|
33
|
+
path = os.path.join(str(out_dir), "indexes", source + ".db")
|
|
34
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
35
|
+
return path
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def cmd_extract(args):
|
|
39
|
+
cfg = pcfg.load(args.config)
|
|
40
|
+
prof = pcfg.profile(cfg, args.profile)
|
|
41
|
+
out = pcfg.data_dir(cfg, args.out)
|
|
42
|
+
root = args.pdf_root or prof["root"]
|
|
43
|
+
probe = args.probe or prof["probe"]
|
|
44
|
+
if not probe or not os.path.exists(str(probe)):
|
|
45
|
+
raise SystemExit("profile %r needs a probe csv (--probe); look for %s"
|
|
46
|
+
% (prof["name"], probe))
|
|
47
|
+
if not os.path.isdir(str(root)):
|
|
48
|
+
raise SystemExit("pdf root does not exist: %s" % root)
|
|
49
|
+
summary = ingest.extract(
|
|
50
|
+
pdf_root=str(root),
|
|
51
|
+
out_db=_db_path(out, prof["source"]),
|
|
52
|
+
probe_csv=str(probe),
|
|
53
|
+
manifest_path=os.path.join(str(out), "indexes",
|
|
54
|
+
prof["source"] + "-manifest.json"),
|
|
55
|
+
chunk=prof["chunk"]["size"], overlap=prof["chunk"]["overlap"],
|
|
56
|
+
min_len=prof["chunk"]["min_len"], min_cpp=prof["min_cpp"],
|
|
57
|
+
limit=args.limit, parser=args.parser or prof["parser"],
|
|
58
|
+
ocr_dir=args.ocr_dir or os.path.join(str(out), "ocr"))
|
|
59
|
+
print(json.dumps({"profile": prof["name"], "summary": {
|
|
60
|
+
k: summary[k] for k in ("books_csv", "books_ingested", "text_pages", "chunks")}},
|
|
61
|
+
ensure_ascii=False))
|
|
62
|
+
return 0
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def cmd_search(args):
|
|
66
|
+
cfg = pcfg.load(args.config)
|
|
67
|
+
out = pcfg.data_dir(cfg, args.out)
|
|
68
|
+
sources = [s.strip() for s in (args.sources or "").split(",") if s.strip()]
|
|
69
|
+
if not sources:
|
|
70
|
+
raise SystemExit("search needs --sources (comma-separated source ids)")
|
|
71
|
+
dbs = {src: os.path.join(str(out), "indexes", src + ".db")
|
|
72
|
+
for src in sources}
|
|
73
|
+
result = ingest.build(
|
|
74
|
+
out_db=os.path.join(str(out), "indexes", "search.db"),
|
|
75
|
+
sources=sources, dbs=dbs,
|
|
76
|
+
eval_path=os.path.join(str(out), "indexes", "search-eval.json"))
|
|
77
|
+
print(json.dumps({k: v for k, v in result.items() if k != "detail"},
|
|
78
|
+
ensure_ascii=False))
|
|
79
|
+
return 0
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _book_list(books_from, limit):
|
|
83
|
+
"""Rows `{rel, pages}` for the OCR batch; a `{rel,pages}` JSONL is required."""
|
|
84
|
+
if not books_from or not os.path.exists(books_from):
|
|
85
|
+
raise SystemExit("book list not found: %s (pass --books-from)" % books_from)
|
|
86
|
+
rows = []
|
|
87
|
+
with open(books_from, encoding="utf-8-sig") as fh:
|
|
88
|
+
for line in fh:
|
|
89
|
+
line = line.strip()
|
|
90
|
+
if not line:
|
|
91
|
+
continue
|
|
92
|
+
rec = json.loads(line)
|
|
93
|
+
if "tier" in rec and rec.get("tier") != 1:
|
|
94
|
+
continue
|
|
95
|
+
if rec.get("vertical"):
|
|
96
|
+
continue
|
|
97
|
+
rel = rec.get("rel") or rec.get("path")
|
|
98
|
+
if rel:
|
|
99
|
+
rows.append({"rel": rel, "pages": int(rec.get("pages") or 0)})
|
|
100
|
+
rows.sort(key=lambda r: r["pages"])
|
|
101
|
+
return rows[:limit] if limit else rows
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _qc(pages, qc_cfg):
|
|
105
|
+
chars = [len(p.get("text") or "") for p in pages]
|
|
106
|
+
blank = sum(1 for c in chars if c < 20)
|
|
107
|
+
dup_pairs = total_pairs = 0
|
|
108
|
+
for p in pages:
|
|
109
|
+
lines = [l.strip() for l in (p.get("text") or "").splitlines() if l.strip()]
|
|
110
|
+
for a, b in zip(lines, lines[1:]):
|
|
111
|
+
total_pairs += 1
|
|
112
|
+
dup_pairs += 1 if a == b else 0
|
|
113
|
+
cjk = sum(1 for ch in "".join(p.get("text") or "" for p in pages)
|
|
114
|
+
if "\u3400" <= ch <= "\u9fff")
|
|
115
|
+
out = {
|
|
116
|
+
"pages_ocr": len(pages),
|
|
117
|
+
"chars_median": sorted(chars)[len(chars) // 2] if chars else 0,
|
|
118
|
+
"blank_rate": round(blank / max(1, len(pages)), 4),
|
|
119
|
+
"dup_line_rate": round(dup_pairs / max(1, total_pairs), 4),
|
|
120
|
+
"cjk_ratio": round(cjk / max(1, sum(chars)), 4),
|
|
121
|
+
}
|
|
122
|
+
if qc_cfg:
|
|
123
|
+
failed = []
|
|
124
|
+
if "blank_rate" in qc_cfg and out["blank_rate"] > float(qc_cfg["blank_rate"]):
|
|
125
|
+
failed.append("blank_rate")
|
|
126
|
+
if "dup_line_rate" in qc_cfg and out["dup_line_rate"] > float(qc_cfg["dup_line_rate"]):
|
|
127
|
+
failed.append("dup_line_rate")
|
|
128
|
+
if "min_cjk" in qc_cfg and out["cjk_ratio"] < float(qc_cfg["min_cjk"]):
|
|
129
|
+
failed.append("cjk_ratio")
|
|
130
|
+
out["qc_failed"] = failed
|
|
131
|
+
return out
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def cmd_ocr(args):
|
|
135
|
+
"""Render pages and run the configured OCR engine into `<out>/ocr/`."""
|
|
136
|
+
import hashlib
|
|
137
|
+
import time
|
|
138
|
+
|
|
139
|
+
from .ocr.base import PageImage
|
|
140
|
+
from .ocr.registry import get_engine
|
|
141
|
+
|
|
142
|
+
cfg = pcfg.load(args.config)
|
|
143
|
+
prof = pcfg.profile(cfg, args.profile)
|
|
144
|
+
out = pcfg.data_dir(cfg, args.out)
|
|
145
|
+
ocr_cfg = dict(prof["ocr"])
|
|
146
|
+
if args.engine:
|
|
147
|
+
ocr_cfg["engine"] = args.engine
|
|
148
|
+
if args.dpi:
|
|
149
|
+
ocr_cfg["dpi"] = int(args.dpi)
|
|
150
|
+
engine = get_engine(ocr_cfg["engine"], models=ocr_cfg["models"],
|
|
151
|
+
backend=ocr_cfg["backend"], params=ocr_cfg["params"])
|
|
152
|
+
model_sha = engine.model_sha256()
|
|
153
|
+
|
|
154
|
+
ocr_root = os.path.join(str(out), "ocr")
|
|
155
|
+
os.makedirs(ocr_root, exist_ok=True)
|
|
156
|
+
state = sqlite3.connect(os.path.join(ocr_root, "state.db"))
|
|
157
|
+
state.execute("CREATE TABLE IF NOT EXISTS books("
|
|
158
|
+
"rel TEXT PRIMARY KEY, book_id TEXT, pages_expected INT,"
|
|
159
|
+
" pages_done INT, status TEXT, started TEXT, finished TEXT, error TEXT)")
|
|
160
|
+
state.commit()
|
|
161
|
+
|
|
162
|
+
books = _book_list(args.books_from, args.books)
|
|
163
|
+
for b in books:
|
|
164
|
+
rel = b["rel"]
|
|
165
|
+
book_id = hashlib.sha1(rel.encode("utf-8")).hexdigest()[:16]
|
|
166
|
+
bdir = os.path.join(ocr_root, book_id)
|
|
167
|
+
os.makedirs(bdir, exist_ok=True)
|
|
168
|
+
pages_file = os.path.join(bdir, "pages.jsonl")
|
|
169
|
+
if os.path.exists(os.path.join(bdir, "DONE")):
|
|
170
|
+
print("skip (done)", rel[:50], flush=True)
|
|
171
|
+
continue
|
|
172
|
+
path = os.path.join(str(prof["root"]), rel)
|
|
173
|
+
if not os.path.exists(path):
|
|
174
|
+
state.execute("INSERT OR REPLACE INTO books VALUES(?,?,?,?,?,?,?,?)",
|
|
175
|
+
(rel, book_id, b["pages"], 0, "MISSING", None, None, "not found"))
|
|
176
|
+
state.commit()
|
|
177
|
+
print("MISSING", rel[:60], flush=True)
|
|
178
|
+
continue
|
|
179
|
+
|
|
180
|
+
started = time.strftime("%Y-%m-%d %H:%M:%S")
|
|
181
|
+
state.execute("INSERT OR REPLACE INTO books VALUES(?,?,?,?,?,?,?,?)",
|
|
182
|
+
(rel, book_id, b["pages"], 0, "RUNNING", started, None, None))
|
|
183
|
+
state.commit()
|
|
184
|
+
pages = []
|
|
185
|
+
try:
|
|
186
|
+
doc = get_parser(args.parser or prof["parser"]).open(path)
|
|
187
|
+
total = doc.page_count
|
|
188
|
+
limit = min(total, args.max_pages) if args.max_pages else total
|
|
189
|
+
with open(pages_file, "w", encoding="utf-8", newline="\n") as fh:
|
|
190
|
+
for pno in range(1, limit + 1):
|
|
191
|
+
bgr, width, height = doc.render_bgr(pno - 1, ocr_cfg["dpi"])
|
|
192
|
+
res = next(iter(engine.run([PageImage(page=pno, image=bgr,
|
|
193
|
+
width=width,
|
|
194
|
+
height=height)])))
|
|
195
|
+
rec = res.as_dict()
|
|
196
|
+
rec.update({"engine": engine.name, "engine_version": engine.version,
|
|
197
|
+
"backend": ocr_cfg["backend"], "dpi": ocr_cfg["dpi"],
|
|
198
|
+
"model_sha256": model_sha})
|
|
199
|
+
pages.append(rec)
|
|
200
|
+
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
|
201
|
+
fh.flush()
|
|
202
|
+
doc.close()
|
|
203
|
+
except Exception as exc:
|
|
204
|
+
state.execute("UPDATE books SET status=?, error=? WHERE rel=?",
|
|
205
|
+
("ERROR", ("%s: %s" % (type(exc).__name__, exc))[:300], rel))
|
|
206
|
+
state.commit()
|
|
207
|
+
print("ERROR", book_id, type(exc).__name__, str(exc)[:160], flush=True)
|
|
208
|
+
continue
|
|
209
|
+
|
|
210
|
+
q = _qc(pages, ocr_cfg["qc"])
|
|
211
|
+
q.update({"rel": rel, "book_id": book_id, "dpi": ocr_cfg["dpi"],
|
|
212
|
+
"lang": ocr_cfg["lang"],
|
|
213
|
+
"engine": engine.name, "engine_version": engine.version,
|
|
214
|
+
"backend": ocr_cfg["backend"], "model_sha256": model_sha,
|
|
215
|
+
"pages_expected": total})
|
|
216
|
+
with open(os.path.join(bdir, "book.json"), "w", encoding="utf-8") as fh:
|
|
217
|
+
json.dump(q, fh, ensure_ascii=False, indent=1)
|
|
218
|
+
open(os.path.join(bdir, "DONE"), "w").close()
|
|
219
|
+
state.execute("UPDATE books SET pages_done=?, status=?, finished=? WHERE rel=?",
|
|
220
|
+
(len(pages), "QC_FAIL" if q.get("qc_failed") else "DONE",
|
|
221
|
+
time.strftime("%Y-%m-%d %H:%M:%S"), rel))
|
|
222
|
+
state.commit()
|
|
223
|
+
print("done %s %d/%d blank=%.2f dup=%.2f cjk=%.2f"
|
|
224
|
+
% (book_id, len(pages), total, q["blank_rate"], q["dup_line_rate"],
|
|
225
|
+
q["cjk_ratio"]), flush=True)
|
|
226
|
+
state.close()
|
|
227
|
+
print(json.dumps({"profile": prof["name"], "books": len(books),
|
|
228
|
+
"engine": engine.name, "engine_version": engine.version,
|
|
229
|
+
"backend": ocr_cfg["backend"], "model_sha256": model_sha},
|
|
230
|
+
ensure_ascii=False))
|
|
231
|
+
return 0
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _read_jsonl(path):
|
|
235
|
+
rows = []
|
|
236
|
+
with open(path, encoding="utf-8-sig") as fh:
|
|
237
|
+
for line in fh:
|
|
238
|
+
line = line.strip()
|
|
239
|
+
if line:
|
|
240
|
+
rows.append(json.loads(line))
|
|
241
|
+
return rows
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def cmd_chapter(args):
|
|
245
|
+
"""Header/回 OCR JSONL -> `toc` rows (classics-index, no runtime import)."""
|
|
246
|
+
from . import chapter as ch
|
|
247
|
+
|
|
248
|
+
cfg = pcfg.load(args.config)
|
|
249
|
+
out = pcfg.data_dir(cfg, args.out)
|
|
250
|
+
db = args.db or os.path.join(str(out), "indexes", "search.db")
|
|
251
|
+
if args.headers:
|
|
252
|
+
rows, info = ch.rows_from_headers(_read_jsonl(args.headers), args.min_run)
|
|
253
|
+
elif args.hui:
|
|
254
|
+
names = {}
|
|
255
|
+
for part in (args.names or "").split(","):
|
|
256
|
+
if "=" in part:
|
|
257
|
+
k, v = part.split("=", 1)
|
|
258
|
+
names[int(k)] = v.strip()
|
|
259
|
+
rows, info = ch.rows_from_hui(_read_jsonl(args.hui), names)
|
|
260
|
+
elif args.toc:
|
|
261
|
+
with open(args.toc, encoding="utf-8-sig") as fh:
|
|
262
|
+
rows, info = ch.rows_from_toc(json.load(fh))
|
|
263
|
+
else:
|
|
264
|
+
raise SystemExit("give one of --headers / --hui / --toc")
|
|
265
|
+
n = ch.write(db, args.source, args.book, rows, meta=info)
|
|
266
|
+
if args.out_json:
|
|
267
|
+
os.makedirs(os.path.dirname(args.out_json) or ".", exist_ok=True)
|
|
268
|
+
with open(args.out_json, "w", encoding="utf-8") as fh:
|
|
269
|
+
json.dump({"source": args.source, "book": args.book,
|
|
270
|
+
"chapters": rows, "info": info}, fh,
|
|
271
|
+
ensure_ascii=False, indent=1)
|
|
272
|
+
print(json.dumps({"db": db, "source": args.source, "book": args.book,
|
|
273
|
+
"rows": n, "info": info}, ensure_ascii=False))
|
|
274
|
+
return 0
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def cmd_meta(args):
|
|
278
|
+
"""Validate `book_meta.json` and copy it into the output (never generate)."""
|
|
279
|
+
from . import meta as pmeta
|
|
280
|
+
|
|
281
|
+
cfg = pcfg.load(args.config)
|
|
282
|
+
out = pcfg.data_dir(cfg, args.out)
|
|
283
|
+
result = pmeta.copy(args.in_path, out, strict=args.strict)
|
|
284
|
+
print(json.dumps(result, ensure_ascii=False, indent=1))
|
|
285
|
+
return 0 if result.get("ok") else 2
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def cmd_validate(args):
|
|
289
|
+
"""Cheap structural check against the output contract."""
|
|
290
|
+
out = pcfg.data_dir(pcfg.load(args.config), args.out)
|
|
291
|
+
idx = os.path.join(str(out), "indexes")
|
|
292
|
+
problems = []
|
|
293
|
+
found = 0
|
|
294
|
+
if os.path.isdir(idx):
|
|
295
|
+
for name in sorted(os.listdir(idx)):
|
|
296
|
+
if not name.endswith(".db"):
|
|
297
|
+
continue
|
|
298
|
+
path = os.path.join(idx, name)
|
|
299
|
+
con = sqlite3.connect(path)
|
|
300
|
+
try:
|
|
301
|
+
tables = {r[0] for r in con.execute(
|
|
302
|
+
"SELECT name FROM sqlite_master WHERE type='table'")}
|
|
303
|
+
cols = ({r[1] for r in con.execute("PRAGMA table_info(chunks)")}
|
|
304
|
+
if "chunks" in tables else set())
|
|
305
|
+
n = (con.execute("SELECT count(*) FROM chunks").fetchone()[0]
|
|
306
|
+
if "chunks" in tables else 0)
|
|
307
|
+
toc = (con.execute("SELECT count(*) FROM toc").fetchone()[0]
|
|
308
|
+
if "toc" in tables else None)
|
|
309
|
+
finally:
|
|
310
|
+
con.close()
|
|
311
|
+
found += 1
|
|
312
|
+
missing = {"chunks", "chunks_fts"} - tables
|
|
313
|
+
if missing:
|
|
314
|
+
problems.append("%s: missing %s" % (name, sorted(missing)))
|
|
315
|
+
if "chunks" in tables and "visibility" not in cols:
|
|
316
|
+
problems.append("%s: chunks.visibility absent" % name)
|
|
317
|
+
extra = (" toc=%d" % toc) if toc is not None else ""
|
|
318
|
+
print("%-16s chunks=%-7d tables=%s%s"
|
|
319
|
+
% (name, n, ",".join(sorted(tables)), extra))
|
|
320
|
+
if not found:
|
|
321
|
+
problems.append("no *.db under %s" % idx)
|
|
322
|
+
if problems:
|
|
323
|
+
for p in problems:
|
|
324
|
+
print("FAIL", p)
|
|
325
|
+
return 2
|
|
326
|
+
print("OK")
|
|
327
|
+
return 0
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def cmd_build(args):
|
|
331
|
+
names = [s.strip() for s in (args.profiles or "").split(",") if s.strip()]
|
|
332
|
+
if not names:
|
|
333
|
+
raise SystemExit("build needs --profiles (comma-separated profile names)")
|
|
334
|
+
for name in names:
|
|
335
|
+
cmd_extract(argparse.Namespace(
|
|
336
|
+
config=args.config, profile=name, out=args.out, pdf_root=None,
|
|
337
|
+
probe=None, limit=args.limit, parser=args.parser, ocr_dir=None))
|
|
338
|
+
sources = [pcfg.profile(pcfg.load(args.config), n)["source"] for n in names]
|
|
339
|
+
return cmd_search(argparse.Namespace(
|
|
340
|
+
config=args.config, out=args.out, sources=",".join(sources)))
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _synthetic_pdf(path, pages=2):
|
|
344
|
+
"""Write a tiny text-layer PDF without depending on any PDF writer."""
|
|
345
|
+
import textwrap
|
|
346
|
+
|
|
347
|
+
text = ("The derivative measures how the output changes when the input "
|
|
348
|
+
"changes. Its definition is the limit of a difference quotient. ") * 12
|
|
349
|
+
lines = textwrap.wrap(text, 78)[:26]
|
|
350
|
+
|
|
351
|
+
def esc(s):
|
|
352
|
+
return s.replace("\\", r"\\").replace("(", r"\(").replace(")", r"\)")
|
|
353
|
+
|
|
354
|
+
def page_stream():
|
|
355
|
+
parts = ["BT /F1 10 Tf 14 TL 72 720 Td"]
|
|
356
|
+
parts.append("(%s) Tj" % esc(lines[0]))
|
|
357
|
+
parts.extend("T* (%s) Tj" % esc(line) for line in lines[1:])
|
|
358
|
+
parts.append("ET")
|
|
359
|
+
return "\n".join(parts).encode("latin-1")
|
|
360
|
+
|
|
361
|
+
content = [page_stream() for _ in range(pages)]
|
|
362
|
+
font_obj = 3 + pages
|
|
363
|
+
objects = []
|
|
364
|
+
objects.append(b"<< /Type /Catalog /Pages 2 0 R >>")
|
|
365
|
+
kids = " ".join("%d 0 R" % (i + 3) for i in range(pages))
|
|
366
|
+
objects.append(("<< /Type /Pages /Kids [%s] /Count %d >>" % (kids, pages))
|
|
367
|
+
.encode("latin-1"))
|
|
368
|
+
for i in range(pages):
|
|
369
|
+
objects.append(("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
|
|
370
|
+
"/Resources << /Font << /F1 %d 0 R >> >> /Contents %d 0 R >>"
|
|
371
|
+
% (font_obj, font_obj + 1 + i)).encode("latin-1"))
|
|
372
|
+
objects.append(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")
|
|
373
|
+
for c in content:
|
|
374
|
+
objects.append(b"<< /Length %d >>\nstream\n" % len(c) + c + b"\nendstream")
|
|
375
|
+
|
|
376
|
+
out = bytearray(b"%PDF-1.4\n")
|
|
377
|
+
offsets = [0]
|
|
378
|
+
for i, obj in enumerate(objects, 1):
|
|
379
|
+
offsets.append(len(out))
|
|
380
|
+
out += b"%d 0 obj\n" % i + obj + b"\nendobj\n"
|
|
381
|
+
xref = len(out)
|
|
382
|
+
n = len(objects) + 1
|
|
383
|
+
out += b"xref\n0 %d\n" % n
|
|
384
|
+
out += b"0000000000 65535 f \n"
|
|
385
|
+
for off in offsets[1:]:
|
|
386
|
+
out += b"%010d 00000 n \n" % off
|
|
387
|
+
out += b"trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n" % (n, xref)
|
|
388
|
+
with open(path, "wb") as fh:
|
|
389
|
+
fh.write(bytes(out))
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def cmd_selftest(args):
|
|
393
|
+
"""Build a synthetic PDF in a temp dir and run extract/search/validate.
|
|
394
|
+
|
|
395
|
+
Proves the CLI wiring end to end without touching a real corpus or
|
|
396
|
+
producing data that could be mistaken for a real build. The scratch dir
|
|
397
|
+
lives in the system temp dir, and its removal is best-effort.
|
|
398
|
+
"""
|
|
399
|
+
import csv
|
|
400
|
+
|
|
401
|
+
tmp = _writable_tmp()
|
|
402
|
+
books = os.path.join(tmp, "books")
|
|
403
|
+
os.makedirs(books)
|
|
404
|
+
try:
|
|
405
|
+
pdf = os.path.join(books, "tiny.pdf")
|
|
406
|
+
_synthetic_pdf(pdf)
|
|
407
|
+
probe = os.path.join(books, "probe.csv")
|
|
408
|
+
with open(probe, "w", encoding="utf-8", newline="") as fh:
|
|
409
|
+
w = csv.writer(fh)
|
|
410
|
+
w.writerow(["rel", "cpp"])
|
|
411
|
+
w.writerow(["tiny.pdf", "900"])
|
|
412
|
+
|
|
413
|
+
out = os.path.join(tmp, "out")
|
|
414
|
+
rc = cmd_extract(argparse.Namespace(
|
|
415
|
+
config=args.config, profile=args.profile or "books", out=out,
|
|
416
|
+
pdf_root=books, probe=probe, limit=1,
|
|
417
|
+
parser=args.parser or "pypdfium2", ocr_dir=None))
|
|
418
|
+
if rc:
|
|
419
|
+
return rc
|
|
420
|
+
rc = cmd_search(argparse.Namespace(
|
|
421
|
+
config=args.config, out=out, sources="books"))
|
|
422
|
+
if rc:
|
|
423
|
+
return rc
|
|
424
|
+
rc = cmd_validate(argparse.Namespace(config=args.config, out=out))
|
|
425
|
+
print("selftest OK" if rc == 0 else "selftest FAILED")
|
|
426
|
+
return rc
|
|
427
|
+
finally:
|
|
428
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def main(argv=None):
|
|
432
|
+
ap = argparse.ArgumentParser(prog="ragpages", description=__doc__.splitlines()[0])
|
|
433
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
434
|
+
common.add_argument("--config", default=None,
|
|
435
|
+
help="pipeline.yaml (default: RAGPAGES_CONFIG env,"
|
|
436
|
+
" else ./pipeline.yaml, else the packaged template)")
|
|
437
|
+
ap.add_argument("--config", default=None,
|
|
438
|
+
help="pipeline.yaml (default: RAGPAGES_CONFIG env,"
|
|
439
|
+
" else ./pipeline.yaml, else the packaged template)")
|
|
440
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
441
|
+
|
|
442
|
+
e = sub.add_parser("extract", parents=[common],
|
|
443
|
+
help="PDF directory -> per-source db")
|
|
444
|
+
e.add_argument("--profile", required=True)
|
|
445
|
+
e.add_argument("--out")
|
|
446
|
+
e.add_argument("--pdf-root")
|
|
447
|
+
e.add_argument("--probe")
|
|
448
|
+
e.add_argument("--ocr-dir", help="OCR output from `ocr` (default: <out>/ocr)")
|
|
449
|
+
e.add_argument("--limit", type=int)
|
|
450
|
+
e.add_argument("--parser")
|
|
451
|
+
e.set_defaults(func=cmd_extract)
|
|
452
|
+
|
|
453
|
+
o = sub.add_parser("ocr", parents=[common], help="PDF pages -> OCR text + provenance")
|
|
454
|
+
o.add_argument("--profile", required=True)
|
|
455
|
+
o.add_argument("--out")
|
|
456
|
+
o.add_argument("--books", type=int, help="how many books from the list")
|
|
457
|
+
o.add_argument("--books-from", required=True,
|
|
458
|
+
help="a {rel,pages} JSONL book list (one record per line)")
|
|
459
|
+
o.add_argument("--max-pages", type=int, default=0)
|
|
460
|
+
o.add_argument("--engine")
|
|
461
|
+
o.add_argument("--dpi", type=int)
|
|
462
|
+
o.add_argument("--parser")
|
|
463
|
+
o.set_defaults(func=cmd_ocr)
|
|
464
|
+
|
|
465
|
+
s = sub.add_parser("search", parents=[common], help="per-source dbs -> search.db")
|
|
466
|
+
s.add_argument("--out")
|
|
467
|
+
s.add_argument("--sources")
|
|
468
|
+
s.set_defaults(func=cmd_search)
|
|
469
|
+
|
|
470
|
+
v = sub.add_parser("validate", parents=[common], help="structural check of the artifacts")
|
|
471
|
+
v.add_argument("--out")
|
|
472
|
+
v.set_defaults(func=cmd_validate)
|
|
473
|
+
|
|
474
|
+
c = sub.add_parser("chapter", parents=[common], help="header/回 OCR -> toc rows")
|
|
475
|
+
c.add_argument("--source", required=True)
|
|
476
|
+
c.add_argument("--book", required=True)
|
|
477
|
+
c.add_argument("--db", help="toc database (default: <out>/indexes/search.db)")
|
|
478
|
+
c.add_argument("--out", help="output root (default: config data dir)")
|
|
479
|
+
c.add_argument("--headers", help="JSONL of {page, vol|lines}")
|
|
480
|
+
c.add_argument("--hui", help="JSONL of {page, texts} for 章回 novels")
|
|
481
|
+
c.add_argument("--toc", help="already-built toc JSON")
|
|
482
|
+
c.add_argument("--names", help="1=Novel One,2=Novel Two for --hui")
|
|
483
|
+
c.add_argument("--min-run", type=int, default=5)
|
|
484
|
+
c.add_argument("--out-json")
|
|
485
|
+
c.set_defaults(func=cmd_chapter)
|
|
486
|
+
|
|
487
|
+
m = sub.add_parser("meta", parents=[common], help="validate + copy book_meta.json")
|
|
488
|
+
m.add_argument("--in", dest="in_path", required=True)
|
|
489
|
+
m.add_argument("--out")
|
|
490
|
+
m.add_argument("--strict", action="store_true",
|
|
491
|
+
help="treat legacy doc_kind values as errors")
|
|
492
|
+
m.set_defaults(func=cmd_meta)
|
|
493
|
+
|
|
494
|
+
b = sub.add_parser("build", parents=[common], help="extract + search")
|
|
495
|
+
b.add_argument("--profiles")
|
|
496
|
+
b.add_argument("--out")
|
|
497
|
+
b.add_argument("--limit", type=int)
|
|
498
|
+
b.add_argument("--parser")
|
|
499
|
+
b.set_defaults(func=cmd_build)
|
|
500
|
+
|
|
501
|
+
t = sub.add_parser("selftest", parents=[common],
|
|
502
|
+
help="synthetic PDF -> extract/search/validate")
|
|
503
|
+
t.add_argument("--profile", default="books",
|
|
504
|
+
help="profile to borrow config from (default: books)")
|
|
505
|
+
t.add_argument("--parser", help="pypdfium2 | pymupdf (default: pypdfium2)")
|
|
506
|
+
t.set_defaults(func=cmd_selftest)
|
|
507
|
+
|
|
508
|
+
args = ap.parse_args(argv)
|
|
509
|
+
return args.func(args)
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
if __name__ == "__main__":
|
|
513
|
+
raise SystemExit(main())
|