"""Exports (spec F, specs/export.md). Pure builders: each turns an existing corpus/search result into a DataFrame or text, and the writers add the settings header (F4) in the encodings of F5. """ from __future__ import annotations import csv import io import re import zipfile from datetime import datetime import pandas as pd from corpus import SECTION_NAMES, SECTION_ORDER, _scope from search import LINE_POSITIONS, hit_mask APP_NAME = "Voynich Codex Reader" IVTFF_FILES = {"ZL": "ZL3b-n.txt (IVTFF 2.0)", "IT": "IT2a-n.txt (IVTFF 2.0)", "RF": "RF1b-e.txt (IVTFF 2.0)"} TOKEN_COLS = ["Folio", "Line", "Position", "LocusType", "Word", "Alt", "Section", "Language", "Hand", "Quire", "UncertainBreak", "Illegible", "Rare", "LinePos"] NGRAM_LISTS = (("b2", "before-2"), ("a2", "after-2"), ("b3", "before-3"), ("a3", "after-3")) # ── Header, file names ──────────────────────────────────────────────────────── def export_header(view, settings: dict, now: datetime | None = None) -> list[str]: """F4: app, date, transliteration and every setting in force (None values are skipped).""" now = now or datetime.now().astimezone() sec = settings.get("section") or "All" lang = settings.get("language") or "All" lines = [ f"{APP_NAME} export", f"date: {now.isoformat(timespec='seconds')}", f"transliteration: {view.source} ({IVTFF_FILES.get(view.source, view.source)})", f"labels: {'on' if view.include_labels else 'off'}", f"section: {'all sections' if sec == 'All' else SECTION_NAMES.get(sec, sec)}", f"language: {'A+B' if lang == 'All' else lang}", ] for k, v in settings.items(): if k in ("section", "language") or v is None or v == "": continue if isinstance(v, bool): v = "yes" if v else "no" lines.append(f"{k}: {v}") return lines def export_filename(view_name: str, target: str, source: str, now: datetime, ext: str) -> str: """F6: voynich____..""" t = (target or "all").replace("*", "x").replace("^", "").replace("$", "") t = re.sub(r"[^A-Za-z0-9._-]+", "-", t).strip("-") or "all" return f"voynich_{view_name}_{t}_{source}_{now:%Y%m%d-%H%M}.{ext}" # ── Writers ─────────────────────────────────────────────────────────────────── def _bools_as_text(df: pd.DataFrame) -> pd.DataFrame: out = df.copy() for c in out.columns: if out[c].dtype == bool: out[c] = out[c].map({True: "true", False: "false"}) return out def write_csv(df: pd.DataFrame, header: list[str]) -> bytes: """F5: UTF-8 with BOM, '# ' header lines, one column-header row, RFC 4180 quoting.""" buf = io.StringIO() for line in header: buf.write(f"# {line}\n") _bools_as_text(df).to_csv(buf, index=False, lineterminator="\n", quoting=csv.QUOTE_MINIMAL, float_format="%.17g") return ("" + buf.getvalue()).encode("utf-8") def write_text(body: str, header: list[str]) -> bytes: return ("".join(f"# {h}\n" for h in header) + body).encode("utf-8") def write_parquet(df: pd.DataFrame, header: list[str]) -> bytes: import pyarrow as pa import pyarrow.parquet as pq table = pa.Table.from_pandas(df, preserve_index=False) meta = dict(table.schema.metadata or {}) meta[b"voynich_export"] = "\n".join(header).encode("utf-8") buf = io.BytesIO() pq.write_table(table.replace_schema_metadata(meta), buf) return buf.getvalue() def write_zip(files: dict[str, bytes], header: list[str]) -> bytes: buf = io.BytesIO() with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z: z.writestr("settings.txt", "\n".join(header) + "\n") for name, data in files.items(): z.writestr(name, data) return buf.getvalue() # ── Page ────────────────────────────────────────────────────────────────────── def page_text(view, folio: str) -> str: """F3: one line per locus, every locus type, in line order: 'f1r.3Pwords'.""" page = view.page_df[view.page_df["Folio"] == folio].sort_values(["Line", "Position"]) out = [] for (line, lt), g in page.groupby(["Line", "LocusType"], sort=True): out.append(f"{folio}.{line}\t{lt}\t{' '.join(g['Word'])}") return "\n".join(out) + ("\n" if out else "") def page_freq(view, folio: str) -> pd.DataFrame: sub = view.df[view.df["Folio"] == folio] lc = sub["Word"].value_counts() rows = sorted(lc.items(), key=lambda x: (-x[1], x[0])) return pd.DataFrame({"word": [w for w, _ in rows], "folio_count": [int(c) for _, c in rows], "manuscript_count": [int(view.global_freq.get(w, 0)) for w, _ in rows]}) # ── Concordance ─────────────────────────────────────────────────────────────── def concordance_rows(conc: pd.DataFrame) -> pd.DataFrame: """F3: one row per hit, in the concordance's own order.""" return pd.DataFrame({ "left": [" ".join(w for w, _ in s) for s in conc["left"]], "keyword": conc["keyword"].astype(str).tolist(), "right": [" ".join(w for w, _ in s) for s in conc["right"]], "folio": conc["Folio"].tolist(), "line": conc["Line"].astype(int).tolist(), "section": [SECTION_NAMES.get(s, s) for s in conc["Section"]], "language": conc["Language"].fillna("").tolist(), "line_position": conc["LinePos"].tolist(), "uncertain_break": conc["UncertainBreak"].astype(bool).tolist(), "alternate_reading": conc["Alt"].fillna("").tolist(), "illegible": conc["Illegible"].astype(bool).tolist(), }) def kwic_text(rows: pd.DataFrame, width: int = 60) -> str: """F3: left context right-aligned to a fixed width, keyword between tabs, right context, locus.""" if rows.empty: return "" w = min(width, max(len(s) for s in rows["left"]) if len(rows) else 0) out = [] for r in rows.itertuples(index=False): left = r.left[-w:] if len(r.left) > w else r.left out.append(f"{left.rjust(w)}\t{r.keyword}\t{r.right}\t{r.folio}.{r.line}") return "\n".join(out) + "\n" # ── Collocates and n-grams ──────────────────────────────────────────────────── COLL_EXPORT_COLS = ["collocate", "O11", "expected", "G2", "LRC", "left", "right", "dp_wc", "dp_cw", "folios", "sections", "lang_A", "lang_B"] COLL_RAW_COLS = ["O12", "O21", "O22", "R1", "C1", "N", "in_family", "dim"] def collocate_rows(tab: pd.DataFrame, rob: pd.DataFrame | None, positional: bool = False) -> pd.DataFrame: """F3: every passing collocate, on-screen columns plus raw cells and per-source robustness.""" cols = COLL_EXPORT_COLS + (["E_pos", "log_ratio_pos"] if positional else []) + COLL_RAW_COLS out = tab[[c for c in cols if c in tab.columns]].copy().reset_index(drop=True) for c in ("in_family", "dim"): if c in out: out[c] = out[c].astype(bool) if rob is not None: for s in rob.columns: out[f"passes_{s}"] = [bool(rob.at[w, s]) if w in rob.index else False for w in out["collocate"]] return out def ngram_rows(res: dict) -> pd.DataFrame: """F3: the four bigram/trigram lists as shown, with node and share of hits.""" n = res.get("n", 0) rows = [] for key, name in NGRAM_LISTS: for gram, count in res["top"].get(key, []): node = gram[-1] if key.startswith("b") else gram[0] rows.append({"list": name, "sequence": " ".join(gram), "node": node, "count": int(count), "share": count / n if n else 0.0}) return pd.DataFrame(rows, columns=["list", "sequence", "node", "count", "share"]) # ── Search ──────────────────────────────────────────────────────────────────── def search_rows(view, patterns, section=None, language=None, views_by_source=None) -> pd.DataFrame: """F3: long format, one row per (pattern, dimension, group) with count, total and rate. `patterns` is [(label, compiled)]. `views_by_source` maps source -> View with the same label setting, for the per-transliteration rows. """ t = _scope(view, section, language) sec_tot = t["Section"].value_counts() lang_tot = t["Language"].value_counts() pos_tot = t["LinePos"].value_counts() fol_tot = t["Folio"].value_counts() sections = [s for s in SECTION_ORDER if sec_tot.get(s, 0)] + \ sorted(s for s in sec_tot.index if s not in SECTION_ORDER) present = set(t["Folio"]) folios = [f for f in view.folios if f in present] rows = [] def add(label, dim, group, count, total, rate=True): rows.append({"pattern": label, "dimension": dim, "group": group, "count": int(count), "total": int(total), "rate_per_1000": (1000.0 * count / total if total else 0.0) if rate else None}) for label, compiled in patterns: h = t[hit_mask(t, compiled)] if len(t) else t n = len(h) for w, c in sorted(h["Word"].value_counts().items(), key=lambda x: (-x[1], x[0])): add(label, "word", w, c, n, rate=False) sc = h["Section"].value_counts() for s in sections: add(label, "section", SECTION_NAMES.get(s, s), sc.get(s, 0), sec_tot[s]) lc = h["Language"].value_counts() for g in ("A", "B"): if lang_tot.get(g, 0): add(label, "language", g, lc.get(g, 0), lang_tot[g]) pc = h["LinePos"].value_counts() for g in LINE_POSITIONS: if pos_tot.get(g, 0): add(label, "line_position", g, pc.get(g, 0), pos_tot[g]) fc = h["Folio"].value_counts() for f in folios: add(label, "folio", f, fc.get(f, 0), fol_tot[f]) for src, v in (views_by_source or {view.source: view}).items(): ts = _scope(v, section, language) add(label, "transliteration", src, int(hit_mask(ts, compiled).sum()) if len(ts) else 0, len(ts)) df = pd.DataFrame(rows, columns=["pattern", "dimension", "group", "count", "total", "rate_per_1000"]) return df # ── Whole view ──────────────────────────────────────────────────────────────── def scoped_tokens(view, section=None, language=None) -> pd.DataFrame: """F3: the scoped statistics tokens in manuscript order.""" t = _scope(view, section, language) out = t[[c for c in TOKEN_COLS if c in t.columns]].copy().reset_index(drop=True) out["Alt"] = out["Alt"].fillna("").astype(str) for c in ("UncertainBreak", "Illegible", "Rare"): if c in out: out[c] = out[c].astype(bool) return out