File size: 16,758 Bytes
11bcfa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
"""
GLM-OCR ๆฑŽ็”จ็”ปๅƒOCRใƒปExcelๅ‡บๅŠ›ใ‚นใ‚ฏใƒชใƒ—ใƒˆ

ใƒขใƒ‡ใƒซ : zai-org/GLM-OCR (HuggingFace)
่จญๅฎš   : YAML ใพใŸใฏ Excel (.xlsx) ใฎใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใƒ•ใ‚กใ‚คใƒซใงๆŠฝๅ‡บ้ …็›ฎใƒป็”ปๅƒใƒปๅ‡บๅŠ›ๅ…ˆใ‚’ๅฎš็พฉ
ไฝฟใ„ๆ–น :
    python glmocr.py --config configs/invoice.yaml
    python glmocr.py --config configs/invoice.xlsx
    python glmocr.py --config configs/invoice.yaml --image scan.pdf
    python glmocr.py --config configs/invoice.yaml --create-excel   # Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆ็”Ÿๆˆ
ๅ‡บๅŠ›   : {output_dir}/{configๅ}.xlsx๏ผˆใ‚ปใ‚ฏใ‚ทใƒงใƒณใ”ใจใซใ‚ทใƒผใƒˆใ‚’ๅˆ†ใ‘ใฆไฟๅญ˜๏ผ‰
         PDF ่ค‡ๆ•ฐใƒšใƒผใ‚ธใฎๅ ดๅˆใฏใ‚ทใƒผใƒˆๅใ‚’ P01_/P02_... ใงใƒšใƒผใ‚ธๅŒบๅˆฅใ™ใ‚‹
"""

import argparse
import json
import re
import sys
from html.parser import HTMLParser
from pathlib import Path

from config_loader import load_config, create_excel_template
from preprocess import apply_preprocess, load_input_images

# Windows ใ‚ณใƒณใ‚ฝใƒผใƒซใฎๆ–‡ๅญ—ๅŒ–ใ‘ๅฏพ็ญ–
if sys.stdout.encoding != "utf-8":
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if sys.stderr.encoding != "utf-8":
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")

import pandas as pd
import torch
from transformers import AutoProcessor, AutoModelForImageTextToText

MODEL_ID = "zai-org/GLM-OCR"


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# JSON ใ‚นใ‚ญใƒผใƒžๅ‹•็š„็”Ÿๆˆ
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def build_json_schema(sections: dict) -> str:
    """YAML sections ๅฎš็พฉใ‹ใ‚‰ GLM-OCR ็”จ JSON ใ‚นใ‚ญใƒผใƒžๆ–‡ๅญ—ๅˆ—ใ‚’็”Ÿๆˆใ™ใ‚‹ใ€‚

    Args:
        sections: YAML ใฎ sections ่พžๆ›ธ

    Returns:
        str: JSON ใ‚นใ‚ญใƒผใƒžๆ–‡ๅญ—ๅˆ—
    """
    schema = {name: cfg["fields"] for name, cfg in sections.items()}
    return json.dumps(schema, ensure_ascii=False, indent=2)


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ใƒขใƒ‡ใƒซ่ชญใฟ่พผใฟ
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def load_model():
    """GLM-OCR ใƒขใƒ‡ใƒซใจ Processor ใ‚’่ชญใฟ่พผใ‚€ใ€‚

    Returns:
        tuple[AutoModelForImageTextToText, AutoProcessor]: ใƒขใƒ‡ใƒซใจใƒ—ใƒญใ‚ปใƒƒใ‚ต
    """
    print(f"[INFO] ใƒขใƒ‡ใƒซใ‚’่ชญใฟ่พผใ‚“ใงใ„ใพใ™: {MODEL_ID}")
    processor = AutoProcessor.from_pretrained(MODEL_ID)
    model = AutoModelForImageTextToText.from_pretrained(
        MODEL_ID,
        torch_dtype="auto",
        device_map="auto",
    )
    model.eval()
    print(f"[INFO] ใƒขใƒ‡ใƒซ่ชญใฟ่พผใฟๅฎŒไบ† (device: {model.device})")
    return model, processor


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ๆŽจ่ซ–
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def run_ocr(model, processor, pil_image: Image.Image, prompt: str) -> str:
    """ๅ˜ไธ€ใƒ—ใƒญใƒณใƒ—ใƒˆใง GLM-OCR ๆŽจ่ซ–ใ‚’ๅฎŸ่กŒใ™ใ‚‹ใ€‚

    Args:
        model: GLM-OCR ใƒขใƒ‡ใƒซ
        processor: GLM-OCR ใƒ—ใƒญใ‚ปใƒƒใ‚ต
        pil_image: ๅ…ฅๅŠ›็”ปๅƒ (PIL.Image)
        prompt: OCR ใƒ—ใƒญใƒณใƒ—ใƒˆๆ–‡ๅญ—ๅˆ—

    Returns:
        str: ใƒขใƒ‡ใƒซใŒ็”Ÿๆˆใ—ใŸใƒ†ใ‚ญใ‚นใƒˆ
    """
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "image", "image": pil_image},
                {"type": "text", "text": prompt},
            ],
        }
    ]

    inputs = processor.apply_chat_template(
        messages,
        tokenize=True,
        add_generation_prompt=True,
        return_dict=True,
        return_tensors="pt",
    )
    inputs.pop("token_type_ids", None)
    inputs = {k: v.to(model.device) for k, v in inputs.items()}

    with torch.no_grad():
        generated_ids = model.generate(**inputs, max_new_tokens=8192)

    output_text = processor.decode(
        generated_ids[0][inputs["input_ids"].shape[1]:],
        skip_special_tokens=True,
    )
    return output_text.strip()


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ใƒ‘ใƒผใ‚น: HTML ใƒ†ใƒผใƒ–ใƒซ โ†’ DataFrame
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class _HtmlTableParser(HTMLParser):
    """HTML ใƒ†ใƒผใƒ–ใƒซใ‚’ใƒ‘ใƒผใ‚นใ—ใฆ่กŒใƒชใ‚นใƒˆใ‚’ๅŽ้›†ใ™ใ‚‹ใ‚ทใƒณใƒ—ใƒซใชใƒ‘ใƒผใ‚ตใƒผใ€‚"""

    def __init__(self):
        super().__init__()
        self.rows: list[list[str]] = []
        self._current_row: list[str] = []
        self._current_cell: str = ""
        self._in_cell: bool = False

    def handle_starttag(self, tag, attrs):
        if tag == "tr":
            self._current_row = []
        elif tag in ("td", "th"):
            self._current_cell = ""
            self._in_cell = True

    def handle_endtag(self, tag):
        if tag in ("td", "th"):
            self._current_row.append(self._current_cell.strip())
            self._in_cell = False
        elif tag == "tr":
            if self._current_row:
                self.rows.append(self._current_row)

    def handle_data(self, data):
        if self._in_cell:
            self._current_cell += data


def parse_html_table(text: str) -> pd.DataFrame:
    """OCR ๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰ HTML ใƒ†ใƒผใƒ–ใƒซใ‚’ๆŠฝๅ‡บใ—ใฆ DataFrame ใซๅค‰ๆ›ใ™ใ‚‹ใ€‚

    Args:
        text: OCR ใƒขใƒ‡ใƒซใฎๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆ

    Returns:
        pd.DataFrame: ใƒ†ใƒผใƒ–ใƒซใƒ‡ใƒผใ‚ฟใ€‚่ฆ‹ใคใ‹ใ‚‰ใชใ„ๅ ดๅˆใฏ็ฉบใฎ DataFrameใ€‚
    """
    match = re.search(r"<table.*?>.*?</table>", text, re.DOTALL | re.IGNORECASE)
    if not match:
        return pd.DataFrame()

    parser = _HtmlTableParser()
    parser.feed(match.group(0))

    if len(parser.rows) < 2:
        return pd.DataFrame()

    return pd.DataFrame(parser.rows[1:], columns=parser.rows[0])


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ใƒ‘ใƒผใ‚น: Markdown ใƒ†ใƒผใƒ–ใƒซ โ†’ DataFrame
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def parse_markdown_table(text: str) -> pd.DataFrame:
    """OCR ๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰ Markdown ใƒ†ใƒผใƒ–ใƒซใ‚’ๆŠฝๅ‡บใ—ใฆ DataFrame ใซๅค‰ๆ›ใ™ใ‚‹ใ€‚

    Args:
        text: OCR ใƒขใƒ‡ใƒซใฎๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆ

    Returns:
        pd.DataFrame: ใƒ†ใƒผใƒ–ใƒซใƒ‡ใƒผใ‚ฟใ€‚่ฆ‹ใคใ‹ใ‚‰ใชใ„ๅ ดๅˆใฏ็ฉบใฎ DataFrameใ€‚
    """
    table_lines = [l for l in text.splitlines() if "|" in l]
    if len(table_lines) < 2:
        return pd.DataFrame()

    data_lines = [l for l in table_lines if not re.match(r"^\|[\s\-:|]+\|$", l)]
    rows = [[c.strip() for c in l.strip().strip("|").split("|")] for l in data_lines]

    if not rows:
        return pd.DataFrame()
    return pd.DataFrame(rows[1:], columns=rows[0])


def parse_table(text: str) -> pd.DataFrame:
    """HTML ใพใŸใฏ Markdown ใƒ†ใƒผใƒ–ใƒซใ‚’่‡ชๅ‹•ๅˆคๅˆฅใ—ใฆใƒ‘ใƒผใ‚นใ™ใ‚‹ใ€‚

    Args:
        text: OCR ใƒขใƒ‡ใƒซใฎๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆ

    Returns:
        pd.DataFrame: ใƒ†ใƒผใƒ–ใƒซใƒ‡ใƒผใ‚ฟใ€‚่ฆ‹ใคใ‹ใ‚‰ใชใ„ๅ ดๅˆใฏ็ฉบใฎ DataFrameใ€‚
    """
    if "<table" in text.lower():
        return parse_html_table(text)
    return parse_markdown_table(text)


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ใƒ‘ใƒผใ‚น: JSON ใƒ†ใ‚ญใ‚นใƒˆ โ†’ dict
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def parse_json_output(text: str) -> dict:
    """OCR ๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰ JSON ้ƒจๅˆ†ใ‚’ๆŠฝๅ‡บใ—ใฆใƒ‘ใƒผใ‚นใ™ใ‚‹ใ€‚

    Args:
        text: OCR ใƒขใƒ‡ใƒซใฎๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆ

    Returns:
        dict: ใƒ‘ใƒผใ‚นใ•ใ‚ŒใŸ JSON ใƒ‡ใƒผใ‚ฟใ€‚ๅคฑๆ•—ๆ™‚ใฏ็ฉบใฎ dictใ€‚
    """
    code_block = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
    json_str = code_block.group(1) if code_block else None

    if not json_str:
        brace_match = re.search(r"\{.*\}", text, re.DOTALL)
        if not brace_match:
            return {}
        json_str = brace_match.group(0)

    try:
        return json.loads(json_str)
    except json.JSONDecodeError:
        json_str_fixed = re.sub(r",\s*([}\]])", r"\1", json_str)
        try:
            return json.loads(json_str_fixed)
        except json.JSONDecodeError:
            return {}


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Excel ไฟๅญ˜๏ผˆๅ…จใ‚ทใƒผใƒˆใพใจใ‚ๆ›ธใ๏ผ‰
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def save_excel(sheets: dict[str, pd.DataFrame], filepath: Path) -> None:
    """่ค‡ๆ•ฐใฎ DataFrame ใ‚’ 1 ใคใฎ Excel ใƒ•ใ‚กใ‚คใƒซใซใ‚ทใƒผใƒˆใ”ใจใซไฟๅญ˜ใ™ใ‚‹ใ€‚

    Args:
        sheets: {ใ‚ทใƒผใƒˆๅ: DataFrame} ใฎ่พžๆ›ธ๏ผˆ็ฉบใฎ DataFrame ใฏ็ฉบใ‚ทใƒผใƒˆใจใ—ใฆไฟๅญ˜๏ผ‰
        filepath: ๅ‡บๅŠ›ๅ…ˆ Excel ใƒ•ใ‚กใ‚คใƒซใฎใƒ‘ใ‚น (.xlsx)
    """
    filepath.parent.mkdir(parents=True, exist_ok=True)
    with pd.ExcelWriter(filepath, engine="openpyxl") as writer:
        for sheet_name, df in sheets.items():
            # Excel ใ‚ทใƒผใƒˆๅใฏ 31 ๆ–‡ๅญ—ไปฅๅ†…ใฎๅˆถ้™ใ‚ใ‚Š
            safe_name = sheet_name[:31]
            df.to_excel(writer, sheet_name=safe_name, index=False)
            row_info = f"{len(df)} ่กŒ" if not df.empty else "ใƒ‡ใƒผใ‚ฟใชใ—"
            print(f"[OK]   ใ‚ทใƒผใƒˆ '{safe_name}' ใ‚’ๆ›ธใ่พผใฟใพใ—ใŸ ({row_info})")
    print(f"[OK]   Excel ไฟๅญ˜ๅฎŒไบ†: {filepath}")


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ใ‚ปใ‚ฏใ‚ทใƒงใƒณ dict โ†’ DataFrame ๅค‰ๆ›
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def section_to_df(section: dict) -> pd.DataFrame:
    """1 ใƒฌใƒ™ใƒซใฎ dict ใ‚’ใ€Œkey / valueใ€ใฎ 2 ๅˆ— DataFrame ใซๅค‰ๆ›ใ™ใ‚‹ใ€‚

    Args:
        section: ใ‚ญใƒผใจๅ€คใ‚’ๆŒใค่พžๆ›ธ

    Returns:
        pd.DataFrame: key / value ใฎ 2 ๅˆ— DataFrame
    """
    if not section:
        return pd.DataFrame()
    return pd.DataFrame({"key": list(section.keys()), "value": list(section.values())})


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ใƒกใ‚คใƒณ
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def main():
    """ใƒกใ‚คใƒณๅ‡ฆ็†: ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ่ชญใฟ่พผใฟ โ†’ ็”ปๅƒOCR โ†’ Excel ๅ‡บๅŠ›ใ€‚"""
    parser = argparse.ArgumentParser(description="GLM-OCR ๆฑŽ็”จ็”ปๅƒOCRใƒปCSVๅ‡บๅŠ›ใ‚นใ‚ฏใƒชใƒ—ใƒˆ")
    parser.add_argument(
        "--config", "-c", required=True, type=Path,
        help="ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใƒ•ใ‚กใ‚คใƒซใฎใƒ‘ใ‚น๏ผˆ.yaml ใพใŸใฏ .xlsx๏ผ‰ไพ‹: configs/invoice.yaml",
    )
    parser.add_argument(
        "--image", "-i", type=Path, default=None,
        help="็”ปๅƒใƒ•ใ‚กใ‚คใƒซใฎใƒ‘ใ‚น๏ผˆ็œ็•ฅๆ™‚ใฏใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใฎ image ่จญๅฎšใ‚’ไฝฟ็”จ๏ผ‰",
    )
    parser.add_argument(
        "--create-excel", action="store_true",
        help="ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใ‚’่ชญใฟ่พผใ‚“ใง Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆใ‚’็”Ÿๆˆใ—ใฆ็ต‚ไบ†ใ™ใ‚‹",
    )
    args = parser.parse_args()

    # โ”€โ”€ ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ่ชญใฟ่พผใฟ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    config_path = args.config.resolve()
    if not config_path.exists():
        print(f"[ERROR] ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใŒ่ฆ‹ใคใ‹ใ‚Šใพใ›ใ‚“: {config_path}", file=sys.stderr)
        sys.exit(1)

    cfg = load_config(config_path)

    # โ”€โ”€ Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆ็”Ÿๆˆใƒขใƒผใƒ‰ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if args.create_excel:
        xlsx_path = config_path.with_suffix(".xlsx")
        create_excel_template(cfg, xlsx_path)
        print(f"[INFO] Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆใ‚’็”Ÿๆˆใ—ใพใ—ใŸ: {xlsx_path}")
        sys.exit(0)
    config_dir = config_path.parent.parent  # configs/ ใฎ่ฆช = ใ‚นใ‚ฏใƒชใƒ—ใƒˆใฎใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒช

    # ็”ปๅƒใƒ‘ใ‚นใฎ่งฃๆฑบ๏ผˆCLIๅผ•ๆ•ฐ > YAML่จญๅฎš๏ผ‰
    if args.image:
        image_path = args.image.resolve()
    else:
        image_path = (config_dir / cfg["image"]).resolve()

    output_dir = (config_dir / cfg.get("output_dir", "output")).resolve()
    extract_table: bool = cfg.get("extract_table", True)
    sections: dict = cfg.get("sections", {})

    if not image_path.exists():
        print(f"[ERROR] ็”ปๅƒใŒ่ฆ‹ใคใ‹ใ‚Šใพใ›ใ‚“: {image_path}", file=sys.stderr)
        sys.exit(1)

    # ๅ‡บๅŠ› Excel ใƒ•ใ‚กใ‚คใƒซๅ: {configๅ}.xlsx
    excel_path = output_dir / f"{config_path.stem}.xlsx"
    preprocess_cfg: dict = cfg.get("preprocess", {})

    print(f"[INFO] ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ : {config_path.name}")
    print(f"[INFO] ๅฏพ่ฑกใƒ•ใ‚กใ‚คใƒซ: {image_path}")
    print(f"[INFO] ๅ‡บๅŠ›ๅ…ˆ    : {excel_path}")
    print(f"[INFO] ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜: {'ใ‚ใ‚Š' if extract_table else 'ใชใ—'}")
    print(f"[INFO] ๆŠฝๅ‡บใ‚ปใ‚ฏใ‚ทใƒงใƒณ: {list(sections.keys())}")
    print(f"[INFO] ๅ‰ๅ‡ฆ็†่จญๅฎš: {preprocess_cfg or 'ๅ…จใ‚นใƒ†ใƒƒใƒ— ON๏ผˆใƒ‡ใƒ•ใ‚ฉใƒซใƒˆ๏ผ‰'}")

    # โ”€โ”€ ๅ…ฅๅŠ›่ชญใฟ่พผใฟ๏ผˆ็”ปๅƒ or PDF ๅ…จใƒšใƒผใ‚ธ๏ผ‰โ”€โ”€
    print(f"\n[INFO] ใƒ•ใ‚กใ‚คใƒซใ‚’่ชญใฟ่พผใ‚“ใงใ„ใพใ™...")
    raw_pages = load_input_images(image_path)
    total_pages = len(raw_pages)
    print(f"[INFO] ใƒšใƒผใ‚ธๆ•ฐ: {total_pages}")

    # โ”€โ”€ ใƒขใƒ‡ใƒซ่ชญใฟ่พผใฟ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    model, processor = load_model()

    # ๆ›ธใ่พผใ‚€ใ‚ทใƒผใƒˆใ‚’ๅŽ้›†ใ™ใ‚‹่พžๆ›ธ {ใ‚ทใƒผใƒˆๅ: DataFrame}
    sheets: dict[str, pd.DataFrame] = {}

    # โ”€โ”€ ๅ„ใƒšใƒผใ‚ธใ‚’ๅ‡ฆ็† โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    for page_no, raw_image in enumerate(raw_pages, start=1):
        # ่ค‡ๆ•ฐใƒšใƒผใ‚ธใฎๅ ดๅˆใฏใ‚ทใƒผใƒˆๅใซ P01_ / P02_ ... ใ‚’ไป˜ไธŽ
        prefix = f"P{page_no:02d}_" if total_pages > 1 else ""
        print(f"\n{'โ”€' * 50}")
        print(f"[INFO] ใƒšใƒผใ‚ธ {page_no}/{total_pages} ใ‚’ๅ‡ฆ็†ไธญ...")

        # ๅ‰ๅ‡ฆ็†
        pil_image = apply_preprocess(raw_image, preprocess_cfg)
        print(f"[INFO] ็”ปๅƒใ‚ตใ‚คใ‚บ: {pil_image.size}")

        # โ”€โ”€ ๆŽจ่ซ–โ‘ : ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜๏ผˆใ‚ชใƒ—ใ‚ทใƒงใƒณ๏ผ‰โ”€โ”€
        if extract_table:
            print("[INFO] ๆŽจ่ซ–โ‘  ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜ ใ‚’ๅฎŸ่กŒไธญ...")
            table_text = run_ocr(model, processor, pil_image, "Table Recognition:")
            print("[RAW] ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜ ๅ‡บๅŠ›:")
            print(table_text)
            print()
            sheets[f"{prefix}table"] = parse_table(table_text)

        # โ”€โ”€ ๆŽจ่ซ–โ‘ก: ๆง‹้€ ๅŒ– JSON ๆŠฝๅ‡บ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        if sections:
            print("[INFO] ๆŽจ่ซ–โ‘ก ๆง‹้€ ๅŒ– JSON ๆŠฝๅ‡บ ใ‚’ๅฎŸ่กŒไธญ...")
            json_schema = build_json_schema(sections)
            extract_prompt = (
                "Extract all the following information from this image "
                "and fill in the JSON template below. "
                "Return only valid JSON, no extra text.\n\n"
                + json_schema
            )
            json_text = run_ocr(model, processor, pil_image, extract_prompt)
            print("[RAW] JSON ๆŠฝๅ‡บ ๅ‡บๅŠ›:")
            print(json_text)
            print()

            data = parse_json_output(json_text)
            for section_name, section_cfg in sections.items():
                label = f"{prefix}{section_cfg.get('label', section_name)}"
                sheets[label] = section_to_df(data.get(section_name, {}))

    # โ”€โ”€ Excel ไฟๅญ˜ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    print()
    save_excel(sheets, excel_path)

    # โ”€โ”€ ็ตๆžœใ‚ตใƒžใƒชใƒผ่กจ็คบ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    print("\n" + "=" * 60)
    print("  ๅ‡บๅŠ›็ตๆžœใ‚ตใƒžใƒชใƒผ")
    print("=" * 60)

    for sheet_name, df in sheets.items():
        print(f"\nโ–ผ {sheet_name}")
        print(df.to_string(index=False) if not df.empty else "  (ใƒ‡ใƒผใ‚ฟใชใ—)")

    print("\n[INFO] ๅ…จๅ‡ฆ็†ใŒๅฎŒไบ†ใ—ใพใ—ใŸใ€‚")


if __name__ == "__main__":
    main()