Pointf5ive commited on
Commit
46d8f34
Β·
1 Parent(s): bfe9493

Stages 7+8: LLM normalisation and review workbench

Browse files
smoke_signal/scripts/05_llm_normalise.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Smoke Signal β€” Stage 7: LLM Normalisation Layer
4
+ =================================================
5
+ Takes low-confidence or visually complex regions from Stage 5
6
+ and sends them to an LLM (via HF Inference API) for cleanup.
7
+
8
+ Rules (non-negotiable):
9
+ - LLM receives: page image crop + raw OCR candidates
10
+ - LLM must return strict JSON only β€” no free text, no preamble
11
+ - Uncertain words must be marked uncertain, NEVER silently guessed
12
+ - LLM may NOT invent text that isn't visually present
13
+ - Only low-confidence / flagged pages are sent (cost + drift control)
14
+ - Every call logs: prompt version, model, input hash, output hash, cost
15
+
16
+ Output per region:
17
+ {
18
+ "text_raw": "original OCR text",
19
+ "text_clean": "LLM corrected text",
20
+ "uncertain_words": ["word1", "word2"],
21
+ "confidence_notes": "why confidence is low",
22
+ "changed_from_ocr": true/false,
23
+ "visible_context": "brief note on what the LLM can see"
24
+ }
25
+
26
+ Usage:
27
+ python scripts/05_llm_normalise.py
28
+ python scripts/05_llm_normalise.py --book-id SS-BOOK-0001
29
+ python scripts/05_llm_normalise.py --dry-run
30
+ python scripts/05_llm_normalise.py --confidence-below 0.80
31
+ """
32
+
33
+ import argparse
34
+ import base64
35
+ import hashlib
36
+ import json
37
+ import sys
38
+ import time
39
+ from datetime import datetime
40
+ from pathlib import Path
41
+ from typing import Optional
42
+
43
+ # ── Paths ──────────────────────────────────────────────────────────────────────
44
+ ROOT = Path(__file__).resolve().parents[1]
45
+ MANIFEST_CSV = ROOT / "manifest" / "source_manifest.csv"
46
+ REGIONS_DIR = ROOT / "regions"
47
+ OCR_RAW_DIR = ROOT / "ocr_raw"
48
+ RENDERS_DIR = ROOT / "renders"
49
+ LOGS_DIR = ROOT / "logs"
50
+ REVIEW_DIR = ROOT / "review"
51
+ CLEANED_DIR = ROOT / "regions" / "cleaned"
52
+
53
+ CLEANED_DIR.mkdir(parents=True, exist_ok=True)
54
+ LOGS_DIR.mkdir(parents=True, exist_ok=True)
55
+
56
+ # ── Config (freeze before running β€” do not change mid-batch) ──────────────────
57
+ CONFIG = {
58
+ "config_version": "ss_llm_v0.1",
59
+ "prompt_version": "ss_prompt_v0.1",
60
+ "model": "meta-llama/Llama-3.2-11B-Vision-Instruct", # HF Inference API
61
+ "confidence_threshold": 0.75, # only send pages below this
62
+ "max_pages_per_run": 50, # cost control β€” cap per batch
63
+ "temperature": 0.1, # low = deterministic, no hallucination
64
+ "max_new_tokens": 512,
65
+ "eligible_statuses": ["ocred"],
66
+ "story_classes": ["narration", "dialogue-speech-bubble", "caption"],
67
+ }
68
+
69
+ # ── Prompt (versioned β€” never change without bumping prompt_version) ───────────
70
+ SYSTEM_PROMPT = """You are a precise OCR correction assistant for children's picture books.
71
+
72
+ RULES β€” follow exactly:
73
+ 1. Return ONLY valid JSON. No preamble, no explanation, no markdown fences.
74
+ 2. Correct OCR errors you can see in the image. Do NOT invent text.
75
+ 3. If a word is unclear or unreadable, add it to uncertain_words β€” do NOT guess.
76
+ 4. Keep the author's exact words, punctuation, and line breaks.
77
+ 5. Do not add, remove, or reorder words unless fixing a clear OCR error.
78
+ 6. changed_from_ocr must be true only if you changed something.
79
+
80
+ Return this exact JSON structure:
81
+ {
82
+ "text_clean": "corrected text here",
83
+ "uncertain_words": ["list", "of", "unclear", "words"],
84
+ "confidence_notes": "brief note on what made this hard to read",
85
+ "changed_from_ocr": false,
86
+ "visible_context_notes": "brief note on what you can see in the image"
87
+ }"""
88
+
89
+ USER_PROMPT_TEMPLATE = """Here is the raw OCR output for a picture book page region:
90
+
91
+ RAW OCR: {raw_text}
92
+ REGION CLASS: {region_class}
93
+ OCR CONFIDENCE: {confidence}
94
+
95
+ Please examine the image crop and return the corrected JSON."""
96
+
97
+
98
+ # ── HF Inference API ───────────────────────────────────────────────────────────
99
+ def _get_hf_token() -> Optional[str]:
100
+ """Get HF token from environment or huggingface_hub cache."""
101
+ import os
102
+ token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")
103
+ if token:
104
+ return token
105
+ try:
106
+ from huggingface_hub import get_token
107
+ return get_token()
108
+ except Exception:
109
+ return None
110
+
111
+
112
+ def call_llm_with_image(
113
+ image_path: Path,
114
+ raw_text: str,
115
+ region_class: str,
116
+ confidence: float,
117
+ ) -> dict:
118
+ """
119
+ Call HF Inference API with image + OCR text.
120
+ Returns parsed JSON result or error dict.
121
+ """
122
+ import urllib.request
123
+ import urllib.error
124
+
125
+ token = _get_hf_token()
126
+ if not token:
127
+ return {
128
+ "error": "no_hf_token",
129
+ "text_clean": raw_text,
130
+ "uncertain_words": [],
131
+ "confidence_notes": "HF token not found β€” set HF_TOKEN env var or run huggingface-cli login",
132
+ "changed_from_ocr": False,
133
+ }
134
+
135
+ # Encode image as base64
136
+ try:
137
+ with open(image_path, "rb") as f:
138
+ image_b64 = base64.b64encode(f.read()).decode("utf-8")
139
+ image_ext = image_path.suffix.lower().replace(".", "")
140
+ media_type = f"image/{image_ext if image_ext in ('png','jpg','jpeg','webp') else 'png'}"
141
+ except Exception as e:
142
+ return {"error": f"image_load_failed: {e}", "text_clean": raw_text,
143
+ "uncertain_words": [], "changed_from_ocr": False}
144
+
145
+ user_message = USER_PROMPT_TEMPLATE.format(
146
+ raw_text=raw_text[:800], # truncate for token budget
147
+ region_class=region_class,
148
+ confidence=round(confidence, 3),
149
+ )
150
+
151
+ payload = json.dumps({
152
+ "model": CONFIG["model"],
153
+ "messages": [
154
+ {"role": "system", "content": SYSTEM_PROMPT},
155
+ {
156
+ "role": "user",
157
+ "content": [
158
+ {
159
+ "type": "image_url",
160
+ "image_url": {"url": f"data:{media_type};base64,{image_b64}"}
161
+ },
162
+ {"type": "text", "text": user_message}
163
+ ]
164
+ }
165
+ ],
166
+ "max_tokens": CONFIG["max_new_tokens"],
167
+ "temperature": CONFIG["temperature"],
168
+ }).encode("utf-8")
169
+
170
+ api_url = f"https://api-inference.huggingface.co/models/{CONFIG['model']}/v1/chat/completions"
171
+
172
+ req = urllib.request.Request(
173
+ api_url,
174
+ data=payload,
175
+ headers={
176
+ "Authorization": f"Bearer {token}",
177
+ "Content-Type": "application/json",
178
+ },
179
+ method="POST",
180
+ )
181
+
182
+ try:
183
+ with urllib.request.urlopen(req, timeout=30) as resp:
184
+ response_data = json.loads(resp.read().decode("utf-8"))
185
+ raw_response = response_data["choices"][0]["message"]["content"].strip()
186
+ except urllib.error.HTTPError as e:
187
+ return {"error": f"http_{e.code}: {e.reason}", "text_clean": raw_text,
188
+ "uncertain_words": [], "changed_from_ocr": False}
189
+ except Exception as e:
190
+ return {"error": str(e), "text_clean": raw_text,
191
+ "uncertain_words": [], "changed_from_ocr": False}
192
+
193
+ # Parse JSON response β€” strip markdown fences if model added them
194
+ try:
195
+ clean = raw_response.strip()
196
+ if clean.startswith("```"):
197
+ clean = clean.split("```")[1]
198
+ if clean.startswith("json"):
199
+ clean = clean[4:]
200
+ result = json.loads(clean.strip())
201
+ except json.JSONDecodeError:
202
+ return {
203
+ "error": "invalid_json_response",
204
+ "raw_response": raw_response[:500],
205
+ "text_clean": raw_text,
206
+ "uncertain_words": [],
207
+ "changed_from_ocr": False,
208
+ }
209
+
210
+ return result
211
+
212
+
213
+ # ── Input hash (for audit trail) ──────────────────────────────────────────────
214
+ def _input_hash(text: str, image_path: Path) -> str:
215
+ h = hashlib.sha256()
216
+ h.update(text.encode("utf-8"))
217
+ if image_path.exists():
218
+ with open(image_path, "rb") as f:
219
+ h.update(f.read(4096)) # first 4kb sufficient for fingerprint
220
+ return h.hexdigest()[:16]
221
+
222
+
223
+ def _output_hash(result: dict) -> str:
224
+ return hashlib.sha256(
225
+ json.dumps(result, sort_keys=True).encode("utf-8")
226
+ ).hexdigest()[:16]
227
+
228
+
229
+ # ── Load region data ───────────────────────────────────────────────────────────
230
+ def load_ordered_regions(book_id: str) -> Optional[dict]:
231
+ path = REGIONS_DIR / f"{book_id}_ordered_regions.json"
232
+ return json.load(open(path)) if path.exists() else None
233
+
234
+
235
+ # ── Per-region normalisation ───────────────────────────────────────────────────
236
+ def normalise_region(
237
+ book_id: str,
238
+ page_num: int,
239
+ region: dict,
240
+ render_path: Optional[str],
241
+ dry_run: bool,
242
+ ) -> dict:
243
+ """Normalise a single region via LLM. Returns enriched region dict."""
244
+
245
+ raw_text = region.get("text", "").strip()
246
+ region_class = region.get("region_class", "narration")
247
+ confidence = region.get("confidence", 1.0)
248
+ region_id = region.get("region_id", f"{book_id}_p{page_num:04d}")
249
+
250
+ if dry_run:
251
+ return {
252
+ **region,
253
+ "text_clean": raw_text,
254
+ "uncertain_words": [],
255
+ "confidence_notes": "dry-run",
256
+ "changed_from_ocr": False,
257
+ "visible_context_notes": "dry-run",
258
+ "llm_model": CONFIG["model"],
259
+ "prompt_version": CONFIG["prompt_version"],
260
+ "normalised_at": datetime.utcnow().isoformat() + "Z",
261
+ "dry_run": True,
262
+ }
263
+
264
+ # Find render image
265
+ img_path = None
266
+ if render_path:
267
+ candidate = ROOT / render_path if not Path(render_path).is_absolute() else Path(render_path)
268
+ if candidate.exists():
269
+ img_path = candidate
270
+
271
+ if img_path is None:
272
+ # Try to find any render for this book/page
273
+ book_renders = RENDERS_DIR / book_id
274
+ if book_renders.exists():
275
+ candidates = sorted(book_renders.glob(f"{book_id}_page_{page_num:04d}_*.png"))
276
+ if candidates:
277
+ img_path = candidates[0]
278
+
279
+ if img_path is None:
280
+ return {
281
+ **region,
282
+ "text_clean": raw_text,
283
+ "uncertain_words": [],
284
+ "confidence_notes": "no_render_available",
285
+ "changed_from_ocr": False,
286
+ "error": "no_render_found",
287
+ }
288
+
289
+ in_hash = _input_hash(raw_text, img_path)
290
+
291
+ llm_result = call_llm_with_image(img_path, raw_text, region_class, confidence)
292
+
293
+ out_hash = _output_hash(llm_result)
294
+
295
+ return {
296
+ **region,
297
+ "text_clean": llm_result.get("text_clean", raw_text),
298
+ "uncertain_words": llm_result.get("uncertain_words", []),
299
+ "confidence_notes": llm_result.get("confidence_notes", ""),
300
+ "changed_from_ocr": llm_result.get("changed_from_ocr", False),
301
+ "visible_context_notes": llm_result.get("visible_context_notes", ""),
302
+ "llm_model": CONFIG["model"],
303
+ "prompt_version": CONFIG["prompt_version"],
304
+ "input_hash": in_hash,
305
+ "output_hash": out_hash,
306
+ "llm_error": llm_result.get("error"),
307
+ "normalised_at": datetime.utcnow().isoformat() + "Z",
308
+ }
309
+
310
+
311
+ # ── Per-book normalisation ────────────────────────────────────────────────────
312
+ def normalise_book(
313
+ book_id: str,
314
+ filename: str,
315
+ confidence_threshold: float,
316
+ max_pages: int,
317
+ dry_run: bool,
318
+ ) -> tuple:
319
+ print(f"\n [{book_id}] {filename}")
320
+
321
+ regions_data = load_ordered_regions(book_id)
322
+ if regions_data is None:
323
+ print(f" βœ— No region data. Run 04_region_detector.py first.")
324
+ return None, {"error": "no_region_data"}
325
+
326
+ pages_to_process = []
327
+ for page in regions_data.get("pages", []):
328
+ page_conf = page.get("page_confidence", 1.0)
329
+ route = page.get("route", "embedded_text")
330
+ if route == "embedded_text":
331
+ continue
332
+ if page_conf < confidence_threshold:
333
+ pages_to_process.append(page)
334
+
335
+ if not pages_to_process:
336
+ print(f" βœ“ No pages below confidence threshold {confidence_threshold} β€” skipping.")
337
+ return regions_data, {}
338
+
339
+ # Apply page cap
340
+ if len(pages_to_process) > max_pages:
341
+ print(f" ⚠️ {len(pages_to_process)} pages need normalisation β€” capping at {max_pages}")
342
+ pages_to_process = pages_to_process[:max_pages]
343
+
344
+ print(f" Pages to normalise: {len(pages_to_process)}")
345
+
346
+ total_changed = 0
347
+ total_uncertain = 0
348
+ total_errors = 0
349
+ call_log = []
350
+
351
+ # Process each page
352
+ page_index = {p["page_number"]: i for i, p in enumerate(regions_data["pages"])}
353
+
354
+ for page in pages_to_process:
355
+ page_num = page["page_number"]
356
+ page_conf = page.get("page_confidence", 0)
357
+ render_path = None
358
+
359
+ # Find render path from OCR raw data
360
+ ocr_path = OCR_RAW_DIR / book_id / f"{book_id}_ocr_raw.json"
361
+ if ocr_path.exists():
362
+ ocr_data = json.load(open(ocr_path))
363
+ for ocr_page in ocr_data.get("pages", []):
364
+ if ocr_page.get("page_number") == page_num:
365
+ render_path = ocr_page.get("render_path")
366
+ break
367
+
368
+ print(f" Page {page_num:3d} (conf={page_conf:.2f}): ", end="", flush=True)
369
+
370
+ normalised_regions = []
371
+ for region in page.get("regions", []):
372
+ region_class = region.get("region_class", "narration")
373
+
374
+ # Only normalise story-relevant regions
375
+ if region_class not in CONFIG["story_classes"]:
376
+ normalised_regions.append(region)
377
+ continue
378
+
379
+ region_conf = region.get("confidence", 1.0)
380
+ if region_conf >= confidence_threshold:
381
+ normalised_regions.append(region)
382
+ continue
383
+
384
+ result = normalise_region(book_id, page_num, region, render_path, dry_run)
385
+
386
+ if result.get("changed_from_ocr"):
387
+ total_changed += 1
388
+ if result.get("uncertain_words"):
389
+ total_uncertain += len(result["uncertain_words"])
390
+ if result.get("llm_error"):
391
+ total_errors += 1
392
+
393
+ call_log.append({
394
+ "book_id": book_id,
395
+ "page_number": page_num,
396
+ "region_id": region.get("region_id"),
397
+ "input_hash": result.get("input_hash"),
398
+ "output_hash": result.get("output_hash"),
399
+ "changed": result.get("changed_from_ocr", False),
400
+ "uncertain_count": len(result.get("uncertain_words", [])),
401
+ "error": result.get("llm_error"),
402
+ "model": CONFIG["model"],
403
+ "prompt_version": CONFIG["prompt_version"],
404
+ })
405
+
406
+ normalised_regions.append(result)
407
+
408
+ # Update page in regions data
409
+ idx = page_index.get(page_num)
410
+ if idx is not None:
411
+ regions_data["pages"][idx]["regions"] = normalised_regions
412
+ regions_data["pages"][idx]["normalised"] = True
413
+
414
+ changed_count = sum(1 for r in normalised_regions if r.get("changed_from_ocr"))
415
+ uncertain_count = sum(len(r.get("uncertain_words", [])) for r in normalised_regions)
416
+ print(f"changed={changed_count} uncertain_words={uncertain_count}")
417
+
418
+ # ── Save cleaned regions ──────────────────────────────────────────────────
419
+ if not dry_run:
420
+ regions_data["normalised_at"] = datetime.utcnow().isoformat() + "Z"
421
+ regions_data["prompt_version"] = CONFIG["prompt_version"]
422
+ regions_data["llm_model"] = CONFIG["model"]
423
+ regions_data["normalisation_log"] = call_log
424
+
425
+ cleaned_path = CLEANED_DIR / f"{book_id}_cleaned_regions.json"
426
+ with open(cleaned_path, "w", encoding="utf-8") as f:
427
+ json.dump(regions_data, f, indent=2)
428
+ print(f" Cleaned regions β†’ {cleaned_path.relative_to(ROOT)}")
429
+
430
+ # Log file
431
+ log_path = LOGS_DIR / f"llm_calls_{book_id}_{datetime.utcnow().strftime('%Y%m%d')}.json"
432
+ with open(log_path, "w") as f:
433
+ json.dump(call_log, f, indent=2)
434
+
435
+ print(f" Total changed={total_changed} | uncertain_words={total_uncertain} | errors={total_errors}")
436
+ return regions_data, {}
437
+
438
+
439
+ # ── Main ───────────────────────────────────────────────────────────────────────
440
+ def main():
441
+ parser = argparse.ArgumentParser(description="Smoke Signal β€” Stage 7: LLM Normalisation")
442
+ parser.add_argument("--book-id", help="Process a single book by ID")
443
+ parser.add_argument("--batch-id", help="Tag this run with a batch ID")
444
+ parser.add_argument("--confidence-below", type=float, default=CONFIG["confidence_threshold"],
445
+ help=f"Only process pages below this confidence (default {CONFIG['confidence_threshold']})")
446
+ parser.add_argument("--max-pages", type=int, default=CONFIG["max_pages_per_run"],
447
+ help=f"Max pages per book per run (default {CONFIG['max_pages_per_run']})")
448
+ parser.add_argument("--dry-run", action="store_true")
449
+ args = parser.parse_args()
450
+
451
+ run_id = args.batch_id or f"SS-RUN-{datetime.utcnow().strftime('%Y%m%d-%H%M%S')}"
452
+ dry_run = args.dry_run
453
+
454
+ print(f"\n{'='*60}")
455
+ print(f" Smoke Signal β€” Stage 7: LLM Normalisation")
456
+ print(f" Run ID : {run_id}")
457
+ print(f" Model : {CONFIG['model']}")
458
+ print(f" Prompt : {CONFIG['prompt_version']}")
459
+ print(f" Threshold : conf < {args.confidence_below}")
460
+ print(f" Max pages : {args.max_pages}")
461
+ if dry_run:
462
+ print(f" Mode : DRY RUN")
463
+ print(f"{'='*60}")
464
+
465
+ # Find books with region data
466
+ if args.book_id:
467
+ region_files = [REGIONS_DIR / f"{args.book_id}_ordered_regions.json"]
468
+ else:
469
+ region_files = sorted(REGIONS_DIR.glob("*_ordered_regions.json"))
470
+
471
+ if not region_files:
472
+ print("\n No region files found. Run 04_region_detector.py first.")
473
+ sys.exit(0)
474
+
475
+ print(f"\n Books to process: {len(region_files)}")
476
+
477
+ results = []
478
+ t_start = time.time()
479
+
480
+ for region_file in region_files:
481
+ book_id = region_file.stem.replace("_ordered_regions", "")
482
+ filename = book_id # fallback
483
+
484
+ _, error = normalise_book(
485
+ book_id,
486
+ filename,
487
+ args.confidence_below,
488
+ args.max_pages,
489
+ dry_run,
490
+ )
491
+
492
+ results.append({"book_id": book_id, "error": error})
493
+
494
+ elapsed = round(time.time() - t_start, 1)
495
+ succeeded = sum(1 for r in results if not r.get("error"))
496
+
497
+ print(f"\n{'─'*60}")
498
+ print(f" Books processed : {len(results)}")
499
+ print(f" Succeeded : {succeeded}")
500
+ print(f" Time : {elapsed}s")
501
+ print(f"{'─'*60}")
502
+ print(f"\n Cleaned regions β†’ {CLEANED_DIR.relative_to(ROOT)}")
503
+ print(f" Next: Run 06_review_workbench.py (Stage 8)\n")
504
+
505
+
506
+ if __name__ == "__main__":
507
+ main()
smoke_signal/scripts/06_review_workbench.py ADDED
@@ -0,0 +1,628 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Smoke Signal β€” Stage 8: Human Review Workbench
4
+ ================================================
5
+ Gradio app for reviewing low-confidence OCR pages.
6
+
7
+ Reviewer actions per page:
8
+ - ACCEPT : text is correct, pass to Codex export
9
+ - EDIT : correct the text, then accept
10
+ - REJECT : unusable, exclude from export
11
+ - QUARANTINE: flag for specialist review
12
+ - ILLUSTRATION ONLY: no text on this page
13
+
14
+ Captures: reviewer ID, timestamp, edits, reason codes, final status.
15
+
16
+ To run locally:
17
+ pip install gradio
18
+ python scripts/06_review_workbench.py
19
+
20
+ To deploy on HF Spaces:
21
+ This file should be copied to the root as smoke_signal_review.py
22
+ or integrated into the main app.py as a new tab.
23
+ """
24
+
25
+ import csv
26
+ import json
27
+ import os
28
+ from datetime import datetime
29
+ from pathlib import Path
30
+ from typing import Optional
31
+
32
+ import gradio as gr
33
+
34
+ # ── Paths ──────────────────────────────────────────────────────────────────────
35
+ ROOT = Path(__file__).resolve().parents[1]
36
+ REVIEW_DIR = ROOT / "review"
37
+ REGIONS_DIR = ROOT / "regions"
38
+ CLEANED_DIR = ROOT / "regions" / "cleaned"
39
+ RENDERS_DIR = ROOT / "renders"
40
+ EXPORTS_DIR = ROOT / "exports"
41
+
42
+ REVIEW_DIR.mkdir(parents=True, exist_ok=True)
43
+ EXPORTS_DIR.mkdir(parents=True, exist_ok=True)
44
+
45
+ QUEUE_CSV = REVIEW_DIR / "review_queue.csv"
46
+ DECISIONS_CSV = REVIEW_DIR / "review_decisions.csv"
47
+
48
+ # ── Reason codes ───────────────────────────────────────────────────────────────
49
+ REASON_CODES = [
50
+ "OCR_MISS",
51
+ "OCR_WRONG_WORD",
52
+ "REGION_MISSING",
53
+ "REGION_FALSE_POSITIVE",
54
+ "READING_ORDER_ERROR",
55
+ "DECORATIVE_FONT",
56
+ "SPEECH_BUBBLE_ERROR",
57
+ "LOW_CONTRAST",
58
+ "SCAN_SKEW_BLUR",
59
+ "NON_STORY_TEXT",
60
+ "RIGHTS_UNCLEAR",
61
+ "DUPLICATE_SOURCE",
62
+ "LLM_OVER_CORRECTION",
63
+ "MANUAL_TRANSCRIPTION_REQUIRED",
64
+ "OTHER",
65
+ ]
66
+
67
+ REVIEW_STATUSES = ["pending", "accepted", "edited", "rejected", "quarantined", "illustration-only"]
68
+
69
+ # ── CSS ────────────────────────────────────────────────────────────────────────
70
+ CSS = """
71
+ @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=Source+Code+Pro:wght@400;600&family=Lato:wght@300;400;700&display=swap');
72
+
73
+ :root {
74
+ --ink: #1a1a2e;
75
+ --paper: #f5f0e8;
76
+ --smoke: #2d3561;
77
+ --signal: #e94560;
78
+ --ash: #8892b0;
79
+ --accepted: #00b894;
80
+ --rejected: #e17055;
81
+ --quarantine: #fdcb6e;
82
+ --pending: #74b9ff;
83
+ }
84
+
85
+ .gradio-container {
86
+ background: var(--paper) !important;
87
+ font-family: 'Lato', sans-serif !important;
88
+ max-width: none !important;
89
+ }
90
+
91
+ footer { display: none !important; }
92
+
93
+ #ss-header {
94
+ background: var(--ink);
95
+ padding: 20px 32px;
96
+ border-bottom: 3px solid var(--signal);
97
+ display: flex;
98
+ align-items: center;
99
+ gap: 20px;
100
+ }
101
+
102
+ #ss-title {
103
+ font-family: 'Playfair Display', serif;
104
+ font-size: 28px;
105
+ font-weight: 900;
106
+ color: var(--paper);
107
+ letter-spacing: -0.5px;
108
+ margin: 0;
109
+ }
110
+
111
+ #ss-subtitle {
112
+ font-family: 'Source Code Pro', monospace;
113
+ font-size: 11px;
114
+ color: var(--ash);
115
+ letter-spacing: 3px;
116
+ text-transform: uppercase;
117
+ margin: 0;
118
+ }
119
+
120
+ #ss-signal {
121
+ color: var(--signal);
122
+ font-size: 36px;
123
+ font-weight: 900;
124
+ }
125
+
126
+ .queue-panel {
127
+ background: white;
128
+ border: 1px solid #e0d9cc;
129
+ border-radius: 8px;
130
+ padding: 16px;
131
+ height: 600px;
132
+ overflow-y: auto;
133
+ }
134
+
135
+ .queue-item {
136
+ padding: 12px 14px;
137
+ border-radius: 6px;
138
+ margin-bottom: 8px;
139
+ cursor: pointer;
140
+ border: 2px solid transparent;
141
+ transition: all 0.15s;
142
+ font-size: 13px;
143
+ }
144
+
145
+ .queue-item:hover { border-color: var(--smoke); }
146
+ .queue-item.active { border-color: var(--signal); background: #fff5f7; }
147
+ .queue-item.pending { border-left: 4px solid var(--pending); }
148
+ .queue-item.accepted { border-left: 4px solid var(--accepted); opacity: 0.6; }
149
+ .queue-item.rejected { border-left: 4px solid var(--rejected); opacity: 0.6; }
150
+ .queue-item.quarantined { border-left: 4px solid var(--quarantine); }
151
+
152
+ .page-image-panel {
153
+ background: #2a2a2a;
154
+ border-radius: 8px;
155
+ min-height: 400px;
156
+ display: flex;
157
+ align-items: center;
158
+ justify-content: center;
159
+ }
160
+
161
+ .confidence-badge {
162
+ display: inline-block;
163
+ padding: 3px 10px;
164
+ border-radius: 999px;
165
+ font-size: 12px;
166
+ font-weight: 700;
167
+ font-family: 'Source Code Pro', monospace;
168
+ }
169
+
170
+ .conf-high { background: #d4f5e9; color: #00695c; }
171
+ .conf-medium { background: #fff3cd; color: #856404; }
172
+ .conf-low { background: #fde8e8; color: #c62828; }
173
+ .conf-quarantine { background: #2a2a2a; color: #fdcb6e; }
174
+
175
+ .action-btn {
176
+ font-weight: 700 !important;
177
+ font-size: 14px !important;
178
+ border-radius: 6px !important;
179
+ min-height: 44px !important;
180
+ transition: transform 0.1s !important;
181
+ }
182
+
183
+ .action-btn:active { transform: scale(0.97) !important; }
184
+
185
+ .accept-btn { background: var(--accepted) !important; color: white !important; }
186
+ .reject-btn { background: var(--rejected) !important; color: white !important; }
187
+ .quar-btn { background: var(--quarantine) !important; color: var(--ink) !important; }
188
+ .illus-btn { background: var(--smoke) !important; color: white !important; }
189
+
190
+ .stats-bar {
191
+ background: var(--ink);
192
+ color: var(--paper);
193
+ padding: 10px 20px;
194
+ border-radius: 6px;
195
+ font-family: 'Source Code Pro', monospace;
196
+ font-size: 12px;
197
+ display: flex;
198
+ gap: 24px;
199
+ margin-bottom: 12px;
200
+ }
201
+
202
+ .stat-item { display: flex; flex-direction: column; gap: 2px; }
203
+ .stat-value { font-size: 20px; font-weight: 600; }
204
+ .stat-label { color: var(--ash); font-size: 10px; letter-spacing: 1px; }
205
+
206
+ .ocr-text-box textarea {
207
+ font-family: 'Source Code Pro', monospace !important;
208
+ font-size: 14px !important;
209
+ background: #fafaf8 !important;
210
+ border: 2px solid #e0d9cc !important;
211
+ border-radius: 6px !important;
212
+ }
213
+
214
+ .ocr-text-box textarea:focus {
215
+ border-color: var(--signal) !important;
216
+ }
217
+ """
218
+
219
+ # ── Data loading ───────────────────────────────────────────────────────────────
220
+ def load_queue() -> list:
221
+ """Load the review queue CSV."""
222
+ if not QUEUE_CSV.exists():
223
+ return []
224
+ with open(QUEUE_CSV, newline="", encoding="utf-8") as f:
225
+ return list(csv.DictReader(f))
226
+
227
+
228
+ def load_decisions() -> dict:
229
+ """Load existing decisions keyed by region_id."""
230
+ decisions = {}
231
+ if not DECISIONS_CSV.exists():
232
+ return decisions
233
+ with open(DECISIONS_CSV, newline="", encoding="utf-8") as f:
234
+ for row in csv.DictReader(f):
235
+ decisions[row.get("region_id", "")] = row
236
+ return decisions
237
+
238
+
239
+ def save_decision(
240
+ region_id: str,
241
+ book_id: str,
242
+ page: int,
243
+ status: str,
244
+ final_text: str,
245
+ reason_code: str,
246
+ reviewer: str,
247
+ notes: str,
248
+ ) -> None:
249
+ """Append or update a decision record."""
250
+ fields = [
251
+ "region_id", "book_id", "page", "status",
252
+ "final_text", "reason_code", "reviewer", "notes", "decided_at"
253
+ ]
254
+ existing = load_decisions()
255
+ existing[region_id] = {
256
+ "region_id": region_id,
257
+ "book_id": book_id,
258
+ "page": page,
259
+ "status": status,
260
+ "final_text": final_text,
261
+ "reason_code": reason_code,
262
+ "reviewer": reviewer,
263
+ "notes": notes,
264
+ "decided_at": datetime.utcnow().isoformat() + "Z",
265
+ }
266
+ write_header = not DECISIONS_CSV.exists()
267
+ with open(DECISIONS_CSV, "w", newline="", encoding="utf-8") as f:
268
+ writer = csv.DictWriter(f, fieldnames=fields)
269
+ writer.writeheader()
270
+ writer.writerows(existing.values())
271
+
272
+
273
+ def get_queue_stats(queue: list, decisions: dict) -> dict:
274
+ total = len(queue)
275
+ decided = len(decisions)
276
+ pending = total - decided
277
+ accepted = sum(1 for d in decisions.values() if d["status"] == "accepted")
278
+ edited = sum(1 for d in decisions.values() if d["status"] == "edited")
279
+ rejected = sum(1 for d in decisions.values() if d["status"] == "rejected")
280
+ quarantined = sum(1 for d in decisions.values() if d["status"] == "quarantined")
281
+ return {
282
+ "total": total, "pending": pending, "accepted": accepted,
283
+ "edited": edited, "rejected": rejected, "quarantined": quarantined,
284
+ }
285
+
286
+
287
+ # ── Image loader ───────────────────────────────────────────────────────────────
288
+ def get_page_image(book_id: str, page: str) -> Optional[str]:
289
+ """Find the rendered page image."""
290
+ try:
291
+ page_num = int(page)
292
+ except (ValueError, TypeError):
293
+ return None
294
+
295
+ book_dir = RENDERS_DIR / str(book_id)
296
+ if book_dir.exists():
297
+ candidates = sorted(book_dir.glob(f"{book_id}_page_{page_num:04d}_*.png"))
298
+ if candidates:
299
+ return str(candidates[0])
300
+ return None
301
+
302
+
303
+ # ── Queue HTML builder ─────────────────────────────────────────────────────────
304
+ def build_queue_html(queue: list, decisions: dict, active_idx: int = 0) -> str:
305
+ if not queue:
306
+ return "<div style='padding:20px;color:#888;font-family:monospace'>No items in review queue.<br>Run the pipeline first.</div>"
307
+
308
+ items = []
309
+ for i, item in enumerate(queue):
310
+ region_id = item.get("region_id", "")
311
+ decision = decisions.get(region_id, {})
312
+ status = decision.get("status", item.get("status", "pending"))
313
+ conf = float(item.get("confidence", 0))
314
+ page = item.get("page", "?")
315
+ book_id = item.get("book_id", "?")
316
+ conf_str = f"{conf:.0%}"
317
+ active = "active" if i == active_idx else ""
318
+ items.append(f"""
319
+ <div class="queue-item {status} {active}" onclick="selectItem({i})" id="qi-{i}">
320
+ <div style="display:flex;justify-content:space-between;align-items:center">
321
+ <span style="font-weight:700;color:#1a1a2e">{book_id} Β· p{page}</span>
322
+ <span style="font-size:11px;color:#888">{status.upper()}</span>
323
+ </div>
324
+ <div style="margin-top:4px;font-size:12px;color:#555">
325
+ conf: <b style="color:{'#c62828' if conf < 0.6 else '#856404' if conf < 0.85 else '#00695c'}">{conf_str}</b>
326
+ &nbsp;Β·&nbsp; {item.get('region_class','?')}
327
+ </div>
328
+ </div>""")
329
+
330
+ return f"<div class='queue-panel'>{''.join(items)}</div>"
331
+
332
+
333
+ def build_stats_html(stats: dict) -> str:
334
+ progress = (stats['accepted'] + stats['edited']) / max(stats['total'], 1) * 100
335
+ return f"""
336
+ <div class="stats-bar">
337
+ <div class="stat-item"><span class="stat-value">{stats['total']}</span><span class="stat-label">TOTAL</span></div>
338
+ <div class="stat-item"><span class="stat-value" style="color:var(--pending)">{stats['pending']}</span><span class="stat-label">PENDING</span></div>
339
+ <div class="stat-item"><span class="stat-value" style="color:var(--accepted)">{stats['accepted'] + stats['edited']}</span><span class="stat-label">APPROVED</span></div>
340
+ <div class="stat-item"><span class="stat-value" style="color:var(--rejected)">{stats['rejected']}</span><span class="stat-label">REJECTED</span></div>
341
+ <div class="stat-item"><span class="stat-value" style="color:var(--quarantine)">{stats['quarantined']}</span><span class="stat-label">QUARANTINED</span></div>
342
+ <div class="stat-item" style="flex:1">
343
+ <span class="stat-label">PROGRESS</span>
344
+ <div style="background:#333;border-radius:4px;height:8px;margin-top:6px">
345
+ <div style="background:var(--accepted);width:{progress:.0f}%;height:8px;border-radius:4px;transition:width 0.3s"></div>
346
+ </div>
347
+ </div>
348
+ </div>"""
349
+
350
+
351
+ # ── Gradio app ────────────────────────────────────────────────────────────────
352
+ def build_app():
353
+
354
+ queue = load_queue()
355
+ decisions = load_decisions()
356
+ state = {"idx": 0, "queue": queue, "decisions": decisions}
357
+
358
+ def get_current_item():
359
+ q = state["queue"]
360
+ if not q:
361
+ return None
362
+ idx = min(state["idx"], len(q) - 1)
363
+ return q[idx]
364
+
365
+ def refresh_view():
366
+ queue = state["queue"]
367
+ decisions = state["decisions"]
368
+ item = get_current_item()
369
+ stats = get_queue_stats(queue, decisions)
370
+ stats_html = build_stats_html(stats)
371
+ queue_html = build_queue_html(queue, decisions, state["idx"])
372
+
373
+ if not item:
374
+ return (
375
+ stats_html, queue_html,
376
+ None, "", "", "", "pending", "", "",
377
+ "No items in queue"
378
+ )
379
+
380
+ region_id = item.get("region_id", "")
381
+ decision = decisions.get(region_id, {})
382
+ book_id = item.get("book_id", "")
383
+ page = item.get("page", "")
384
+ conf = float(item.get("confidence", 0))
385
+ conf_class = "conf-low" if conf < 0.6 else "conf-medium" if conf < 0.85 else "conf-high"
386
+
387
+ raw_text = item.get("raw_ocr", "")
388
+ final_text = decision.get("final_text", raw_text)
389
+ status = decision.get("status", "pending")
390
+ reason = decision.get("reason_code", "")
391
+ reviewer = decision.get("reviewer", "")
392
+ notes = decision.get("notes", "")
393
+
394
+ img_path = get_page_image(book_id, page)
395
+
396
+ info = f"<span class='confidence-badge {conf_class}'>conf: {conf:.0%}</span> &nbsp; {book_id} Β· page {page} Β· {item.get('region_class','?')}"
397
+
398
+ return (
399
+ stats_html, queue_html,
400
+ img_path, raw_text, final_text,
401
+ info, status, reason, reviewer, notes
402
+ )
403
+
404
+ def navigate(direction: int):
405
+ q = state["queue"]
406
+ if not q:
407
+ return refresh_view()
408
+ state["idx"] = max(0, min(state["idx"] + direction, len(q) - 1))
409
+ return refresh_view()
410
+
411
+ def submit_decision(final_text, status, reason_code, reviewer, notes):
412
+ item = get_current_item()
413
+ if not item:
414
+ return refresh_view()
415
+
416
+ region_id = item.get("region_id", "")
417
+ book_id = item.get("book_id", "")
418
+ page = item.get("page", "")
419
+
420
+ # Determine actual status
421
+ raw_text = item.get("raw_ocr", "")
422
+ act_status = status
423
+ if status == "accepted" and final_text.strip() != raw_text.strip():
424
+ act_status = "edited"
425
+
426
+ save_decision(
427
+ region_id=region_id,
428
+ book_id=book_id,
429
+ page=page,
430
+ status=act_status,
431
+ final_text=final_text,
432
+ reason_code=reason_code,
433
+ reviewer=reviewer or "reviewer",
434
+ notes=notes,
435
+ )
436
+
437
+ state["decisions"] = load_decisions()
438
+
439
+ # Auto-advance to next pending item
440
+ q = state["queue"]
441
+ for i in range(state["idx"] + 1, len(q)):
442
+ rid = q[i].get("region_id", "")
443
+ if rid not in state["decisions"]:
444
+ state["idx"] = i
445
+ break
446
+
447
+ return refresh_view()
448
+
449
+ def quick_action(action: str, reviewer_name: str):
450
+ item = get_current_item()
451
+ if not item:
452
+ return refresh_view()
453
+ region_id = item.get("region_id", "")
454
+ book_id = item.get("book_id", "")
455
+ page = item.get("page", "")
456
+ raw_text = item.get("raw_ocr", "")
457
+
458
+ status_map = {
459
+ "accept": "accepted",
460
+ "reject": "rejected",
461
+ "quarantine": "quarantined",
462
+ "illus": "illustration-only",
463
+ }
464
+ save_decision(
465
+ region_id=region_id, book_id=book_id, page=page,
466
+ status=status_map.get(action, "accepted"),
467
+ final_text=raw_text, reason_code="", reviewer=reviewer_name or "reviewer", notes="",
468
+ )
469
+ state["decisions"] = load_decisions()
470
+
471
+ # Auto-advance
472
+ q = state["queue"]
473
+ for i in range(state["idx"] + 1, len(q)):
474
+ rid = q[i].get("region_id", "")
475
+ if rid not in state["decisions"]:
476
+ state["idx"] = i
477
+ break
478
+
479
+ return refresh_view()
480
+
481
+ def export_approved():
482
+ """Export all accepted/edited decisions to JSONL for Codex."""
483
+ decisions = load_decisions()
484
+ approved = [d for d in decisions.values() if d["status"] in ("accepted", "edited")]
485
+
486
+ if not approved:
487
+ return "No approved items to export yet."
488
+
489
+ ts = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
490
+ out_path = EXPORTS_DIR / f"review_export_{ts}.jsonl"
491
+ with open(out_path, "w", encoding="utf-8") as f:
492
+ for d in approved:
493
+ f.write(json.dumps(d) + "\n")
494
+
495
+ return f"Exported {len(approved)} approved records β†’ {out_path.relative_to(ROOT)}"
496
+
497
+ # ── Layout ────────────────────────────────────────────────────────────────
498
+ with gr.Blocks(title="Smoke Signal β€” Review Workbench", css=CSS) as app:
499
+
500
+ gr.HTML("""
501
+ <div id="ss-header">
502
+ <span id="ss-signal">β—ˆ</span>
503
+ <div>
504
+ <p id="ss-title">Smoke Signal</p>
505
+ <p id="ss-subtitle">OCR Review Workbench Β· Human-in-the-Loop</p>
506
+ </div>
507
+ </div>
508
+ """)
509
+
510
+ # Stats bar
511
+ stats_html = gr.HTML()
512
+
513
+ with gr.Row():
514
+ # ── Left: queue ───────────────────────────────────────────────────
515
+ with gr.Column(scale=1):
516
+ gr.Markdown("### Review Queue")
517
+ queue_html = gr.HTML()
518
+
519
+ with gr.Row():
520
+ prev_btn = gr.Button("← Prev", size="sm")
521
+ next_btn = gr.Button("Next β†’", size="sm")
522
+
523
+ reviewer_name = gr.Textbox(
524
+ label="Your name / ID",
525
+ placeholder="e.g. jamal",
526
+ scale=1,
527
+ )
528
+
529
+ # ── Centre: page image ────────────────────────────────────────────
530
+ with gr.Column(scale=2):
531
+ gr.Markdown("### Page Image")
532
+ page_image = gr.Image(
533
+ label="",
534
+ type="filepath",
535
+ height=480,
536
+ show_download_button=False,
537
+ )
538
+ item_info = gr.HTML()
539
+
540
+ # ── Right: text + actions ─────────────────────────────────────────
541
+ with gr.Column(scale=2):
542
+ gr.Markdown("### OCR Text")
543
+ raw_text_box = gr.Textbox(
544
+ label="Raw OCR (read-only)",
545
+ lines=5,
546
+ interactive=False,
547
+ elem_classes=["ocr-text-box"],
548
+ )
549
+ final_text_box = gr.Textbox(
550
+ label="Final Text (edit if needed)",
551
+ lines=8,
552
+ interactive=True,
553
+ elem_classes=["ocr-text-box"],
554
+ )
555
+
556
+ with gr.Row():
557
+ accept_btn = gr.Button("βœ“ Accept", elem_classes=["action-btn", "accept-btn"])
558
+ reject_btn = gr.Button("βœ— Reject", elem_classes=["action-btn", "reject-btn"])
559
+
560
+ with gr.Row():
561
+ quar_btn = gr.Button("βš‘ Quarantine", elem_classes=["action-btn", "quar-btn"])
562
+ illus_btn = gr.Button("β—‰ Illus Only", elem_classes=["action-btn", "illus-btn"])
563
+
564
+ gr.Markdown("### Decision Details")
565
+ status_dd = gr.Dropdown(
566
+ label="Status",
567
+ choices=REVIEW_STATUSES,
568
+ value="pending",
569
+ )
570
+ reason_dd = gr.Dropdown(
571
+ label="Reason Code",
572
+ choices=[""] + REASON_CODES,
573
+ value="",
574
+ )
575
+ notes_box = gr.Textbox(label="Notes", lines=2)
576
+
577
+ submit_btn = gr.Button(
578
+ "Save Decision",
579
+ variant="primary",
580
+ size="lg",
581
+ )
582
+
583
+ export_btn = gr.Button("⬇ Export Approved to Codex", variant="secondary")
584
+ export_status = gr.Textbox(label="Export status", interactive=False)
585
+
586
+ # ── Wire events ───────────────────────────────────────────────────────
587
+ outputs = [
588
+ stats_html, queue_html,
589
+ page_image, raw_text_box, final_text_box,
590
+ item_info, status_dd, reason_dd, reviewer_name, notes_box,
591
+ ]
592
+
593
+ app.load(refresh_view, outputs=outputs)
594
+
595
+ prev_btn.click(lambda: navigate(-1), outputs=outputs)
596
+ next_btn.click(lambda: navigate(1), outputs=outputs)
597
+
598
+ accept_btn.click(
599
+ lambda rev: quick_action("accept", rev),
600
+ inputs=[reviewer_name], outputs=outputs
601
+ )
602
+ reject_btn.click(
603
+ lambda rev: quick_action("reject", rev),
604
+ inputs=[reviewer_name], outputs=outputs
605
+ )
606
+ quar_btn.click(
607
+ lambda rev: quick_action("quarantine", rev),
608
+ inputs=[reviewer_name], outputs=outputs
609
+ )
610
+ illus_btn.click(
611
+ lambda rev: quick_action("illus", rev),
612
+ inputs=[reviewer_name], outputs=outputs
613
+ )
614
+
615
+ submit_btn.click(
616
+ submit_decision,
617
+ inputs=[final_text_box, status_dd, reason_dd, reviewer_name, notes_box],
618
+ outputs=outputs,
619
+ )
620
+
621
+ export_btn.click(export_approved, outputs=[export_status])
622
+
623
+ return app
624
+
625
+
626
+ if __name__ == "__main__":
627
+ app = build_app()
628
+ app.launch(share=False)