showeed commited on
Commit
efd3c0f
ยท
verified ยท
1 Parent(s): 91bbc2d

Upload 9 files

Browse files
OCR_tool_glm/OCRๆคœ่จผ.webp ADDED

Git LFS Details

  • SHA256: 9d75b17a06da5c1450bfe88298e8612847dd5eb338e7cf6174632d21722367c4
  • Pointer size: 130 Bytes
  • Size of remote file: 47.9 kB
OCR_tool_glm/config_loader.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ่ชญใฟ่พผใฟใƒปExcel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆ็”Ÿๆˆใƒขใ‚ธใƒฅใƒผใƒซ
3
+
4
+ YAML ใพใŸใฏ Excel (.xlsx) ใฎใฉใกใ‚‰ใงใ‚‚ๅŒใ˜ dict ๆง‹้€ ใ‚’่ฟ”ใ™ใ€‚
5
+ glmocr.py / glmocr_ollama.py ๅŒๆ–นใ‹ใ‚‰ import ใ—ใฆไฝฟใ†ใ€‚
6
+
7
+ Excel ใƒ•ใ‚ฉใƒผใƒžใƒƒใƒˆ๏ผˆ3 ใ‚ทใƒผใƒˆๆง‹ๆˆ๏ผ‰:
8
+ settings โ€ฆ image / output_dir / extract_table
9
+ preprocess โ€ฆ ๅ‰ๅ‡ฆ็†ใ‚นใƒ†ใƒƒใƒ—ใฎ ON/OFF
10
+ sections โ€ฆ ๆŠฝๅ‡บใ‚ปใ‚ฏใ‚ทใƒงใƒณใƒปใƒ•ใ‚ฃใƒผใƒซใƒ‰ใฎไธ€่ฆงใƒ†ใƒผใƒ–ใƒซ
11
+
12
+ ไฝฟใ„ๆ–น:
13
+ from config_loader import load_config, create_excel_template
14
+
15
+ cfg = load_config(Path("configs/invoice.yaml")) # YAML
16
+ cfg = load_config(Path("configs/invoice.xlsx")) # Excel
17
+ create_excel_template(cfg, Path("configs/new.xlsx"))
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from pathlib import Path
23
+
24
+ import openpyxl
25
+ from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
26
+ import yaml
27
+
28
+
29
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
30
+ # ๅ†…้ƒจใƒฆใƒผใƒ†ใ‚ฃใƒชใƒ†ใ‚ฃ
31
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
32
+
33
+ def _to_bool(value) -> bool:
34
+ """ใ‚ปใƒซๅ€คใ‚’ bool ใซๅค‰ๆ›ใ™ใ‚‹๏ผˆExcel ใฎ TRUE/FALSE ๆ–‡ๅญ—ๅˆ—ใซใ‚‚ๅฏพๅฟœ๏ผ‰ใ€‚"""
35
+ if isinstance(value, bool):
36
+ return value
37
+ return str(value).strip().upper() in ("TRUE", "YES", "1", "ใ€‡", "ON")
38
+
39
+
40
+ def _header_style(ws, row: int, fill_color: str = "4472C4"):
41
+ """ๆŒ‡ๅฎš่กŒใ‚’ใƒ˜ใƒƒใƒ€ใƒผ่กŒใจใ—ใฆใ‚นใ‚ฟใ‚คใƒซใ‚’้ฉ็”จใ™ใ‚‹ใ€‚"""
42
+ fill = PatternFill(start_color=fill_color, end_color=fill_color, fill_type="solid")
43
+ font = Font(color="FFFFFF", bold=True)
44
+ border = Border(
45
+ bottom=Side(style="medium", color="FFFFFF"),
46
+ )
47
+ for cell in ws[row]:
48
+ cell.fill = fill
49
+ cell.font = font
50
+ cell.alignment = Alignment(horizontal="center", vertical="center")
51
+ cell.border = border
52
+
53
+
54
+ def _zebra_row(ws, row: int, is_odd: bool):
55
+ """ๅถๆ•ฐ/ๅฅ‡ๆ•ฐ่กŒใง่ƒŒๆ™ฏ่‰ฒใ‚’ไบคไบ’ใซใ™ใ‚‹๏ผˆใ‚ผใƒ–ใƒฉใ‚นใƒˆใƒฉใ‚คใƒ—๏ผ‰ใ€‚"""
56
+ color = "EAF2FF" if is_odd else "FFFFFF"
57
+ fill = PatternFill(start_color=color, end_color=color, fill_type="solid")
58
+ for cell in ws[row]:
59
+ cell.fill = fill
60
+
61
+
62
+ def _set_column_widths(ws, widths: list[int]):
63
+ """ๅˆ—ๅน…ใ‚’ไธ€ๆ‹ฌ่จญๅฎšใ™ใ‚‹ใ€‚"""
64
+ cols = list(ws.column_dimensions.keys())
65
+ for i, w in enumerate(widths):
66
+ col = cols[i] if i < len(cols) else chr(65 + i)
67
+ ws.column_dimensions[col].width = w
68
+
69
+
70
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
71
+ # YAML ่ชญใฟ่พผใฟ
72
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
73
+
74
+ def _load_yaml(path: Path) -> dict:
75
+ """YAML ใƒ•ใ‚กใ‚คใƒซใ‚’ใƒญใƒผใƒ‰ใ—ใฆ dict ใ‚’่ฟ”ใ™ใ€‚"""
76
+ with path.open(encoding="utf-8") as f:
77
+ return yaml.safe_load(f)
78
+
79
+
80
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
81
+ # Excel ่ชญใฟ่พผใฟ
82
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
83
+
84
+ def _load_excel(path: Path) -> dict:
85
+ """Excel ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ (.xlsx) ใ‚’ใƒญใƒผใƒ‰ใ—ใฆ YAML ไบ’ๆ›ใฎ dict ใ‚’่ฟ”ใ™ใ€‚
86
+
87
+ ๆœŸๅพ…ใ™ใ‚‹ใ‚ทใƒผใƒˆ:
88
+ settings : Aๅˆ—=ใ‚ญใƒผ, Bๅˆ—=ๅ€ค (ใƒ˜ใƒƒใƒ€ใƒผ่กŒใฏ่ชญใฟ้ฃ›ใฐใ™)
89
+ preprocess : Aๅˆ—=ใ‚นใƒ†ใƒƒใƒ—ๅ, Bๅˆ—=TRUE/FALSE
90
+ sections : Aๅˆ—=section_key, Bๅˆ—=section_label, Cๅˆ—=field_key
91
+ """
92
+ wb = openpyxl.load_workbook(path, data_only=True)
93
+ cfg: dict = {}
94
+
95
+ # โ”€โ”€ settings ใ‚ทใƒผใƒˆ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
96
+ if "settings" in wb.sheetnames:
97
+ ws = wb["settings"]
98
+ rows = list(ws.iter_rows(min_row=2, values_only=True)) # 1่กŒ็›ฎใฏใƒ˜ใƒƒใƒ€ใƒผ
99
+ for row in rows:
100
+ if not row[0]:
101
+ continue
102
+ key = str(row[0]).strip()
103
+ val = row[1]
104
+ if key == "extract_table":
105
+ cfg[key] = _to_bool(val)
106
+ else:
107
+ cfg[key] = str(val).strip() if val is not None else ""
108
+
109
+ # โ”€โ”€ preprocess ใ‚ทใƒผใƒˆ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
110
+ if "preprocess" in wb.sheetnames:
111
+ ws = wb["preprocess"]
112
+ rows = list(ws.iter_rows(min_row=2, values_only=True))
113
+ preprocess: dict = {}
114
+ for row in rows:
115
+ if not row[0]:
116
+ continue
117
+ step = str(row[0]).strip()
118
+ preprocess[step] = _to_bool(row[1]) if row[1] is not None else True
119
+ cfg["preprocess"] = preprocess
120
+
121
+ # โ”€โ”€ sections ใ‚ทใƒผใƒˆ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
122
+ if "sections" in wb.sheetnames:
123
+ ws = wb["sections"]
124
+ rows = list(ws.iter_rows(min_row=2, values_only=True))
125
+ sections: dict = {}
126
+ for row in rows:
127
+ if not row[0]:
128
+ continue
129
+ sec_key = str(row[0]).strip()
130
+ sec_label = str(row[1]).strip() if row[1] else sec_key
131
+ field_key = str(row[2]).strip() if row[2] else None
132
+ if not field_key:
133
+ continue
134
+ if sec_key not in sections:
135
+ sections[sec_key] = {"label": sec_label, "fields": {}}
136
+ sections[sec_key]["fields"][field_key] = ""
137
+ cfg["sections"] = sections
138
+
139
+ return cfg
140
+
141
+
142
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
143
+ # ๅ…ฌ้–‹้–ขๆ•ฐ: ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ่ชญใฟ่พผใฟ
144
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
145
+
146
+ def load_config(config_path: Path) -> dict:
147
+ """YAML ใพใŸใฏ Excel (.xlsx) ใฎใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใ‚’่ชญใฟ่พผใ‚“ใง dict ใ‚’่ฟ”ใ™ใ€‚
148
+
149
+ ใƒ•ใ‚กใ‚คใƒซๆ‹กๅผตๅญใง่‡ชๅ‹•ๅˆคๅˆฅใ™ใ‚‹:
150
+ .yaml / .yml โ†’ YAML ใจใ—ใฆ่ชญใฟ่พผใ‚€
151
+ .xlsx โ†’ Excel ใจใ—ใฆ่ชญใฟ่พผใ‚€
152
+
153
+ Args:
154
+ config_path: ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใƒ•ใ‚กใ‚คใƒซใฎใƒ‘ใ‚น
155
+
156
+ Returns:
157
+ dict: ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ่พžๆ›ธ๏ผˆYAML ใจๅŒไธ€ๆง‹้€ ๏ผ‰
158
+
159
+ Raises:
160
+ ValueError: ๅฏพๅฟœใ—ใฆใ„ใชใ„ๆ‹กๅผตๅญใฎๅ ดๅˆ
161
+ """
162
+ suffix = config_path.suffix.lower()
163
+ if suffix in (".yaml", ".yml"):
164
+ return _load_yaml(config_path)
165
+ if suffix == ".xlsx":
166
+ return _load_excel(config_path)
167
+ raise ValueError(f"ๅฏพๅฟœใ—ใฆใ„ใชใ„ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐๅฝขๅผใงใ™: {suffix}๏ผˆ.yaml / .xlsx ใฎใฟๆœ‰ๅŠน๏ผ‰")
168
+
169
+
170
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
171
+ # ๅ…ฌ้–‹้–ขๆ•ฐ: Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆ็”Ÿๆˆ
172
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
173
+
174
+ # ใ‚ปใ‚ฏใ‚ทใƒงใƒณไธ€่ฆงใ‚ทใƒผใƒˆใฎใƒ˜ใƒƒใƒ€ใƒผ่ชฌๆ˜Žๆ–‡
175
+ _SECTIONS_HEADER_NOTE = (
176
+ "section_key๏ผˆๅค‰ๆ›ดไธๅฏ๏ผ‰"
177
+ " โ”‚ section_label๏ผˆExcelๅ‡บๅŠ›ๆ™‚ใฎใ‚ทใƒผใƒˆๅ๏ผ‰"
178
+ " โ”‚ field_key๏ผˆๅค‰ๆ›ดไธๅฏ๏ผ‰"
179
+ )
180
+
181
+ def create_excel_template(cfg: dict, xlsx_path: Path) -> None:
182
+ """ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ dict ใ‹ใ‚‰็ทจ้›†ใ—ใ‚„ใ™ใ„ Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆใ‚’็”Ÿๆˆใ™ใ‚‹ใ€‚
183
+
184
+ ็”Ÿๆˆใ•ใ‚Œใ‚‹ใ‚ทใƒผใƒˆ:
185
+ settings โ€ฆ ๅŸบๆœฌ่จญๅฎš๏ผˆimage / output_dir / extract_table๏ผ‰
186
+ preprocess โ€ฆ ๅ‰ๅ‡ฆ็†ใ‚นใƒ†ใƒƒใƒ— ON/OFF
187
+ sections โ€ฆ ๅ…จใ‚ปใ‚ฏใ‚ทใƒงใƒณใƒปใƒ•ใ‚ฃใƒผใƒซใƒ‰ใฎไธ€่ฆงใƒ†ใƒผใƒ–ใƒซ
188
+
189
+ Args:
190
+ cfg: load_config() ใงๅ–ๅพ—ใ—ใŸใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ dict
191
+ xlsx_path: ๅ‡บๅŠ›ๅ…ˆ xlsx ใƒ•ใ‚กใ‚คใƒซใƒ‘ใ‚น
192
+ """
193
+ wb = openpyxl.Workbook()
194
+
195
+ # โ”€โ”€ settings ใ‚ทใƒผใƒˆ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
196
+ ws_s = wb.active
197
+ ws_s.title = "settings"
198
+
199
+ ws_s.append(["ใ‚ญใƒผ", "ๅ€ค", "่ชฌๆ˜Ž"])
200
+ _header_style(ws_s, 1, "2E75B6")
201
+
202
+ data_s = [
203
+ ("image", cfg.get("image", ""), "ๅฏพ่ฑกใƒ•ใ‚กใ‚คใƒซใƒ‘ใ‚น๏ผˆ็”ปๅƒใพใŸใฏ PDF๏ผ‰"),
204
+ ("output_dir", cfg.get("output_dir", "output"), "Excel ๅ‡บๅŠ›ๅ…ˆใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒช"),
205
+ ("extract_table", cfg.get("extract_table", True), "ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜ใ‚’ๅฎŸ่กŒใ™ใ‚‹๏ผˆTRUE/FALSE๏ผ‰"),
206
+ ]
207
+ for i, row in enumerate(data_s, start=2):
208
+ ws_s.append(list(row))
209
+ _zebra_row(ws_s, i, i % 2 == 0)
210
+
211
+ _set_column_widths(ws_s, [22, 28, 44])
212
+
213
+ # โ”€โ”€ preprocess ใ‚ทใƒผใƒˆ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
214
+ ws_p = wb.create_sheet("preprocess")
215
+
216
+ ws_p.append(["ๅ‰ๅ‡ฆ็†ใ‚นใƒ†ใƒƒใƒ—", "ๆœ‰ๅŠน๏ผˆTRUE/FALSE๏ผ‰", "่ชฌๆ˜Ž"])
217
+ _header_style(ws_p, 1, "2E75B6")
218
+
219
+ default_pre = {"deskew": True, "denoise": True, "enhance_contrast": True, "sharpen": True}
220
+ pre_desc = {
221
+ "deskew": "ๅ‚พใ่ฃœๆญฃ๏ผˆใ‚นใ‚ญใƒฃใƒณใƒปๆ‰‹ๆŒใกๆ’ฎๅฝฑใฎๅ‚พใใ‚’ Hough ๅค‰ๆ›ใง่‡ชๅ‹•่ฃœๆญฃ๏ผ‰",
222
+ "denoise": "ใƒŽใ‚คใ‚บ้™คๅŽป๏ผˆใƒใ‚คใƒฉใƒ†ใƒฉใƒซใƒ•ใ‚ฃใƒซใ‚ฟใ€ใ‚จใƒƒใ‚ธใ‚’ไฟ่ญทใ—ใชใŒใ‚‰ๅนณๆป‘ๅŒ–๏ผ‰",
223
+ "enhance_contrast": "ใ‚ณใƒณใƒˆใƒฉใ‚นใƒˆๅผท่ชฟ๏ผˆ็…งๆ˜Žใƒ ใƒฉใซๆœ‰ๅŠนใช CLAHE๏ผ‰",
224
+ "sharpen": "ใ‚ทใƒฃใƒผใƒ—ๅŒ–๏ผˆUnsharp Masking ใงใผใ‘ใ‚’่ฃœๆญฃ๏ผ‰",
225
+ }
226
+ pre_cfg = cfg.get("preprocess", default_pre)
227
+ for i, (step, desc) in enumerate(pre_desc.items(), start=2):
228
+ ws_p.append([step, pre_cfg.get(step, True), desc])
229
+ _zebra_row(ws_p, i, i % 2 == 0)
230
+
231
+ _set_column_widths(ws_p, [22, 22, 54])
232
+
233
+ # โ”€โ”€ sections ใ‚ทใƒผใƒˆ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
234
+ ws_sec = wb.create_sheet("sections")
235
+
236
+ ws_sec.append(["section_key", "section_label", "field_key"])
237
+ _header_style(ws_sec, 1, "2E75B6")
238
+
239
+ row_idx = 2
240
+ sections = cfg.get("sections", {})
241
+ prev_sec = None
242
+ for sec_key, sec_cfg in sections.items():
243
+ label = sec_cfg.get("label", sec_key)
244
+ fields = sec_cfg.get("fields", {})
245
+ # ใ‚ปใ‚ฏใ‚ทใƒงใƒณใŒๅค‰ใ‚ใ‚‹ใŸใณใซ่‰ฒใ‚’ๅˆ‡ใ‚Šๆ›ฟใˆใ‚‹
246
+ is_odd = (list(sections.keys()).index(sec_key) % 2 == 0)
247
+ for field_key in fields:
248
+ ws_sec.append([sec_key, label, field_key])
249
+ _zebra_row(ws_sec, row_idx, is_odd)
250
+ row_idx += 1
251
+
252
+ _set_column_widths(ws_sec, [18, 22, 22])
253
+
254
+ # ๆณจ้‡ˆ่กŒ
255
+ ws_sec.append([])
256
+ ws_sec.append(["โ€ป section_key ใจ field_key ใฏใ‚นใ‚ฏใƒชใƒ—ใƒˆใŒๅ‚็…งใ™ใ‚‹ใ‚ญใƒผๅใงใ™ใ€‚ๅค‰ๆ›ดใ™ใ‚‹ๅ ดๅˆใฏไธ€่‡ดใ‚’็ขบ่ชใ—ใฆใใ ใ•ใ„ใ€‚"])
257
+ note_cell = ws_sec.cell(row=row_idx + 2, column=1)
258
+ note_cell.font = Font(color="888888", italic=True)
259
+
260
+ xlsx_path.parent.mkdir(parents=True, exist_ok=True)
261
+ wb.save(str(xlsx_path))
262
+ print(f"[OK] Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆ็”Ÿๆˆ: {xlsx_path}")
OCR_tool_glm/configs/invoice.xlsx ADDED
Binary file (7.53 kB). View file
 
OCR_tool_glm/configs/invoice.yaml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
2
+ # GLM-OCR ใ‚ฟใ‚นใ‚ฏ่จญๅฎš: ่ซ‹ๆฑ‚ๆ›ธ (Invoice)
3
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
4
+
5
+ # ๅฏพ่ฑกใƒ•ใ‚กใ‚คใƒซ๏ผˆ็”ปๅƒ: .jpg/.png/.webp ใชใฉใ€ใพใŸใฏPDF: .pdf๏ผ‰
6
+ image: "OCRๆคœ่จผ.webp"
7
+
8
+ # ๅ‡บๅŠ›ๅ…ˆใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒช๏ผˆใ‚นใ‚ฏใƒชใƒ—ใƒˆใ‹ใ‚‰ใฎ็›ธๅฏพใƒ‘ใ‚น๏ผ‰
9
+ output_dir: "output"
10
+
11
+ # ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜ใ‚’ๅฎŸ่กŒใ™ใ‚‹ใ‹๏ผˆๆ˜Ž็ดฐ่กŒใชใฉใŒใ‚ใ‚‹ๅ ดๅˆใฏ true๏ผ‰
12
+ extract_table: true
13
+
14
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
15
+ # ๅ‰ๅ‡ฆ็†่จญๅฎš๏ผˆOCR็ฒพๅบฆๅ‘ไธŠใฎใŸใ‚ใฎ็”ปๅƒๅ‰ๅ‡ฆ็†๏ผ‰
16
+ # ็œ็•ฅใ—ใŸๅ ดๅˆใฏใ™ในใฆ true๏ผˆๅ…จใ‚นใƒ†ใƒƒใƒ—ๆœ‰ๅŠน๏ผ‰
17
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
18
+ preprocess:
19
+ deskew: true # ๅ‚พใ่ฃœๆญฃ๏ผˆใ‚นใ‚ญใƒฃใƒณใƒปๆ‰‹ๆŒใกๆ’ฎๅฝฑใฎๅ‚พใใ‚’่‡ชๅ‹•่ฃœๆญฃ๏ผ‰
20
+ denoise: true # ใƒŽใ‚คใ‚บ้™คๅŽป๏ผˆใƒใ‚คใƒฉใƒ†ใƒฉใƒซใƒ•ใ‚ฃใƒซใ‚ฟใ€ใ‚จใƒƒใ‚ธใ‚’ไฟ่ญทใ—ใชใŒใ‚‰ๅนณๆป‘ๅŒ–๏ผ‰
21
+ enhance_contrast: true # ใ‚ณใƒณใƒˆใƒฉใ‚นใƒˆๅผท่ชฟ๏ผˆ็…งๆ˜Žใƒ ใƒฉใซๆœ‰ๅŠนใช CLAHE๏ผ‰
22
+ sharpen: true # ใ‚ทใƒฃใƒผใƒ—ๅŒ–๏ผˆUnsharp Masking ใงใผใ‘ใ‚’่ฃœๆญฃ๏ผ‰
23
+
24
+ # ๆŠฝๅ‡บใ™ใ‚‹ใ‚ปใ‚ฏใ‚ทใƒงใƒณๅฎš็พฉ
25
+ # - ใ‚ญใƒผๅ ใŒใใฎใพใพๅ‡บๅŠ›ใƒ•ใ‚กใ‚คใƒซๅใซใชใ‚Šใพใ™๏ผˆไพ‹: header โ†’ output_header.tsv๏ผ‰
26
+ # - label ใฏๅฎŸ่กŒใƒญใ‚ฐใซ่กจ็คบใ™ใ‚‹ๆ—ฅๆœฌ่ชžๅ
27
+ # - fields ใฎๅ€คใฏ็ฉบๆ–‡ๅญ—ใฎใพใพ๏ผˆใƒขใƒ‡ใƒซใŒๅŸ‹ใ‚ใฆใใ‚Œใพใ™๏ผ‰
28
+ sections:
29
+ header:
30
+ label: "ใƒ˜ใƒƒใƒ€ใƒผๆƒ…ๅ ฑ"
31
+ fields:
32
+ date: ""
33
+ invoice_no: ""
34
+ due_date: ""
35
+
36
+ issuer:
37
+ label: "็™บ่กŒ่€…ๆƒ…ๅ ฑ"
38
+ fields:
39
+ company: ""
40
+ address: ""
41
+ tel: ""
42
+ email: ""
43
+ registration_no: ""
44
+
45
+ billed_to:
46
+ label: "่ซ‹ๆฑ‚ๅ…ˆๆƒ…ๅ ฑ"
47
+ fields:
48
+ company: ""
49
+ address: ""
50
+
51
+ summary:
52
+ label: "ๅˆ่จˆๆƒ…ๅ ฑ"
53
+ fields:
54
+ subtotal: ""
55
+ tax_10pct: ""
56
+ tax_8pct: ""
57
+ total: ""
58
+
59
+ remittance:
60
+ label: "ๆŒฏ่พผๆƒ…ๅ ฑ"
61
+ fields:
62
+ bank: ""
63
+ branch: ""
64
+ account_type: ""
65
+ account_no: ""
66
+ account_name: ""
67
+ note: ""
OCR_tool_glm/configs/my.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
2
+ # GLM-OCR ใ‚ฟใ‚นใ‚ฏ่จญๅฎš: ้ ˜ๅŽๆ›ธ (Receipt)
3
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
4
+ # ้ ˜ๅŽๆ›ธใฏๆ˜Ž็ดฐใƒ†ใƒผใƒ–ใƒซใŒใชใ„ๅ ดๅˆใŒๅคšใ„ใฎใง extract_table: false
5
+
6
+ image: "test_yaml.webp"
7
+ output_dir: "output"
8
+ extract_table: true
9
+
10
+ sections:
11
+ address:
12
+ label: "ๅฎ›ๅ"
13
+ fields:
14
+ name: ""
15
+ address: ""
16
+ tel: ""
17
+
18
+ date:
19
+ label: "ๅ–ๅผ•ๆ—ฅ"
20
+ fields:
21
+ date: ""
22
+ receipt_no: ""
23
+ payment_method: ""
24
+
25
+ title:
26
+ label: "ใ‚ฟใ‚คใƒˆใƒซ"
27
+ fields:
28
+ title_name: ""
OCR_tool_glm/glmocr.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ GLM-OCR ๆฑŽ็”จ็”ปๅƒOCRใƒปExcelๅ‡บๅŠ›ใ‚นใ‚ฏใƒชใƒ—ใƒˆ
3
+
4
+ ใƒขใƒ‡ใƒซ : zai-org/GLM-OCR (HuggingFace)
5
+ ่จญๅฎš : YAML ใพใŸใฏ Excel (.xlsx) ใฎใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใƒ•ใ‚กใ‚คใƒซใงๆŠฝๅ‡บ้ …็›ฎใƒป็”ปๅƒใƒปๅ‡บๅŠ›ๅ…ˆใ‚’ๅฎš็พฉ
6
+ ไฝฟใ„ๆ–น :
7
+ python glmocr.py --config configs/invoice.yaml
8
+ python glmocr.py --config configs/invoice.xlsx
9
+ python glmocr.py --config configs/invoice.yaml --image scan.pdf
10
+ python glmocr.py --config configs/invoice.yaml --create-excel # Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆ็”Ÿๆˆ
11
+ ๅ‡บๅŠ› : {output_dir}/{configๅ}.xlsx๏ผˆใ‚ปใ‚ฏใ‚ทใƒงใƒณใ”ใจใซใ‚ทใƒผใƒˆใ‚’ๅˆ†ใ‘ใฆไฟๅญ˜๏ผ‰
12
+ PDF ่ค‡ๆ•ฐใƒšใƒผใ‚ธใฎๅ ดๅˆใฏใ‚ทใƒผใƒˆๅใ‚’ P01_/P02_... ใงใƒšใƒผใ‚ธๅŒบๅˆฅใ™ใ‚‹
13
+ """
14
+
15
+ import argparse
16
+ import json
17
+ import re
18
+ import sys
19
+ from html.parser import HTMLParser
20
+ from pathlib import Path
21
+
22
+ from config_loader import load_config, create_excel_template
23
+ from preprocess import apply_preprocess, load_input_images
24
+
25
+ # Windows ใ‚ณใƒณใ‚ฝใƒผใƒซใฎๆ–‡ๅญ—ๅŒ–ใ‘ๅฏพ็ญ–
26
+ if sys.stdout.encoding != "utf-8":
27
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
28
+ if sys.stderr.encoding != "utf-8":
29
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
30
+
31
+ import pandas as pd
32
+ import torch
33
+ from transformers import AutoProcessor, AutoModelForImageTextToText
34
+
35
+ MODEL_ID = "zai-org/GLM-OCR"
36
+
37
+
38
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
39
+ # JSON ใ‚นใ‚ญใƒผใƒžๅ‹•็š„็”Ÿๆˆ
40
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
41
+ def build_json_schema(sections: dict) -> str:
42
+ """YAML sections ๅฎš็พฉใ‹ใ‚‰ GLM-OCR ็”จ JSON ใ‚นใ‚ญใƒผใƒžๆ–‡ๅญ—ๅˆ—ใ‚’็”Ÿๆˆใ™ใ‚‹ใ€‚
43
+
44
+ Args:
45
+ sections: YAML ใฎ sections ่พžๆ›ธ
46
+
47
+ Returns:
48
+ str: JSON ใ‚นใ‚ญใƒผใƒžๆ–‡ๅญ—ๅˆ—
49
+ """
50
+ schema = {name: cfg["fields"] for name, cfg in sections.items()}
51
+ return json.dumps(schema, ensure_ascii=False, indent=2)
52
+
53
+
54
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
55
+ # ใƒขใƒ‡ใƒซ่ชญใฟ่พผใฟ
56
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
57
+ def load_model():
58
+ """GLM-OCR ใƒขใƒ‡ใƒซใจ Processor ใ‚’่ชญใฟ่พผใ‚€ใ€‚
59
+
60
+ Returns:
61
+ tuple[AutoModelForImageTextToText, AutoProcessor]: ใƒขใƒ‡ใƒซใจใƒ—ใƒญใ‚ปใƒƒใ‚ต
62
+ """
63
+ print(f"[INFO] ใƒขใƒ‡ใƒซใ‚’่ชญใฟ่พผใ‚“ใงใ„ใพใ™: {MODEL_ID}")
64
+ processor = AutoProcessor.from_pretrained(MODEL_ID)
65
+ model = AutoModelForImageTextToText.from_pretrained(
66
+ MODEL_ID,
67
+ torch_dtype="auto",
68
+ device_map="auto",
69
+ )
70
+ model.eval()
71
+ print(f"[INFO] ใƒขใƒ‡ใƒซ่ชญใฟ่พผใฟๅฎŒไบ† (device: {model.device})")
72
+ return model, processor
73
+
74
+
75
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
76
+ # ๆŽจ่ซ–
77
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
78
+ def run_ocr(model, processor, pil_image: Image.Image, prompt: str) -> str:
79
+ """ๅ˜ไธ€ใƒ—ใƒญใƒณใƒ—ใƒˆใง GLM-OCR ๆŽจ่ซ–ใ‚’ๅฎŸ่กŒใ™ใ‚‹ใ€‚
80
+
81
+ Args:
82
+ model: GLM-OCR ใƒขใƒ‡ใƒซ
83
+ processor: GLM-OCR ใƒ—ใƒญใ‚ปใƒƒใ‚ต
84
+ pil_image: ๅ…ฅๅŠ›็”ปๅƒ (PIL.Image)
85
+ prompt: OCR ใƒ—ใƒญใƒณใƒ—ใƒˆๆ–‡ๅญ—ๅˆ—
86
+
87
+ Returns:
88
+ str: ใƒขใƒ‡ใƒซใŒ็”Ÿๆˆใ—ใŸใƒ†ใ‚ญใ‚นใƒˆ
89
+ """
90
+ messages = [
91
+ {
92
+ "role": "user",
93
+ "content": [
94
+ {"type": "image", "image": pil_image},
95
+ {"type": "text", "text": prompt},
96
+ ],
97
+ }
98
+ ]
99
+
100
+ inputs = processor.apply_chat_template(
101
+ messages,
102
+ tokenize=True,
103
+ add_generation_prompt=True,
104
+ return_dict=True,
105
+ return_tensors="pt",
106
+ )
107
+ inputs.pop("token_type_ids", None)
108
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
109
+
110
+ with torch.no_grad():
111
+ generated_ids = model.generate(**inputs, max_new_tokens=8192)
112
+
113
+ output_text = processor.decode(
114
+ generated_ids[0][inputs["input_ids"].shape[1]:],
115
+ skip_special_tokens=True,
116
+ )
117
+ return output_text.strip()
118
+
119
+
120
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
121
+ # ใƒ‘ใƒผใ‚น: HTML ใƒ†ใƒผใƒ–ใƒซ โ†’ DataFrame
122
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
123
+ class _HtmlTableParser(HTMLParser):
124
+ """HTML ใƒ†ใƒผใƒ–ใƒซใ‚’ใƒ‘ใƒผใ‚นใ—ใฆ่กŒใƒชใ‚นใƒˆใ‚’ๅŽ้›†ใ™ใ‚‹ใ‚ทใƒณใƒ—ใƒซใชใƒ‘ใƒผใ‚ตใƒผใ€‚"""
125
+
126
+ def __init__(self):
127
+ super().__init__()
128
+ self.rows: list[list[str]] = []
129
+ self._current_row: list[str] = []
130
+ self._current_cell: str = ""
131
+ self._in_cell: bool = False
132
+
133
+ def handle_starttag(self, tag, attrs):
134
+ if tag == "tr":
135
+ self._current_row = []
136
+ elif tag in ("td", "th"):
137
+ self._current_cell = ""
138
+ self._in_cell = True
139
+
140
+ def handle_endtag(self, tag):
141
+ if tag in ("td", "th"):
142
+ self._current_row.append(self._current_cell.strip())
143
+ self._in_cell = False
144
+ elif tag == "tr":
145
+ if self._current_row:
146
+ self.rows.append(self._current_row)
147
+
148
+ def handle_data(self, data):
149
+ if self._in_cell:
150
+ self._current_cell += data
151
+
152
+
153
+ def parse_html_table(text: str) -> pd.DataFrame:
154
+ """OCR ๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰ HTML ใƒ†ใƒผใƒ–ใƒซใ‚’ๆŠฝๅ‡บใ—ใฆ DataFrame ใซๅค‰ๆ›ใ™ใ‚‹ใ€‚
155
+
156
+ Args:
157
+ text: OCR ใƒขใƒ‡ใƒซใฎๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆ
158
+
159
+ Returns:
160
+ pd.DataFrame: ใƒ†ใƒผใƒ–ใƒซใƒ‡ใƒผใ‚ฟใ€‚่ฆ‹ใคใ‹ใ‚‰ใชใ„ๅ ดๅˆใฏ็ฉบใฎ DataFrameใ€‚
161
+ """
162
+ match = re.search(r"<table.*?>.*?</table>", text, re.DOTALL | re.IGNORECASE)
163
+ if not match:
164
+ return pd.DataFrame()
165
+
166
+ parser = _HtmlTableParser()
167
+ parser.feed(match.group(0))
168
+
169
+ if len(parser.rows) < 2:
170
+ return pd.DataFrame()
171
+
172
+ return pd.DataFrame(parser.rows[1:], columns=parser.rows[0])
173
+
174
+
175
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
176
+ # ใƒ‘ใƒผใ‚น: Markdown ใƒ†ใƒผใƒ–ใƒซ โ†’ DataFrame
177
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
178
+ def parse_markdown_table(text: str) -> pd.DataFrame:
179
+ """OCR ๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰ Markdown ใƒ†ใƒผใƒ–ใƒซใ‚’ๆŠฝๅ‡บใ—ใฆ DataFrame ใซๅค‰ๆ›ใ™ใ‚‹ใ€‚
180
+
181
+ Args:
182
+ text: OCR ใƒขใƒ‡ใƒซใฎๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆ
183
+
184
+ Returns:
185
+ pd.DataFrame: ใƒ†ใƒผใƒ–ใƒซใƒ‡ใƒผใ‚ฟใ€‚่ฆ‹ใคใ‹ใ‚‰ใชใ„ๅ ดๅˆใฏ็ฉบใฎ DataFrameใ€‚
186
+ """
187
+ table_lines = [l for l in text.splitlines() if "|" in l]
188
+ if len(table_lines) < 2:
189
+ return pd.DataFrame()
190
+
191
+ data_lines = [l for l in table_lines if not re.match(r"^\|[\s\-:|]+\|$", l)]
192
+ rows = [[c.strip() for c in l.strip().strip("|").split("|")] for l in data_lines]
193
+
194
+ if not rows:
195
+ return pd.DataFrame()
196
+ return pd.DataFrame(rows[1:], columns=rows[0])
197
+
198
+
199
+ def parse_table(text: str) -> pd.DataFrame:
200
+ """HTML ใพใŸใฏ Markdown ใƒ†ใƒผใƒ–ใƒซใ‚’่‡ชๅ‹•ๅˆคๅˆฅใ—ใฆใƒ‘ใƒผใ‚นใ™ใ‚‹ใ€‚
201
+
202
+ Args:
203
+ text: OCR ใƒขใƒ‡ใƒซใฎๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆ
204
+
205
+ Returns:
206
+ pd.DataFrame: ใƒ†ใƒผใƒ–ใƒซใƒ‡ใƒผใ‚ฟใ€‚่ฆ‹ใคใ‹ใ‚‰ใชใ„ๅ ดๅˆใฏ็ฉบใฎ DataFrameใ€‚
207
+ """
208
+ if "<table" in text.lower():
209
+ return parse_html_table(text)
210
+ return parse_markdown_table(text)
211
+
212
+
213
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
214
+ # ใƒ‘ใƒผใ‚น: JSON ใƒ†ใ‚ญใ‚นใƒˆ โ†’ dict
215
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
216
+ def parse_json_output(text: str) -> dict:
217
+ """OCR ๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰ JSON ้ƒจๅˆ†ใ‚’ๆŠฝๅ‡บใ—ใฆใƒ‘ใƒผใ‚นใ™ใ‚‹ใ€‚
218
+
219
+ Args:
220
+ text: OCR ใƒขใƒ‡ใƒซใฎๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆ
221
+
222
+ Returns:
223
+ dict: ใƒ‘ใƒผใ‚นใ•ใ‚ŒใŸ JSON ใƒ‡ใƒผใ‚ฟใ€‚ๅคฑๆ•—ๆ™‚ใฏ็ฉบใฎ dictใ€‚
224
+ """
225
+ code_block = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
226
+ json_str = code_block.group(1) if code_block else None
227
+
228
+ if not json_str:
229
+ brace_match = re.search(r"\{.*\}", text, re.DOTALL)
230
+ if not brace_match:
231
+ return {}
232
+ json_str = brace_match.group(0)
233
+
234
+ try:
235
+ return json.loads(json_str)
236
+ except json.JSONDecodeError:
237
+ json_str_fixed = re.sub(r",\s*([}\]])", r"\1", json_str)
238
+ try:
239
+ return json.loads(json_str_fixed)
240
+ except json.JSONDecodeError:
241
+ return {}
242
+
243
+
244
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
245
+ # Excel ไฟๅญ˜๏ผˆๅ…จใ‚ทใƒผใƒˆใพใจใ‚ๆ›ธใ๏ผ‰
246
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
247
+ def save_excel(sheets: dict[str, pd.DataFrame], filepath: Path) -> None:
248
+ """่ค‡ๆ•ฐใฎ DataFrame ใ‚’ 1 ใคใฎ Excel ใƒ•ใ‚กใ‚คใƒซใซใ‚ทใƒผใƒˆใ”ใจใซไฟๅญ˜ใ™ใ‚‹ใ€‚
249
+
250
+ Args:
251
+ sheets: {ใ‚ทใƒผใƒˆๅ: DataFrame} ใฎ่พžๆ›ธ๏ผˆ็ฉบใฎ DataFrame ใฏ็ฉบใ‚ทใƒผใƒˆใจใ—ใฆไฟๅญ˜๏ผ‰
252
+ filepath: ๅ‡บๅŠ›ๅ…ˆ Excel ใƒ•ใ‚กใ‚คใƒซใฎใƒ‘ใ‚น (.xlsx)
253
+ """
254
+ filepath.parent.mkdir(parents=True, exist_ok=True)
255
+ with pd.ExcelWriter(filepath, engine="openpyxl") as writer:
256
+ for sheet_name, df in sheets.items():
257
+ # Excel ใ‚ทใƒผใƒˆๅใฏ 31 ๆ–‡ๅญ—ไปฅๅ†…ใฎๅˆถ้™ใ‚ใ‚Š
258
+ safe_name = sheet_name[:31]
259
+ df.to_excel(writer, sheet_name=safe_name, index=False)
260
+ row_info = f"{len(df)} ่กŒ" if not df.empty else "ใƒ‡ใƒผใ‚ฟใชใ—"
261
+ print(f"[OK] ใ‚ทใƒผใƒˆ '{safe_name}' ใ‚’ๆ›ธใ่พผใฟใพใ—ใŸ ({row_info})")
262
+ print(f"[OK] Excel ไฟๅญ˜ๅฎŒไบ†: {filepath}")
263
+
264
+
265
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
266
+ # ใ‚ปใ‚ฏใ‚ทใƒงใƒณ dict โ†’ DataFrame ๅค‰ๆ›
267
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
268
+ def section_to_df(section: dict) -> pd.DataFrame:
269
+ """1 ใƒฌใƒ™ใƒซใฎ dict ใ‚’ใ€Œkey / valueใ€ใฎ 2 ๅˆ— DataFrame ใซๅค‰ๆ›ใ™ใ‚‹ใ€‚
270
+
271
+ Args:
272
+ section: ใ‚ญใƒผใจๅ€คใ‚’ๆŒใค่พžๆ›ธ
273
+
274
+ Returns:
275
+ pd.DataFrame: key / value ใฎ 2 ๅˆ— DataFrame
276
+ """
277
+ if not section:
278
+ return pd.DataFrame()
279
+ return pd.DataFrame({"key": list(section.keys()), "value": list(section.values())})
280
+
281
+
282
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
283
+ # ใƒกใ‚คใƒณ
284
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
285
+ def main():
286
+ """ใƒกใ‚คใƒณๅ‡ฆ็†: ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ่ชญใฟ่พผใฟ โ†’ ็”ปๅƒOCR โ†’ Excel ๅ‡บๅŠ›ใ€‚"""
287
+ parser = argparse.ArgumentParser(description="GLM-OCR ๆฑŽ็”จ็”ปๅƒOCRใƒปCSVๅ‡บๅŠ›ใ‚นใ‚ฏใƒชใƒ—ใƒˆ")
288
+ parser.add_argument(
289
+ "--config", "-c", required=True, type=Path,
290
+ help="ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใƒ•ใ‚กใ‚คใƒซใฎใƒ‘ใ‚น๏ผˆ.yaml ใพใŸใฏ .xlsx๏ผ‰ไพ‹: configs/invoice.yaml",
291
+ )
292
+ parser.add_argument(
293
+ "--image", "-i", type=Path, default=None,
294
+ help="็”ปๅƒใƒ•ใ‚กใ‚คใƒซใฎใƒ‘ใ‚น๏ผˆ็œ็•ฅๆ™‚ใฏใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใฎ image ่จญๅฎšใ‚’ไฝฟ็”จ๏ผ‰",
295
+ )
296
+ parser.add_argument(
297
+ "--create-excel", action="store_true",
298
+ help="ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใ‚’่ชญใฟ่พผใ‚“ใง Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆใ‚’็”Ÿๆˆใ—ใฆ็ต‚ไบ†ใ™ใ‚‹",
299
+ )
300
+ args = parser.parse_args()
301
+
302
+ # โ”€โ”€ ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ่ชญใฟ่พผใฟ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
303
+ config_path = args.config.resolve()
304
+ if not config_path.exists():
305
+ print(f"[ERROR] ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใŒ่ฆ‹ใคใ‹ใ‚Šใพใ›ใ‚“: {config_path}", file=sys.stderr)
306
+ sys.exit(1)
307
+
308
+ cfg = load_config(config_path)
309
+
310
+ # โ”€โ”€ Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆ็”Ÿๆˆใƒขใƒผใƒ‰ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
311
+ if args.create_excel:
312
+ xlsx_path = config_path.with_suffix(".xlsx")
313
+ create_excel_template(cfg, xlsx_path)
314
+ print(f"[INFO] Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆใ‚’็”Ÿๆˆใ—ใพใ—ใŸ: {xlsx_path}")
315
+ sys.exit(0)
316
+ config_dir = config_path.parent.parent # configs/ ใฎ่ฆช = ใ‚นใ‚ฏใƒชใƒ—ใƒˆใฎใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒช
317
+
318
+ # ็”ปๅƒใƒ‘ใ‚นใฎ่งฃๆฑบ๏ผˆCLIๅผ•ๆ•ฐ > YAML่จญๅฎš๏ผ‰
319
+ if args.image:
320
+ image_path = args.image.resolve()
321
+ else:
322
+ image_path = (config_dir / cfg["image"]).resolve()
323
+
324
+ output_dir = (config_dir / cfg.get("output_dir", "output")).resolve()
325
+ extract_table: bool = cfg.get("extract_table", True)
326
+ sections: dict = cfg.get("sections", {})
327
+
328
+ if not image_path.exists():
329
+ print(f"[ERROR] ็”ปๅƒใŒ่ฆ‹ใคใ‹ใ‚Šใพใ›ใ‚“: {image_path}", file=sys.stderr)
330
+ sys.exit(1)
331
+
332
+ # ๅ‡บๅŠ› Excel ใƒ•ใ‚กใ‚คใƒซๅ: {configๅ}.xlsx
333
+ excel_path = output_dir / f"{config_path.stem}.xlsx"
334
+ preprocess_cfg: dict = cfg.get("preprocess", {})
335
+
336
+ print(f"[INFO] ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ : {config_path.name}")
337
+ print(f"[INFO] ๅฏพ่ฑกใƒ•ใ‚กใ‚คใƒซ: {image_path}")
338
+ print(f"[INFO] ๅ‡บๅŠ›ๅ…ˆ : {excel_path}")
339
+ print(f"[INFO] ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜: {'ใ‚ใ‚Š' if extract_table else 'ใชใ—'}")
340
+ print(f"[INFO] ๆŠฝๅ‡บใ‚ปใ‚ฏใ‚ทใƒงใƒณ: {list(sections.keys())}")
341
+ print(f"[INFO] ๅ‰ๅ‡ฆ็†่จญๅฎš: {preprocess_cfg or 'ๅ…จใ‚นใƒ†ใƒƒใƒ— ON๏ผˆใƒ‡ใƒ•ใ‚ฉใƒซใƒˆ๏ผ‰'}")
342
+
343
+ # โ”€โ”€ ๅ…ฅๅŠ›่ชญใฟ่พผใฟ๏ผˆ็”ปๅƒ or PDF ๅ…จใƒšใƒผใ‚ธ๏ผ‰โ”€โ”€
344
+ print(f"\n[INFO] ใƒ•ใ‚กใ‚คใƒซใ‚’่ชญใฟ่พผใ‚“ใงใ„ใพใ™...")
345
+ raw_pages = load_input_images(image_path)
346
+ total_pages = len(raw_pages)
347
+ print(f"[INFO] ใƒšใƒผใ‚ธๆ•ฐ: {total_pages}")
348
+
349
+ # โ”€โ”€ ใƒขใƒ‡ใƒซ่ชญใฟ่พผใฟ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
350
+ model, processor = load_model()
351
+
352
+ # ๆ›ธใ่พผใ‚€ใ‚ทใƒผใƒˆใ‚’ๅŽ้›†ใ™ใ‚‹่พžๆ›ธ {ใ‚ทใƒผใƒˆๅ: DataFrame}
353
+ sheets: dict[str, pd.DataFrame] = {}
354
+
355
+ # โ”€โ”€ ๅ„ใƒšใƒผใ‚ธใ‚’ๅ‡ฆ็† โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
356
+ for page_no, raw_image in enumerate(raw_pages, start=1):
357
+ # ่ค‡ๆ•ฐใƒšใƒผใ‚ธใฎๅ ดๅˆใฏใ‚ทใƒผใƒˆๅใซ P01_ / P02_ ... ใ‚’ไป˜ไธŽ
358
+ prefix = f"P{page_no:02d}_" if total_pages > 1 else ""
359
+ print(f"\n{'โ”€' * 50}")
360
+ print(f"[INFO] ใƒšใƒผใ‚ธ {page_no}/{total_pages} ใ‚’ๅ‡ฆ็†ไธญ...")
361
+
362
+ # ๅ‰ๅ‡ฆ็†
363
+ pil_image = apply_preprocess(raw_image, preprocess_cfg)
364
+ print(f"[INFO] ็”ปๅƒใ‚ตใ‚คใ‚บ: {pil_image.size}")
365
+
366
+ # โ”€โ”€ ๆŽจ่ซ–โ‘ : ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜๏ผˆใ‚ชใƒ—ใ‚ทใƒงใƒณ๏ผ‰โ”€โ”€
367
+ if extract_table:
368
+ print("[INFO] ๆŽจ่ซ–โ‘  ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜ ใ‚’ๅฎŸ่กŒไธญ...")
369
+ table_text = run_ocr(model, processor, pil_image, "Table Recognition:")
370
+ print("[RAW] ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜ ๅ‡บๅŠ›:")
371
+ print(table_text)
372
+ print()
373
+ sheets[f"{prefix}table"] = parse_table(table_text)
374
+
375
+ # โ”€โ”€ ๆŽจ่ซ–โ‘ก: ๆง‹้€ ๅŒ– JSON ๆŠฝๅ‡บ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
376
+ if sections:
377
+ print("[INFO] ๆŽจ่ซ–โ‘ก ๆง‹้€ ๅŒ– JSON ๆŠฝๅ‡บ ใ‚’ๅฎŸ่กŒไธญ...")
378
+ json_schema = build_json_schema(sections)
379
+ extract_prompt = (
380
+ "Extract all the following information from this image "
381
+ "and fill in the JSON template below. "
382
+ "Return only valid JSON, no extra text.\n\n"
383
+ + json_schema
384
+ )
385
+ json_text = run_ocr(model, processor, pil_image, extract_prompt)
386
+ print("[RAW] JSON ๆŠฝๅ‡บ ๅ‡บๅŠ›:")
387
+ print(json_text)
388
+ print()
389
+
390
+ data = parse_json_output(json_text)
391
+ for section_name, section_cfg in sections.items():
392
+ label = f"{prefix}{section_cfg.get('label', section_name)}"
393
+ sheets[label] = section_to_df(data.get(section_name, {}))
394
+
395
+ # โ”€โ”€ Excel ไฟๅญ˜ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
396
+ print()
397
+ save_excel(sheets, excel_path)
398
+
399
+ # โ”€โ”€ ็ตๆžœใ‚ตใƒžใƒชใƒผ่กจ็คบ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
400
+ print("\n" + "=" * 60)
401
+ print(" ๅ‡บๅŠ›็ตๆžœใ‚ตใƒžใƒชใƒผ")
402
+ print("=" * 60)
403
+
404
+ for sheet_name, df in sheets.items():
405
+ print(f"\nโ–ผ {sheet_name}")
406
+ print(df.to_string(index=False) if not df.empty else " (ใƒ‡ใƒผใ‚ฟใชใ—)")
407
+
408
+ print("\n[INFO] ๅ…จๅ‡ฆ็†ใŒๅฎŒไบ†ใ—ใพใ—ใŸใ€‚")
409
+
410
+
411
+ if __name__ == "__main__":
412
+ main()
OCR_tool_glm/glmocr_ollama.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ GLM-OCR (Ollama) ๆฑŽ็”จ็”ปๅƒOCRใƒปExcelๅ‡บๅŠ›ใ‚นใ‚ฏใƒชใƒ—ใƒˆ
3
+
4
+ ใƒขใƒ‡ใƒซ : glm-ocr:latest (Ollama ใƒญใƒผใ‚ซใƒซๅฎŸ่กŒ)
5
+ ่จญๅฎš : YAML ใพใŸใฏ Excel (.xlsx) ใฎใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใƒ•ใ‚กใ‚คใƒซใงๆŠฝๅ‡บ้ …็›ฎใƒป็”ปๅƒใƒปๅ‡บๅŠ›ๅ…ˆใ‚’ๅฎš็พฉ
6
+ ไฝฟใ„ๆ–น :
7
+ python glmocr_ollama.py --config configs/invoice.yaml
8
+ python glmocr_ollama.py --config configs/invoice.xlsx
9
+ python glmocr_ollama.py --config configs/invoice.yaml --image scan.pdf
10
+ python glmocr_ollama.py --config configs/invoice.yaml --model glm-ocr:latest
11
+ python glmocr_ollama.py --config configs/invoice.yaml --create-excel # Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆ็”Ÿๆˆ
12
+ ๅ‡บๅŠ› : {output_dir}/{configๅ}.xlsx๏ผˆใ‚ปใ‚ฏใ‚ทใƒงใƒณใ”ใจใซใ‚ทใƒผใƒˆใ‚’ๅˆ†ใ‘ใฆไฟๅญ˜๏ผ‰
13
+ PDF ่ค‡ๆ•ฐใƒšใƒผใ‚ธใฎๅ ดๅˆใฏใ‚ทใƒผใƒˆๅใ‚’ P01_/P02_... ใงใƒšใƒผใ‚ธๅŒบๅˆฅใ™ใ‚‹
14
+
15
+ ๅ‰ๆๆกไปถ:
16
+ - Ollama ใŒ่ตทๅ‹•ใ—ใฆใ„ใ‚‹ใ“ใจ (ollama serve)
17
+ - glm-ocr ใƒขใƒ‡ใƒซใŒ pull ๆธˆใฟใงใ‚ใ‚‹ใ“ใจ (ollama pull glm-ocr)
18
+ """
19
+
20
+ import argparse
21
+ import base64
22
+ import json
23
+ import re
24
+ import sys
25
+ from html.parser import HTMLParser
26
+ from io import BytesIO
27
+ from pathlib import Path
28
+
29
+ from config_loader import load_config, create_excel_template
30
+ from preprocess import apply_preprocess, load_input_images
31
+
32
+ # Windows ใ‚ณใƒณใ‚ฝใƒผใƒซใฎๆ–‡ๅญ—ๅŒ–ใ‘ๅฏพ็ญ–
33
+ if sys.stdout.encoding != "utf-8":
34
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
35
+ if sys.stderr.encoding != "utf-8":
36
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
37
+
38
+ import ollama
39
+ import pandas as pd
40
+
41
+ DEFAULT_MODEL = "glm-ocr:latest"
42
+
43
+
44
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
45
+ # JSON ใ‚นใ‚ญใƒผใƒžๅ‹•็š„็”Ÿๆˆ
46
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
47
+ def build_json_schema(sections: dict) -> str:
48
+ """YAML sections ๅฎš็พฉใ‹ใ‚‰ GLM-OCR ็”จ JSON ใ‚นใ‚ญใƒผใƒžๆ–‡ๅญ—ๅˆ—ใ‚’็”Ÿๆˆใ™ใ‚‹ใ€‚
49
+
50
+ Args:
51
+ sections: YAML ใฎ sections ่พžๆ›ธ
52
+
53
+ Returns:
54
+ str: JSON ใ‚นใ‚ญใƒผใƒžๆ–‡ๅญ—ๅˆ—
55
+ """
56
+ schema = {name: cfg["fields"] for name, cfg in sections.items()}
57
+ return json.dumps(schema, ensure_ascii=False, indent=2)
58
+
59
+
60
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
61
+ # Ollama ๆŽฅ็ถš็ขบ่ช
62
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
63
+ def check_model(model: str) -> None:
64
+ """ๆŒ‡ๅฎšใƒขใƒ‡ใƒซใŒ Ollama ใซใ‚ใ‚‹ใ‹็ขบ่ชใ™ใ‚‹ใ€‚ใชใ‘ใ‚Œใฐ็ต‚ไบ†ใ€‚
65
+
66
+ Args:
67
+ model: Ollama ใƒขใƒ‡ใƒซๅ (ไพ‹: "glm-ocr:latest")
68
+
69
+ Raises:
70
+ SystemExit: ใƒขใƒ‡ใƒซใŒ่ฆ‹ใคใ‹ใ‚‰ใชใ„ๅ ดๅˆ
71
+ """
72
+ try:
73
+ models = [m.model for m in ollama.list().models]
74
+ except Exception as e:
75
+ print(f"[ERROR] Ollama ใซๆŽฅ็ถšใงใใพใ›ใ‚“: {e}", file=sys.stderr)
76
+ print("[ERROR] 'ollama serve' ใง Ollama ใ‚’่ตทๅ‹•ใ—ใฆใใ ใ•ใ„ใ€‚", file=sys.stderr)
77
+ sys.exit(1)
78
+
79
+ if model not in models:
80
+ print(f"[ERROR] ใƒขใƒ‡ใƒซ '{model}' ใŒ่ฆ‹ใคใ‹ใ‚Šใพใ›ใ‚“ใ€‚", file=sys.stderr)
81
+ print(f"[ERROR] ๅˆฉ็”จๅฏ่ƒฝใชใƒขใƒ‡ใƒซ: {models}", file=sys.stderr)
82
+ print(f"[ERROR] 'ollama pull {model}' ใงๅ–ๅพ—ใ—ใฆใใ ใ•ใ„ใ€‚", file=sys.stderr)
83
+ sys.exit(1)
84
+
85
+ print(f"[INFO] ใƒขใƒ‡ใƒซ็ขบ่ชOK: {model}")
86
+
87
+
88
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
89
+ # ๆŽจ่ซ–
90
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
91
+ def pil_to_base64(pil_image: Image.Image) -> str:
92
+ """PIL Image ใ‚’ base64 ๆ–‡ๅญ—ๅˆ—ใซๅค‰ๆ›ใ™ใ‚‹ใ€‚
93
+
94
+ Args:
95
+ pil_image: ๅ…ฅๅŠ›็”ปๅƒ
96
+
97
+ Returns:
98
+ str: base64 ใ‚จใƒณใ‚ณใƒผใƒ‰ใ•ใ‚ŒใŸ PNG ็”ปๅƒๆ–‡ๅญ—ๅˆ—
99
+ """
100
+ buf = BytesIO()
101
+ pil_image.save(buf, format="PNG")
102
+ return base64.b64encode(buf.getvalue()).decode()
103
+
104
+
105
+ def run_ocr(model: str, pil_image: Image.Image, prompt: str) -> str:
106
+ """Ollama ใ‚’ไฝฟใฃใฆๅ˜ไธ€ใƒ—ใƒญใƒณใƒ—ใƒˆใง GLM-OCR ๆŽจ่ซ–ใ‚’ๅฎŸ่กŒใ™ใ‚‹ใ€‚
107
+
108
+ Args:
109
+ model: Ollama ใƒขใƒ‡ใƒซๅ
110
+ pil_image: ๅ…ฅๅŠ›็”ปๅƒ (PIL.Image)
111
+ prompt: OCR ใƒ—ใƒญใƒณใƒ—ใƒˆๆ–‡ๅญ—ๅˆ—
112
+
113
+ Returns:
114
+ str: ใƒขใƒ‡ใƒซใŒ็”Ÿๆˆใ—ใŸใƒ†ใ‚ญใ‚นใƒˆ
115
+ """
116
+ response = ollama.chat(
117
+ model=model,
118
+ messages=[
119
+ {
120
+ "role": "user",
121
+ "content": prompt,
122
+ "images": [pil_to_base64(pil_image)],
123
+ }
124
+ ],
125
+ )
126
+ return response.message.content.strip()
127
+
128
+
129
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
130
+ # ใƒ‘ใƒผใ‚น: HTML ใƒ†ใƒผใƒ–ใƒซ โ†’ DataFrame
131
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€๏ฟฝ๏ฟฝ๏ฟฝโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
132
+ class _HtmlTableParser(HTMLParser):
133
+ """HTML ใƒ†ใƒผใƒ–ใƒซใ‚’ใƒ‘ใƒผใ‚นใ—ใฆ่กŒใƒชใ‚นใƒˆใ‚’ๅŽ้›†ใ™ใ‚‹ใ‚ทใƒณใƒ—ใƒซใชใƒ‘ใƒผใ‚ตใƒผใ€‚"""
134
+
135
+ def __init__(self):
136
+ super().__init__()
137
+ self.rows: list[list[str]] = []
138
+ self._current_row: list[str] = []
139
+ self._current_cell: str = ""
140
+ self._in_cell: bool = False
141
+
142
+ def handle_starttag(self, tag, attrs):
143
+ if tag == "tr":
144
+ self._current_row = []
145
+ elif tag in ("td", "th"):
146
+ self._current_cell = ""
147
+ self._in_cell = True
148
+
149
+ def handle_endtag(self, tag):
150
+ if tag in ("td", "th"):
151
+ self._current_row.append(self._current_cell.strip())
152
+ self._in_cell = False
153
+ elif tag == "tr":
154
+ if self._current_row:
155
+ self.rows.append(self._current_row)
156
+
157
+ def handle_data(self, data):
158
+ if self._in_cell:
159
+ self._current_cell += data
160
+
161
+
162
+ def parse_html_table(text: str) -> pd.DataFrame:
163
+ """OCR ๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰ HTML ใƒ†ใƒผใƒ–ใƒซใ‚’ๆŠฝๅ‡บใ—ใฆ DataFrame ใซๅค‰ๆ›ใ™ใ‚‹ใ€‚
164
+
165
+ Args:
166
+ text: OCR ใƒขใƒ‡ใƒซใฎๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆ
167
+
168
+ Returns:
169
+ pd.DataFrame: ใƒ†ใƒผใƒ–ใƒซใƒ‡ใƒผใ‚ฟใ€‚่ฆ‹ใคใ‹ใ‚‰ใชใ„ๅ ดๅˆใฏ็ฉบใฎ DataFrameใ€‚
170
+ """
171
+ match = re.search(r"<table.*?>.*?</table>", text, re.DOTALL | re.IGNORECASE)
172
+ if not match:
173
+ return pd.DataFrame()
174
+
175
+ parser = _HtmlTableParser()
176
+ parser.feed(match.group(0))
177
+
178
+ if len(parser.rows) < 2:
179
+ return pd.DataFrame()
180
+
181
+ return pd.DataFrame(parser.rows[1:], columns=parser.rows[0])
182
+
183
+
184
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
185
+ # ใƒ‘ใƒผใ‚น: Markdown ใƒ†ใƒผใƒ–ใƒซ โ†’ DataFrame
186
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
187
+ def parse_markdown_table(text: str) -> pd.DataFrame:
188
+ """OCR ๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰ Markdown ใƒ†ใƒผใƒ–ใƒซใ‚’ๆŠฝๅ‡บใ—ใฆ DataFrame ใซๅค‰ๆ›ใ™ใ‚‹ใ€‚
189
+
190
+ Args:
191
+ text: OCR ใƒขใƒ‡ใƒซใฎๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆ
192
+
193
+ Returns:
194
+ pd.DataFrame: ใƒ†ใƒผใƒ–ใƒซใƒ‡ใƒผใ‚ฟใ€‚่ฆ‹ใคใ‹ใ‚‰ใชใ„ๅ ดๅˆใฏ็ฉบใฎ DataFrameใ€‚
195
+ """
196
+ table_lines = [l for l in text.splitlines() if "|" in l]
197
+ if len(table_lines) < 2:
198
+ return pd.DataFrame()
199
+
200
+ data_lines = [l for l in table_lines if not re.match(r"^\|[\s\-:|]+\|$", l)]
201
+ rows = [[c.strip() for c in l.strip().strip("|").split("|")] for l in data_lines]
202
+
203
+ if not rows:
204
+ return pd.DataFrame()
205
+ return pd.DataFrame(rows[1:], columns=rows[0])
206
+
207
+
208
+ def parse_table(text: str) -> pd.DataFrame:
209
+ """HTML ใพใŸใฏ Markdown ใƒ†ใƒผใƒ–ใƒซใ‚’่‡ชๅ‹•ๅˆคๅˆฅใ—ใฆใƒ‘ใƒผใ‚นใ™ใ‚‹ใ€‚
210
+
211
+ Args:
212
+ text: OCR ใƒขใƒ‡ใƒซใฎๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆ
213
+
214
+ Returns:
215
+ pd.DataFrame: ใƒ†ใƒผใƒ–ใƒซใƒ‡ใƒผใ‚ฟใ€‚่ฆ‹ใคใ‹ใ‚‰ใชใ„ๅ ดๅˆใฏ็ฉบใฎ DataFrameใ€‚
216
+ """
217
+ if "<table" in text.lower():
218
+ return parse_html_table(text)
219
+ return parse_markdown_table(text)
220
+
221
+
222
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
223
+ # ใƒ‘ใƒผใ‚น: JSON ใƒ†ใ‚ญใ‚นใƒˆ โ†’ dict
224
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
225
+ def parse_json_output(text: str) -> dict:
226
+ """OCR ๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰ JSON ้ƒจๅˆ†ใ‚’ๆŠฝๅ‡บใ—ใฆใƒ‘ใƒผใ‚นใ™ใ‚‹ใ€‚
227
+
228
+ Args:
229
+ text: OCR ใƒขใƒ‡ใƒซใฎๅ‡บๅŠ›ใƒ†ใ‚ญใ‚นใƒˆ
230
+
231
+ Returns:
232
+ dict: ใƒ‘ใƒผใ‚นใ•ใ‚ŒใŸ JSON ใƒ‡ใƒผใ‚ฟใ€‚ๅคฑๆ•—ๆ™‚ใฏ็ฉบใฎ dictใ€‚
233
+ """
234
+ code_block = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
235
+ json_str = code_block.group(1) if code_block else None
236
+
237
+ if not json_str:
238
+ brace_match = re.search(r"\{.*\}", text, re.DOTALL)
239
+ if not brace_match:
240
+ return {}
241
+ json_str = brace_match.group(0)
242
+
243
+ try:
244
+ return json.loads(json_str)
245
+ except json.JSONDecodeError:
246
+ json_str_fixed = re.sub(r",\s*([}\]])", r"\1", json_str)
247
+ try:
248
+ return json.loads(json_str_fixed)
249
+ except json.JSONDecodeError:
250
+ return {}
251
+
252
+
253
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
254
+ # Excel ไฟๅญ˜๏ผˆๅ…จใ‚ทใƒผใƒˆใพใจใ‚ๆ›ธใ๏ผ‰
255
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
256
+ def save_excel(sheets: dict[str, pd.DataFrame], filepath: Path) -> None:
257
+ """่ค‡ๆ•ฐใฎ DataFrame ใ‚’ 1 ใคใฎ Excel ใƒ•ใ‚กใ‚คใƒซใซใ‚ทใƒผใƒˆใ”ใจใซไฟๅญ˜ใ™ใ‚‹ใ€‚
258
+
259
+ Args:
260
+ sheets: {ใ‚ทใƒผใƒˆๅ: DataFrame} ใฎ่พžๆ›ธ๏ผˆ็ฉบใฎ DataFrame ใฏ็ฉบใ‚ทใƒผใƒˆใจใ—ใฆไฟๅญ˜๏ผ‰
261
+ filepath: ๅ‡บๅŠ›ๅ…ˆ Excel ใƒ•ใ‚กใ‚คใƒซใฎใƒ‘ใ‚น (.xlsx)
262
+ """
263
+ filepath.parent.mkdir(parents=True, exist_ok=True)
264
+ with pd.ExcelWriter(filepath, engine="openpyxl") as writer:
265
+ for sheet_name, df in sheets.items():
266
+ safe_name = sheet_name[:31]
267
+ df.to_excel(writer, sheet_name=safe_name, index=False)
268
+ row_info = f"{len(df)} ่กŒ" if not df.empty else "ใƒ‡ใƒผใ‚ฟใชใ—"
269
+ print(f"[OK] ใ‚ทใƒผใƒˆ '{safe_name}' ใ‚’ๆ›ธใ่พผใฟใพใ—ใŸ ({row_info})")
270
+ print(f"[OK] Excel ไฟๅญ˜ๅฎŒไบ†: {filepath}")
271
+
272
+
273
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
274
+ # ใ‚ปใ‚ฏใ‚ทใƒงใƒณ dict โ†’ DataFrame ๅค‰ๆ›
275
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
276
+ def section_to_df(section: dict) -> pd.DataFrame:
277
+ """1 ใƒฌใƒ™ใƒซใฎ dict ใ‚’ใ€Œkey / valueใ€ใฎ 2 ๅˆ— DataFrame ใซๅค‰ๆ›ใ™ใ‚‹ใ€‚
278
+
279
+ Args:
280
+ section: ใ‚ญใƒผใจๅ€คใ‚’ๆŒใค่พžๆ›ธ
281
+
282
+ Returns:
283
+ pd.DataFrame: key / value ใฎ 2 ๅˆ— DataFrame
284
+ """
285
+ if not section:
286
+ return pd.DataFrame()
287
+ return pd.DataFrame({"key": list(section.keys()), "value": list(section.values())})
288
+
289
+
290
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
291
+ # ใƒกใ‚คใƒณ
292
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
293
+ def main():
294
+ """ใƒกใ‚คใƒณๅ‡ฆ็†: ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ่ชญใฟ่พผใฟ โ†’ Ollama OCR โ†’ Excel ๅ‡บๅŠ›ใ€‚"""
295
+ parser = argparse.ArgumentParser(
296
+ description="GLM-OCR (Ollama) ๆฑŽ็”จ็”ปๅƒOCRใƒปExcelๅ‡บๅŠ›ใ‚นใ‚ฏใƒชใƒ—ใƒˆ"
297
+ )
298
+ parser.add_argument(
299
+ "--config", "-c", required=True, type=Path,
300
+ help="ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใƒ•ใ‚กใ‚คใƒซใฎใƒ‘ใ‚น๏ผˆ.yaml ใพใŸใฏ .xlsx๏ผ‰ไพ‹: configs/invoice.yaml",
301
+ )
302
+ parser.add_argument(
303
+ "--image", "-i", type=Path, default=None,
304
+ help="็”ปๅƒใƒ•ใ‚กใ‚คใƒซใฎใƒ‘ใ‚น๏ผˆ็œ็•ฅๆ™‚ใฏใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใฎ image ่จญๅฎšใ‚’ไฝฟ็”จ๏ผ‰",
305
+ )
306
+ parser.add_argument(
307
+ "--model", "-m", type=str, default=DEFAULT_MODEL,
308
+ help=f"Ollama ใƒขใƒ‡ใƒซๅ (ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆ: {DEFAULT_MODEL})",
309
+ )
310
+ parser.add_argument(
311
+ "--create-excel", action="store_true",
312
+ help="ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใ‚’่ชญใฟ่พผใ‚“ใง Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆใ‚’็”Ÿๆˆใ—ใฆ็ต‚ไบ†ใ™ใ‚‹",
313
+ )
314
+ args = parser.parse_args()
315
+
316
+ # โ”€โ”€ ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ่ชญใฟ่พผใฟ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
317
+ config_path = args.config.resolve()
318
+ if not config_path.exists():
319
+ print(f"[ERROR] ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐใŒ่ฆ‹ใคใ‹ใ‚Šใพใ›ใ‚“: {config_path}", file=sys.stderr)
320
+ sys.exit(1)
321
+
322
+ cfg = load_config(config_path)
323
+
324
+ # โ”€โ”€ Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆ็”Ÿๆˆใƒขใƒผใƒ‰ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
325
+ if args.create_excel:
326
+ xlsx_path = config_path.with_suffix(".xlsx")
327
+ create_excel_template(cfg, xlsx_path)
328
+ print(f"[INFO] Excel ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆใ‚’็”Ÿๆˆใ—ใพใ—ใŸ: {xlsx_path}")
329
+ sys.exit(0)
330
+ config_dir = config_path.parent.parent # configs/ ใฎ่ฆช = ใ‚นใ‚ฏใƒชใƒ—ใƒˆใฎใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒช
331
+
332
+ # ็”ปๅƒใƒ‘ใ‚นใฎ่งฃๆฑบ๏ผˆCLIๅผ•ๆ•ฐ > YAML่จญๅฎš๏ผ‰
333
+ if args.image:
334
+ image_path = args.image.resolve()
335
+ else:
336
+ image_path = (config_dir / cfg["image"]).resolve()
337
+
338
+ output_dir = (config_dir / cfg.get("output_dir", "output")).resolve()
339
+ extract_table: bool = cfg.get("extract_table", True)
340
+ sections: dict = cfg.get("sections", {})
341
+ model: str = args.model
342
+ excel_path = output_dir / f"{config_path.stem}.xlsx"
343
+ preprocess_cfg: dict = cfg.get("preprocess", {})
344
+
345
+ if not image_path.exists():
346
+ print(f"[ERROR] ใƒ•ใ‚กใ‚คใƒซใŒ่ฆ‹ใคใ‹ใ‚Šใพใ›ใ‚“: {image_path}", file=sys.stderr)
347
+ sys.exit(1)
348
+
349
+ print(f"[INFO] ใ‚ณใƒณใƒ•ใ‚ฃใ‚ฐ : {config_path.name}")
350
+ print(f"[INFO] ใƒขใƒ‡ใƒซ : {model} (Ollama)")
351
+ print(f"[INFO] ๅฏพ่ฑกใƒ•ใ‚กใ‚คใƒซ: {image_path}")
352
+ print(f"[INFO] ๅ‡บๅŠ›ๅ…ˆ : {excel_path}")
353
+ print(f"[INFO] ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜: {'ใ‚ใ‚Š' if extract_table else 'ใชใ—'}")
354
+ print(f"[INFO] ๆŠฝๅ‡บใ‚ปใ‚ฏใ‚ทใƒงใƒณ: {list(sections.keys())}")
355
+ print(f"[INFO] ๅ‰ๅ‡ฆ็†่จญๅฎš: {preprocess_cfg or 'ๅ…จใ‚นใƒ†ใƒƒใƒ— ON๏ผˆใƒ‡ใƒ•ใ‚ฉใƒซใƒˆ๏ผ‰'}")
356
+
357
+ # โ”€โ”€ Ollama ๆŽฅ็ถšใƒปใƒขใƒ‡ใƒซ็ขบ่ช โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
358
+ check_model(model)
359
+
360
+ # โ”€โ”€ ๅ…ฅๅŠ›่ชญใฟ่พผใฟ๏ผˆ็”ปๅƒ or PDF ๅ…จใƒšใƒผใ‚ธ๏ผ‰โ”€โ”€
361
+ print(f"\n[INFO] ใƒ•ใ‚กใ‚คใƒซใ‚’่ชญใฟ่พผใ‚“ใงใ„ใพใ™...")
362
+ raw_pages = load_input_images(image_path)
363
+ total_pages = len(raw_pages)
364
+ print(f"[INFO] ใƒšใƒผใ‚ธๆ•ฐ: {total_pages}")
365
+
366
+ # ๆ›ธใ่พผใ‚€ใ‚ทใƒผใƒˆใ‚’ๅŽ้›†ใ™ใ‚‹่พžๆ›ธ {ใ‚ทใƒผใƒˆๅ: DataFrame}
367
+ sheets: dict[str, pd.DataFrame] = {}
368
+
369
+ # โ”€โ”€ ๅ„ใƒšใƒผใ‚ธใ‚’ๅ‡ฆ็† โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
370
+ for page_no, raw_image in enumerate(raw_pages, start=1):
371
+ prefix = f"P{page_no:02d}_" if total_pages > 1 else ""
372
+ print(f"\n{'โ”€' * 50}")
373
+ print(f"[INFO] ใƒšใƒผใ‚ธ {page_no}/{total_pages} ใ‚’ๅ‡ฆ็†ไธญ...")
374
+
375
+ pil_image = apply_preprocess(raw_image, preprocess_cfg)
376
+ print(f"[INFO] ็”ปๅƒใ‚ตใ‚คใ‚บ: {pil_image.size}")
377
+
378
+ # โ”€โ”€ ๆŽจ่ซ–โ‘ : ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜๏ผˆใ‚ชใƒ—ใ‚ทใƒงใƒณ๏ผ‰โ”€โ”€
379
+ if extract_table:
380
+ print("[INFO] ๆŽจ่ซ–โ‘  ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜ ใ‚’ๅฎŸ่กŒไธญ...")
381
+ table_text = run_ocr(model, pil_image, "Table Recognition:")
382
+ print("[RAW] ใƒ†ใƒผใƒ–ใƒซ่ช่ญ˜ ๅ‡บๅŠ›:")
383
+ print(table_text)
384
+ print()
385
+ sheets[f"{prefix}table"] = parse_table(table_text)
386
+
387
+ # โ”€โ”€ ๆŽจ่ซ–โ‘ก: ๆง‹้€ ๅŒ– JSON ๆŠฝๅ‡บ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
388
+ if sections:
389
+ print("[INFO] ๆŽจ่ซ–โ‘ก ๆง‹้€ ๅŒ– JSON ๆŠฝๅ‡บ ใ‚’ๅฎŸ่กŒไธญ...")
390
+ json_schema = build_json_schema(sections)
391
+ extract_prompt = (
392
+ "Extract all the following information from this image "
393
+ "and fill in the JSON template below. "
394
+ "Return only valid JSON, no extra text.\n\n"
395
+ + json_schema
396
+ )
397
+ json_text = run_ocr(model, pil_image, extract_prompt)
398
+ print("[RAW] JSON ๆŠฝๅ‡บ ๅ‡บๅŠ›:")
399
+ print(json_text)
400
+ print()
401
+
402
+ data = parse_json_output(json_text)
403
+ for section_name, section_cfg in sections.items():
404
+ label = f"{prefix}{section_cfg.get('label', section_name)}"
405
+ sheets[label] = section_to_df(data.get(section_name, {}))
406
+
407
+ # โ”€โ”€ Excel ไฟๅญ˜ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
408
+ print()
409
+ save_excel(sheets, excel_path)
410
+
411
+ # โ”€โ”€ ็ตๆžœใ‚ตใƒžใƒชใƒผ่กจ็คบ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
412
+ print("\n" + "=" * 60)
413
+ print(" ๅ‡บๅŠ›็ตๆžœใ‚ตใƒžใƒชใƒผ")
414
+ print("=" * 60)
415
+
416
+ for sheet_name, df in sheets.items():
417
+ print(f"\nโ–ผ {sheet_name}")
418
+ print(df.to_string(index=False) if not df.empty else " (ใƒ‡ใƒผใ‚ฟใชใ—)")
419
+
420
+ print("\n[INFO] ๅ…จๅ‡ฆ็†ใŒๅฎŒไบ†ใ—ใพใ—ใŸใ€‚")
421
+
422
+
423
+ if __name__ == "__main__":
424
+ main()
OCR_tool_glm/output/my.xlsx ADDED
Binary file (6.6 kB). View file
 
OCR_tool_glm/preprocess.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ OCR ๅ‰ๅ‡ฆ็†ใƒขใ‚ธใƒฅใƒผใƒซ
3
+
4
+ ๆฑšใ‚ŒใŸ็”ปๅƒใƒปใ‚นใ‚ญใƒฃใƒณๆ–‡ๆ›ธใฎ OCR ็ฒพๅบฆใ‚’้ซ˜ใ‚ใ‚‹ใŸใ‚ใฎๅ‰ๅ‡ฆ็†ใƒ‘ใ‚คใƒ—ใƒฉใ‚คใƒณใจใ€
5
+ PDF ใ‚’ PIL Image ใƒชใ‚นใƒˆใซๅค‰ๆ›ใ™ใ‚‹ๆฉŸ่ƒฝใ‚’ๆไพ›ใ™ใ‚‹ใ€‚
6
+
7
+ ไฝฟใ„ๆ–น๏ผˆใ‚คใƒณใƒใƒผใƒˆไพ‹๏ผ‰:
8
+ from preprocess import load_input_images, apply_preprocess
9
+
10
+ pages = load_input_images(Path("scan.pdf")) # PDF โ†’ 1ใƒšใƒผใ‚ธ1ๆžšใฎใƒชใ‚นใƒˆ
11
+ pages = load_input_images(Path("photo.webp")) # ็”ปๅƒ โ†’ [1ๆžš]
12
+
13
+ cleaned = apply_preprocess(pages[0], config={"deskew": True, "denoise": True})
14
+
15
+ ๅ‰ๅ‡ฆ็†ใ‚นใƒ†ใƒƒใƒ—๏ผˆYAML ใฎ preprocess ใ‚ปใ‚ฏใ‚ทใƒงใƒณใงๅ„ ON/OFF ๅฏ่ƒฝ๏ผ‰:
16
+ deskew : ๅ‚พใ่ฃœๆญฃ๏ผˆHough ๅค‰ๆ›๏ผ‰
17
+ denoise : ใƒŽใ‚คใ‚บ้™คๅŽป๏ผˆใƒใ‚คใƒฉใƒ†ใƒฉใƒซใƒ•ใ‚ฃใƒซใ‚ฟ๏ผ‰
18
+ enhance_contrast : ใ‚ณใƒณใƒˆใƒฉใ‚นใƒˆๅผท่ชฟ๏ผˆCLAHE / LAB ่‰ฒ็ฉบ้–“๏ผ‰
19
+ sharpen : ใ‚ทใƒฃใƒผใƒ—ๅŒ–๏ผˆUnsharp Masking๏ผ‰
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from pathlib import Path
25
+
26
+ import cv2
27
+ import fitz # PyMuPDF
28
+ import numpy as np
29
+ from PIL import Image
30
+
31
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
32
+ # PDFใƒป็”ปๅƒใฎ่ชญใฟ่พผใฟ
33
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
34
+
35
+ #: PDF ใƒฉใ‚นใ‚ฟใƒฉใ‚คใ‚บๆ™‚ใฎ่งฃๅƒๅบฆใ€‚200 dpi ไปฅไธŠใŒ OCR ใซๆŽจๅฅจใ•ใ‚Œใ‚‹ใ€‚
36
+ PDF_DPI = 200
37
+
38
+ #: ๅฏพๅฟœใ™ใ‚‹็”ปๅƒๆ‹กๅผตๅญ
39
+ IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tiff", ".tif"}
40
+
41
+
42
+ def load_pdf_pages(pdf_path: Path, dpi: int = PDF_DPI) -> list[Image.Image]:
43
+ """PDF ใฎๅ…จใƒšใƒผใ‚ธใ‚’ PIL Image ใฎใƒชใ‚นใƒˆใซๅค‰ๆ›ใ™ใ‚‹ใ€‚
44
+
45
+ Args:
46
+ pdf_path: PDF ใƒ•ใ‚กใ‚คใƒซใฎใƒ‘ใ‚น
47
+ dpi: ใƒฉใ‚นใ‚ฟใƒฉใ‚คใ‚บ่งฃๅƒๅบฆ๏ผˆ้ซ˜ใ„ใปใฉ้ซ˜็ฒพๅบฆใ ใŒใƒกใƒขใƒชใ‚’ๆถˆ่ฒป๏ผ‰
48
+
49
+ Returns:
50
+ list[Image.Image]: 1 ่ฆ็ด  = 1 ใƒšใƒผใ‚ธใฎ RGB ็”ปๅƒใƒชใ‚นใƒˆ
51
+ """
52
+ doc = fitz.open(str(pdf_path))
53
+ mat = fitz.Matrix(dpi / 72, dpi / 72)
54
+ pages: list[Image.Image] = []
55
+ for page in doc:
56
+ pix = page.get_pixmap(matrix=mat, colorspace=fitz.csRGB)
57
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
58
+ pages.append(img)
59
+ doc.close()
60
+ return pages
61
+
62
+
63
+ def load_input_images(path: Path) -> list[Image.Image]:
64
+ """็”ปๅƒใพใŸใฏ PDF ใ‚’่ชญใฟ่พผใฟใ€PIL Image ใฎใƒชใ‚นใƒˆใ‚’่ฟ”ใ™ใ€‚
65
+
66
+ PDF ใฎๅ ดๅˆใฏใƒšใƒผใ‚ธใ”ใจใซ 1 ่ฆ็ด ใ€็”ปๅƒใฎๅ ดๅˆใฏ [1 ่ฆ็ด ] ใ‚’่ฟ”ใ™ใ€‚
67
+
68
+ Args:
69
+ path: ๅ…ฅๅŠ›ใƒ•ใ‚กใ‚คใƒซใฎใƒ‘ใ‚น๏ผˆPDF ใพใŸใฏ็”ปๅƒ๏ผ‰
70
+
71
+ Returns:
72
+ list[Image.Image]: ใƒšใƒผใ‚ธ๏ผˆใพใŸใฏ็”ปๅƒ๏ผ‰ใ”ใจใฎ RGB ็”ปๅƒใƒชใ‚นใƒˆ
73
+
74
+ Raises:
75
+ ValueError: ๅฏพๅฟœใ—ใฆใ„ใชใ„ๆ‹กๅผตๅญใŒๆŒ‡ๅฎšใ•ใ‚ŒใŸๅ ดๅˆ
76
+ """
77
+ suffix = path.suffix.lower()
78
+ if suffix == ".pdf":
79
+ return load_pdf_pages(path)
80
+ if suffix in IMAGE_EXTENSIONS:
81
+ return [Image.open(path).convert("RGB")]
82
+ raise ValueError(f"ๅฏพๅฟœใ—ใฆใ„ใชใ„ใƒ•ใ‚กใ‚คใƒซๅฝขๅผใงใ™: {suffix}")
83
+
84
+
85
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
86
+ # ๅ†…้ƒจใƒฆใƒผใƒ†ใ‚ฃใƒชใƒ†ใ‚ฃ
87
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
88
+
89
+ def _to_bgr(pil_image: Image.Image) -> np.ndarray:
90
+ """PIL Image (RGB) โ†’ OpenCV BGR ndarray ใซๅค‰ๆ›ใ™ใ‚‹ใ€‚"""
91
+ return cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
92
+
93
+
94
+ def _to_pil(bgr: np.ndarray) -> Image.Image:
95
+ """OpenCV BGR ndarray โ†’ PIL Image (RGB) ใซๅค‰ๆ›ใ™ใ‚‹ใ€‚"""
96
+ return Image.fromarray(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
97
+
98
+
99
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
100
+ # ๅ‰ๅ‡ฆ็†ใ‚นใƒ†ใƒƒใƒ—๏ผˆๅ„้–ขๆ•ฐใฏ BGR ndarray ใ‚’ๅ—ใ‘ๅ–ใ‚Š BGR ndarray ใ‚’่ฟ”ใ™๏ผ‰
101
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
102
+
103
+ def _deskew(bgr: np.ndarray) -> np.ndarray:
104
+ """Hough ๅค‰ๆ›ใงๆ–‡ๆ›ธใฎๅ‚พใใ‚’ๆคœๅ‡บใ—ใฆๅ›ž่ปข่ฃœๆญฃใ™ใ‚‹ใ€‚
105
+
106
+ ใ‚นใ‚ญใƒฃใƒŠใ‚„ๆ‰‹ๆŒใกๆ’ฎๅฝฑใงๅ‚พใ„ใŸๆ–‡ๆ›ธใ‚’่‡ชๅ‹•ใงใพใฃใ™ใใซใ™ใ‚‹ใ€‚
107
+ ๅ‚พใ่ง’ใŒ 0.3 ๅบฆๆœชๆบ€ใฎๅ ดๅˆใฏ่ฃœๆญฃใ‚’ใ‚นใ‚ญใƒƒใƒ—ใ™ใ‚‹ใ€‚
108
+
109
+ Args:
110
+ bgr: ๅ…ฅๅŠ›็”ปๅƒ (BGR ndarray)
111
+
112
+ Returns:
113
+ np.ndarray: ๅ‚พใ่ฃœๆญฃๅพŒใฎ็”ปๅƒ
114
+ """
115
+ gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
116
+ blur = cv2.GaussianBlur(gray, (9, 9), 0)
117
+ edges = cv2.Canny(blur, 50, 150, apertureSize=3)
118
+ lines = cv2.HoughLines(edges, 1, np.pi / 180, threshold=150)
119
+
120
+ if lines is None:
121
+ return bgr
122
+
123
+ angles: list[float] = []
124
+ for line in lines:
125
+ theta = float(line[0][1])
126
+ angle = (theta * 180.0 / np.pi) - 90.0
127
+ if abs(angle) < 45.0:
128
+ angles.append(angle)
129
+
130
+ if not angles:
131
+ return bgr
132
+
133
+ median_angle = float(np.median(angles))
134
+ if abs(median_angle) < 0.3:
135
+ return bgr
136
+
137
+ h, w = bgr.shape[:2]
138
+ M = cv2.getRotationMatrix2D((w / 2.0, h / 2.0), median_angle, 1.0)
139
+ return cv2.warpAffine(
140
+ bgr, M, (w, h),
141
+ flags=cv2.INTER_CUBIC,
142
+ borderMode=cv2.BORDER_REPLICATE,
143
+ )
144
+
145
+
146
+ def _denoise(bgr: np.ndarray) -> np.ndarray:
147
+ """ใƒใ‚คใƒฉใƒ†ใƒฉใƒซใƒ•ใ‚ฃใƒซใ‚ฟใงใƒŽใ‚คใ‚บใ‚’้™คๅŽปใ—ใชใŒใ‚‰ใ‚จใƒƒใ‚ธ๏ผˆๆ–‡ๅญ—่ผช้ƒญ๏ผ‰ใ‚’ไฟ่ญทใ™ใ‚‹ใ€‚
148
+
149
+ ใ‚ฌใ‚ฆใ‚ทใ‚ขใƒณใƒ–ใƒฉใƒผใจ้•ใ„ใ€ใ‚จใƒƒใ‚ธใ‚’ไฟใกใชใŒใ‚‰ใƒŽใ‚คใ‚บใ ใ‘ใ‚’ๅนณๆป‘ๅŒ–ใ™ใ‚‹ใ€‚
150
+
151
+ Args:
152
+ bgr: ๅ…ฅๅŠ›็”ปๅƒ (BGR ndarray)
153
+
154
+ Returns:
155
+ np.ndarray: ใƒŽใ‚คใ‚บ้™คๅŽปๅพŒใฎ็”ปๅƒ
156
+ """
157
+ return cv2.bilateralFilter(bgr, d=9, sigmaColor=75, sigmaSpace=75)
158
+
159
+
160
+ def _enhance_contrast(bgr: np.ndarray) -> np.ndarray:
161
+ """CLAHE๏ผˆๅˆถ้™ไป˜ใ้ฉๅฟœใƒ’ใ‚นใƒˆใ‚ฐใƒฉใƒ ๅนณๅฆๅŒ–๏ผ‰ใงๅฑ€ๆ‰€ใ‚ณใƒณใƒˆใƒฉใ‚นใƒˆใ‚’ๅผท่ชฟใ™ใ‚‹ใ€‚
162
+
163
+ ็…งๆ˜Žใƒ ใƒฉใŒใ‚ใ‚‹็”ปๅƒใงใ‚‚ๆ–‡ๅญ—ใŒๅ‡ไธ€ใซๆ˜Ž็žญใซใชใ‚‹ใ€‚
164
+ LAB ่‰ฒ็ฉบ้–“ใฎๆ˜Žๅบฆใƒใƒฃใƒณใƒใƒซ (L) ใฎใฟใซ้ฉ็”จใ—ใ€่‰ฒ็›ธใฏๅค‰ๅŒ–ใ•ใ›ใชใ„ใ€‚
165
+
166
+ Args:
167
+ bgr: ๅ…ฅๅŠ›็”ปๅƒ (BGR ndarray)
168
+
169
+ Returns:
170
+ np.ndarray: ใ‚ณใƒณใƒˆใƒฉใ‚นใƒˆๅผท่ชฟๅพŒใฎ็”ปๅƒ
171
+ """
172
+ lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)
173
+ l_ch, a_ch, b_ch = cv2.split(lab)
174
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
175
+ l_enhanced = clahe.apply(l_ch)
176
+ return cv2.cvtColor(cv2.merge([l_enhanced, a_ch, b_ch]), cv2.COLOR_LAB2BGR)
177
+
178
+
179
+ def _sharpen(bgr: np.ndarray) -> np.ndarray:
180
+ """Unsharp Masking ใงๆ–‡ๅญ—ใฎใ‚จใƒƒใ‚ธใ‚’ๅผท่ชฟใ—ใฆใ‚ทใƒฃใƒผใƒ—ใซใ™ใ‚‹ใ€‚
181
+
182
+ ใผใ‚„ใ‘ใŸ็”ปๅƒใ‚„ใ‚นใ‚ญใƒฃใƒณๅพŒใฎใ‚ฝใƒ•ใƒˆใƒใ‚นใ‚’่ฃœๆญฃใ™ใ‚‹ใ€‚
183
+
184
+ Args:
185
+ bgr: ๅ…ฅๅŠ›็”ปๅƒ (BGR ndarray)
186
+
187
+ Returns:
188
+ np.ndarray: ใ‚ทใƒฃใƒผใƒ—ๅŒ–ๅพŒใฎ็”ปๅƒ
189
+ """
190
+ blurred = cv2.GaussianBlur(bgr, (0, 0), sigmaX=3)
191
+ return cv2.addWeighted(bgr, 1.5, blurred, -0.5, 0)
192
+
193
+
194
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
195
+ # ๅ‰ๅ‡ฆ็†ใƒ‘ใ‚คใƒ—ใƒฉใ‚คใƒณ๏ผˆๅ…ฌ้–‹้–ขๆ•ฐ๏ผ‰
196
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
197
+
198
+ def apply_preprocess(
199
+ pil_image: Image.Image,
200
+ config: dict | None = None,
201
+ ) -> Image.Image:
202
+ """OCR ๅ‰ๅ‡ฆ็†ใƒ‘ใ‚คใƒ—ใƒฉใ‚คใƒณใ‚’ๅฎŸ่กŒใ—ใฆ PIL Image ใ‚’่ฟ”ใ™ใ€‚
203
+
204
+ ๅ„ใ‚นใƒ†ใƒƒใƒ—ใฏ config ใฎ True/False ใงๅ€‹ๅˆฅใซ ON/OFF ใงใใ‚‹ใ€‚
205
+ config ใ‚’็œ็•ฅใ—ใŸๅ ดๅˆใฏใ™ในใฆใฎๅ‰ๅ‡ฆ็†ใŒๆœ‰ๅŠนใซใชใ‚‹ใ€‚
206
+
207
+ Args:
208
+ pil_image: ๅ‰ๅ‡ฆ็†ๅฏพ่ฑกใฎ PIL Image (RGB)
209
+ config: ๅ‰ๅ‡ฆ็†่จญๅฎš่พžๆ›ธใ€‚ใ‚ญใƒผใจๆ—ขๅฎšๅ€คใฏไปฅไธ‹ใฎ้€šใ‚Šใ€‚
210
+ - deskew (bool, default True): ๅ‚พใ่ฃœๆญฃ
211
+ - denoise (bool, default True): ใƒŽใ‚คใ‚บ้™คๅŽป
212
+ - enhance_contrast (bool, default True): ใ‚ณใƒณใƒˆใƒฉใ‚นใƒˆๅผท่ชฟ
213
+ - sharpen (bool, default True): ใ‚ทใƒฃใƒผใƒ—ๅŒ–
214
+
215
+ Returns:
216
+ Image.Image: ๅ‰ๅ‡ฆ็†ๆธˆใฟใฎ PIL Image (RGB)
217
+
218
+ Example:
219
+ >>> cleaned = apply_preprocess(img, {"deskew": True, "denoise": False})
220
+ """
221
+ cfg = config or {}
222
+
223
+ bgr = _to_bgr(pil_image)
224
+
225
+ if cfg.get("deskew", True):
226
+ bgr = _deskew(bgr)
227
+
228
+ if cfg.get("denoise", True):
229
+ bgr = _denoise(bgr)
230
+
231
+ if cfg.get("enhance_contrast", True):
232
+ bgr = _enhance_contrast(bgr)
233
+
234
+ if cfg.get("sharpen", True):
235
+ bgr = _sharpen(bgr)
236
+
237
+ return _to_pil(bgr)