"""Muuntaa Quarton tuottaman paperi.md:n taiton lohkoiksi (lohkot.json). Tekee samalla kirjoitusohjeen merkintätapakorjaukset: - kuvioiden ja taulukoiden otsikot yläpuolelle muodossa "Kuvio 1." / "Taulukko 1.", huomautus ja lähde alapuolelle; liitteiden taulukot "Liitetaulukko 1." - oikea miinusmerkki (−), rajavälien en-viiva (–), tuhaterotin välilyönnillä - lihavoinnit pois leipätekstistä (ohje: vältä lihavointia), kursiivi säilyy - otsikkonumerointi 1, 1.1 (tiivistelmä, lähteet ja liitteet numeroimatta) Aja: python3 lohkot.py (lukee paperi.md, kirjoittaa lohkot.json) Kuvien koot luetaan PNG-otsakkeesta (300 dpi). """ import html import json import re import struct from pathlib import Path from markdown_it import MarkdownIt HERE = Path(__file__).parent md_text = (HERE / "paperi.md").read_text(encoding="utf-8") ESS = "Lähde: European Social Survey (ESS), kierrokset 1–11 (2002–2024); omat laskelmat." LAHDE = { "fig-gss": "Lähde: General Social Survey (GSS) 1972–2024; omat laskelmat.", "fig-tasaarvo": "Lähteet: ESS kierrokset 1–11; UNDP Gender Inequality Index; omat laskelmat.", "tbl-tasaarvo": "Lähteet: ESS kierrokset 1–11; UNDP Gender Inequality Index; omat laskelmat.", } # Otsikottomat taulukot saavat otsikon (ohje: kaikki taulukot numeroidaan ja otsikoidaan) OTSIKOTTOMAT = { "Ulottuvuus | ESS-muuttuja": "Analyysin muuttujat ja asteikot.", "Vaihe | Käsittely": "Muuttujien käsittely ja rajaukset.", } def png_mm(path, dpi=300): with open(path, "rb") as f: head = f.read(24) w, h = struct.unpack(">II", head[16:24]) return round(w / dpi * 25.4, 1), round(h / dpi * 25.4, 1) URL = re.compile(r"(https?://\S+|doi\.org/\S+|`[^`]*`)") def korjaa(t): """Kirjoitusohjeen merkit; URL:t ja koodi jätetään ennalleen.""" osat = URL.split(t) for i in range(0, len(osat), 2): s = osat[i] s = re.sub(r"(?Kuva (\d+)', r"kuvio \1", md_text) md_text = re.sub(r'Taulukko \d+', lambda m: f"taulukko {uusi_tbl[m.group(1)]}", md_text) md_text = re.sub(r"\(kuvio (\d+)\)", r"(kuvio \1)", md_text) # LaTeX-kaavat tekstiksi: Unicode-kreikka ja alaindeksinumerot (Lato sisältää merkit) SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉") def kaava(m): k = m.group(1) k = k.replace(r"y_{ic}", "y").replace(r"\varepsilon_{ic}", "ε").replace(r"\alpha_c", "α(maa)") k = k.replace(r"\,\text{nainen}_i", " · nainen").replace(r"\beta", "β").replace(r"\alpha", "α") k = re.sub(r"_(\d)", lambda x: x.group(1).translate(SUB), k) return k md_text = re.sub(r"\$([^$]+)\$", kaava, md_text) md = MarkdownIt("commonmark").enable("table") tokens = md.parse(md_text) blocks = [] i = 0 num = [0, 0, 0] liite = None liite_tbl = 0 tbl_n = 0 pending = None # avoin kuvio/taulukko (div id) pending_caption = None in_refs = False def push_heading(level, text): global liite, in_refs text = korjaa(text) numero = None if level == 1 and text.startswith("Erkanevatko"): return # julkaisun nimi on kannessa if text in ("Tiivistelmä",): blocks.append({"t": "h", "level": 1, "num": None, "text": text, "sivu": "uusi"}) return if text == "Lähteet": in_refs = True blocks.append({"t": "h", "level": 1, "num": None, "text": text, "sivu": "uusi"}) return if text.startswith("Liite "): in_refs = False liite = text.split()[1].rstrip(":") blocks.append({"t": "h", "level": 1, "num": None, "text": text, "sivu": "uusi"}) return if liite: blocks.append({"t": "h", "level": level, "num": None, "text": text}) return if level == 1: num[0] += 1; num[1] = 0; num[2] = 0 numero = f"{num[0]}" elif level == 2: num[1] += 1; num[2] = 0 numero = f"{num[0]}.{num[1]}" else: num[2] += 1 numero = f"{num[0]}.{num[1]}.{num[2]}" blocks.append({"t": "h", "level": level, "num": numero, "text": text, "sivu": "uusi" if level == 1 else None}) while i < len(tokens): t = tokens[i] if t.type == "html_block": m = re.search(r'
', t.content) if m: pending = m.group(1) i += 1 continue if t.type == "heading_open": level = int(t.tag[1]) push_heading(level, plain(tokens[i + 1].children)) i += 3 continue if t.type == "paragraph_open": inl = tokens[i + 1] kids = inl.children or [] if kids and kids[0].type == "image": src = str(HERE / kids[0].attrs["src"]) w, h = png_mm(src) blocks.append({"t": "fig", "id": pending, "src": src, "w_mm": w, "h_mm": h}) i += 3 continue text = inline_md(kids) m = re.match(r"^(Kuva|Taulukko) (\d+): (.*)$", text) if m and pending: caption = korjaa(m.group(3)) otsikko, _, huom = caption.partition(". ") otsikko = otsikko.rstrip(".") + "." if m.group(1) == "Kuva": fig = next(b for b in reversed(blocks) if b["t"] == "fig" and b["id"] == pending) fig.update({"num": int(m.group(2)), "title": otsikko, "note": ("Huom. " + huom) if huom else "", "lahde": LAHDE.get(pending, ESS)}) else: pending_caption = (otsikko, huom) i += 3 continue if in_refs: blocks.append({"t": "ref", "md": korjaa(text)}) else: blocks.append({"t": "p", "md": korjaa(text)}) i += 3 continue if t.type in ("bullet_list_open", "ordered_list_open"): kind = "ul" if t.type == "bullet_list_open" else "ol" items, depth, j = [], 0, i while True: tk = tokens[j] if tk.type in ("bullet_list_open", "ordered_list_open"): depth += 1 elif tk.type in ("bullet_list_close", "ordered_list_close"): depth -= 1 if depth == 0: break elif tk.type == "inline" and depth == 1: items.append(korjaa(inline_md(tk.children))) j += 1 blocks.append({"t": kind, "items": items}) i = j + 1 continue if t.type == "table_open": headers, rows, row, aligns = [], [], [], [] j = i while tokens[j].type != "table_close": tk = tokens[j] if tk.type == "th_open": st = tk.attrs.get("style", "") or "" aligns.append("center" if "center" in st else "right" if "right" in st else "left") if tk.type == "inline": row.append(korjaa(plain(tk.children))) if tk.type == "tr_close": (headers if not headers else rows).append(row) row = [] j += 1 headers = headers[0] rows = [[c if headers[k] in ("Vuosi", "Kierros") else tuhannet(c) for k, c in enumerate(r)] for r in rows] if pending_caption: otsikko, huom = pending_caption else: otsikko, huom = OTSIKOTTOMAT.get(" | ".join(headers[:2]), "Taulukko."), "" if liite: liite_tbl += 1 label, n = "Liitetaulukko", liite_tbl else: tbl_n += 1 label, n = "Taulukko", tbl_n note = [] if huom: note.append("Huom. " + huom) if "*" in " ".join(" ".join(r) for r in rows): note.append("* p < 0,05, ** p < 0,01, *** p < 0,001.") blocks.append({"t": "tbl", "label": label, "num": n, "title": otsikko, "headers": headers, "rows": rows, "align": aligns, "note": " ".join(note), "lahde": LAHDE.get(pending, ESS) if pending and pending.startswith("tbl") else ""}) pending_caption = None pending = None i = j + 1 continue if t.type in ("fence", "code_block"): blocks.append({"t": "code", "text": t.content.rstrip()}) i += 1 continue i += 1 # Tekstiviittaukset kuvioihin ja uudelleennumeroituihin taulukoihin def viitteet(t): t = re.sub(r"\bKuva (\d+)", r"kuvio \1", t) return re.sub(r"\bTaulukko ([12])\b", lambda m: f"taulukko {int(m.group(1)) + 1}", t) for b in blocks: if b["t"] == "p": b["md"] = viitteet(b["md"]) elif b["t"] in ("ul", "ol"): b["items"] = [viitteet(x) for x in b["items"]] tiiv = [] for b in blocks: if b["t"] == "h" and b["text"] == "Tiivistelmä": tiiv = [] continue if tiiv is not None and b["t"] == "p" and len([x for x in blocks if x["t"] == "h"]) and not any( x["t"] == "h" and x["text"] != "Tiivistelmä" for x in blocks[: blocks.index(b)]): tiiv.append(b["md"]) merkit = len(" ".join(tiiv).replace("*", "")) (HERE / "lohkot.json").write_text(json.dumps(blocks, ensure_ascii=False, indent=1), encoding="utf-8") laskuri = {} for b in blocks: laskuri[b["t"]] = laskuri.get(b["t"], 0) + 1 print("lohkot:", laskuri, "| tiivistelmän merkit:", merkit)