Upload 9 files
Browse files- OCR_tool_glm/OCRๆค่จผ.webp +3 -0
- OCR_tool_glm/config_loader.py +262 -0
- OCR_tool_glm/configs/invoice.xlsx +0 -0
- OCR_tool_glm/configs/invoice.yaml +67 -0
- OCR_tool_glm/configs/my.yaml +28 -0
- OCR_tool_glm/glmocr.py +412 -0
- OCR_tool_glm/glmocr_ollama.py +424 -0
- OCR_tool_glm/output/my.xlsx +0 -0
- OCR_tool_glm/preprocess.py +237 -0
OCR_tool_glm/OCRๆค่จผ.webp
ADDED
|
Git LFS Details
|
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)
|