Spaces:
Running on Zero

File size: 11,575 Bytes
e4a0a18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""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_<view>_<target>_<source>_<yyyymmdd-hhmm>.<ext>."""
    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.3<TAB>P<TAB>words'."""
    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