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'
{words_html}
\n' else: lines_html += (f'
' f'{LOCUS_TAGS.get(ltype, ltype)}{words_html}
\n') return ( f'
{_section_badge(v.folio_section.get(folio, ""))}   {folio}
' f'
{lines_html}
' ) 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"""
Collocates · ±{st['window']} · {stat}
{chips}
Collocates →
""" def build_detail(v, folio: str, word: str, coll_summary: str = "") -> str: if not word: return 'Click any word to explore it' word = word.strip() if word not in v.global_freq: hint = ("" if v.include_labels else " It may occur only in label text; tick Count label & ring text to include it.") return f'"{word}" is not counted in {v.source}.{hint}' 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}/{tot}' else: rank_html = '—' 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'
' f'
' f'
{pval}%
' f'
{label}
' f'
{pos[key]}x
' f'
' ) 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 'none' chips = "" for w2, cnt in top: chips += ( f'' f'{w2}' f'{cnt}x' f'' ) 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'' f'{w2}' f'd{dist}' f'{gf2}x' f'' ) 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'{shared}{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}{shared}' if shared else w2) chips += ( f'' f'{display}' f'{gf2}x' f'' ) return chips or 'none' 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'
') 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'
') chips = "" for cf in cross_folios: bold = "font-weight:bold;border-color:#333" if cf == folio else "" chips += (f'{cf}') glyph_html = "" for ch in word: glyph_html += ( f'
' f'
{ch}
' f'
{ch}
' f'
' ) lf_display = lf if lf > 0 else "-" n_folios = len(v.folios) return f"""
{word}
{word}  .  {len(word)} glyphs  .  {v.source}
Glyph breakdown
{glyph_html}
{lf_display}
folio
{gf}
ms-wide
{rank_html}
rank
{len(cross_folios)}/{n_folios}
folios
{pct}th
pctile
Positional preference · corpus-wide  {dom_label}
{pos_bars}
{coll_summary}
Neighbors
Preceded by
{prev_chips}
Followed by
{next_chips}
Frequency across manuscript  {spread_label}
{spark_bars}
Rate by section, per 1000 tokens
{sec_bars}
Similar words (by edit distance)
{sim_chips}
Morphological family
Shares prefix {word[:pfx_hl]}-
{pfx_chips}
Shares suffix -{word[-sfx_hl:]}
{sfx_chips}
Within-folio distribution
By line
{line_bars}
By slot position
{slot_bars}
Appears in {len(cross_folios)} folios
{chips}
""" 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 ( '' '' '' '' '' '' '' '' f'{rows}
#GlyphEVALocalGlobal
' ) # ── 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'
← Previous' f'Next →
') 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'
Show: {disp_link(True, "Voynichese")} · ' f'{disp_link(False, "EVA")}' f'Sort: {sort_link("ms", "manuscript order")} · ' f'{sort_link("left", "left context")} · {sort_link("right", "right context")}
') if conc.empty: return head + sorts + 'No occurrences in this scope.' rows = "" for _, r in conc.iloc[start:end].iterrows(): flags = "" if r["UncertainBreak"]: flags += ',' if r["Alt"]: flags += f'alt' if r["Illegible"]: flags += '?' prev, nxt = neighbour_lines(v, r["Folio"], int(r["Line"])) rows += ( f'
' f'{_ctx(r["left"])}' f'' f'{_marked(r["keyword"], kw_layers) if kw_layers else _esc(r["keyword"])}' f'{_ctx(r["right"])}' f'{r["Folio"]}' f'.{r["Line"]}' f'{_section_badge(r["Section"])}' f'{_esc(r["Language"] or "–")}' f'{r["LinePos"]}' f'{flags}' f'{_neighbour_html(prev, "prev")}{_neighbour_html(nxt, "next")}' f'{"" if prev or nxt else "
No other lines on this page.
"}
') hdr = ('
LeftKeyword' 'RightFolio.lineSection' 'LangPositionFlags
') return (head + sorts + f'
' + hdr + rows + '
' + _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
{per_src}
{words}
{more}
""" 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'
Exported {_esc(dl["name"])} ({dl["size"]}) · ' f'' f'Download {_esc(dl["name"])}
') 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'
{_esc(msg)}
' if msg else "" return (f'
{tabs}{script}{_export_menu(st)}' f'' f'{labels}' f'' f'{folio}{hits}
{note}{_download_html(dl)}
') 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'
{_main_html(st)}
' 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"" 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)