#!/usr/bin/env python3 """Render Docling JSON table(s) as a local HTML preview.""" import argparse import html import json from pathlib import Path import re def render_table(table, idx): cells = table.get("data", {}).get("table_cells", []) if not cells: return f'

Tabel {idx + 1}

Ingen tabelceller fundet.

' max_row = max(int(c.get("end_row_offset_idx", int(c.get("start_row_offset_idx", 0)) + int(c.get("row_span", 1))) - 1) for c in cells) max_col = max(int(c.get("end_col_offset_idx", int(c.get("start_col_offset_idx", 0)) + int(c.get("col_span", 1))) - 1) for c in cells) grid = {} for c in cells: r = int(c.get("start_row_offset_idx", 0)) col = int(c.get("start_col_offset_idx", 0)) grid[(r, col)] = (c, max(1, int(c.get("row_span", 1))), max(1, int(c.get("col_span", 1)))) out = [f'

Tabel {idx + 1}

'] r = 0 while r <= max_row: out.append("") col = 0 while col <= max_col: item = grid.get((r, col)) if item: c, rs, cs = item text = html.escape(str(c.get("text", ""))).replace("\n", "
") classes = [] if c.get("column_header"): classes.append("column-header") if c.get("row_header"): classes.append("row-header") if not text.strip(): classes.append("empty") attrs = (f' rowspan="{rs}"' if rs > 1 else "") + (f' colspan="{cs}"' if cs > 1 else "") cls = f' class="{" ".join(classes)}"' if classes else "" out.append(f"{text or ' '}") col += cs else: out.append('') col += 1 out.append("") r += 1 out.append("
∅
") return "".join(out) def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("json_files", nargs="+", help="Docling JSON file(s)") ap.add_argument("-o", "--output", help="Output HTML file") args = ap.parse_args() files = [Path(p) for p in args.json_files] docs = [] for path in files: obj = json.loads(path.read_text(encoding="utf-8")) title = obj.get("name", path.stem) headings = [t.get("text", "") for t in obj.get("texts", []) if t.get("label") == "section_header" and t.get("text")] heading = headings[0] if headings else title sections = [f'

{html.escape(heading)}

{html.escape(path.name)}

'] tables = obj.get("tables", []) if not tables: sections.append("

Ingen tabeller fundet.

") sections.extend(render_table(table, i) for i, table in enumerate(tables)) sections.append("
") docs.append("".join(sections)) output = Path(args.output) if args.output else files[0].with_suffix(".preview.html") page = """ Docling-skema preview """ + "\n".join(docs) + "\n" output.write_text(page, encoding="utf-8") print(f"Skrev: {output}") if __name__ == "__main__": main()