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''
f'{_section_label(code)}')
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'
')
prev_sec = sec
h = max(2, int(val / mx * height)) if val else 2
col = color_on if val else color_off
bars += (f'')
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''
for s in rob.columns)
return f'{dots}'
# ── 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'{seg}')
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'
{folio}
No text on this page in {v.source}.'
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''
f'{_marked(w, layers) if layers else w} '
)
if ltype == "P":
lines_html += f'
'
)
def build_corpus_stats(v) -> str:
c = v.corpus
top_rows = "".join(
f'
{w}
'
f'
{w}
'
f'
{gf}
'
for w, gf in c["top5"]
)
scope = "all text" if v.include_labels else "paragraph text"
return f"""
Corpus statistics · {v.source} · {scope}
{c['tokens']:,}
total tokens
{c['types']:,}
unique types
{c['ttr']:.3f}
type/token ratio
{c['hapax']:,}
hapax legomena
{c['folios']}
folios
{c['avg_wl']:.1f}
avg token length
Most frequent words (ms-wide)
{top_rows}
"""
def build_folio_stats(v, folio: str) -> str:
subset = _folio_tokens(v, folio)
if subset.empty:
hint = ("" if v.include_labels else
" Tick Count label & ring text to include this page's labels.")
return (f'
Folio {folio}
'
f'No counted text on this page.{hint}
')
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''
f'{w}'
f'{c}'
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'')
return f"""
Folio {folio}
{f_tokens}
tokens
{f_types}
unique types
{f_ttr:.2f}
TTR
{f_hapax}
hapax
{f_lines}
lines
{f_density:.1f}
tok/line
{f_avg_wl:.1f}
avg tok len
#{f_rank}/{n_ranked}
size rank
Top words this folio
{top3_html}
Word length distribution
{bars}
"""
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'
'
f''
f'
{rate:.1f}
'
f'
{_section_label(s)[:5]}
'
f'
'
)
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 = 'none pass the thresholds'
else:
chips = ""
for _, r in tab.head(5).iterrows():
w2 = r["collocate"]
dim = " dim" if r["dim"] else ""
chips += (
f''
f'{_esc(w2)}'
f'{r[key]:.2f}{_rob_dots(rob, w2)}'
f'↗'
f'')
stat = "log2 O/E_pos" if st["positional"] else "LRC"
return f"""
"""
def build_freq_table(v, folio: str) -> str:
subset = _folio_tokens(v, folio)
if subset.empty:
return 'No counted text on this page.'
lc = subset["Word"].value_counts()
rows = ""
for i, (w, local) in enumerate(lc.items()):
rows += (
f'
'
f'
{i+1}
'
f'
{w}
'
f'
{w}
'
f'
{local}
'
f'
{v.global_freq.get(w, 0)}
'
f'
'
)
return (
'
'
'
'
'
#
'
'
Glyph
'
'
EVA
'
'
Local
'
'
Global
'
'
'
f'{rows}
'
)
# ── HTML builders: collocates and concordance modes ───────────────────────────
def _mode_heading(st, title, sub=""):
tg = _target(st)
if tg and tg["kind"] == "pattern":
name = (f''
f'{_esc(tg["label"])}')
else:
name = f'{_esc(st["word"])}'
return f'
{title}{name}{sub}
'
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'
')
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'{body}')
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'
{" ".join(parts)}'
f'{_esc(" ".join(gram))}
'
f'{count}{pct}
')
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'
No sequence occurs {NGRAM_MIN} or more times.
'
return (f'
{title}'
f'{hint}
{rows}
')
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'{n:,} occurrences · adjacent words in the same line '
f'· listed from {NGRAM_MIN}×')
if not n:
body = '
No occurrences in this scope.
'
else:
body = ('
'
+ _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)
+ '
')
return f'Neighbouring bigrams & trigrams{sub}{body}'
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'
{_esc(params)}
'
ngrams = build_ngram_view(st, tg)
if tab.empty:
return head + pline + ngrams + 'No collocate passes the thresholds with these settings.'
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 = '
#
Collocate
'
for c, h, _f, title in cols:
arrow = (" ▲" if st["casc"] else " ▼") if st["csort"] == c else ""
ths += f'
{h}{arrow}
'
ths += '
' + " ".join(SOURCES) + "
"
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'
{f.format(r[c])}
' for c, _h, f, _t in cols)
rows += (f'
{i}
'
f'
{_esc(w2)}'
f' ↗'
f'{_esc(w2)}'
f'{"in family" if plabel and r["in_family"] else ""}'
f'
{tds}
{_rob_dots(rob, w2)}
')
reset = (' · rank order'
if st["csort"] else "")
return (head + pline + ngrams +
f'
{label}{reset}
'
f'
{ths}
'
f'{rows}
'
+ _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'{_esc(w)}')
return " ".join(out)
def _neighbour_html(item, label):
if item is None:
return ""
ltype, words = item
tag = f'{LOCUS_TAGS.get(ltype, "")}' if ltype != "P" else ""
return (f'
{label}{tag}'
f'{_esc(" ".join(words))}
')
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'with {_esc(st["with_word"])} within ±{st["window"]}'
f'×')
elif st.get("kclus"):
side, ctx, node = st["kclus"]
seq = " ".join(list(ctx) + [node] if side == "L" else [node] + list(ctx))
chip = (f'sequence {_esc(seq)}'
f'×')
head = _mode_heading(st, "Concordance", f'{label}{chip}')
def sort_link(key, text):
cls = "sort-on" if st["ksort"] == key else ""
return f'{text}'
glyph = st.get("kglyph", True)
def disp_link(on, text):
cls = "sort-on" if glyph == on else ""
return f'{text}'
sorts = (f'
'
+ _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 = '
'
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'')
html += (f'
{bars}
'
f'
{_esc(label(g))}
')
return html + "
"
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'')
rows += f'
{bars}
'
return f'
{rows}
'
def build_search_view(st) -> str:
v = VIEWS[st["key"]]
pats = _patterns(st)
head = (f'
Search'
f'{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"]}
')
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''
f'{_marked(w, [(compile_pattern(p["q"], p["exact"]), col, tint)])}'
f'{_esc(w)}'
f'{c}'
f'↗'
for w, c in r["top"]) or 'No matches in this scope.'
more = (f'
Top {len(r["top"])} of {r["types"]:,} words
'
if r["types"] > len(r["top"]) else "")
cards += f"""
{_esc(label)}{r["tokens"]:,} tokens · {r["types"]:,} words · {r["share"]:.1%} of tokens
"""
secs = [s for s in SECTION_ORDER if any(s in r["by_section"] for _c, r in results)]
legend = "".join(f'{_esc(label)}'
for (_i, label, _c, col, _t) in pats)
charts = f"""
{legend}
Rate by section, per 1,000 tokens
{_cmp_chart(secs, [(c, r["by_section"]) for c, r in results], lambda g: _section_label(g)[:6])}
By Currier language
{_cmp_chart(["A", "B"], [(c, r["by_language"]) for c, r in results])}
By line position
{_cmp_chart(["initial", "medial", "final", "alone"], [(c, r["by_linepos"]) for c, r in results])}
Hits per folio
{_folio_strips(v, [(c, r["per_folio"]) for c, r in results])}
"""
glyph = st.get("kglyph", True)
show = f'
{_script_switch(st, "")}
'
return head + show + f'
{cards}
' + 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'{text}'
return f'Show: {link(True, "Voynichese")} · {link(False, "EVA")}'
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''
f'{_esc(label)}'
f'{n:,}'
f'×')
msg = f'
{_esc(st["smsg"])}
' if st.get("smsg") else ""
return f'
{chips}
{msg}'
def build_keyboard() -> str:
keys = "".join(
f'' for k in EVA_KEYS)
for k, name, short in (("*", "one or more glyphs", "any"), ("^", "word start", "start"),
("$", "word end", "end")):
keys += (f'')
keys += (''
'')
return f'
{keys}
'
# ── 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'')
return (f'Export ▾'
f'
{items}
')
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'
')
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'
{build_search_view(st)}
'
if st["mode"] == "coll" and _target(st):
return f'
{build_collocates_view(st)}
'
if st["mode"] == "conc" and _target(st):
return f'
{build_concordance_view(st)}
'
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''
for m, name in MODE_TABS)
glyph = st.get("kglyph", True)
script = (f''
f''
f'')
src = "".join(f'' for s_ in SOURCES)
secs = "".join(f''
for lbl, val in _section_choices(v))
labels = (f'')
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''
f''
f'{pos}'
f'')
hits = ""
if st["patterns"]:
dis = "" if _hit_folios(st) else " disabled"
hits = (f''
f''
f'')
note = f'
')
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'