{ "cells": [ { "cell_type": "markdown", "id": "147fd50f", "metadata": {}, "source": [ "# Save tables as JSON and CSV" ] }, { "cell_type": "code", "execution_count": 1, "id": "831f0525", "metadata": { "execution": { "iopub.execute_input": "2026-11-01T08:16:27.943392Z", "iopub.status.busy": "2026-11-01T08:16:27.943313Z", "iopub.status.idle": "2026-11-01T08:16:38.336602Z", "shell.execute_reply": "2026-11-01T08:16:38.336220Z" }, "scrolled": false }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Loaded DBNet detector (CPU, threads=8)\n", "Loaded SVTR recognizer (vocab=185 chars, CPU, threads=8)\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "[occular] LM (pure Python): compact_lm.npz (268 MB), unigrams=2010937, alpha=0.5 beta=1.0 beam=100\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved invoice.json with 2 table(s)\n" ] } ], "source": [ "import json\n", "from pathlib import Path\n", "from occular import ocr_detailed\n", "\n", "lines = ocr_detailed(\"invoice.png\", tables=True)\n", "data = {\"results\": list(lines), \"tables\": lines.tables}\n", "Path(\"invoice.json\").write_text(\n", " json.dumps(data, ensure_ascii=False, indent=2), encoding=\"utf-8\"\n", ")\n", "print(\"Saved invoice.json with\", len(lines.tables), \"table(s)\")" ] }, { "cell_type": "code", "execution_count": 2, "id": "8428e185", "metadata": { "execution": { "iopub.execute_input": "2026-11-01T08:16:38.337616Z", "iopub.status.busy": "2026-11-01T08:16:38.337479Z", "iopub.status.idle": "2026-11-01T08:16:38.340763Z", "shell.execute_reply": "2026-11-01T08:16:38.340439Z" }, "scrolled": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CSV — header and first data row\n", "N,\"Товары (работы, услуги)\",Кол- во,Ед.,Цена,Сумма\n", "в,Транспортно-экспедиционные услуги по маршруту Нижний Новгород — Казань,4,рейс,\"18 500,00\",\"74 000,00\"\n" ] } ], "source": [ "import csv\n", "\n", "table = lines.tables[-1]\n", "rows = [[\"\"] * table[\"n_cols\"] for _ in range(table[\"n_rows\"])]\n", "for cell in table[\"cells\"]:\n", " rows[cell[\"r\"]][cell[\"c\"]] = cell[\"text\"]\n", "with open(\"table.csv\", \"w\", newline=\"\", encoding=\"utf-8-sig\") as file:\n", " csv.writer(file).writerows(rows)\n", "print(\"CSV — header and first data row\")\n", "saved_csv = Path(\"table.csv\").read_text(encoding=\"utf-8-sig\")\n", "print(\"\\n\".join(saved_csv.splitlines()[:2]))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.3" } }, "nbformat": 4, "nbformat_minor": 5 }