| """ |
| 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 |
|
|
| |
| 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" |
|
|
|
|
| |
| |
| |
| 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() |
|
|
|
|
| |
| |
| |
| 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]) |
|
|
|
|
| |
| |
| |
| 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) |
|
|
|
|
| |
| |
| |
| 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 {} |
|
|
|
|
| |
| |
| |
| 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(): |
| |
| 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}") |
|
|
|
|
| |
| |
| |
| 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) |
|
|
| |
| 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 |
|
|
| |
| 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_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๏ผใใใฉใซใ๏ผ'}") |
|
|
| |
| 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() |
|
|
| |
| sheets: dict[str, pd.DataFrame] = {} |
|
|
| |
| for page_no, raw_image in enumerate(raw_pages, start=1): |
| |
| 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) |
|
|
| |
| 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, {})) |
|
|
| |
| 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() |
|
|