File size: 16,758 Bytes
11bcfa7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 | """
GLM-OCR ๆฑ็จ็ปๅOCRใปExcelๅบๅในใฏใชใใ
ใขใใซ : zai-org/GLM-OCR (HuggingFace)
่จญๅฎ : YAML ใพใใฏ Excel (.xlsx) ใฎใณใณใใฃใฐใใกใคใซใงๆฝๅบ้
็ฎใป็ปๅใปๅบๅๅ
ใๅฎ็พฉ
ไฝฟใๆน :
python glmocr.py --config configs/invoice.yaml
python glmocr.py --config configs/invoice.xlsx
python glmocr.py --config configs/invoice.yaml --image scan.pdf
python glmocr.py --config configs/invoice.yaml --create-excel # Excel ใใณใใฌใผใ็ๆ
ๅบๅ : {output_dir}/{configๅ}.xlsx๏ผใปใฏใทใงใณใใจใซใทใผใใๅใใฆไฟๅญ๏ผ
PDF ่คๆฐใใผใธใฎๅ ดๅใฏใทใผใๅใ P01_/P02_... ใงใใผใธๅบๅฅใใ
"""
import argparse
import json
import re
import sys
from html.parser import HTMLParser
from pathlib import Path
from config_loader import load_config, create_excel_template
from preprocess import apply_preprocess, load_input_images
# Windows ใณใณใฝใผใซใฎๆๅญๅใๅฏพ็ญ
if sys.stdout.encoding != "utf-8":
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if sys.stderr.encoding != "utf-8":
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
import pandas as pd
import torch
from transformers import AutoProcessor, AutoModelForImageTextToText
MODEL_ID = "zai-org/GLM-OCR"
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# JSON ในใญใผใๅ็็ๆ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def build_json_schema(sections: dict) -> str:
"""YAML sections ๅฎ็พฉใใ GLM-OCR ็จ JSON ในใญใผใๆๅญๅใ็ๆใใใ
Args:
sections: YAML ใฎ sections ่พๆธ
Returns:
str: JSON ในใญใผใๆๅญๅ
"""
schema = {name: cfg["fields"] for name, cfg in sections.items()}
return json.dumps(schema, ensure_ascii=False, indent=2)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ใขใใซ่ชญใฟ่พผใฟ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def load_model():
"""GLM-OCR ใขใใซใจ Processor ใ่ชญใฟ่พผใใ
Returns:
tuple[AutoModelForImageTextToText, AutoProcessor]: ใขใใซใจใใญใปใใต
"""
print(f"[INFO] ใขใใซใ่ชญใฟ่พผใใงใใพใ: {MODEL_ID}")
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForImageTextToText.from_pretrained(
MODEL_ID,
torch_dtype="auto",
device_map="auto",
)
model.eval()
print(f"[INFO] ใขใใซ่ชญใฟ่พผใฟๅฎไบ (device: {model.device})")
return model, processor
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๆจ่ซ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def run_ocr(model, processor, pil_image: Image.Image, prompt: str) -> str:
"""ๅไธใใญใณใใใง GLM-OCR ๆจ่ซใๅฎ่กใใใ
Args:
model: GLM-OCR ใขใใซ
processor: GLM-OCR ใใญใปใใต
pil_image: ๅ
ฅๅ็ปๅ (PIL.Image)
prompt: OCR ใใญใณใใๆๅญๅ
Returns:
str: ใขใใซใ็ๆใใใใญในใ
"""
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": pil_image},
{"type": "text", "text": prompt},
],
}
]
inputs = processor.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_dict=True,
return_tensors="pt",
)
inputs.pop("token_type_ids", None)
inputs = {k: v.to(model.device) for k, v in inputs.items()}
with torch.no_grad():
generated_ids = model.generate(**inputs, max_new_tokens=8192)
output_text = processor.decode(
generated_ids[0][inputs["input_ids"].shape[1]:],
skip_special_tokens=True,
)
return output_text.strip()
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ใใผใน: HTML ใใผใใซ โ DataFrame
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class _HtmlTableParser(HTMLParser):
"""HTML ใใผใใซใใใผในใใฆ่กใชในใใๅ้ใใใทใณใใซใชใใผใตใผใ"""
def __init__(self):
super().__init__()
self.rows: list[list[str]] = []
self._current_row: list[str] = []
self._current_cell: str = ""
self._in_cell: bool = False
def handle_starttag(self, tag, attrs):
if tag == "tr":
self._current_row = []
elif tag in ("td", "th"):
self._current_cell = ""
self._in_cell = True
def handle_endtag(self, tag):
if tag in ("td", "th"):
self._current_row.append(self._current_cell.strip())
self._in_cell = False
elif tag == "tr":
if self._current_row:
self.rows.append(self._current_row)
def handle_data(self, data):
if self._in_cell:
self._current_cell += data
def parse_html_table(text: str) -> pd.DataFrame:
"""OCR ๅบๅใใญในใใใ HTML ใใผใใซใๆฝๅบใใฆ DataFrame ใซๅคๆใใใ
Args:
text: OCR ใขใใซใฎๅบๅใใญในใ
Returns:
pd.DataFrame: ใใผใใซใใผใฟใ่ฆใคใใใชใๅ ดๅใฏ็ฉบใฎ DataFrameใ
"""
match = re.search(r"<table.*?>.*?</table>", text, re.DOTALL | re.IGNORECASE)
if not match:
return pd.DataFrame()
parser = _HtmlTableParser()
parser.feed(match.group(0))
if len(parser.rows) < 2:
return pd.DataFrame()
return pd.DataFrame(parser.rows[1:], columns=parser.rows[0])
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ใใผใน: Markdown ใใผใใซ โ DataFrame
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def parse_markdown_table(text: str) -> pd.DataFrame:
"""OCR ๅบๅใใญในใใใ Markdown ใใผใใซใๆฝๅบใใฆ DataFrame ใซๅคๆใใใ
Args:
text: OCR ใขใใซใฎๅบๅใใญในใ
Returns:
pd.DataFrame: ใใผใใซใใผใฟใ่ฆใคใใใชใๅ ดๅใฏ็ฉบใฎ DataFrameใ
"""
table_lines = [l for l in text.splitlines() if "|" in l]
if len(table_lines) < 2:
return pd.DataFrame()
data_lines = [l for l in table_lines if not re.match(r"^\|[\s\-:|]+\|$", l)]
rows = [[c.strip() for c in l.strip().strip("|").split("|")] for l in data_lines]
if not rows:
return pd.DataFrame()
return pd.DataFrame(rows[1:], columns=rows[0])
def parse_table(text: str) -> pd.DataFrame:
"""HTML ใพใใฏ Markdown ใใผใใซใ่ชๅๅคๅฅใใฆใใผในใใใ
Args:
text: OCR ใขใใซใฎๅบๅใใญในใ
Returns:
pd.DataFrame: ใใผใใซใใผใฟใ่ฆใคใใใชใๅ ดๅใฏ็ฉบใฎ DataFrameใ
"""
if "<table" in text.lower():
return parse_html_table(text)
return parse_markdown_table(text)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ใใผใน: JSON ใใญในใ โ dict
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def parse_json_output(text: str) -> dict:
"""OCR ๅบๅใใญในใใใ JSON ้จๅใๆฝๅบใใฆใใผในใใใ
Args:
text: OCR ใขใใซใฎๅบๅใใญในใ
Returns:
dict: ใใผในใใใ JSON ใใผใฟใๅคฑๆๆใฏ็ฉบใฎ dictใ
"""
code_block = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
json_str = code_block.group(1) if code_block else None
if not json_str:
brace_match = re.search(r"\{.*\}", text, re.DOTALL)
if not brace_match:
return {}
json_str = brace_match.group(0)
try:
return json.loads(json_str)
except json.JSONDecodeError:
json_str_fixed = re.sub(r",\s*([}\]])", r"\1", json_str)
try:
return json.loads(json_str_fixed)
except json.JSONDecodeError:
return {}
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Excel ไฟๅญ๏ผๅ
จใทใผใใพใจใๆธใ๏ผ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def save_excel(sheets: dict[str, pd.DataFrame], filepath: Path) -> None:
"""่คๆฐใฎ DataFrame ใ 1 ใคใฎ Excel ใใกใคใซใซใทใผใใใจใซไฟๅญใใใ
Args:
sheets: {ใทใผใๅ: DataFrame} ใฎ่พๆธ๏ผ็ฉบใฎ DataFrame ใฏ็ฉบใทใผใใจใใฆไฟๅญ๏ผ
filepath: ๅบๅๅ
Excel ใใกใคใซใฎใใน (.xlsx)
"""
filepath.parent.mkdir(parents=True, exist_ok=True)
with pd.ExcelWriter(filepath, engine="openpyxl") as writer:
for sheet_name, df in sheets.items():
# Excel ใทใผใๅใฏ 31 ๆๅญไปฅๅ
ใฎๅถ้ใใ
safe_name = sheet_name[:31]
df.to_excel(writer, sheet_name=safe_name, index=False)
row_info = f"{len(df)} ่ก" if not df.empty else "ใใผใฟใชใ"
print(f"[OK] ใทใผใ '{safe_name}' ใๆธใ่พผใฟใพใใ ({row_info})")
print(f"[OK] Excel ไฟๅญๅฎไบ: {filepath}")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ใปใฏใทใงใณ dict โ DataFrame ๅคๆ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def section_to_df(section: dict) -> pd.DataFrame:
"""1 ใฌใใซใฎ dict ใใkey / valueใใฎ 2 ๅ DataFrame ใซๅคๆใใใ
Args:
section: ใญใผใจๅคใๆใค่พๆธ
Returns:
pd.DataFrame: key / value ใฎ 2 ๅ DataFrame
"""
if not section:
return pd.DataFrame()
return pd.DataFrame({"key": list(section.keys()), "value": list(section.values())})
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ใกใคใณ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def main():
"""ใกใคใณๅฆ็: ใณใณใใฃใฐ่ชญใฟ่พผใฟ โ ็ปๅOCR โ Excel ๅบๅใ"""
parser = argparse.ArgumentParser(description="GLM-OCR ๆฑ็จ็ปๅOCRใปCSVๅบๅในใฏใชใใ")
parser.add_argument(
"--config", "-c", required=True, type=Path,
help="ใณใณใใฃใฐใใกใคใซใฎใใน๏ผ.yaml ใพใใฏ .xlsx๏ผไพ: configs/invoice.yaml",
)
parser.add_argument(
"--image", "-i", type=Path, default=None,
help="็ปๅใใกใคใซใฎใใน๏ผ็็ฅๆใฏใณใณใใฃใฐใฎ image ่จญๅฎใไฝฟ็จ๏ผ",
)
parser.add_argument(
"--create-excel", action="store_true",
help="ใณใณใใฃใฐใ่ชญใฟ่พผใใง Excel ใใณใใฌใผใใ็ๆใใฆ็ตไบใใ",
)
args = parser.parse_args()
# โโ ใณใณใใฃใฐ่ชญใฟ่พผใฟ โโโโโโโโโโโโโโโโโโโโ
config_path = args.config.resolve()
if not config_path.exists():
print(f"[ERROR] ใณใณใใฃใฐใ่ฆใคใใใพใใ: {config_path}", file=sys.stderr)
sys.exit(1)
cfg = load_config(config_path)
# โโ Excel ใใณใใฌใผใ็ๆใขใผใ โโโโโโโโโโ
if args.create_excel:
xlsx_path = config_path.with_suffix(".xlsx")
create_excel_template(cfg, xlsx_path)
print(f"[INFO] Excel ใใณใใฌใผใใ็ๆใใพใใ: {xlsx_path}")
sys.exit(0)
config_dir = config_path.parent.parent # configs/ ใฎ่ฆช = ในใฏใชใใใฎใใฃใฌใฏใใช
# ็ปๅใในใฎ่งฃๆฑบ๏ผCLIๅผๆฐ > YAML่จญๅฎ๏ผ
if args.image:
image_path = args.image.resolve()
else:
image_path = (config_dir / cfg["image"]).resolve()
output_dir = (config_dir / cfg.get("output_dir", "output")).resolve()
extract_table: bool = cfg.get("extract_table", True)
sections: dict = cfg.get("sections", {})
if not image_path.exists():
print(f"[ERROR] ็ปๅใ่ฆใคใใใพใใ: {image_path}", file=sys.stderr)
sys.exit(1)
# ๅบๅ Excel ใใกใคใซๅ: {configๅ}.xlsx
excel_path = output_dir / f"{config_path.stem}.xlsx"
preprocess_cfg: dict = cfg.get("preprocess", {})
print(f"[INFO] ใณใณใใฃใฐ : {config_path.name}")
print(f"[INFO] ๅฏพ่ฑกใใกใคใซ: {image_path}")
print(f"[INFO] ๅบๅๅ
: {excel_path}")
print(f"[INFO] ใใผใใซ่ช่ญ: {'ใใ' if extract_table else 'ใชใ'}")
print(f"[INFO] ๆฝๅบใปใฏใทใงใณ: {list(sections.keys())}")
print(f"[INFO] ๅๅฆ็่จญๅฎ: {preprocess_cfg or 'ๅ
จในใใใ ON๏ผใใใฉใซใ๏ผ'}")
# โโ ๅ
ฅๅ่ชญใฟ่พผใฟ๏ผ็ปๅ or PDF ๅ
จใใผใธ๏ผโโ
print(f"\n[INFO] ใใกใคใซใ่ชญใฟ่พผใใงใใพใ...")
raw_pages = load_input_images(image_path)
total_pages = len(raw_pages)
print(f"[INFO] ใใผใธๆฐ: {total_pages}")
# โโ ใขใใซ่ชญใฟ่พผใฟ โโโโโโโโโโโโโโโโโโโโโโโโ
model, processor = load_model()
# ๆธใ่พผใใทใผใใๅ้ใใ่พๆธ {ใทใผใๅ: DataFrame}
sheets: dict[str, pd.DataFrame] = {}
# โโ ๅใใผใธใๅฆ็ โโโโโโโโโโโโโโโโโโโโโโโโ
for page_no, raw_image in enumerate(raw_pages, start=1):
# ่คๆฐใใผใธใฎๅ ดๅใฏใทใผใๅใซ P01_ / P02_ ... ใไปไธ
prefix = f"P{page_no:02d}_" if total_pages > 1 else ""
print(f"\n{'โ' * 50}")
print(f"[INFO] ใใผใธ {page_no}/{total_pages} ใๅฆ็ไธญ...")
# ๅๅฆ็
pil_image = apply_preprocess(raw_image, preprocess_cfg)
print(f"[INFO] ็ปๅใตใคใบ: {pil_image.size}")
# โโ ๆจ่ซโ : ใใผใใซ่ช่ญ๏ผใชใใทใงใณ๏ผโโ
if extract_table:
print("[INFO] ๆจ่ซโ ใใผใใซ่ช่ญ ใๅฎ่กไธญ...")
table_text = run_ocr(model, processor, pil_image, "Table Recognition:")
print("[RAW] ใใผใใซ่ช่ญ ๅบๅ:")
print(table_text)
print()
sheets[f"{prefix}table"] = parse_table(table_text)
# โโ ๆจ่ซโก: ๆง้ ๅ JSON ๆฝๅบ โโโโโโโโโโ
if sections:
print("[INFO] ๆจ่ซโก ๆง้ ๅ JSON ๆฝๅบ ใๅฎ่กไธญ...")
json_schema = build_json_schema(sections)
extract_prompt = (
"Extract all the following information from this image "
"and fill in the JSON template below. "
"Return only valid JSON, no extra text.\n\n"
+ json_schema
)
json_text = run_ocr(model, processor, pil_image, extract_prompt)
print("[RAW] JSON ๆฝๅบ ๅบๅ:")
print(json_text)
print()
data = parse_json_output(json_text)
for section_name, section_cfg in sections.items():
label = f"{prefix}{section_cfg.get('label', section_name)}"
sheets[label] = section_to_df(data.get(section_name, {}))
# โโ Excel ไฟๅญ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
print()
save_excel(sheets, excel_path)
# โโ ็ตๆใตใใชใผ่กจ็คบ โโโโโโโโโโโโโโโโโโโโโ
print("\n" + "=" * 60)
print(" ๅบๅ็ตๆใตใใชใผ")
print("=" * 60)
for sheet_name, df in sheets.items():
print(f"\nโผ {sheet_name}")
print(df.to_string(index=False) if not df.empty else " (ใใผใฟใชใ)")
print("\n[INFO] ๅ
จๅฆ็ใๅฎไบใใพใใใ")
if __name__ == "__main__":
main()
|