"""Runic Reader: photograph -> transliteration -> known inscription or draft translation. Tab 1 replays the paper pipeline on held-out test photographs (cached model outputs) and lets the user correct the reading; corpus search runs live on CPU. Tab 2 runs the models live on a new transliteration or photograph (slow on CPU).""" import json import os import random import threading import gradio as gr from PIL import Image, ImageDraw from runic_demo.align import align, disagreement, expert_fix from runic_demo.models import Models, crop_to_box from runic_demo.search import CorpusIndex HERE = os.path.dirname(os.path.abspath(__file__)) LIVE = os.environ.get("RUNIC_LIVE_MODELS", "1") == "1" PAPER_URL = os.environ.get("RUNIC_PAPER_URL", "") CODE_URL = os.environ.get("RUNIC_CODE_URL", "") index = CorpusIndex(os.path.join(HERE, "data", "corpus.jsonl")) calib = json.load(open(os.path.join(HERE, "data", "calib.json"))) EX = {r["id"]: r for r in map(json.loads, open(os.path.join(HERE, "data", "examples.jsonl")))} FEATURED = [i for i in ("rdb10392_0", "rdb11500_0", "rdb11962_0", "rdb09736_0", "rdb11776_0", "rdb11449_0", "rdb11002_0", "rdb10819_0") if i in EX] CHOICES = FEATURED + sorted(i for i in EX if i not in FEATURED) models = Models() def warm(): try: models.load() except Exception as e: # the demo still works without models (cached outputs + search) models.error = repr(e) if LIVE: threading.Thread(target=warm, daemon=True).start() def label(i): r = EX[i] return f"{'★ ' if i in FEATURED else ''}{i} · {r['domain']}" # ---------------------------------------------------------------- rendering helpers def draw_box(i): r = EX[i] im = Image.open(os.path.join(HERE, "media", "full", f"{i}.jpg")).convert("RGB") if r["box"]: d = ImageDraw.Draw(im) d.rectangle(r["box"], outline=(230, 60, 30), width=max(3, im.width // 250)) return im def highlight(text, second): flags = disagreement(text, second) return [(w + " ", "check" if k in flags else None) for k, w in enumerate(text.split())] def calibrated(margin): for row in calib["table"]: if margin >= row["min_margin"]: return row return calib["table"][-1] def rec_name(r): name = r["signum"] if r.get("signum") not in (None, "None", "") else r["id"] src = {"srd": "Rundata", "rdb": "RuneS", "ch": "Gamla runor"}.get(r["src"], r["src"]) return f"{name} ({src})" def search_view(text): res = index.identify(text) if not res["hits"]: return "Type or correct a transliteration to search the corpus.", [], None seen, rows = set(), [] for r, s in res["hits"]: if str(r["cluster"]) in seen: continue seen.add(str(r["cluster"])) rows.append([rec_name(r), round(s, 3), r["translit_raw"][:160], r["translation"][:220]]) if len(rows) == 5: break top = res["hits"][0][0] row = calibrated(res["margin"]) share = int(100 * row["top_share"]) if row["top_share"] <= 0.3: head = f"### Known inscription: **{rec_name(top)}**" elif row["top_share"] <= 0.5: head = f"### Possible match: **{rec_name(top)}**" else: head = "### No confident match" msg = (f"{head}\n\nMatch margin {res['margin']:.3f}: among held-out test photographs, the " f"{share}% with the largest margins were identified correctly **{row['precision']:.0f}%** of the time.") if row["top_share"] <= 0.5: msg += f"\n\n**Scholarly translation ({top['lang']}):** {top['translation']}" else: msg += ("\n\nThe inscription may be unpublished, or the reading is still too noisy. " "Correct the flagged words, or use the draft machine translation below.") return msg, rows, res["top_cluster"] def cer(h, g): n, m = len(h), len(g) prev = list(range(m + 1)) for i in range(1, n + 1): cur = [i] + [0] * m for j in range(1, m + 1): cur[j] = min(prev[j - 1] + (h[i - 1] != g[j - 1]), prev[j] + 1, cur[j - 1] + 1) prev = cur return 100 * prev[m] / max(m, 1) def reference_view(i, text, top_cluster): r = EX[i] h, g = text.split(), r["ref_translit"].split() errs = sum(o[0] != "M" for o in align(h, g)) ok = "✅ correct" if top_cluster == r["cluster"] else "❌ not this inscription" return (f"**Reference transliteration:** {r['ref_translit']}\n\n" f"**Reference translation ({r['lang']}):** {r['ref_translation']}\n\n" f"Current text: {errs} word errors, {cer(text, r['ref_translit']):.0f}% character error rate; " f"top search result: {ok}.") # ---------------------------------------------------------------- tab 1 callbacks def load_example(i): r = EX[i] crop = Image.open(os.path.join(HERE, "media", "crop", f"{i}.jpg")) credit = (f"Image: {r['credit']}. Record: [RuneS]({r['find_page']})" + (f", [source]({r['image_source']})" if r.get("image_source") else "") + ".") conf = (f"Reading confidence (recognizer likelihood): more confident than {100 - r['confidence_pct']}% " f"of test photographs." if r["nll"] is not None else "") msg, rows, top = search_view(r["reading"]) return (draw_box(i), crop, credit, conf, highlight(r["reading"], r["second"]), r["reading"], msg, rows, top, r["mt"] or "(empty)", "", reference_view(i, r["reading"], top), "") def on_search(i, text): msg, rows, top = search_view(text) return highlight(text, EX[i]["second"]), msg, rows, top, reference_view(i, text, top) def on_expert(i, text): new, desc = expert_fix(text, EX[i]["ref_translit"], EX[i]["second"]) note = f"Simulated expert {desc}." if desc else "The text already matches the reference." return (new, note) + on_search(i, new) def on_translate(i, text): return translate_live(text, EX[i]["lang"]) def translate_live(text, lang): if not text.strip(): return "Nothing to translate." if not LIVE: return "Live models are switched off in this deployment." if models.error: return f"Models could not be loaded: {models.error}" try: return models.translate(text.strip(), lang) except Exception as e: return f"Translation failed: {e!r}" def random_example(): return gr.update(value=random.choice(CHOICES)) # ---------------------------------------------------------------- tab 2 callbacks def own_text(text, lang): msg, rows, _ = search_view(text) return msg, rows def own_photo(image): if image is None: return None, None, "", "Upload a photograph first." if not LIVE or models.error: return None, None, "", f"Live models are unavailable here ({models.error or 'switched off'})." im = image.convert("RGB") box, raw = models.locate(im) crop, cbox = crop_to_box(im, box) shown = im.copy() if cbox: ImageDraw.Draw(shown).rectangle(cbox, outline=(230, 60, 30), width=max(3, im.width // 250)) from runic_demo.loopcut import cut_loops reading = cut_loops(models.read(crop)) return shown, crop, reading, ("Inscription located." if box else "No box found; the whole image was read.") CSS = ".small {font-size: 0.85em; opacity: 0.8}" INTRO = f"""# Runic Reader From a photograph of a runic inscription to its transliteration, then either **identification of a known inscription** in a corpus of 10,125 records (Rundata, RuneS), or a **draft translation** into English or Swedish. The pipeline (Qwen3.5-4B: zero-shot localization, a LoRA recognizer on the crop, a LoRA translator) is described in our paper{f' ([link]({PAPER_URL}))' if PAPER_URL else ''}; the recognizer is imperfect, so the demo lets you correct words, highlighting those where a second recognizer disagrees.{f' Code: [{CODE_URL}]({CODE_URL}).' if CODE_URL else ''}""" with gr.Blocks(title="Runic Reader", css=CSS) as demo: gr.Markdown(INTRO) with gr.Tab("Test photographs"): gr.Markdown("312 held-out test photographs from RuneS with open licences; the models never saw them in " "training. Model outputs are cached, the corpus search runs live. ★ = featured.", elem_classes="small") with gr.Row(): pick = gr.Dropdown(choices=[(label(i), i) for i in CHOICES], value=CHOICES[0], label="Photograph", scale=4) rnd = gr.Button("Random", scale=1) with gr.Row(): full = gr.Image(label="1. Photograph with the located inscription", height=380, interactive=False) crop = gr.Image(label="Crop given to the recognizer", height=380, interactive=False) credit = gr.Markdown(elem_classes="small") gr.Markdown("### 2. Machine reading") conf = gr.Markdown(elem_classes="small") hl = gr.HighlightedText(label="Words flagged “check”: a second recognizer reads them differently", color_map={"check": "orange"}, show_legend=False, combine_adjacent=False) text = gr.Textbox(label="Transliteration (edit and search again)", lines=2) with gr.Row(): b_search = gr.Button("Search corpus", variant="primary") b_expert = gr.Button("Simulated expert: fix one word") b_reset = gr.Button("Reset") note = gr.Markdown(elem_classes="small") gr.Markdown("### 3. Known inscription?") verdict = gr.Markdown() table = gr.Dataframe(headers=["record", "score", "transliteration", "translation"], wrap=True, interactive=False) top_state = gr.State() gr.Markdown("### 4. Draft machine translation") with gr.Row(): mt_cached = gr.Textbox(label="Translation of the machine reading", interactive=False) mt_live = gr.Textbox(label="Translation of the current text (live)", interactive=False) b_mt = gr.Button("Translate current text (slow on CPU)") with gr.Accordion("Reference (open after trying)", open=False): ref = gr.Markdown() outs = [full, crop, credit, conf, hl, text, verdict, table, top_state, mt_cached, mt_live, ref, note] pick.change(load_example, pick, outs) b_reset.click(load_example, pick, outs) rnd.click(random_example, None, pick) b_search.click(on_search, [pick, text], [hl, verdict, table, top_state, ref]) text.submit(on_search, [pick, text], [hl, verdict, table, top_state, ref]) b_expert.click(on_expert, [pick, text], [text, note, hl, verdict, table, top_state, ref]) b_mt.click(on_translate, [pick, text], mt_live) demo.load(load_example, pick, outs) with gr.Tab("Your own inscription"): gr.Markdown("Type a transliteration in the Rundata convention (e.g. `sualfi auk kuþmuntr raistu stain`), " "or upload a photograph. Models run live; on this free CPU machine a translation takes " "about a minute and a photograph several minutes.", elem_classes="small") with gr.Row(): photo = gr.Image(label="Photograph", type="pil", height=320) photo_box = gr.Image(label="Located inscription", height=320, interactive=False) photo_crop = gr.Image(label="Crop", height=320, interactive=False) b_read = gr.Button("Read photograph (slow on CPU)") read_note = gr.Markdown(elem_classes="small") own = gr.Textbox(label="Transliteration", lines=2) lang = gr.Radio([("English", "en"), ("Swedish", "sv")], value="en", label="Translate into") with gr.Row(): b_own_search = gr.Button("Search corpus", variant="primary") b_own_mt = gr.Button("Translate (slow on CPU)") own_verdict = gr.Markdown() own_table = gr.Dataframe(headers=["record", "score", "transliteration", "translation"], wrap=True, interactive=False) own_mt = gr.Textbox(label="Draft machine translation", interactive=False) b_read.click(own_photo, photo, [photo_box, photo_crop, own, read_note]) b_own_search.click(own_text, [own, lang], [own_verdict, own_table]) own.submit(own_text, [own, lang], [own_verdict, own_table]) b_own_mt.click(translate_live, [own, lang], own_mt) with gr.Tab("About"): gr.Markdown(open(os.path.join(HERE, "ABOUT.md")).read()) if __name__ == "__main__": demo.queue(default_concurrency_limit=1).launch()