| |
| """Phase 1: Re-OCR with single Chandra instance (port 8521), 2 concurrent workers. |
| Updates DB rows to source_type='ocr_chandra_v2'. |
| Commits every doc for resilience. Skips already-processed docs. |
| """ |
| import duckdb, re, json, time, base64, io, os, sys, hashlib |
| import requests |
| from pathlib import Path |
| from PIL import Image |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| from collections import defaultdict |
| from qwen_vl_utils.vision_process import smart_resize |
| import logging |
|
|
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s", handlers=[ |
| logging.StreamHandler(sys.stdout), |
| logging.FileHandler("/tmp/reocr_phase1.log", mode="a"), |
| ]) |
| log = logging.getLogger("reocr") |
|
|
| DB_PATH = "/root/gwanbo-ocr/data/gwanbo.db" |
| ST_ROOT = Path("/root/peti/artifacts/searchThema/pdfs") |
| PETY_ROOT = Path("/root/peti/artifacts/pety/pdfs") |
| CHANDRA_URL = "http://localhost:8521/v1/chat/completions" |
| OCR_PROMPT = "OCR this image. Return the full text." |
| MAX_TOKENS = 8192 |
| WORKERS = 2 |
| MAX_PIXELS = 1280 * 1280 |
| DPI = 150 |
| LOG_INTERVAL = 25 |
|
|
| CORRECTIONS = { |
| "판보": "관보", "필요인": "금요일", "확요인": "화요일", |
| "멸요인": "월요일", "분인": "본인", "동록재선": "등록재산", |
| "변동사함": "변동사항", "평주직할시": "광주직할시", |
| "대우남구": "대구남구", "썬울": "서울", "뷰산": "부산", |
| } |
|
|
| def fix_text(t): |
| for a, b in CORRECTIONS.items(): |
| t = t.replace(a, b) |
| return t |
|
|
| def load_cache(): |
| cache = defaultdict(list) |
| for fn in ['/tmp/pdftotext_cache.jsonl', '/tmp/pdf_issue_cache_v2.jsonl']: |
| if not os.path.exists(fn): |
| continue |
| with open(fn) as f: |
| for line in f: |
| rec = json.loads(line) |
| iss = str(rec.get("issue", "")) |
| if iss and rec.get("year"): |
| cache[(int(rec["year"]), iss)].append({ |
| "path": rec["path"], |
| "pages": rec.get("pages", 0), |
| }) |
| return cache |
|
|
| def find_pdf(cache, year, issue, total_pages): |
| key = (int(year), str(issue)) |
| if key not in cache: |
| return None |
| for c in cache[key]: |
| if c["pages"] == total_pages: |
| return c["path"] |
| return cache[key][0]["path"] if cache[key] else None |
|
|
| def resolve_pdf_path(path_str): |
| if path_str.startswith("/"): |
| if os.path.exists(path_str): |
| return path_str |
| return None |
| for root in [ST_ROOT, PETY_ROOT]: |
| full = root.parent.parent / path_str |
| if os.path.exists(str(full)): |
| return str(full) |
| full = root.parent / path_str |
| if os.path.exists(str(full)): |
| return str(full) |
| return path_str if os.path.exists(path_str) else None |
|
|
| def render_page(pdf_path, page_num): |
| import fitz |
| doc = fitz.open(pdf_path) |
| if page_num >= doc.page_count: |
| doc.close() |
| return None |
| page = doc[page_num] |
| mat = fitz.Matrix(DPI / 72, DPI / 72) |
| pix = page.get_pixmap(matrix=mat) |
| doc.close() |
| img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) |
| h, w = smart_resize(img.height, img.width, factor=28, max_pixels=MAX_PIXELS) |
| if (h, w) != (img.height, img.width): |
| img = img.resize((w, h), Image.LANCZOS) |
| buf = io.BytesIO() |
| img.save(buf, format="JPEG", quality=75) |
| return base64.b64encode(buf.getvalue()).decode() |
|
|
| def ocr_chandra(b64): |
| payload = { |
| "messages": [{"role": "user", "content": [ |
| {"type": "text", "text": OCR_PROMPT}, |
| {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}}, |
| ]}], |
| "max_tokens": MAX_TOKENS, "temperature": 0.0, |
| } |
| for attempt in range(3): |
| try: |
| r = requests.post(CHANDRA_URL, json=payload, timeout=600) |
| if r.status_code == 200: |
| d = r.json() |
| txt = d["choices"][0]["message"]["content"] |
| fin = d["choices"][0].get("finish_reason", "?") |
| toks = d.get("usage", {}).get("completion_tokens", 0) |
| return txt, toks, fin |
| log.warning(f"HTTP {r.status_code}, attempt {attempt+1}") |
| time.sleep(3) |
| except Exception as e: |
| log.warning(f"Request error: {e}, attempt {attempt+1}") |
| time.sleep(5) |
| return None, 0, "error" |
|
|
| def main(): |
| log.info("Loading cache...") |
| cache = load_cache() |
| log.info(f" {len(cache)} issue keys") |
|
|
| conn = duckdb.connect(DB_PATH) |
|
|
| already_done = conn.execute("SELECT DISTINCT doc_id FROM page_texts WHERE source_type='ocr_chandra_v2'").fetchall() |
| done_set = set(r[0] for r in already_done) |
| log.info(f" Already processed: {len(done_set)} docs (skipped)") |
|
|
| total_done = 0 |
| total_fail = 0 |
| total_truncated = 0 |
| t_start = time.time() |
|
|
| for src in ["ocr_chandra", "ocr_searchthema"]: |
| log.info(f"=== Processing {src} ===") |
|
|
| docs = conn.execute(f""" |
| SELECT DISTINCT doc_id, year, total_pages |
| FROM page_texts WHERE source_type='{src}' |
| """).fetchall() |
| log.info(f" {len(docs)} total docs") |
|
|
| work_items = [] |
| matched = 0 |
| skipped = 0 |
| unmatched = 0 |
|
|
| for doc_id, yr, tp in docs: |
| if doc_id in done_set: |
| skipped += 1 |
| continue |
|
|
| page0 = conn.execute(""" |
| SELECT text_content FROM page_texts |
| WHERE doc_id=? AND source_type=? AND page_num=0 |
| """, [doc_id, src]).fetchone() |
|
|
| first_text = page0[0] if page0 else "" |
| issue_nums = re.findall(r'제(\d{4,5})호', first_text or "") |
| if not issue_nums: |
| issue_nums = re.findall(r'제(\d{4,5})', first_text or "") |
| if not issue_nums: |
| unmatched += 1 |
| continue |
|
|
| pdf_path = find_pdf(cache, yr, issue_nums[0], tp) |
| if not pdf_path: |
| unmatched += 1 |
| continue |
|
|
| resolved = resolve_pdf_path(pdf_path) |
| if not resolved: |
| unmatched += 1 |
| continue |
|
|
| page_nums = conn.execute(""" |
| SELECT page_num FROM page_texts |
| WHERE doc_id=? AND source_type=? ORDER BY page_num |
| """, [doc_id, src]).fetchall() |
| page_nums = [r[0] for r in page_nums] |
|
|
| work_items.append((doc_id, yr, issue_nums[0], resolved, page_nums)) |
| matched += 1 |
|
|
| log.info(f" matched={matched}, skipped={skipped}, unmatched={unmatched}") |
| if not work_items: |
| continue |
|
|
| src_done = 0 |
|
|
| def process_doc(item): |
| doc_id, yr, issue, pdf_path, page_nums = item |
| results = [] |
| for pn in page_nums: |
| b64 = render_page(pdf_path, pn) |
| if not b64: |
| results.append((pn, None, 0, "render_fail")) |
| continue |
| txt, toks, fin = ocr_chandra(b64) |
| if txt: |
| results.append((pn, fix_text(txt), toks, fin)) |
| else: |
| results.append((pn, None, 0, "ocr_fail")) |
| return doc_id, results |
|
|
| with ThreadPoolExecutor(max_workers=WORKERS) as pool: |
| futures = {pool.submit(process_doc, item): item for item in work_items} |
|
|
| for fut in as_completed(futures): |
| doc_id, results = fut.result() |
| src_done += 1 |
|
|
| updated = 0 |
| for pn, txt, toks, fin in results: |
| if txt: |
| tl = len(txt) |
| conn.execute(""" |
| UPDATE page_texts |
| SET text_content=?, text_len=?, source_type='ocr_chandra_v2' |
| WHERE doc_id=? AND page_num=? |
| """, [txt, tl, doc_id, pn]) |
| updated += 1 |
| if fin == "length": |
| total_truncated += 1 |
| else: |
| total_fail += 1 |
|
|
| conn.commit() |
| done_set.add(doc_id) |
| total_done += updated |
|
|
| if src_done % LOG_INTERVAL == 0: |
| el = time.time() - t_start |
| rate = total_done / max(el, 1) |
| remaining = 55179 - total_done |
| eta = remaining / max(rate, 0.01) / 3600 |
| log.info(f"[{src_done}/{len(work_items)}] pages={total_done:,} fail={total_fail} " |
| f"trunc={total_truncated} rate={rate:.2f}p/s ETA={eta:.1f}h") |
|
|
| conn.commit() |
| el = time.time() - t_start |
| log.info(f" {src} done: {src_done} docs processed in {el:.0f}s") |
|
|
| conn.commit() |
| el = time.time() - t_start |
|
|
| log.info(f"=== Phase 1 Complete ===") |
| log.info(f" Total pages OCR'd: {total_done:,}") |
| log.info(f" Failed: {total_fail}") |
| log.info(f" Truncated: {total_truncated}") |
| log.info(f" Time: {el:.0f}s ({el/3600:.1f}h)") |
| log.info(f" Rate: {total_done/max(el,1):.2f} p/s") |
|
|
| for st in ['ocr_chandra', 'ocr_searchthema', 'ocr_chandra_v2', 'digital', 'digital_gs']: |
| c = conn.execute(f"SELECT count(*) FROM page_texts WHERE source_type='{st}'").fetchone()[0] |
| log.info(f" {st}: {c:,}") |
|
|
| out = "/tmp/page_texts_phase1.parquet" |
| conn.execute(f"COPY page_texts TO '{out}' (FORMAT PARQUET, COMPRESSION ZSTD)") |
| sz = os.path.getsize(out) / 1e9 |
| log.info(f"Exported: {out} ({sz:.2f} GB)") |
|
|
| conn.close() |
|
|
| if __name__ == "__main__": |
| main() |
|
|