Download app.py from kambris/VM: direct link, hf CLI and curl.
- Browser
- Download file 108 kB
-
https://huggingface.co/spaces/kambris/VM/resolve/main/app.py
- Command line
-
hf download hf://spaces/kambris/VM/app.py
-
curl -L -o app.py https://huggingface.co/spaces/kambris/VM/resolve/main/app.py
108 kB
import base64
import html as _html
import tempfile
import time
import urllib.request
import uuid
from collections import Counter
from datetime import datetime
from functools import lru_cache
from pathlib import Path
import gradio as gr
import numpy as np
import pandas as pd
from corpus import (SECTION_NAMES, SECTION_ORDER, SOURCE_NAMES, build_view, collocates,
concordance, neighbour_lines, paginate, parameter_line, register_views,
robustness, similar_words, view_key)
import export as ex
from search import ERROR_TEXT, PatternError, canonical, compile_pattern, hit_mask, match_spans, search
# ZeroGPU hardware refuses to start an app with no @spaces.GPU function. This app
# needs no GPU; the placeholder lets it run on ZeroGPU as well as CPU Basic.
try:
import spaces
@spaces.GPU
def _zero_gpu_placeholder():
return None
except ImportError:
pass
# Gradio 6 moved css/js/head from the Blocks() constructor to launch().
# Detect the major version so the same file works on Gradio 4/5 and 6+.
GR_MAJOR = int(gr.__version__.split(".")[0])
# ββ Load data βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# data/tokens.parquet is built offline by build_tokens.py from the IVTFF files.
_HERE = Path(__file__).resolve().parent
def _fetch(url: str, timeout: int) -> bytes:
"""voynich.nu answers 406 to Python's default User-Agent, so send a browser-like one."""
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 (VoynichCodexReader)"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.read()
_RAW_URLS = {
"ZL": "https://www.voynich.nu/data/ZL3b-n.txt",
"IT": "https://www.voynich.nu/data/IT2a-n.txt",
"RF": "https://www.voynich.nu/data/RF1b-e.txt",
}
def _load_tokens() -> pd.DataFrame:
"""Prefer the committed tokens file; if it is missing, build it once from voynich.nu."""
for p in (_HERE / "data" / "tokens.parquet", _HERE / "tokens.parquet"):
if p.exists():
return pd.read_parquet(p)
from build_tokens import parse_ivtff_text
frames = []
for src, url in _RAW_URLS.items():
print(f"tokens.parquet not found; downloading {url}")
frames.append(parse_ivtff_text(_fetch(url, 60).decode("utf-8", errors="replace"), src))
tokens = pd.concat(frames, ignore_index=True)
try:
out = _HERE / "data" / "tokens.parquet"
out.parent.mkdir(exist_ok=True)
tokens.to_parquet(out, index=False)
except OSError as exc:
print(f"Could not cache tokens.parquet: {exc}")
return tokens
TOKENS = _load_tokens()
SOURCES = [s for s in SOURCE_NAMES if s in set(TOKENS["Source"])]
DEFAULT_SOURCE = "ZL" if "ZL" in SOURCES else SOURCES[0]
DEFAULT_KEY = view_key(DEFAULT_SOURCE, False)
VIEWS = {view_key(s, lab): build_view(TOKENS, s, lab) for s in SOURCES for lab in (False, True)}
register_views(VIEWS)
SECTION_COLORS = {
"H": "#5b8c3a", "A": "#2f6f9f", "C": "#7a5ea8", "Z": "#c0802f",
"B": "#b0505a", "P": "#3a8c86", "S": "#8b6f47", "T": "#888888",
}
COLL_PAGE = 50
CONC_PAGE = 100
# Spec D: up to three patterns, coloured in the order they were added (D4).
PATTERN_COLORS = ["#2f6fd0", "#c0392b", "#2e8b57"]
PATTERN_TINTS = ["rgba(47,111,208,0.22)", "rgba(192,57,43,0.20)", "rgba(46,139,87,0.22)"]
MAX_PATTERNS = 3
EVA_KEYS = list("acdefghiklmnopqrstvxyz")
def _section_label(code: str) -> str:
return SECTION_NAMES.get(code, code or "Unassigned")
# ββ EVA font ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_FONT_URL = "https://www.voynich.nu/software/EVA2.ttf"
_FONT_LOCAL = Path("EVA2.ttf")
def _load_eva_font_css() -> str:
for p in [_FONT_LOCAL, Path(__file__).with_name("EVA2.ttf")]:
if p.exists():
b64 = base64.b64encode(p.read_bytes()).decode()
return (f"@font-face {{ font-family: 'EVA Hand 1';"
f" src: url('data:font/truetype;base64,{b64}') format('truetype'); }}")
try:
data = _fetch(_FONT_URL, 15)
_FONT_LOCAL.write_bytes(data)
b64 = base64.b64encode(data).decode()
return (f"@font-face {{ font-family: 'EVA Hand 1';"
f" src: url('data:font/truetype;base64,{b64}') format('truetype'); }}")
except Exception as exc:
print(f"EVA font unavailable: {exc}")
return ""
EVA_FONT_CSS = _load_eva_font_css()
# ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _js(s: str) -> str:
return str(s).replace("\\", "\\\\").replace("'", "\\'")
def _esc(s) -> str:
return _html.escape(str(s))
def _section_badge(code: str) -> str:
col = SECTION_COLORS.get(code, "#888")
return (f'<span class="section-badge" style="border-color:{col};color:{col}">'
f'{_section_label(code)}</span>')
def _sparkline_by_section(v, series, height=28, color_on="#8b6f47", color_off="#e8e0ce"):
"""One 1px bar per folio, with a marker between sections (AC15)."""
mx = max(series) if series and max(series) > 0 else 1
bars, prev_sec = "", None
for f, val in zip(v.folios, series):
sec = v.folio_section.get(f, "")
if prev_sec is not None and sec != prev_sec:
bars += (f'<div title="{_section_label(sec)} starts at {f}" style="width:1px;'
f'height:{height + 4}px;background:#b9a57f;margin:0 2px;flex-shrink:0"></div>')
prev_sec = sec
h = max(2, int(val / mx * height)) if val else 2
col = color_on if val else color_off
bars += (f'<div title="{f}: {val}" style="width:1px;height:{h}px;'
f'background:{col};flex-shrink:0"></div>')
return bars
def _spread_label(series) -> str:
"""
Measure how spread out a word is across folios relative to how spread out
it *could* be given its total frequency.
A word appearing 4 times can appear on at most 4 folios. If it does, that
is maximally scattered. A word appearing 200 times could in principle touch
every folio in the current view; if it only shows up on a small share of
them it is genuinely clustered.
spread_ratio = folios_present / min(total_occurrences, total_folios)
> 0.75 β scattered
> 0.40 β clustered
else β highly clustered
"""
s = pd.Series(series)
total = int(s.sum())
n = len(s)
if total == 0:
return "absent"
folios_present = int((s > 0).sum())
max_possible = min(total, n)
spread_ratio = folios_present / max_possible
if spread_ratio > 0.75:
return "scattered"
elif spread_ratio > 0.40:
return "clustered"
else:
return "highly clustered"
def _folio_tokens(v, folio):
return v.df[v.df["Folio"] == folio]
def _section_folios(v, section):
if not section or section == "All":
return v.folios
return [f for f in v.folios if v.folio_section.get(f) == section]
# ββ App state βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# One dict carries everything a render needs (spec C: modes, scope, toggles, paging).
def _initial_state():
return {
"key": DEFAULT_KEY, "folio": VIEWS[DEFAULT_KEY].folios[0], "section": "All",
"word": "", "mode": "page", "msg": "",
"window": 3, "language": "All", "excl": False, "positional": False, "certain": False,
"position": "Any", "with_word": "", "ksort": "ms", "kpage": 0,
"csort": "", "casc": False, "cpage": 0,
# Script switch (spec E, E2): True draws words in the Voynichese (EVA font) glyphs
# in Concordance and Search; the top bar and each view's "Show" line share it.
"kglyph": True,
# Spec E, E6: a bigram/trigram filter on the concordance, (side, context words, node).
"kclus": None,
# Spec D: active patterns [{"q", "exact"}], the pattern driving Collocates/Concordance
# (None means the selected word drives them), and the search box message.
"patterns": [], "pidx": None, "smsg": "",
}
def _scope_kwargs(st):
return dict(section=st["section"], language=st["language"], exclude_adjacent=st["excl"],
certain_only=st["certain"], positional=st["positional"])
@lru_cache(maxsize=256)
def _coll_cached(key, word, window, section, language, excl, certain, positional,
pq=None, pexact=False):
v = VIEWS[key]
kw = dict(section=section, language=language, exclude_adjacent=excl,
certain_only=certain, positional=positional)
if pq is not None:
kw["pattern"] = compile_pattern(pq, pexact)
tab = collocates(v, word, window, **kw)
rob = robustness(VIEWS, v.source, word, window, include_labels=v.include_labels,
sources=tuple(SOURCES), **kw)
return tab, rob
def _coll(st, use_target=False):
"""Collocates of the selected word, or of the driving pattern when use_target is set."""
excl = st["excl"] and st["window"] > 1
tg = _target(st) if use_target else None
pq, pex = (tg["q"], tg["exact"]) if tg and tg["kind"] == "pattern" else (None, False)
return _coll_cached(st["key"], st["word"], int(st["window"]), st["section"], st["language"],
excl, st["certain"], st["positional"], pq, pex)
def _rob_dots(rob, w):
if rob is None or w not in rob.index:
return ""
r = rob.loc[w]
dots = "".join(
f'<span class="rdot{" on" if r[s] else ""}" title="{s}: {"passes" if r[s] else "does not pass"}"></span>'
for s in rob.columns)
return f'<span class="rdots">{dots}</span>'
# ββ Spec D: pattern helpers βββββββββββββββββββββββββββββββββββββββββββββββββββ
def _pattern_label(p) -> str:
return canonical(p["q"], p["exact"])
def _patterns(st):
"""[(index, label, compiled, colour, tint)] for every active pattern."""
return [(i, _pattern_label(p), compile_pattern(p["q"], p["exact"]), PATTERN_COLORS[i], PATTERN_TINTS[i])
for i, p in enumerate(st["patterns"])]
@lru_cache(maxsize=512)
def _search_one(key, q, exact, section, language):
return search(VIEWS[key], [compile_pattern(q, exact)], section=section, language=language)[0]
def _pattern_result(st, p, key=None):
return _search_one(key or st["key"], p["q"], p["exact"], st["section"], st["language"])
def _hit_folios(st):
"""Folios with a hit of any active pattern, in manuscript order, within the scope (D5)."""
v = VIEWS[st["key"]]
hit = set()
for p in st["patterns"]:
hit.update(_pattern_result(st, p)["hit_folios"])
return [f for f in v.folios if f in hit]
def _target(st):
"""What drives Collocates and Concordance: an active pattern, or the selected word."""
i = st.get("pidx")
if i is not None and i < len(st["patterns"]):
p = st["patterns"][i]
return {"kind": "pattern", "i": i, "label": _pattern_label(p),
"compiled": compile_pattern(p["q"], p["exact"]), "q": p["q"], "exact": p["exact"],
"color": PATTERN_COLORS[i]}
return {"kind": "word", "word": st["word"]} if st["word"] else None
def _marked(word: str, layers) -> str:
"""The word with matched glyphs tinted; `layers` is [(compiled, colour, tint)], earlier wins."""
owner = [None] * len(word)
for k, (compiled, _c, _t) in enumerate(layers):
for a, b in match_spans(word, compiled):
for j in range(a, b):
if owner[j] is None:
owner[j] = k
if all(o is None for o in owner):
return _esc(word)
out, j = "", 0
while j < len(word):
k = owner[j]
e = j
while e < len(word) and owner[e] == k:
e += 1
seg = _esc(word[j:e])
if k is None:
out += seg
else:
_c, col, tint = layers[k]
# A solid light backing keeps the tint readable on the darkest frequency shading.
out += (f'<span class="pm" style="color:{col};background:linear-gradient({tint},{tint}),#fffdf7;'
f'box-shadow:inset 0 -3px 0 {col}">{seg}</span>')
j = e
return out
# ββ HTML builders: page mode ββββββββββββββββββββββββββββββββββββββββββββββββββ
LOCUS_TAGS = {"L": "label", "C": "circle", "R": "radius"}
def build_folio_page(v, folio: str, highlight: str = "", layers=()) -> str:
page = v.page_df[v.page_df["Folio"] == folio]
if page.empty:
return f'<div class="ms-folio-id">{folio}</div><i style="color:#aaa">No text on this page in {v.source}.</i>'
lc = page["Word"].value_counts()
lo, hi = lc.min(), lc.max()
lines_html = ""
for (line, ltype), line_df in page.sort_values(["Line", "Position"]).groupby(["Line", "LocusType"], sort=True):
words_html = ""
for w in line_df["Word"]:
freq = int(lc.get(w, 1))
norm = (freq - lo) / (hi - lo) if hi > lo else 0.0
r = int(210 - norm * 140)
g = int(180 - norm * 140)
b = int(140 - norm * 100)
bg = f"rgba({r},{g},{b},{0.15 + 0.6 * norm:.2f})"
gf = v.global_freq.get(w)
gf_txt = gf if gf is not None else "not counted in this view"
hl = " hl" if highlight and w == highlight else ""
words_html += (
f'<span class="word{hl}" style="background:{bg}" '
f'onclick="selectWord(\'{_js(w)}\')" '
f'title="EVA: {w} | page: {freq} | ms-wide: {gf_txt}">'
f'{_marked(w, layers) if layers else w}</span> '
)
if ltype == "P":
lines_html += f'<div class="ms-line">{words_html}</div>\n'
else:
lines_html += (f'<div class="ms-line ms-label"><span class="locus-tag">'
f'{LOCUS_TAGS.get(ltype, ltype)}</span>{words_html}</div>\n')
return (
f'<div class="ms-folio-id">{_section_badge(v.folio_section.get(folio, ""))} {folio}</div>'
f'<div class="ms-body">{lines_html}</div>'
)
def build_corpus_stats(v) -> str:
c = v.corpus
top_rows = "".join(
f'<tr><td style="font-family:\'EVA Hand 1\',serif;font-size:14px;padding:2px 8px 2px 0">{w}</td>'
f'<td style="font-family:monospace;font-size:10px;color:#888;padding:2px 8px 2px 0">{w}</td>'
f'<td style="font-variant-numeric:tabular-nums;padding:2px 0">{gf}</td></tr>'
for w, gf in c["top5"]
)
scope = "all text" if v.include_labels else "paragraph text"
return f"""
<div class="stats-section">
<div class="stats-heading">Corpus statistics · {v.source} · {scope}</div>
<div class="stats-grid">
<div class="stat-cell"><div class="stat-value">{c['tokens']:,}</div><div class="stat-label">total tokens</div></div>
<div class="stat-cell"><div class="stat-value">{c['types']:,}</div><div class="stat-label">unique types</div></div>
<div class="stat-cell"><div class="stat-value">{c['ttr']:.3f}</div><div class="stat-label">type/token ratio</div></div>
<div class="stat-cell"><div class="stat-value">{c['hapax']:,}</div><div class="stat-label">hapax legomena</div></div>
<div class="stat-cell"><div class="stat-value">{c['folios']}</div><div class="stat-label">folios</div></div>
<div class="stat-cell"><div class="stat-value">{c['avg_wl']:.1f}</div><div class="stat-label">avg token length</div></div>
</div>
<div class="stats-subheading">Most frequent words (ms-wide)</div>
<table style="border-collapse:collapse;font-size:12px">{top_rows}</table>
</div>"""
def build_folio_stats(v, folio: str) -> str:
subset = _folio_tokens(v, folio)
if subset.empty:
hint = ("" if v.include_labels else
" Tick <b>Count label & ring text</b> to include this page's labels.")
return (f'<div class="stats-section"><div class="stats-heading">Folio {folio}</div>'
f'<i style="color:#999;font-size:12px">No counted text on this page.{hint}</i></div>')
lc = subset["Word"].value_counts()
f_tokens = len(subset)
f_types = subset["Word"].nunique()
f_ttr = f_types / f_tokens if f_tokens else 0
f_hapax = int((lc == 1).sum())
f_lines = subset["Line"].nunique()
f_avg_wl = subset["Word"].str.len().mean()
f_density = f_tokens / f_lines if f_lines else 0
n_ranked = len(v.folio_token_counts)
f_rank = int(v.folio_token_counts.rank(ascending=False, method="min")[folio])
top3_html = "".join(
f'<span class="top-chip">'
f'<span style="font-family:\'EVA Hand 1\',serif;font-size:13px">{w}</span>'
f'<span class="top-chip-count">{c}</span></span>'
for w, c in lc.head(3).items()
)
wl_counts = subset["Word"].str.len().value_counts().sort_index()
wl_max = wl_counts.max() if not wl_counts.empty else 1
bars = ""
for length in range(1, int(subset["Word"].str.len().max()) + 1):
cnt = int(wl_counts.get(length, 0))
h = max(2, int(cnt / wl_max * 28)) if cnt else 2
col = "#8b6f47" if cnt else "#eee"
bars += (f'<div title="Length {length}: {cnt}" style="width:6px;height:{h}px;'
f'background:{col};border-radius:2px 2px 0 0;flex-shrink:0"></div>')
return f"""
<div class="stats-section">
<div class="stats-heading">Folio {folio}</div>
<div class="stats-grid">
<div class="stat-cell"><div class="stat-value">{f_tokens}</div><div class="stat-label">tokens</div></div>
<div class="stat-cell"><div class="stat-value">{f_types}</div><div class="stat-label">unique types</div></div>
<div class="stat-cell"><div class="stat-value">{f_ttr:.2f}</div><div class="stat-label">TTR</div></div>
<div class="stat-cell"><div class="stat-value">{f_hapax}</div><div class="stat-label">hapax</div></div>
<div class="stat-cell"><div class="stat-value">{f_lines}</div><div class="stat-label">lines</div></div>
<div class="stat-cell"><div class="stat-value">{f_density:.1f}</div><div class="stat-label">tok/line</div></div>
<div class="stat-cell"><div class="stat-value">{f_avg_wl:.1f}</div><div class="stat-label">avg tok len</div></div>
<div class="stat-cell"><div class="stat-value">#{f_rank}<span style="font-size:11px;color:#aaa">/{n_ranked}</span></div><div class="stat-label">size rank</div></div>
</div>
<div class="stats-subheading">Top words this folio</div>
<div style="display:flex;flex-wrap:wrap;gap:5px;margin-bottom:12px">{top3_html}</div>
<div class="stats-subheading">Word length distribution</div>
<div style="display:flex;align-items:flex-end;gap:2px;height:34px;overflow-x:auto">{bars}</div>
</div>"""
def _section_rate_bars(v, word: str) -> str:
counts = v.df[v.df["Word"] == word]["Section"].value_counts()
secs = [s for s in SECTION_ORDER if v.section_totals.get(s)] + \
[s for s in v.section_totals if s not in SECTION_ORDER]
rates = {s: counts.get(s, 0) / v.section_totals[s] * 1000 for s in secs}
r_max = max(rates.values()) if rates and max(rates.values()) > 0 else 1
html = ""
for s in secs:
rate = rates[s]
col = SECTION_COLORS.get(s, "#888")
h = max(2, int(rate / r_max * 36)) if rate else 2
html += (
f'<div style="flex:1;text-align:center;min-width:0">'
f'<div title="{_section_label(s)}: {rate:.1f}/1000 tokens ({int(counts.get(s, 0))}x)" '
f'style="height:{h}px;background:{col};border-radius:2px;margin-bottom:3px"></div>'
f'<div style="font-size:9px;color:{col};font-weight:600">{rate:.1f}</div>'
f'<div style="font-size:9px;color:#aaa;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{_section_label(s)[:5]}</div>'
f'</div>'
)
return html
def build_collocate_summary(st) -> str:
"""Sidebar: top 5 collocates with score and robustness dots, plus a link (C4, C5)."""
tab, rob = _coll(st)
key = "log_ratio_pos" if st["positional"] else "LRC"
if tab.empty:
chips = '<i style="color:#ccc;font-size:11px">none pass the thresholds</i>'
else:
chips = ""
for _, r in tab.head(5).iterrows():
w2 = r["collocate"]
dim = " dim" if r["dim"] else ""
chips += (
f'<span class="coll-chip{dim}" onclick="appAction(\'wfilter\',\'{_js(w2)}\')" '
f'title="Open the concordance filtered to lines with both words">'
f'<span style="font-family:\'EVA Hand 1\',serif;font-size:13px">{_esc(w2)}</span>'
f'<span class="coll-score">{r[key]:.2f}</span>{_rob_dots(rob, w2)}'
f'<span class="coll-arrow" title="Select {_esc(w2)}" '
f'onclick="event.stopPropagation();selectWord(\'{_js(w2)}\')">↗</span>'
f'</span>')
stat = "log2 O/E_pos" if st["positional"] else "LRC"
return f"""
<div class="detail-section">
<div class="detail-label">Collocates <span style="font-weight:400;text-transform:none;letter-spacing:0;color:#bbb;font-size:9px">· Β±{st['window']} · {stat}</span></div>
<div style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:6px">{chips}</div>
<a class="coll-link" onclick="appAction('wmode','coll')">Collocates →</a>
</div>"""
def build_detail(v, folio: str, word: str, coll_summary: str = "") -> str:
if not word:
return '<i style="color:#aaa">Click any word to explore it</i>'
word = word.strip()
if word not in v.global_freq:
hint = ("" if v.include_labels else
" It may occur only in label text; tick <b>Count label & ring text</b> to include it.")
return f'<i style="color:#aaa">"{word}" is not counted in {v.source}.{hint}</i>'
subset = _folio_tokens(v, folio)
lc = subset["Word"].value_counts()
lf = int(lc.get(word, 0))
gf = int(v.global_freq.get(word, 0))
tot = len(lc)
if lf > 0:
rank = int((lc > lf).sum()) + 1
rank_html = f'#{rank}<span style="font-size:10px;color:#aaa">/{tot}</span>'
else:
rank_html = '<span style="color:#aaa">—</span>'
cross_folios = v.word_folios.get(word, [])
pct = v.percentile(gf)
pos = v.pos_map.get(word, {"start": 0, "mid": 0, "end": 0})
ptot = pos["start"] + pos["mid"] + pos["end"]
def _pct(k): return int(pos[k] / ptot * 100) if ptot else 0
pos_bars = ""
for label, key, color in [("start", "start", "#2980b9"), ("mid", "mid", "#8b6f47"), ("end", "end", "#c0392b")]:
pval = _pct(key)
pos_bars += (
f'<div style="flex:1;text-align:center">'
f'<div style="height:{max(4, pval//2)}px;background:{color};border-radius:2px;margin-bottom:3px"></div>'
f'<div style="font-size:10px;font-weight:600;color:{color}">{pval}%</div>'
f'<div style="font-size:9px;color:#aaa">{label}</div>'
f'<div style="font-size:9px;color:#bbb">{pos[key]}x</div>'
f'</div>'
)
if ptot == 0:
dom_label = "isolated"
else:
dominant = max(pos, key=lambda k: pos[k])
dom_label = {"start": "line-initial", "mid": "medial", "end": "line-final"}[dominant]
def _bigram_chips(mapping, color):
top = sorted(mapping.items(), key=lambda x: -x[1])[:5]
if not top: return '<i style="color:#ccc;font-size:11px">none</i>'
chips = ""
for w2, cnt in top:
chips += (
f'<span onclick="selectWord(\'{_js(w2)}\')" class="bigram-chip" style="border-color:{color}20;color:{color}">'
f'<span style="font-family:\'EVA Hand 1\',serif;font-size:13px;color:#2c1810">{w2}</span>'
f'<span style="font-size:10px;margin-left:3px;color:{color}">{cnt}x</span>'
f'</span>'
)
return chips
prev_chips = _bigram_chips(v.prev_map.get(word, {}), "#2980b9")
next_chips = _bigram_chips(v.next_map.get(word, {}), "#c0392b")
series = v.word_series(word)
spark_bars = _sparkline_by_section(v, series)
spread_label = _spread_label(series)
sec_bars = _section_rate_bars(v, word)
sim_chips = ""
for w2, dist in similar_words(view_key(v.source, v.include_labels), word):
gf2 = v.global_freq.get(w2, 0)
sim_chips += (
f'<span onclick="selectWord(\'{_js(w2)}\')" class="sim-chip">'
f'<span style="font-family:\'EVA Hand 1\',serif;font-size:13px">{w2}</span>'
f'<span class="sim-dist">d{dist}</span>'
f'<span style="font-size:9px;color:#aaa">{gf2}x</span>'
f'</span>'
)
p2, s2 = word[:2], word[-2:]
p3, s3 = (word[:3] if len(word) >= 3 else word[:2]), (word[-3:] if len(word) >= 3 else word[-2:])
pfx_words = sorted(
[w2 for w2 in v.all_words if w2 != word and (w2.startswith(p3) or w2.startswith(p2))],
key=lambda w2: -v.global_freq.get(w2, 0)
)[:6]
sfx_words = sorted(
[w2 for w2 in v.all_words if w2 != word and (w2.endswith(s3) or w2.endswith(s2))],
key=lambda w2: -v.global_freq.get(w2, 0)
)[:6]
def _morph_chips(words_list, hl_len, align):
chips = ""
for w2 in words_list:
gf2 = v.global_freq.get(w2, 0)
if align == "prefix":
shared = w2[:hl_len] if w2.startswith(word[:hl_len]) else ""
rest = w2[len(shared):]
display = (f'<span style="color:#2980b9;font-weight:600">{shared}</span>{rest}'
if shared else w2)
else:
shared = w2[-hl_len:] if w2.endswith(word[-hl_len:]) else ""
stem = w2[:-len(shared)] if shared else w2
display = (f'{stem}<span style="color:#c0392b;font-weight:600">{shared}</span>'
if shared else w2)
chips += (
f'<span onclick="selectWord(\'{_js(w2)}\')" class="morph-chip">'
f'<span style="font-family:\'EVA Hand 1\',serif;font-size:13px">{display}</span>'
f'<span style="font-size:9px;color:#aaa;margin-left:3px">{gf2}x</span>'
f'</span>'
)
return chips or '<i style="color:#ccc;font-size:11px">none</i>'
pfx_hl = len(p3) if pfx_words and pfx_words[0].startswith(p3) else len(p2)
sfx_hl = len(s3) if sfx_words and sfx_words[0].endswith(s3) else len(s2)
pfx_chips = _morph_chips(pfx_words, pfx_hl, "prefix")
sfx_chips = _morph_chips(sfx_words, sfx_hl, "suffix")
wl = subset[subset["Word"] == word]["Line"].value_counts()
lines = sorted(subset["Line"].unique())
mwl = wl.max() if not wl.empty else 1
line_bars = ""
for ln in lines:
cnt = int(wl.get(ln, 0))
h = max(2, int(cnt / mwl * 28)) if cnt else 2
c = "#c0392b" if cnt else "#eee"
line_bars += (f'<div title="Line {ln}: {cnt}x" style="width:5px;height:{h}px;'
f'background:{c};border-radius:2px 2px 0 0;flex-shrink:0"></div>')
wp = subset[subset["Word"] == word]["Position"].value_counts()
max_slot = int(subset["Position"].max()) if not subset.empty else 1
mwp = wp.max() if not wp.empty else 1
slot_bars = ""
for sl in range(1, max_slot + 1):
cnt = int(wp.get(sl, 0))
h = max(2, int(cnt / mwp * 28)) if cnt else 2
c = "#2980b9" if cnt else "#eee"
slot_bars += (f'<div title="Slot {sl}: {cnt}x" style="width:5px;height:{h}px;'
f'background:{c};border-radius:2px 2px 0 0;flex-shrink:0"></div>')
chips = ""
for cf in cross_folios:
bold = "font-weight:bold;border-color:#333" if cf == folio else ""
chips += (f'<span onclick="navigateToFolio(\'{_js(cf)}\')" '
f'style="cursor:pointer;border:1px solid #ccc;border-radius:3px;'
f'padding:1px 5px;font-size:11px;font-family:monospace;{bold}">{cf}</span>')
glyph_html = ""
for ch in word:
glyph_html += (
f'<div style="text-align:center;min-width:22px">'
f'<div style="font-family:\'EVA Hand 1\',serif;font-size:22px;color:#2c1810">{ch}</div>'
f'<div style="font-family:monospace;font-size:9px;color:#aaa">{ch}</div>'
f'</div>'
)
lf_display = lf if lf > 0 else "-"
n_folios = len(v.folios)
return f"""
<div style="font-family:'EVA Hand 1',serif;font-size:30px;letter-spacing:3px;margin-bottom:2px">{word}</div>
<div style="font-family:monospace;font-size:11px;color:#888;margin-bottom:10px">{word} . {len(word)} glyphs . {v.source}</div>
<div class="detail-section">
<div class="detail-label">Glyph breakdown</div>
<div style="display:flex;gap:4px;flex-wrap:wrap">{glyph_html}</div>
</div>
<div style="display:flex;gap:6px;margin-bottom:10px;flex-wrap:wrap">
<div class="mini-stat"><div class="mini-val">{lf_display}</div><div class="mini-lbl">folio</div></div>
<div class="mini-stat"><div class="mini-val">{gf}</div><div class="mini-lbl">ms-wide</div></div>
<div class="mini-stat"><div class="mini-val">{rank_html}</div><div class="mini-lbl">rank</div></div>
<div class="mini-stat"><div class="mini-val">{len(cross_folios)}<span style="font-size:10px;color:#aaa">/{n_folios}</span></div><div class="mini-lbl">folios</div></div>
<div class="mini-stat"><div class="mini-val">{pct}<span style="font-size:10px;color:#aaa">th</span></div><div class="mini-lbl">pctile</div></div>
</div>
<div class="detail-section">
<div class="detail-label">Positional preference <span style="font-weight:400;text-transform:none;letter-spacing:0;color:#bbb;font-size:9px">· corpus-wide</span> <span class="detail-badge">{dom_label}</span></div>
<div style="display:flex;gap:6px;align-items:flex-end;height:56px">{pos_bars}</div>
</div>
{coll_summary}
<div class="detail-section">
<div class="detail-label">Neighbors</div>
<div style="font-size:9px;color:#aaa;text-transform:uppercase;margin-bottom:4px">Preceded by</div>
<div style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:8px">{prev_chips}</div>
<div style="font-size:9px;color:#aaa;text-transform:uppercase;margin-bottom:4px">Followed by</div>
<div style="display:flex;flex-wrap:wrap;gap:4px">{next_chips}</div>
</div>
<div class="detail-section">
<div class="detail-label">Frequency across manuscript <span class="detail-badge">{spread_label}</span></div>
<div style="display:flex;align-items:flex-end;gap:0;height:34px;overflow-x:auto;margin-bottom:8px">{spark_bars}</div>
<div style="font-size:9px;color:#aaa;text-transform:uppercase;margin-bottom:3px">Rate by section, per 1000 tokens</div>
<div style="display:flex;gap:4px;align-items:flex-end;height:48px">{sec_bars}</div>
</div>
<div class="detail-section">
<div class="detail-label">Similar words (by edit distance)</div>
<div style="display:flex;flex-wrap:wrap;gap:4px">{sim_chips}</div>
</div>
<div class="detail-section">
<div class="detail-label">Morphological family</div>
<div style="font-size:9px;color:#2980b9;text-transform:uppercase;margin-bottom:4px">Shares prefix <code style="background:#f0f6ff;padding:1px 4px;border-radius:2px">{word[:pfx_hl]}-</code></div>
<div style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:8px">{pfx_chips}</div>
<div style="font-size:9px;color:#c0392b;text-transform:uppercase;margin-bottom:4px">Shares suffix <code style="background:#fff0f0;padding:1px 4px;border-radius:2px">-{word[-sfx_hl:]}</code></div>
<div style="display:flex;flex-wrap:wrap;gap:4px">{sfx_chips}</div>
</div>
<div class="detail-section">
<div class="detail-label">Within-folio distribution</div>
<div style="font-size:9px;color:#aaa;text-transform:uppercase;margin-bottom:3px">By line</div>
<div style="display:flex;align-items:flex-end;gap:2px;height:30px;overflow-x:auto;margin-bottom:8px">{line_bars}</div>
<div style="font-size:9px;color:#aaa;text-transform:uppercase;margin-bottom:3px">By slot position</div>
<div style="display:flex;align-items:flex-end;gap:2px;height:30px;overflow-x:auto">{slot_bars}</div>
</div>
<div class="detail-section">
<div class="detail-label">Appears in {len(cross_folios)} folios</div>
<div style="display:flex;flex-wrap:wrap;gap:4px;max-height:120px;overflow-y:auto">{chips}</div>
</div>
"""
def build_freq_table(v, folio: str) -> str:
subset = _folio_tokens(v, folio)
if subset.empty:
return '<i style="color:#aaa;font-size:12px">No counted text on this page.</i>'
lc = subset["Word"].value_counts()
rows = ""
for i, (w, local) in enumerate(lc.items()):
rows += (
f'<tr onclick="selectWord(\'{_js(w)}\')" style="cursor:pointer">'
f'<td style="color:#aaa;padding:3px 6px">{i+1}</td>'
f'<td style="font-family:\'EVA Hand 1\',serif;font-size:15px;padding:3px 6px">{w}</td>'
f'<td style="font-family:monospace;font-size:10px;color:#888;padding:3px 6px">{w}</td>'
f'<td style="padding:3px 6px">{local}</td>'
f'<td style="color:#bbb;padding:3px 6px">{v.global_freq.get(w, 0)}</td>'
f'</tr>'
)
return (
'<table style="border-collapse:collapse;width:100%;font-size:12px">'
'<thead><tr style="border-bottom:1px solid #ddd">'
'<th style="padding:4px 6px;text-align:left;font-weight:normal;color:#aaa;font-size:10px">#</th>'
'<th style="padding:4px 6px;text-align:left;font-weight:normal;color:#aaa;font-size:10px">Glyph</th>'
'<th style="padding:4px 6px;text-align:left;font-weight:normal;color:#aaa;font-size:10px">EVA</th>'
'<th style="padding:4px 6px;text-align:left;font-weight:normal;color:#aaa;font-size:10px">Local</th>'
'<th style="padding:4px 6px;text-align:left;font-weight:normal;color:#aaa;font-size:10px">Global</th>'
'</tr></thead>'
f'<tbody>{rows}</tbody></table>'
)
# ββ HTML builders: collocates and concordance modes βββββββββββββββββββββββββββ
def _mode_heading(st, title, sub=""):
tg = _target(st)
if tg and tg["kind"] == "pattern":
name = (f'<span class="mode-pattern" style="color:{tg["color"]};border-color:{tg["color"]}">'
f'{_esc(tg["label"])}</span>')
else:
name = f'<span class="mode-word">{_esc(st["word"])}</span>'
return f'<div class="mode-head"><span class="mode-title">{title}</span>{name}{sub}</div>'
def _pager(kind, start, end, n, size, page):
if n <= size:
return ""
prev_dis = " disabled" if start == 0 else ""
next_dis = " disabled" if end >= n else ""
return (f'<div class="pager"><a class="pg{prev_dis}" onclick="appAction(\'{kind}\',\'{page - 1}\')">← Previous</a>'
f'<a class="pg{next_dis}" onclick="appAction(\'{kind}\',\'{page + 1}\')">Next →</a></div>')
COLL_COLS = [
# (column, header, format, title)
("O11", "O", "{:.0f}", "Observed co-occurrences"),
("expected", "E", "{:.1f}", "Expected co-occurrences"),
("G2", "GΒ²", "{:.1f}", "Log-likelihood (cut-off β₯ 10.83, not a significance claim)"),
("LRC", "LRC", "{:.2f}", "Conservative log ratio"),
("left", "L", "{:.0f}", "Co-occurrences to the left"),
("right", "R", "{:.0f}", "Co-occurrences to the right"),
("dp_wc", "ΞP wβc", "{:.3f}", "How well the word predicts the collocate"),
("dp_cw", "ΞP cβw", "{:.3f}", "How well the collocate predicts the word"),
("folios", "Folios", "{:.0f}", "Folios where the pair co-occurs"),
("sections", "Sect.", "{:.0f}", "Sections where the pair co-occurs"),
("lang_A", "A", "{:.0f}", "Co-occurrences in Currier A"),
("lang_B", "B", "{:.0f}", "Co-occurrences in Currier B"),
]
POS_COLS = [("E_pos", "E_pos", "{:.1f}", "Positional expected count"),
("log_ratio_pos", "log2 O/E_pos", "{:.2f}", "Log ratio against the positional baseline")]
# ββ Collocates: bigrams and trigrams around the keyword ββββββββββββββββββββββ
NGRAM_TOP = 10 # rows per panel
NGRAM_MIN = 2 # a sequence must occur at least this often to be listed
@lru_cache(maxsize=128)
def _ngram_counts(key, word, pq, pexact, section, language, certain):
"""Counts of the 2- and 3-word sequences that end or start with a hit (same line only).
Uses the same tokens, scope and hit definition as Collocates and Concordance: view.tok
(whole lines), the exact word or every word a pattern matches, and with certain_only the
flagged tokens (uncertain break, alternate or illegible reading) are neither hits nor
part of a sequence.
"""
t = VIEWS[key].tok
if section and section != "All":
t = t[t["Section"] == section]
if language and language != "All":
t = t[t["Language"] == language]
t = t.reset_index(drop=True)
cnt = {k: Counter() for k in ("b2", "b3", "a2", "a3")}
if t.empty:
return {"n": 0, "top": {k: [] for k in cnt}}
words = t["Word"].to_numpy()
if pq is None:
hit = words == word
else:
hit = hit_mask(t, compile_pattern(pq, pexact)).to_numpy()
flagged = t["Flagged"].to_numpy() if certain else np.zeros(len(t), bool)
hits = np.flatnonzero(hit & ~flagged)
idx, line_len = t["Idx"].to_numpy(), t["LineLen"].to_numpy()
for h in hits:
# Rows of a line are contiguous and ordered by Idx, so row h-k is k words earlier.
for name, back, fwd in (("b2", 1, 0), ("b3", 2, 0), ("a2", 0, 1), ("a3", 0, 2)):
if idx[h] - back < 0 or idx[h] + fwd >= line_len[h]:
continue
a, b = h - back, h + fwd + 1
if flagged[a:b].any():
continue
cnt[name][tuple(words[a:b])] += 1
top = {k: [(g, c) for g, c in sorted(v.items(), key=lambda x: (-x[1], x[0]))
if c >= NGRAM_MIN][:NGRAM_TOP] for k, v in cnt.items()}
return {"n": len(hits), "top": top}
def _ngram_row(gram, count, n, key_idx, layers):
parts = []
for j, w in enumerate(gram):
if j == key_idx:
body = _marked(w, layers) if layers else _esc(w)
parts.append(f'<span class="ng-key">{body}</span>')
else:
parts.append(_esc(w))
share = count / n * 100 if n else 0
pct = f"{share:.0f}%" if share >= 1 else "<1%"
# Spec E, E6: tapping a row opens the concordance of exactly these lines.
side = "L" if key_idx > 0 else "R"
ctx = [w for j, w in enumerate(gram) if j != key_idx]
arg = _js(",".join([side, gram[key_idx]] + ctx))
return (f'<div class="ng-row" onclick="appAction(\'ngram\',\'{arg}\')" '
f'title="Open these lines in the concordance"><div class="ng-g"><span class="ng-glyph">{" ".join(parts)}</span>'
f'<span class="ng-eva">{_esc(" ".join(gram))}</span></div>'
f'<span class="ng-n">{count}</span><span class="ng-pct">{pct}</span></div>')
def _ngram_panel(title, hint, items, n, key_idx, layers):
if items:
rows = "".join(_ngram_row(g, c, n, key_idx, layers) for g, c in items)
else:
rows = f'<div class="ng-none">No sequence occurs {NGRAM_MIN} or more times.</div>'
return (f'<div class="ng-panel"><div class="ng-title">{title}'
f'<span class="ng-hint">{hint}</span></div>{rows}</div>')
def build_ngram_view(st, tg) -> str:
"""Before/after bigrams and trigrams of the keyword (or of every word a pattern matches in)."""
if tg["kind"] == "pattern":
word, pq, pex = "", tg["q"], tg["exact"]
layers = [(tg["compiled"], tg["color"], PATTERN_TINTS[tg["i"]])]
else:
word, pq, pex, layers = tg["word"], None, False, []
res = _ngram_counts(st["key"], word, pq, pex, st["section"], st["language"], bool(st["certain"]))
n, top = res["n"], res["top"]
sub = (f'<span class="ng-sub">{n:,} occurrences · adjacent words in the same line '
f'· listed from {NGRAM_MIN}×</span>')
if not n:
body = '<div class="ng-none">No occurrences in this scope.</div>'
else:
body = ('<div class="ng-grid">'
+ _ngram_panel("Before · bigrams", "1 word before + keyword", top["b2"], n, 1, layers)
+ _ngram_panel("After · bigrams", "keyword + 1 word after", top["a2"], n, 0, layers)
+ _ngram_panel("Before · trigrams", "2 words before + keyword", top["b3"], n, 2, layers)
+ _ngram_panel("After · trigrams", "keyword + 2 words after", top["a3"], n, 0, layers)
+ '</div>')
return f'<details class="ng-wrap" open><summary>Neighbouring bigrams & trigrams{sub}</summary>{body}</details>'
def _coll_sorted(st, tab):
if st["csort"] and st["csort"] in tab.columns:
tab = tab.sort_values([st["csort"], "collocate"], ascending=[st["casc"], True], kind="stable")
return tab
def build_collocates_view(st) -> str:
v = VIEWS[st["key"]]
excl = st["excl"] and st["window"] > 1
tg = _target(st)
plabel = tg["label"] if tg and tg["kind"] == "pattern" else ""
params = parameter_line(v, int(st["window"]), st["section"], st["language"], excl,
st["certain"], st["positional"], pattern_label=plabel)
tab, rob = _coll(st, use_target=True)
head = _mode_heading(st, "Collocates")
pline = f'<div class="param-line">{_esc(params)}</div>'
ngrams = build_ngram_view(st, tg)
if tab.empty:
return head + pline + ngrams + '<i style="color:#999">No collocate passes the thresholds with these settings.</i>'
cols = COLL_COLS + (POS_COLS if st["positional"] else [])
tab = _coll_sorted(st, tab)
start, end, _ = paginate(len(tab), st["cpage"], COLL_PAGE)
label = f"{start + 1}β{end} of {len(tab)} collocates"
ths = '<th>#</th><th>Collocate</th>'
for c, h, _f, title in cols:
arrow = (" β²" if st["casc"] else " βΌ") if st["csort"] == c else ""
ths += f'<th class="sortable" title="{_esc(title)}" onclick="appAction(\'csort\',\'{c}\')">{h}{arrow}</th>'
ths += '<th title="Passes the same thresholds in each transliteration">' + " ".join(SOURCES) + "</th>"
rows = ""
for i, (_, r) in enumerate(tab.iloc[start:end].iterrows(), start=start + 1):
w2 = r["collocate"]
dim = ' class="dim" title="Co-occurs in fewer than 3 folios"' if r["dim"] else ""
tds = "".join(f'<td class="num">{f.format(r[c])}</td>' for c, _h, f, _t in cols)
rows += (f'<tr{dim}><td class="muted">{i}</td>'
f'<td><a class="coll-word" onclick="collocateFilter(\'{_js(w2)}\')" '
f'title="Open the concordance filtered to lines with both words">{_esc(w2)}</a>'
f' <a class="coll-arrow" title="Select {_esc(w2)}" onclick="selectWord(\'{_js(w2)}\')">↗</a>'
f'<span class="eva-sub">{_esc(w2)}</span>'
f'{"<span class=fam-tag>in family</span>" if plabel and r["in_family"] else ""}'
f'</td>{tds}<td>{_rob_dots(rob, w2)}</td></tr>')
reset = (' · <a class="pg" onclick="appAction(\'csort\',\'\')">rank order</a>'
if st["csort"] else "")
return (head + pline + ngrams +
f'<div class="count-line">{label}{reset}</div>'
f'<div class="table-wrap"><table class="coll-table"><thead><tr>{ths}</tr></thead>'
f'<tbody>{rows}</tbody></table></div>'
+ _pager("cpage", start, end, len(tab), COLL_PAGE, st["cpage"]))
def _ctx(words):
out = []
for w, flagged in words:
cls = ' class="unc"' if flagged else ""
out.append(f'<span{cls}>{_esc(w)}</span>')
return " ".join(out)
def _neighbour_html(item, label):
if item is None:
return ""
ltype, words = item
tag = f'<span class="locus-tag">{LOCUS_TAGS.get(ltype, "")}</span>' if ltype != "P" else ""
return (f'<div class="kwic-nb"><span class="nb-lbl">{label}</span>{tag}'
f'<span class="nb-text">{_esc(" ".join(words))}</span></div>')
def _conc_df(st):
"""The concordance exactly as the view shows it (shared with spec F exports)."""
v = VIEWS[st["key"]]
pos = None if st["position"] == "Any" else st["position"]
tg = _target(st)
pat = tg["compiled"] if tg and tg["kind"] == "pattern" else None
return concordance(v, st["word"], int(st["window"]), section=st["section"],
language=st["language"], position=pos,
with_word=st["with_word"] or None, certain_only=st["certain"],
sort=st["ksort"], pattern=pat, cluster=st.get("kclus"))
def build_concordance_view(st) -> str:
v = VIEWS[st["key"]]
tg = _target(st)
pat = tg["compiled"] if tg and tg["kind"] == "pattern" else None
conc = _conc_df(st)
kw_layers = [(pat, tg["color"], PATTERN_TINTS[tg["i"]])] if pat is not None else []
start, end, label = paginate(len(conc), st["kpage"], CONC_PAGE)
chip = ""
if st["with_word"]:
chip = (f'<span class="filter-chip">with <b>{_esc(st["with_word"])}</b> within Β±{st["window"]}'
f'<a onclick="appAction(\'clearfilter\',\'\')" title="Remove filter">×</a></span>')
elif st.get("kclus"):
side, ctx, node = st["kclus"]
seq = " ".join(list(ctx) + [node] if side == "L" else [node] + list(ctx))
chip = (f'<span class="filter-chip">sequence <b>{_esc(seq)}</b>'
f'<a onclick="appAction(\'clearfilter\',\'\')" title="Remove filter">×</a></span>')
head = _mode_heading(st, "Concordance", f'<span class="mode-count">{label}</span>{chip}')
def sort_link(key, text):
cls = "sort-on" if st["ksort"] == key else ""
return f'<a class="{cls}" onclick="appAction(\'ksort\',\'{key}\')">{text}</a>'
glyph = st.get("kglyph", True)
def disp_link(on, text):
cls = "sort-on" if glyph == on else ""
return f'<a class="{cls}" onclick="appAction(\'kglyph\',\'{1 if on else 0}\')">{text}</a>'
sorts = (f'<div class="sort-line"><span class="disp">Show: {disp_link(True, "Voynichese")} · '
f'{disp_link(False, "EVA")}</span>'
f'Sort: {sort_link("ms", "manuscript order")} · '
f'{sort_link("left", "left context")} · {sort_link("right", "right context")}</div>')
if conc.empty:
return head + sorts + '<i style="color:#999">No occurrences in this scope.</i>'
rows = ""
for _, r in conc.iloc[start:end].iterrows():
flags = ""
if r["UncertainBreak"]:
flags += '<span class="flag" title="Uncertain word break">,</span>'
if r["Alt"]:
flags += f'<span class="flag" title="Alternate reading: {_esc(r["Alt"])}">alt</span>'
if r["Illegible"]:
flags += '<span class="flag" title="Illegible glyph">?</span>'
prev, nxt = neighbour_lines(v, r["Folio"], int(r["Line"]))
rows += (
f'<details class="kwic"><summary>'
f'<span class="kl">{_ctx(r["left"])}</span>'
f'<span class="kk" title="{_esc(r["keyword"])}">'
f'{_marked(r["keyword"], kw_layers) if kw_layers else _esc(r["keyword"])}</span>'
f'<span class="kr">{_ctx(r["right"])}</span>'
f'<span class="km"><a onclick="event.preventDefault();navigateToFolio(\'{_js(r["Folio"])}\')">{r["Folio"]}</a>'
f'.{r["Line"]}</span>'
f'<span class="km">{_section_badge(r["Section"])}</span>'
f'<span class="km">{_esc(r["Language"] or "β")}</span>'
f'<span class="km">{r["LinePos"]}</span>'
f'<span class="km">{flags}</span>'
f'</summary>{_neighbour_html(prev, "prev")}{_neighbour_html(nxt, "next")}'
f'{"" if prev or nxt else "<div class=kwic-nb>No other lines on this page.</div>"}</details>')
hdr = ('<div class="kwic kwic-head"><span class="kl">Left</span><span class="kk">Keyword</span>'
'<span class="kr">Right</span><span class="km">Folio.line</span><span class="km">Section</span>'
'<span class="km">Lang</span><span class="km">Position</span><span class="km">Flags</span></div>')
return (head + sorts + f'<div class="conc{" glyphs" if glyph else ""}">' + hdr + rows + '</div>'
+ _pager("kpage", start, end, len(conc), CONC_PAGE, st["kpage"]))
# ββ HTML builders: search (spec D) ββββββββββββββββββββββββββββββββββββββββββββ
def _cmp_chart(groups, series, label=lambda g: g, height=64) -> str:
"""Grouped bars, one bar per active pattern in its colour, on one shared scale (D6)."""
vals = [d.get(g, 0.0) for _c, d in series for g in groups]
mx = max(vals + [0.0]) or 1.0
html = '<div class="cmp">'
for g in groups:
bars = ""
for col, d in series:
val = d.get(g, 0.0)
h = max(2, int(val / mx * height)) if val else 2
bars += (f'<div class="cmp-bar" title="{_esc(label(g))}: {val:.1f} per 1,000 tokens" '
f'style="height:{h}px;background:{col if val else "#e8e0ce"}"></div>')
html += (f'<div class="cmp-group"><div class="cmp-bars" style="height:{height}px">{bars}</div>'
f'<div class="cmp-lbl">{_esc(label(g))}</div></div>')
return html + "</div>"
def _folio_strips(v, series_folio, height=22) -> str:
"""One row per pattern: a 1px bar per folio, on one shared scale (D6)."""
mx = max([c for _col, d in series_folio for c in d.values()] + [0]) or 1
rows = ""
for col, d in series_folio:
bars = ""
for f in v.folios:
c = d.get(f, 0)
h = max(1, int(c / mx * height)) if c else 1
bars += (f'<div title="{f}: {c}" style="width:1px;height:{h}px;flex-shrink:0;'
f'background:{col if c else "#eee4cf"}"></div>')
rows += f'<div class="strip" style="height:{height}px">{bars}</div>'
return f'<div class="strips">{rows}</div>'
def build_search_view(st) -> str:
v = VIEWS[st["key"]]
pats = _patterns(st)
head = (f'<div class="mode-head"><span class="mode-title">Search</span>'
f'<span class="mode-count">{len(pats)} pattern{"s" if len(pats) != 1 else ""} · '
f'{_esc(v.source)}, {"labels on" if v.include_labels else "labels off"}, '
f'{"all sections" if st["section"] == "All" else _section_label(st["section"])}, '
f'{"A+B" if st["language"] == "All" else st["language"]}</span></div>')
cards, results = "", []
for (i, label, _c, col, tint), p in zip(pats, st["patterns"]):
r = _pattern_result(st, p)
results.append((col, r))
per_src = " · ".join(
f'{s} {_search_one(view_key(s, v.include_labels), p["q"], p["exact"], st["section"], st["language"])["tokens"]:,}'
for s in SOURCES)
words = "".join(
f'<span class="sw-chip" onclick="selectWord(\'{_js(w)}\')" title="Select {_esc(w)}">'
f'<span class="sw-wd"><span class="sw-w">{_marked(w, [(compile_pattern(p["q"], p["exact"]), col, tint)])}</span>'
f'<span class="sw-eva">{_esc(w)}</span></span>'
f'<span class="sw-n">{c}</span>'
f'<span class="coll-arrow" title="Concordance for {_esc(label)}" '
f'onclick="event.stopPropagation();appAction(\'pconc\',\'{i}\')">↗</span></span>'
for w, c in r["top"]) or '<i style="color:#999">No matches in this scope.</i>'
more = (f'<div class="muted" style="font-size:11px;margin-top:4px">Top {len(r["top"])} of {r["types"]:,} words</div>'
if r["types"] > len(r["top"]) else "")
cards += f"""
<div class="pcard" style="border-left-color:{col}">
<div class="pcard-head"><span class="pq" style="color:{col}">{_esc(label)}</span>
<span class="pstat"><b>{r["tokens"]:,}</b> tokens · <b>{r["types"]:,}</b> words · {r["share"]:.1%} of tokens</span></div>
<div class="pcard-src">{per_src}</div>
<div class="pcard-links"><a onclick="appAction('pconc','{i}')">Concordance →</a>
<a onclick="appAction('pcoll','{i}')">Collocates →</a></div>
<div class="sw-list">{words}</div>{more}
</div>"""
secs = [s for s in SECTION_ORDER if any(s in r["by_section"] for _c, r in results)]
legend = "".join(f'<span class="lg"><span class="lg-dot" style="background:{col}"></span>{_esc(label)}</span>'
for (_i, label, _c, col, _t) in pats)
charts = f"""
<div class="cmp-wrap">
<div class="cmp-legend">{legend}</div>
<div class="cmp-title">Rate by section, per 1,000 tokens</div>
{_cmp_chart(secs, [(c, r["by_section"]) for c, r in results], lambda g: _section_label(g)[:6])}
<div class="cmp-row">
<div><div class="cmp-title">By Currier language</div>
{_cmp_chart(["A", "B"], [(c, r["by_language"]) for c, r in results])}</div>
<div><div class="cmp-title">By line position</div>
{_cmp_chart(["initial", "medial", "final", "alone"], [(c, r["by_linepos"]) for c, r in results])}</div>
</div>
<div class="cmp-title">Hits per folio</div>
{_folio_strips(v, [(c, r["per_folio"]) for c, r in results])}
</div>"""
glyph = st.get("kglyph", True)
show = f'<div class="sort-line" style="text-align:right">{_script_switch(st, "")}</div>'
return head + show + f'<div class="srch{" glyphs" if glyph else ""}">{cards}</div>' + charts
def _script_switch(st, cls="disp") -> str:
"""'Show: Voynichese Β· EVA', shared by every view through st["kglyph"] (spec E, E2)."""
glyph = st.get("kglyph", True)
def link(on, text):
c = "sort-on" if glyph == on else ""
return f'<a class="{c}" onclick="appAction(\'kglyph\',\'{1 if on else 0}\')">{text}</a>'
return f'<span class="{cls}">Show: {link(True, "Voynichese")} · {link(False, "EVA")}</span>'
def build_pattern_chips(st) -> str:
chips = ""
for p, (i, label, _c, col, _t) in zip(st["patterns"], _patterns(st)):
n = _pattern_result(st, p)["tokens"]
chips += (f'<span class="pchip" style="border-color:{col}">'
f'<span class="pchip-q" style="color:{col}">{_esc(label)}</span>'
f'<span class="pchip-n">{n:,}</span>'
f'<a class="pchip-x" title="Remove {_esc(label)}" onclick="appAction(\'rmpat\',\'{i}\')">×</a></span>')
msg = f'<div class="smsg">{_esc(st["smsg"])}</div>' if st.get("smsg") else ""
return f'<div class="pchips">{chips}</div>{msg}'
def build_keyboard() -> str:
keys = "".join(
f'<button type="button" class="gkey" onmousedown="event.preventDefault()" '
f'onclick="glyphKey(\'{k}\')" aria-label="{k}"><span class="gk-g">{k}</span>'
f'<span class="gk-l">{k}</span></button>' for k in EVA_KEYS)
for k, name, short in (("*", "one or more glyphs", "any"), ("^", "word start", "start"),
("$", "word end", "end")):
keys += (f'<button type="button" class="gkey gk-sym" onmousedown="event.preventDefault()" '
f'onclick="glyphKey(\'{k}\')" title="{name}" aria-label="{name}">'
f'<span class="gk-g">{k}</span><span class="gk-l">{short}</span></button>')
keys += ('<button type="button" class="gkey gk-sym gk-wide" onmousedown="event.preventDefault()" '
'onclick="glyphKey(\'BS\')" aria-label="Backspace"><span class="gk-g">⌫</span>'
'<span class="gk-l">delete</span></button>'
'<button type="button" class="gkey gk-sym gk-wide" onmousedown="event.preventDefault()" '
'onclick="glyphKey(\'CLR\')" aria-label="Clear"><span class="gk-g">✕</span>'
'<span class="gk-l">clear</span></button>')
return f'<div class="gkeys">{keys}</div>'
# ββ Spec F: export ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
EXPORT_DIR = Path(tempfile.gettempdir()) / "voynich_exports"
EXPORT_DIR.mkdir(parents=True, exist_ok=True)
EXPORT_TTL = 3600 # F7: files older than an hour are removed at the next export
BIG_BYTES = 20_000_000 # F8: menu labels show a size above this
EXPORT_OPTIONS = {
"page": [("page_txt", "Folio text (TXT)"), ("page_freq", "Folio word counts (CSV)")],
"conc": [("conc_csv", "Concordance (CSV)"), ("conc_kwic", "Concordance, aligned KWIC (TXT)")],
"coll": [("coll_csv", "Collocates (CSV)"), ("ngram_csv", "Bigrams & trigrams (CSV)"),
("coll_zip", "Collocates + n-grams (ZIP)")],
"search": [("search_csv", "Search results (CSV)")],
}
TOKEN_OPTIONS = [("tok_csv", "Whole view tokens (CSV)"), ("tok_parquet", "Whole view tokens (Parquet)")]
def _export_menu(st) -> str:
v = VIEWS[st["key"]]
opts = list(EXPORT_OPTIONS.get(st["mode"], [])) + TOKEN_OPTIONS
items = ""
for kind, label in opts:
if kind.startswith("tok"):
est = int(v.folio_token_counts.sum() * 70) # rough CSV bytes per token
if est > BIG_BYTES:
label += f" Β· ~{est / 1e6:.0f} MB"
items += (f'<button type="button" class="tb-mi" '
f'onclick="this.closest(\'details\').open=false;appAction(\'export\',\'{kind}\')">'
f'{_esc(label)}</button>')
return (f'<details class="tb-exp"><summary title="Download what this view shows">Export ▾</summary>'
f'<div class="tb-menu">{items}</div></details>')
def _target_name(st) -> str:
tg = _target(st)
if tg is None:
return ""
return tg["label"] if tg["kind"] == "pattern" else tg["word"]
def _export_settings(st, kind) -> dict:
"""F2/F4: every setting the exported result depends on, in reading order."""
v = VIEWS[st["key"]]
out = {"section": st["section"], "language": st["language"]}
if kind.startswith("page"):
out["folio"] = st["folio"]
elif kind.startswith("conc"):
tg = _target(st)
out["pattern" if tg and tg["kind"] == "pattern" else "word"] = _target_name(st)
out["sort"] = {"ms": "manuscript order", "left": "left context", "right": "right context"}[st["ksort"]]
out["line position"] = None if st["position"] == "Any" else st["position"]
out["certain readings only"] = bool(st["certain"])
if st["with_word"]:
out["filter"] = f'with {st["with_word"]} within Β±{st["window"]}'
elif st.get("kclus"):
side, ctx, node = st["kclus"]
out["filter"] = "sequence " + " ".join(list(ctx) + [node] if side == "L" else [node] + list(ctx))
elif kind.startswith(("coll", "ngram")):
tg = _target(st)
out["pattern" if tg and tg["kind"] == "pattern" else "word"] = _target_name(st)
excl = st["excl"] and st["window"] > 1
out["parameters"] = parameter_line(v, int(st["window"]), st["section"], st["language"], excl,
st["certain"], st["positional"],
pattern_label=_target_name(st) if tg and tg["kind"] == "pattern" else "")
if st["csort"]:
out["sort"] = f'{st["csort"]} {"ascending" if st["casc"] else "descending"}'
if kind != "coll_csv":
out["n-grams"] = f"adjacent words in the same line, top {NGRAM_TOP} per list, count >= {NGRAM_MIN}"
elif kind.startswith("search"):
out["patterns"] = "; ".join(_pattern_label(p) for p in st["patterns"])
return out
def _ngram_res(st):
tg = _target(st)
if tg["kind"] == "pattern":
return _ngram_counts(st["key"], "", tg["q"], tg["exact"], st["section"], st["language"], bool(st["certain"]))
return _ngram_counts(st["key"], tg["word"], None, False, st["section"], st["language"], bool(st["certain"]))
def build_export(st, kind, now=None):
"""Return (bytes, file name) for one export kind of the current state (F3)."""
now = now or datetime.now().astimezone()
v = VIEWS[st["key"]]
head = ex.export_header(v, _export_settings(st, kind), now)
fname = lambda view_name, target, ext: ex.export_filename(view_name, target, v.source, now, ext) # noqa: E731
if kind == "page_txt":
return ex.write_text(ex.page_text(v, st["folio"]), head), fname("page", st["folio"], "txt")
if kind == "page_freq":
return ex.write_csv(ex.page_freq(v, st["folio"]), head), fname("pagefreq", st["folio"], "csv")
if kind in ("conc_csv", "conc_kwic"):
rows = ex.concordance_rows(_conc_df(st))
if kind == "conc_csv":
return ex.write_csv(rows, head), fname("concordance", _target_name(st), "csv")
return ex.write_text(ex.kwic_text(rows), head), fname("kwic", _target_name(st), "txt")
if kind in ("coll_csv", "ngram_csv", "coll_zip"):
tab, rob = _coll(st, use_target=True)
coll = ex.write_csv(ex.collocate_rows(_coll_sorted(st, tab), rob, st["positional"]), head)
ngr = ex.write_csv(ex.ngram_rows(_ngram_res(st)), head)
if kind == "coll_csv":
return coll, fname("collocates", _target_name(st), "csv")
if kind == "ngram_csv":
return ngr, fname("ngrams", _target_name(st), "csv")
files = {fname("collocates", _target_name(st), "csv"): coll,
fname("ngrams", _target_name(st), "csv"): ngr}
return ex.write_zip(files, head), fname("collocates", _target_name(st), "zip")
if kind == "search_csv":
pats = [(_pattern_label(p), compile_pattern(p["q"], p["exact"])) for p in st["patterns"]]
by_src = {s: VIEWS[view_key(s, v.include_labels)] for s in SOURCES}
df = ex.search_rows(v, pats, st["section"], st["language"], by_src)
target = "+".join(_pattern_label(p) for p in st["patterns"])
return ex.write_csv(df, head), fname("search", target, "csv")
if kind in ("tok_csv", "tok_parquet"):
df = ex.scoped_tokens(v, st["section"], st["language"])
target = "all" if st["section"] == "All" else _section_label(st["section"])
if st["language"] != "All":
target += f"-{st['language']}"
if kind == "tok_csv":
return ex.write_csv(df, head), fname("tokens", target, "csv")
return ex.write_parquet(df, head), fname("tokens", target, "parquet")
raise ValueError(kind)
def _write_export(data: bytes, name: str) -> Path:
now = time.time()
for old in EXPORT_DIR.glob("*/*"):
try:
if now - old.stat().st_mtime > EXPORT_TTL:
old.unlink()
old.parent.rmdir()
except OSError:
pass
d = EXPORT_DIR / uuid.uuid4().hex
d.mkdir()
p = d / name
p.write_bytes(data)
return p
def _download_html(dl) -> str:
if not dl:
return ""
url = "/gradio_api/file=" + dl["path"]
return (f'<div class="dl-bar">Exported <b>{_esc(dl["name"])}</b> ({dl["size"]}) · '
f'<a class="dl-link" data-dl="{dl["id"]}" href="{_esc(url)}" download="{_esc(dl["name"])}">'
f'Download {_esc(dl["name"])}</a></div>')
def _size(n: int) -> str:
return f"{n / 1e6:.1f} MB" if n >= 1e6 else f"{max(1, round(n / 1e3))} KB"
# ββ Render ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _main_html(st):
if st["mode"] == "search" and st["patterns"]:
return f'<div class="mode-body">{build_search_view(st)}</div>'
if st["mode"] == "coll" and _target(st):
return f'<div class="mode-body">{build_collocates_view(st)}</div>'
if st["mode"] == "conc" and _target(st):
return f'<div class="mode-body">{build_concordance_view(st)}</div>'
layers = [(c, col, tint) for (_i, _l, c, col, tint) in _patterns(st)]
return build_folio_page(VIEWS[st["key"]], st["folio"], st["word"], layers)
def _detail(st):
v = VIEWS[st["key"]]
word = (st["word"] or "").strip()
summary = build_collocate_summary(st) if word and word in v.global_freq else ""
return build_detail(v, st["folio"], word, summary)
MODE_TABS = (("page", "Page"), ("coll", "Collocates"), ("conc", "Concordance"), ("search", "Search"))
def build_topbar(st, enabled, msg="", dl=None) -> str:
"""Spec E, E1: every global control in one bar over the main pane."""
v = VIEWS[st["key"]]
tabs = "".join(
f'<button type="button" class="tb-tab{" on" if st["mode"] == m else ""}"'
f'{"" if enabled[m] else " disabled"} onclick="appAction(\'mode\',\'{m}\')">{name}</button>'
for m, name in MODE_TABS)
glyph = st.get("kglyph", True)
script = (f'<span class="tb-seg" title="How words are drawn">'
f'<button type="button" class="{"on" if glyph else ""}" onclick="appAction(\'kglyph\',\'1\')">'
f'<span class="tb-voy">qokedy</span> Voynichese</button>'
f'<button type="button" class="{"" if glyph else "on"}" onclick="appAction(\'kglyph\',\'0\')">EVA</button></span>')
src = "".join(f'<option value="{s_}"{" selected" if s_ == v.source else ""} title="{_esc(SOURCE_NAMES[s_])}">'
f'{_esc(SOURCE_NAMES[s_])}</option>' for s_ in SOURCES)
secs = "".join(f'<option value="{_esc(val)}"{" selected" if val == st["section"] else ""}>{_esc(lbl)}</option>'
for lbl, val in _section_choices(v))
labels = (f'<label class="tb-check" title="Count label, circle and radius text in the statistics">'
f'<input type="checkbox"{" checked" if v.include_labels else ""} '
f'onchange="appAction(\'labels\', this.checked ? \'1\' : \'0\')"> Labels</label>')
seq = _section_folios(v, st["section"])
f = st["folio"]
pos = (f"{seq.index(f) + 1}/{len(seq)}" if f in seq else f"{v.folio_idx[f] + 1}/{len(v.folios)}")
folio = (f'<span class="tb-folio"><button type="button" class="tb-arrow" title="Previous folio" '
f'onclick="appAction(\'nav\',\'-1\')">‹</button>'
f'<input class="tb-fin" type="text" value="{_esc(f)}" aria-label="Folio β type one to jump" '
f'title="Type a folio and press Enter" enterkeyhint="go" autocomplete="off" spellcheck="false" '
f'onfocus="this.select()" onchange="navigateToFolio(this.value)">'
f'<span class="tb-pos">{pos}</span>'
f'<button type="button" class="tb-arrow" title="Next folio" '
f'onclick="appAction(\'nav\',\'1\')">›</button></span>')
hits = ""
if st["patterns"]:
dis = "" if _hit_folios(st) else " disabled"
hits = (f'<span class="tb-hits" title="Folios with a pattern hit">'
f'<button type="button"{dis} onclick="appAction(\'hit\',\'-1\')">◀ hit</button>'
f'<button type="button"{dis} onclick="appAction(\'hit\',\'1\')">hit ▶</button></span>')
note = f'<div class="tb-msg">{_esc(msg)}</div>' if msg else ""
return (f'<div class="topbar"><div class="tb-row">{tabs}<span class="tb-sep"></span>{script}{_export_menu(st)}'
f'<select class="tb-sel" aria-label="Transliteration" onchange="appAction(\'source\', this.value)">{src}</select>'
f'{labels}'
f'<select class="tb-sel" aria-label="Section" onchange="appAction(\'section\', this.value)">{secs}</select>'
f'<span class="tb-sep"></span>{folio}{hits}</div>{note}{_download_html(dl)}</div>')
def render(st):
v = VIEWS[st["key"]]
if st.get("pidx") is not None and st["pidx"] >= len(st["patterns"]):
st["pidx"] = None
has_target = _target(st) is not None
if (st["mode"] in ("coll", "conc") and not has_target) or (st["mode"] == "search" and not st["patterns"]):
st["mode"] = "page"
enabled = {"page": True, "coll": has_target, "conc": has_target, "search": bool(st["patterns"])}
msg, st["msg"] = st["msg"], ""
dl, st["dl"] = st.get("dl"), None # F7: the fallback link lasts until the next action
chips = build_pattern_chips(st)
st["smsg"] = ""
main = build_topbar(st, enabled, msg, dl) + f'<div class="ms-content">{_main_html(st)}</div>'
return (st, main, build_freq_table(v, st["folio"]), _detail(st), build_folio_stats(v, st["folio"]),
chips, build_corpus_stats(v))
def _reset_pages(st):
st["cpage"] = st["kpage"] = 0
return st
# ββ Callbacks βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def navigate(st, delta):
st = dict(st)
v = VIEWS[st["key"]]
seq = _section_folios(v, st["section"]) or v.folios
f = st["folio"]
st["folio"] = seq[max(0, min(len(seq) - 1, seq.index(f) + delta))] if f in seq else seq[0]
st["mode"] = "page" # C2
return render(st)
def _resolve_folio(v, target: str):
t = (target or "").split("|")[0].strip()
if not t:
return None
if not t.lower().startswith("f"):
t = "f" + t
lookup = {f.lower(): f for f in v.folios}
return lookup.get(t.lower())
def navigate_to(st, target):
"""Jump box, folio chips and concordance folios. Unknown IDs keep the current page (A AC10)."""
st = dict(st)
v = VIEWS[st["key"]]
nf = _resolve_folio(v, target)
shown = (target or "").split("|")[0].strip()
if nf is None:
if shown:
st["msg"] = f'Folio "{shown}" not found'
return render(st)
if st["section"] != "All" and v.folio_section.get(nf) != st["section"]:
st["section"] = "All"
st["folio"] = nf
st["mode"] = "page" # C2
return render(st)
def change_section(st, section):
st = _reset_pages(dict(st))
v = VIEWS[st["key"]]
st["section"] = section
seq = _section_folios(v, section)
if st["folio"] not in seq and seq:
st["folio"] = seq[0]
return render(st)
def change_view(st, source, include_labels):
"""Transliteration / label toggle: re-render everything from the new view (A AC8, C AC12)."""
st = _reset_pages(dict(st))
st["key"] = view_key(source, include_labels)
v = VIEWS[st["key"]]
if st["folio"] not in v.folio_idx:
st["folio"] = v.folios[0]
if st["section"] != "All" and st["section"] not in v.sections_present():
st["section"] = "All"
return render(st)
def on_word(st, word):
st = _reset_pages(dict(st))
word = (word or "").split("|")[0].strip()
st["pidx"] = None
if word == st["word"]:
return render(st)
st["word"] = word
st["with_word"] = ""
st["kclus"] = None
st["csort"] = ""
return render(st)
def on_settings(st, window, language, excl, positional, certain, position):
st = _reset_pages(dict(st))
st.update(window=int(window), language=language, excl=bool(excl),
positional=bool(positional), certain=bool(certain), position=position)
return render(st)
def set_mode(st, mode):
st = dict(st)
st["mode"] = mode # render() falls back to Page if the mode has no target
return render(st)
def add_pattern(st, query, exact):
"""Commit the search box as the next pattern (D4). Invalid input keeps the previous results."""
st = dict(st)
try:
compile_pattern(query, bool(exact))
except PatternError:
st["smsg"] = ERROR_TEXT
return (*render(st), gr.update())
label = canonical(query, bool(exact))
if any(_pattern_label(p) == label for p in st["patterns"]):
st["smsg"] = f"{label} is already active"
return (*render(st), gr.update())
if len(st["patterns"]) >= MAX_PATTERNS:
st["smsg"] = "Remove a pattern to add another"
return (*render(st), gr.update())
st["patterns"] = st["patterns"] + [{"q": (query or "").strip().lower(), "exact": bool(exact)}]
st["mode"] = "search"
return (*render(st), gr.update(value=""))
def hit_step(st, delta):
"""β hit / hit βΆ: the previous or next folio with a match, wrapping at the ends (D5)."""
st = dict(st)
hits = _hit_folios(st)
if not hits:
return render(st)
v = VIEWS[st["key"]]
cur = v.folio_idx.get(st["folio"], -1)
if delta > 0:
nxt = [f for f in hits if v.folio_idx[f] > cur]
st["folio"] = nxt[0] if nxt else hits[0]
else:
prv = [f for f in hits if v.folio_idx[f] < cur]
st["folio"] = prv[-1] if prv else hits[-1]
st["mode"] = "page"
return render(st)
def on_action(st, value):
"""JS bridge: 'action|arg|nonce' from links inside the main pane and sidebar."""
parts = (value or "").split("|")
if len(parts) < 2:
return render(dict(st))
action, arg = parts[0], parts[1]
st = dict(st)
if action == "mode":
return set_mode(st, arg)
# Spec E, E1: top-bar controls.
if action == "nav":
return navigate(st, int(arg))
if action == "hit":
return hit_step(st, int(arg))
if action == "section":
return change_section(st, arg)
if action == "source":
return change_view(st, arg, VIEWS[st["key"]].include_labels)
if action == "labels":
return change_view(st, VIEWS[st["key"]].source, arg == "1")
if action == "wmode": # sidebar link: the selected word drives the mode
st["pidx"] = None
return set_mode(st, arg)
if action == "filter": # C5: collocate click β filtered concordance
st.update(mode="conc", with_word=arg, kclus=None, kpage=0)
elif action == "wfilter": # sidebar word collocate
st.update(pidx=None, mode="conc", with_word=arg, kclus=None, kpage=0)
elif action == "rmpat": # D4: remove a pattern chip
i = int(arg)
st["patterns"] = [p for k, p in enumerate(st["patterns"]) if k != i]
if st.get("pidx") == i:
st["pidx"] = None
elif st.get("pidx") is not None and st["pidx"] > i:
st["pidx"] -= 1
elif action in ("pconc", "pcoll"): # D7, D7a: a pattern drives Concordance or Collocates
st.update(pidx=int(arg), with_word="", kclus=None, kpage=0, cpage=0, csort="",
mode="conc" if action == "pconc" else "coll")
elif action == "clearfilter":
st.update(with_word="", kclus=None, kpage=0)
elif action == "ngram": # spec E, E6: bigram/trigram row β filtered concordance
side, node, *ctx = arg.split(",")
st.update(mode="conc", with_word="", kclus=[side, ctx, node], kpage=0)
elif action == "export": # spec F
try:
data, name = build_export(st, arg)
p = _write_export(data, name)
st["dl"] = {"path": str(p), "name": name, "size": _size(len(data)), "id": p.parent.name}
except Exception as exc: # never lose the view over a failed export
print(f"Export {arg} failed: {exc!r}")
st["msg"] = "Export failed; please try again"
elif action == "kglyph": # concordance display: Voynichese glyphs vs plain EVA
st["kglyph"] = arg != "0"
elif action == "kpage":
st["kpage"] = max(0, int(arg))
elif action == "cpage":
st["cpage"] = max(0, int(arg))
elif action == "ksort":
st.update(ksort=arg, kpage=0)
elif action == "csort":
if arg and st["csort"] == arg:
st["casc"] = not st["casc"]
else:
st.update(csort=arg, casc=False)
st["cpage"] = 0
return render(st)
def toggle_table(visible):
new_vis = not visible
return new_vis, gr.update(visible=new_vis), gr.update(value="Hide table" if new_vis else "Frequency table")
def toggle_corpus_stats(visible):
new_vis = not visible
return new_vis, gr.update(visible=new_vis), gr.update(value="Hide corpus stats" if new_vis else "Corpus statistics")
def _section_choices(v):
return [("All sections", "All")] + [(_section_label(s), s) for s in v.sections_present()]
def on_load():
return render(_initial_state())
# ββ JS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
JS = """
// The manuscript styling is designed for light mode; Gradio's dark theme washes it out.
(function () {
const u = new URL(window.location.href);
if (u.searchParams.get('__theme') !== 'light') {
u.searchParams.set('__theme', 'light');
window.location.replace(u.toString());
}
})();
function _findField(elemId) {
let el = document.querySelector('#' + elemId + ' textarea, #' + elemId + ' input');
if (el) return el;
const wrap = document.getElementById(elemId);
if (wrap) {
if (wrap.matches('textarea, input')) return wrap;
el = wrap.querySelector('textarea, input');
if (el) return el;
}
el = document.querySelector('[data-testid="' + elemId + '"] textarea, [data-testid="' + elemId + '"] input');
return el || null;
}
function _gradioSet(elemId, value) {
const el = _findField(elemId);
if (!el) { console.warn('[bridge] no field found for', elemId); return false; }
const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, 'value').set;
setter.call(el, value);
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
return true;
}
function _send(elemId, value) {
// A nonce makes repeated clicks on the same target still fire a change event.
const v = value + '|' + Date.now();
if (!_gradioSet(elemId, v)) setTimeout(() => _gradioSet(elemId, v), 120);
}
// On a phone the page and the sidebar are stacked, so whatever a tap changes can be
// off-screen. Scroll to it once Gradio has re-rendered it.
function _narrow() { return window.matchMedia('(max-width: 900px)').matches; }
function _revealAfterUpdate(elemId) {
if (!_narrow()) return;
const el = document.getElementById(elemId);
if (!el) return;
// Wait until the re-render has settled, so the scroll lands where the content ends up.
let timer = null;
const obs = new MutationObserver(() => {
clearTimeout(timer);
timer = setTimeout(() => {
obs.disconnect();
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}, 300);
});
obs.observe(el, { childList: true, subtree: true, characterData: true });
setTimeout(() => obs.disconnect(), 8000);
}
document.addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
const t = b.textContent.trim();
if (t === 'Add') _revealAfterUpdate('folio-col');
}, true);
window.selectWord = function(word) {
_revealAfterUpdate('detail-panel');
document.querySelectorAll('.word').forEach(el => {
el.style.outline = '';
if (el.textContent.trim() === word) el.style.outline = '2px solid #2980b9';
});
_send('word-selector', word);
};
// Spec D glyph keyboard: insert at the cursor of the search box.
window.glyphKey = function(k) {
const el = _findField('search-box');
if (!el) return;
let v = el.value || '';
let a = (el.selectionStart ?? v.length), b = (el.selectionEnd ?? v.length);
if (k === 'CLR') { v = ''; a = 0; }
else if (k === 'BS') { if (a === b && a > 0) a -= 1; v = v.slice(0, a) + v.slice(b); }
else { v = v.slice(0, a) + k + v.slice(b); a += k.length; }
const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, v);
el.dispatchEvent(new Event('input', { bubbles: true }));
try { el.setSelectionRange(a, a); } catch (e) {}
};
document.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && e.target.closest && e.target.closest('#search-box')) _revealAfterUpdate('folio-col');
}, true);
window.navigateToFolio = function(folio) { _revealAfterUpdate('folio-col'); _send('folio-nav-target', folio); };
window.appAction = function(action, arg) {
if (!['rmpat', 'csort', 'ksort', 'clearfilter', 'kglyph', 'labels', 'export'].includes(action)) _revealAfterUpdate('folio-col');
_send('action-bridge', action + '|' + arg);
};
// Spec F, F7: start each export's download once, as soon as its link appears.
(function () {
const seen = new Set();
const fire = () => document.querySelectorAll('a.dl-link[data-dl]').forEach(a => {
if (seen.has(a.dataset.dl)) return;
seen.add(a.dataset.dl);
a.click();
});
new MutationObserver(fire).observe(document.documentElement, { childList: true, subtree: true });
})();
window.collocateFilter = function(word) { _revealAfterUpdate('folio-col'); _send('action-bridge', 'filter|' + word); };
"""
# ββ CSS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CSS = EVA_FONT_CSS + """
html, body { margin: 0 !important; height: 100%; overflow: hidden !important; }
footer { display: none !important; }
.gradio-container { max-width: 100% !important; padding: 0 !important; margin: 0 !important; }
#main-row {
position: fixed !important; inset: 0 !important;
display: flex !important; flex-direction: row !important; flex-wrap: nowrap !important;
gap: 0 !important; min-height: 0 !important; max-height: none !important;
overflow: hidden !important;
}
#folio-col { height: 100vh; height: 100dvh; overflow: hidden !important; }
#folio-col, #folio-col .block { padding: 0 !important; border: none !important; box-shadow: none !important; background: transparent !important; }
.ms-scroll { height: 100vh; height: 100dvh; overflow-y: auto; background: #fdf6e3; border-right: 1px solid #ddd; padding: 48px 64px; box-sizing: border-box; }
.ms-folio-id { text-align: right; font-size: 10px; color: #bbb; letter-spacing: 3px; text-transform: uppercase; margin-bottom: 24px; }
.ms-line { margin-bottom: 10px; line-height: 2; }
.ms-label { opacity: 0.8; border-left: 2px solid #e2d4b4; padding-left: 10px; }
.ms-label .word { font-size: 18px; }
.locus-tag { font-family: system-ui, sans-serif; font-size: 9px; color: #b09a6e; text-transform: uppercase; letter-spacing: 1px; margin-right: 8px; vertical-align: middle; }
.word { font-family: 'EVA Hand 1', 'Palatino Linotype', serif; font-size: 22px; color: #2c1810; padding: 0 2px; border-radius: 2px; cursor: pointer; display: inline-block; }
.word:hover { outline: 1px solid #c0392b; }
.word.hl { outline: 2px solid #2980b9; }
.section-badge { display: inline-block; border: 1px solid; border-radius: 3px; padding: 0 5px; font-size: 9px; letter-spacing: 0.5px; text-transform: uppercase; font-weight: 600; background: #fff; }
.nav-msg { color: #c0392b; font-size: 11px; margin-top: 4px; }
#sidebar-col { border-left: 1px solid #eee; overflow-y: auto !important; height: 100vh; height: 100dvh; min-height: 0 !important; }
#sidebar-col .block { border: none !important; box-shadow: none !important; }
.sidebar-pad { padding: 20px 16px 48px; }
.stats-section { background: #faf8f3; border: 1px solid #e8e0ce; border-radius: 6px; padding: 12px 14px; margin-bottom: 10px; }
.stats-heading { font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: 1.5px; color: #8b6f47; margin-bottom: 10px; }
.stats-subheading { font-size: 10px; color: #aaa; text-transform: uppercase; letter-spacing: 1px; margin: 10px 0 5px; }
.stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; margin-bottom: 2px; }
.stat-cell { background: #fff; border: 1px solid #e5ddd0; border-radius: 4px; padding: 6px 5px; text-align: center; }
.stat-value { font-size: 17px; font-weight: 700; color: #2c1810; line-height: 1.1; }
.stat-label { font-size: 9px; color: #aaa; text-transform: uppercase; letter-spacing: 0.5px; margin-top: 2px; }
.top-chip { display: inline-flex; align-items: center; gap: 4px; background: #fff; border: 1px solid #e5ddd0; border-radius: 3px; padding: 2px 7px 2px 5px; }
.top-chip-count { font-size: 11px; color: #8b6f47; font-variant-numeric: tabular-nums; }
.detail-section { background: #faf8f3; border: 1px solid #e8e0ce; border-radius: 5px; padding: 10px 12px; margin-bottom: 8px; }
.detail-label { font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: 1.2px; color: #8b6f47; margin-bottom: 8px; }
.detail-badge { background: #fff; border: 1px solid #e8e0ce; border-radius: 3px; padding: 1px 5px; font-size: 9px; font-weight: 400; color: #555; text-transform: none; letter-spacing: 0; }
.mini-stat { flex: 1; min-width: 44px; border: 1px solid #e8e0ce; border-radius: 4px; padding: 5px 4px; text-align: center; background: #fff; }
.mini-val { font-size: 16px; font-weight: 700; color: #2c1810; line-height: 1.1; }
.mini-lbl { font-size: 9px; color: #aaa; text-transform: uppercase; margin-top: 1px; }
.bigram-chip { display: inline-flex; align-items: center; gap: 2px; border: 1px solid; border-radius: 3px; padding: 2px 6px; cursor: pointer; background: #fff; }
.bigram-chip:hover { opacity: 0.75; }
.sim-chip { display: inline-flex; align-items: center; gap: 4px; border: 1px solid #ddd; border-radius: 3px; padding: 2px 6px; cursor: pointer; background: #fff; }
.sim-chip:hover { border-color: #8b6f47; }
.sim-dist { font-size: 9px; background: #f0ede8; border-radius: 2px; padding: 1px 3px; color: #8b6f47; font-weight: 600; }
.morph-chip { display: inline-flex; align-items: center; border: 1px solid #e0d8cc; border-radius: 3px; padding: 2px 6px; cursor: pointer; background: #fff; }
.morph-chip:hover { border-color: #8b6f47; }
.coll-chip { display: inline-flex; align-items: center; gap: 4px; border: 1px solid #d9c9a8; border-radius: 3px; padding: 2px 6px; cursor: pointer; background: #fff; }
.coll-chip:hover { border-color: #8b6f47; }
.coll-chip.dim { opacity: 0.5; }
.coll-score { font-size: 9px; color: #8b6f47; font-variant-numeric: tabular-nums; }
.coll-arrow { font-size: 11px; color: #2980b9; cursor: pointer; padding: 0 2px; }
.coll-link { font-size: 11px; color: #8b6f47; cursor: pointer; text-decoration: underline; }
.rdots { display: inline-flex; gap: 2px; }
.rdot { width: 6px; height: 6px; border-radius: 50%; border: 1px solid #8b6f47; display: inline-block; }
.rdot.on { background: #8b6f47; }
.mode-body { font-family: system-ui, sans-serif; }
.mode-head { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; margin-bottom: 6px; }
.mode-title { font-size: 10px; letter-spacing: 3px; text-transform: uppercase; color: #8b6f47; font-weight: 600; }
.mode-word { font-family: 'EVA Hand 1', serif; font-size: 28px; color: #2c1810; }
.mode-count, .count-line { font-size: 12px; color: #888; }
.param-line { font-family: monospace; font-size: 11px; color: #8b6f47; background: #faf3e2; border: 1px solid #eadcbc; border-radius: 3px; padding: 4px 8px; margin-bottom: 8px; }
.filter-chip { font-size: 11px; border: 1px solid #c0a875; border-radius: 10px; padding: 1px 8px; background: #fff; }
.filter-chip a { margin-left: 6px; cursor: pointer; color: #c0392b; font-weight: 700; }
.sort-line { font-size: 11px; color: #999; margin: 4px 0 10px; }
.sort-line a, .pg { cursor: pointer; color: #8b6f47; text-decoration: underline; }
.sort-line a.sort-on { color: #2c1810; font-weight: 700; text-decoration: none; }
.pager { display: flex; justify-content: space-between; margin: 14px 0 40px; font-size: 12px; }
.pg.disabled { color: #ccc; pointer-events: none; text-decoration: none; }
.muted { color: #aaa; }
.table-wrap { overflow-x: auto; }
.coll-table { border-collapse: collapse; font-size: 12px; width: 100%; background: #fffdf7; }
.coll-table th { text-align: right; font-weight: 600; color: #8b6f47; font-size: 10px; padding: 4px 6px; border-bottom: 1px solid #e2d4b4; white-space: nowrap; }
.coll-table th:nth-child(-n+2) { text-align: left; }
.coll-table th.sortable { cursor: pointer; }
.coll-table td { padding: 3px 6px; border-bottom: 1px solid #f0e8d6; }
.coll-table td.num { text-align: right; font-variant-numeric: tabular-nums; }
.coll-table tr.dim td { opacity: 0.45; }
.coll-word { font-family: 'EVA Hand 1', serif; font-size: 16px; color: #2c1810; cursor: pointer; }
.eva-sub { font-family: monospace; font-size: 10px; color: #aaa; margin-left: 6px; }
/* Concordance: Voynichese rendering (the rows keep their grid; only the type changes) */
.sort-line .disp { float: right; }
.conc.glyphs summary .kl, .conc.glyphs summary .kr { font-family: 'EVA Hand 1', serif; font-size: 17px; line-height: 1.7; color: #4a3b2a; }
.conc.glyphs summary .kk { font-family: 'EVA Hand 1', serif; font-size: 19px; font-weight: 400; line-height: 1.6; }
.conc.glyphs .kwic-nb .nb-text { font-family: 'EVA Hand 1', serif; font-size: 15px; color: #6b5a47; }
/* Collocates: before/after bigrams and trigrams */
.ng-wrap { margin: 6px 0 14px; border: 1px solid #eadcbc; border-radius: 4px; background: #fffdf7; padding: 0 12px 10px; }
.ng-wrap > summary { cursor: pointer; padding: 7px 0; font-size: 10px; letter-spacing: 3px; text-transform: uppercase; color: #8b6f47; font-weight: 600; list-style: none; }
.ng-wrap > summary::-webkit-details-marker { display: none; }
.ng-wrap > summary::before { content: "βΎ "; }
.ng-wrap:not([open]) > summary::before { content: "βΈ "; }
.ng-sub { letter-spacing: 0; text-transform: none; font-weight: 400; color: #999; font-size: 11px; margin-left: 10px; }
.ng-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 24px; }
.ng-title { font-size: 11px; font-weight: 600; color: #2c1810; border-bottom: 1px solid #e2d4b4; padding-bottom: 2px; margin-bottom: 2px; }
.ng-hint { font-weight: 400; color: #999; margin-left: 8px; font-size: 10px; }
.ng-row { display: flex; align-items: center; gap: 8px; padding: 2px 0; border-bottom: 1px solid #f0e8d6; }
.ng-g { flex: 1; min-width: 0; }
.ng-glyph { display: block; font-family: 'EVA Hand 1', serif; font-size: 17px; line-height: 1.6; color: #2c1810; overflow-wrap: anywhere; }
.ng-key { color: #c0392b; }
.ng-eva { display: block; font-family: monospace; font-size: 10px; color: #aaa; overflow-wrap: anywhere; }
.ng-n { min-width: 28px; text-align: right; font-size: 12px; color: #2c1810; font-variant-numeric: tabular-nums; }
.ng-pct { min-width: 30px; text-align: right; font-size: 10px; color: #999; font-variant-numeric: tabular-nums; }
.ng-none { font-size: 11px; color: #aaa; font-style: italic; padding: 4px 0; }
@media (max-width: 900px) { .ng-grid { grid-template-columns: minmax(0, 1fr); } }
.kwic summary, .kwic-head { display: grid; grid-template-columns: minmax(0,1fr) auto minmax(0,1fr) 70px 90px 34px 54px 44px; gap: 8px; align-items: baseline; padding: 3px 4px; border-bottom: 1px solid #f0e8d6; list-style: none; cursor: pointer; }
.kwic summary::-webkit-details-marker { display: none; }
.kwic summary:hover { background: #f8efd9; }
.kwic-head { font-size: 10px; color: #8b6f47; font-weight: 600; text-transform: uppercase; cursor: default; border-bottom: 1px solid #e2d4b4; }
.kl { text-align: right; white-space: nowrap; overflow: hidden; direction: rtl; font-family: monospace; font-size: 12px; color: #555; }
.kl > span { direction: ltr; unicode-bidi: embed; }
.kk { font-family: monospace; font-size: 13px; font-weight: 700; color: #c0392b; }
.kr { white-space: nowrap; overflow: hidden; font-family: monospace; font-size: 12px; color: #555; }
.kwic-head .kl, .kwic-head .kr, .kwic-head .kk { font-family: system-ui, sans-serif; font-size: 10px; color: #8b6f47; font-weight: 600; }
.km { font-size: 11px; color: #777; white-space: nowrap; }
.km a { cursor: pointer; color: #2980b9; text-decoration: underline; }
.unc { text-decoration: underline dotted; text-underline-offset: 3px; }
.flag { display: inline-block; font-size: 9px; border: 1px solid #c0392b; color: #c0392b; border-radius: 2px; padding: 0 3px; margin-right: 2px; }
.kwic-nb { font-family: monospace; font-size: 11px; color: #aaa; padding: 2px 4px 2px 24px; }
.nb-lbl { font-family: system-ui, sans-serif; font-size: 9px; text-transform: uppercase; margin-right: 8px; }
/* Phones and narrow windows: stack the page above the sidebar and let the page scroll. */
@media (max-width: 900px) {
html, body { height: auto !important; overflow: auto !important; }
#main-row { position: static !important; flex-direction: column !important;
overflow: visible !important; height: auto !important; }
#folio-col, #sidebar-col { min-width: 0 !important; width: 100% !important; max-width: 100% !important;
height: auto !important; overflow: visible !important; flex: none !important; }
.ms-scroll { height: 62vh; height: 62dvh; padding: 20px 16px; border-right: none; border-bottom: 1px solid #ddd; }
.ms-folio-id { margin-bottom: 12px; }
.word { font-size: 20px; }
#sidebar-col { border-left: none; }
.sidebar-pad { padding: 12px 16px 48px; }
.kwic summary, .kwic-head { grid-template-columns: minmax(0,1fr) auto minmax(0,1fr) 64px; }
.kwic summary .km:nth-child(n+5), .kwic-head .km:nth-child(n+5) { display: none; }
}
/* Spec D: glyph search */
.gkeys { display: flex; flex-wrap: wrap; gap: 4px; margin: 6px 0 4px; }
/* Each key is a glyph box over an opaque label strip, so tall or descending EVA glyphs
(f, i, k, m, p, t, y) can never cover their Latin letter. */
.gkey { min-width: 40px; min-height: 52px; display: inline-flex; flex-direction: column; align-items: stretch;
justify-content: flex-start; gap: 0; border: 1px solid #d9c9a8; border-radius: 4px; background: #fff;
color: #2c1810; cursor: pointer; padding: 0; box-sizing: border-box; overflow: hidden; }
.gkey:hover { border-color: #8b6f47; }
.gkey:active { background: #f3e9d2; }
.gkey:focus-visible { outline: 2px solid #2980b9; }
.gk-g { position: relative; z-index: 0; display: flex; align-items: center; justify-content: center;
height: 36px; padding: 0 4px; font-family: 'EVA Hand 1', serif; font-size: 18px; line-height: 1; }
.gk-l { position: relative; z-index: 1; display: block; margin-top: auto; background: #f7f0e0;
border-top: 1px solid #eadcbc; font-family: monospace; font-size: 11px; font-weight: 600;
color: #6b5a47; line-height: 15px; text-align: center; }
.gk-sym .gk-g { font-family: monospace; font-size: 16px; }
.gk-wide { min-width: 52px; }
.pchips { display: flex; flex-wrap: wrap; gap: 5px; margin: 4px 0; }
.pchip { display: inline-flex; align-items: center; gap: 6px; border: 1.5px solid; border-radius: 12px; padding: 1px 4px 1px 9px; background: #fff; font-size: 12px; }
.pchip-q { font-family: monospace; font-weight: 700; }
.pchip-n { color: #888; font-variant-numeric: tabular-nums; }
.pchip-x { cursor: pointer; color: #999; font-weight: 700; padding: 0 5px; font-size: 14px; }
.pchip-x:hover { color: #c0392b; }
.smsg { color: #c0392b; font-size: 11px; margin: 2px 0 4px; }
.pm { border-radius: 2px; }
.mode-pattern { font-family: monospace; font-size: 18px; font-weight: 700; border: 1.5px solid; border-radius: 4px; padding: 1px 7px; }
.fam-tag { font-size: 9px; border: 1px solid #8b6f47; color: #8b6f47; border-radius: 8px; padding: 0 5px; margin-left: 6px; white-space: nowrap; }
.pcard { border: 1px solid #e8e0ce; border-left: 4px solid; border-radius: 4px; background: #fffdf7; padding: 10px 12px; margin: 10px 0; }
.pcard-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 10px; }
.pq { font-family: monospace; font-size: 16px; font-weight: 700; }
.pstat { font-size: 12px; color: #555; font-variant-numeric: tabular-nums; }
.pcard-src { font-size: 11px; color: #888; margin: 3px 0 6px; font-variant-numeric: tabular-nums; }
.pcard-links { display: flex; gap: 14px; font-size: 12px; margin-bottom: 8px; }
.pcard-links a { color: #8b6f47; cursor: pointer; text-decoration: underline; }
.sw-list { display: flex; flex-wrap: wrap; gap: 4px; max-height: 190px; overflow-y: auto; }
.sw-chip { display: inline-flex; align-items: center; gap: 4px; border: 1px solid #e0d8cc; border-radius: 3px; padding: 1px 5px; background: #fff; cursor: pointer; }
.sw-chip:hover { border-color: #8b6f47; }
.sw-wd { display: inline-flex; flex-direction: column; align-items: flex-start; }
.sw-w { font-family: monospace; font-size: 13px; color: #2c1810; }
.sw-eva { display: none; }
.srch.glyphs .sw-w { font-family: 'EVA Hand 1', serif; font-size: 18px; line-height: 1.5; }
.srch.glyphs .sw-eva { display: block; font-family: monospace; font-size: 9px; color: #aaa; line-height: 1.1; }
.srch.glyphs .sw-list { max-height: 260px; }
.sw-n { font-size: 10px; color: #999; font-variant-numeric: tabular-nums; }
.cmp-wrap { border-top: 1px solid #e8e0ce; margin-top: 14px; padding-top: 10px; }
.cmp-legend { display: flex; flex-wrap: wrap; gap: 12px; font-size: 12px; margin-bottom: 6px; }
.lg { display: inline-flex; align-items: center; gap: 5px; font-family: monospace; }
.lg-dot { width: 10px; height: 10px; border-radius: 2px; display: inline-block; }
.cmp-title { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: #8b6f47; font-weight: 600; margin: 10px 0 4px; }
.cmp { display: flex; gap: 8px; align-items: flex-end; flex-wrap: wrap; }
.cmp-group { display: flex; flex-direction: column; align-items: center; min-width: 34px; }
.cmp-bars { display: flex; gap: 2px; align-items: flex-end; }
.cmp-bar { width: 9px; border-radius: 2px 2px 0 0; }
.cmp-lbl { font-size: 9px; color: #888; margin-top: 3px; white-space: nowrap; }
.cmp-row { display: flex; flex-wrap: wrap; gap: 28px; }
.strips { display: flex; flex-direction: column; gap: 3px; overflow-x: auto; }
.strip { display: flex; align-items: flex-end; gap: 0; }
/* Spec E: top bar over the main pane */
.ms-scroll { padding-top: 0 !important; }
.topbar { position: sticky; top: 0; z-index: 5; margin: 0 -64px 24px; padding: 10px 64px 8px;
background: #fbf2db; border-bottom: 1px solid #e2d4b4; font-family: system-ui, sans-serif;
box-shadow: 0 2px 6px rgba(80, 60, 30, 0.06); }
.tb-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; margin-bottom: 6px; }
.tb-row:last-child { margin-bottom: 0; }
.topbar button, .tb-sel { min-height: 32px; box-sizing: border-box; font-size: 13px;
border: 1px solid #d9c9a8; border-radius: 4px; background: #fff; color: #2c1810; }
.topbar button { cursor: pointer; padding: 0 10px; }
.topbar button:hover:not(:disabled) { border-color: #8b6f47; }
.topbar button:disabled { color: #c9bda5; background: #f7f0e0; cursor: default; }
.tb-tab.on { background: #2c1810; color: #fdf6e3; border-color: #2c1810; }
.tb-seg { display: inline-flex; }
.tb-seg button { border-radius: 0; }
.tb-seg button:first-child { border-radius: 4px 0 0 4px; }
.tb-seg button:last-child { border-radius: 0 4px 4px 0; border-left: none; }
.tb-seg button.on { background: #8b6f47; color: #fff; border-color: #8b6f47; }
.tb-voy { font-family: 'EVA Hand 1', serif; font-size: 15px; margin-right: 2px; }
.tb-sel { padding: 0 6px; max-width: 220px; }
.tb-check { display: inline-flex; align-items: center; gap: 5px; font-size: 13px; color: #2c1810; min-height: 32px; cursor: pointer; }
.tb-folio { display: inline-flex; align-items: center; gap: 4px; }
.tb-arrow { font-size: 18px !important; min-width: 34px; padding: 0 !important; }
.tb-fin { width: 64px; height: 32px !important; min-height: 32px; padding: 0 4px !important; margin: 0 !important; box-sizing: border-box; border: 1px solid #d9c9a8; border-radius: 4px;
background: #fff; font-weight: 700; font-size: 13px; text-align: center; color: #2c1810; }
.tb-fin:focus { outline: 2px solid #2980b9; }
.tb-pos { color: #999; font-size: 11px; }
.tb-hits { display: inline-flex; gap: 4px; }
.tb-sep { width: 1px; height: 22px; background: #e2d4b4; margin: 0 4px; }
.ng-row { cursor: pointer; }
.ng-row:hover { background: #f8efd9; }
.tb-exp { position: relative; }
.tb-exp > summary { list-style: none; cursor: pointer; min-height: 32px; box-sizing: border-box; display: inline-flex;
align-items: center; padding: 0 10px; font-size: 13px; border: 1px solid #d9c9a8; border-radius: 4px;
background: #fff; color: #2c1810; user-select: none; }
.tb-exp > summary::-webkit-details-marker { display: none; }
.tb-exp[open] > summary { border-color: #8b6f47; background: #f8efd9; }
.tb-menu { position: absolute; top: 36px; left: 0; z-index: 20; min-width: 240px; background: #fff;
border: 1px solid #d9c9a8; border-radius: 6px; box-shadow: 0 6px 18px rgba(60, 40, 10, 0.15);
padding: 4px; display: flex; flex-direction: column; }
.topbar .tb-mi { border: none; text-align: left; min-height: 36px; padding: 0 10px; border-radius: 4px; }
.topbar .tb-mi:hover { background: #f8efd9; }
.dl-bar { font-size: 12px; color: #6b5a47; margin-top: 6px; }
.dl-link { color: #2980b9; text-decoration: underline; margin-left: 4px; }
.tb-msg { color: #c0392b; font-size: 12px; margin-top: 4px; }
@media (max-width: 900px) {
.topbar { padding: 6px 12px 6px; margin: 0 -16px 10px; }
.tb-row { gap: 5px; margin-bottom: 5px; }
.topbar button, .tb-sel { font-size: 12px; }
.tb-tab { padding: 0 7px !important; }
.tb-voy { display: none; }
.tb-seg button { padding: 0 8px !important; }
.tb-sel { max-width: 27vw; }
.tb-sel:last-of-type { max-width: 36vw; }
.tb-check { font-size: 12px; }
.tb-hits button { padding: 0 8px !important; }
.tb-sep { display: none; }
.tb-exp > summary { font-size: 12px; padding: 0 8px; }
.tb-menu { position: fixed; left: 12px; right: 12px; top: auto; min-width: 0; }
}
.js-bridge, #word-selector, #folio-nav-target, #action-bridge {
position: absolute !important; width: 1px !important; height: 1px !important;
padding: 0 !important; margin: -1px !important; border: 0 !important;
overflow: hidden !important; clip: rect(0, 0, 0, 0) !important;
white-space: nowrap !important; opacity: 0 !important; pointer-events: none !important; }
"""
# ββ UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
HEAD = f"<script>{JS}</script>"
blocks_kwargs = {"title": "Voynich Codex Reader"}
launch_kwargs = {}
launch_kwargs["allowed_paths"] = [str(EXPORT_DIR)] # spec F, F7: serve export files
if GR_MAJOR >= 6:
launch_kwargs.update(css=CSS, head=HEAD)
else:
blocks_kwargs.update(css=CSS, head=HEAD)
_default_view = VIEWS[DEFAULT_KEY]
with gr.Blocks(**blocks_kwargs) as demo:
app_state = gr.State(_initial_state())
table_visible = gr.State(False)
corpus_stats_visible = gr.State(False)
with gr.Row(equal_height=True, elem_id="main-row"):
with gr.Column(scale=7, min_width=520, elem_id="folio-col"):
main_html = gr.HTML(elem_classes=["ms-scroll"])
with gr.Column(scale=2, min_width=280, elem_id="sidebar-col"):
with gr.Column(elem_classes=["sidebar-pad"]):
gr.Markdown("### Voynich Codex")
# Spec E, E1: transliteration, labels, section, views and folio navigation live
# in the top bar over the main pane.
with gr.Accordion("Glyph search", open=True):
with gr.Row():
search_box = gr.Textbox(elem_id="search-box", placeholder="Pattern, e.g. ^qok*y$",
show_label=False, container=False, scale=3)
add_btn = gr.Button("Add", size="sm", scale=1, min_width=50)
exact_cb = gr.Checkbox(value=False, label="Exact (whole word)")
gr.HTML(build_keyboard())
chips_html = gr.HTML()
with gr.Accordion("Collocation settings", open=False):
window_sl = gr.Slider(1, 5, value=3, step=1, label="Window (Β± words, same line)")
lang_rd = gr.Radio(["All", "A", "B"], value="All", label="Currier language")
excl_cb = gr.Checkbox(value=False, label="Exclude adjacent words (Β±1)")
pos_cb = gr.Checkbox(value=False, label="Positional baseline")
certain_cb = gr.Checkbox(value=False, label="Certain readings only")
linepos_dd = gr.Dropdown(["Any", "initial", "medial", "final", "alone"], value="Any",
label="Concordance: line position")
folio_stats_html = gr.HTML()
detail_html = gr.HTML(elem_id="detail-panel")
corpus_btn = gr.Button("Corpus statistics", size="sm")
corpus_html = gr.HTML(build_corpus_stats(_default_view), visible=False)
table_btn = gr.Button("Frequency table", size="sm")
freq_html = gr.HTML(visible=False)
word_sel = gr.Textbox(elem_id="word-selector", elem_classes=["js-bridge"],
lines=1, interactive=True, container=False, show_label=False)
folio_nav_target = gr.Textbox(elem_id="folio-nav-target", elem_classes=["js-bridge"],
lines=1, interactive=True, container=False, show_label=False)
action_bridge = gr.Textbox(elem_id="action-bridge", elem_classes=["js-bridge"],
lines=1, interactive=True, container=False, show_label=False)
outs = [app_state, main_html, freq_html, detail_html, folio_stats_html, chips_html, corpus_html]
folio_nav_target.change(fn=navigate_to, inputs=[app_state, folio_nav_target], outputs=outs)
word_sel.change(fn=on_word, inputs=[app_state, word_sel], outputs=outs)
action_bridge.change(fn=on_action, inputs=[app_state, action_bridge], outputs=outs)
add_btn.click(fn=add_pattern, inputs=[app_state, search_box, exact_cb], outputs=outs + [search_box])
search_box.submit(fn=add_pattern, inputs=[app_state, search_box, exact_cb], outputs=outs + [search_box])
settings = [window_sl, lang_rd, excl_cb, pos_cb, certain_cb, linepos_dd]
for comp in settings:
comp.input(fn=on_settings, inputs=[app_state] + settings, outputs=outs)
# C14: excluding Β±1 makes no sense with a Β±1 window.
window_sl.input(fn=lambda w: gr.update(interactive=int(w) > 1), inputs=[window_sl], outputs=[excl_cb])
table_btn.click(fn=toggle_table, inputs=[table_visible], outputs=[table_visible, freq_html, table_btn])
corpus_btn.click(fn=toggle_corpus_stats, inputs=[corpus_stats_visible], outputs=[corpus_stats_visible, corpus_html, corpus_btn])
demo.load(fn=on_load, outputs=outs)
if __name__ == "__main__":
demo.launch(**launch_kwargs)
import base64
import html as _html
import tempfile
import time
import urllib.request
import uuid
from collections import Counter
from datetime import datetime
from functools import lru_cache
from pathlib import Path
import gradio as gr
import numpy as np
import pandas as pd
from corpus import (SECTION_NAMES, SECTION_ORDER, SOURCE_NAMES, build_view, collocates,
concordance, neighbour_lines, paginate, parameter_line, register_views,
robustness, similar_words, view_key)
import export as ex
from search import ERROR_TEXT, PatternError, canonical, compile_pattern, hit_mask, match_spans, search
# ZeroGPU hardware refuses to start an app with no @spaces.GPU function. This app
# needs no GPU; the placeholder lets it run on ZeroGPU as well as CPU Basic.
try:
import spaces
def _zero_gpu_placeholder():
return None
except ImportError:
pass
# Gradio 6 moved css/js/head from the Blocks() constructor to launch().
# Detect the major version so the same file works on Gradio 4/5 and 6+.
GR_MAJOR = int(gr.__version__.split(".")[0])
# ββ Load data βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# data/tokens.parquet is built offline by build_tokens.py from the IVTFF files.
_HERE = Path(__file__).resolve().parent
def _fetch(url: str, timeout: int) -> bytes:
"""voynich.nu answers 406 to Python's default User-Agent, so send a browser-like one."""
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 (VoynichCodexReader)"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.read()
_RAW_URLS = {
"ZL": "https://www.voynich.nu/data/ZL3b-n.txt",
"IT": "https://www.voynich.nu/data/IT2a-n.txt",
"RF": "https://www.voynich.nu/data/RF1b-e.txt",
}
def _load_tokens() -> pd.DataFrame:
"""Prefer the committed tokens file; if it is missing, build it once from voynich.nu."""
for p in (_HERE / "data" / "tokens.parquet", _HERE / "tokens.parquet"):
if p.exists():
return pd.read_parquet(p)
from build_tokens import parse_ivtff_text
frames = []
for src, url in _RAW_URLS.items():
print(f"tokens.parquet not found; downloading {url}")
frames.append(parse_ivtff_text(_fetch(url, 60).decode("utf-8", errors="replace"), src))
tokens = pd.concat(frames, ignore_index=True)
try:
out = _HERE / "data" / "tokens.parquet"
out.parent.mkdir(exist_ok=True)
tokens.to_parquet(out, index=False)
except OSError as exc:
print(f"Could not cache tokens.parquet: {exc}")
return tokens
TOKENS = _load_tokens()
SOURCES = [s for s in SOURCE_NAMES if s in set(TOKENS["Source"])]
DEFAULT_SOURCE = "ZL" if "ZL" in SOURCES else SOURCES[0]
DEFAULT_KEY = view_key(DEFAULT_SOURCE, False)
VIEWS = {view_key(s, lab): build_view(TOKENS, s, lab) for s in SOURCES for lab in (False, True)}
register_views(VIEWS)
SECTION_COLORS = {
"H": "#5b8c3a", "A": "#2f6f9f", "C": "#7a5ea8", "Z": "#c0802f",
"B": "#b0505a", "P": "#3a8c86", "S": "#8b6f47", "T": "#888888",
}
COLL_PAGE = 50
CONC_PAGE = 100
# Spec D: up to three patterns, coloured in the order they were added (D4).
PATTERN_COLORS = ["#2f6fd0", "#c0392b", "#2e8b57"]
PATTERN_TINTS = ["rgba(47,111,208,0.22)", "rgba(192,57,43,0.20)", "rgba(46,139,87,0.22)"]
MAX_PATTERNS = 3
EVA_KEYS = list("acdefghiklmnopqrstvxyz")