""" コンフィグ読み込み・Excel テンプレート生成モジュール YAML または Excel (.xlsx) のどちらでも同じ dict 構造を返す。 glmocr.py / glmocr_ollama.py 双方から import して使う。 Excel フォーマット(3 シート構成): settings … image / output_dir / extract_table preprocess … 前処理ステップの ON/OFF sections … 抽出セクション・フィールドの一覧テーブル 使い方: from config_loader import load_config, create_excel_template cfg = load_config(Path("configs/invoice.yaml")) # YAML cfg = load_config(Path("configs/invoice.xlsx")) # Excel create_excel_template(cfg, Path("configs/new.xlsx")) """ from __future__ import annotations from pathlib import Path import openpyxl from openpyxl.styles import Font, PatternFill, Alignment, Border, Side import yaml # ───────────────────────────────────────────── # 内部ユーティリティ # ───────────────────────────────────────────── def _to_bool(value) -> bool: """セル値を bool に変換する(Excel の TRUE/FALSE 文字列にも対応)。""" if isinstance(value, bool): return value return str(value).strip().upper() in ("TRUE", "YES", "1", "〇", "ON") def _header_style(ws, row: int, fill_color: str = "4472C4"): """指定行をヘッダー行としてスタイルを適用する。""" fill = PatternFill(start_color=fill_color, end_color=fill_color, fill_type="solid") font = Font(color="FFFFFF", bold=True) border = Border( bottom=Side(style="medium", color="FFFFFF"), ) for cell in ws[row]: cell.fill = fill cell.font = font cell.alignment = Alignment(horizontal="center", vertical="center") cell.border = border def _zebra_row(ws, row: int, is_odd: bool): """偶数/奇数行で背景色を交互にする(ゼブラストライプ)。""" color = "EAF2FF" if is_odd else "FFFFFF" fill = PatternFill(start_color=color, end_color=color, fill_type="solid") for cell in ws[row]: cell.fill = fill def _set_column_widths(ws, widths: list[int]): """列幅を一括設定する。""" cols = list(ws.column_dimensions.keys()) for i, w in enumerate(widths): col = cols[i] if i < len(cols) else chr(65 + i) ws.column_dimensions[col].width = w # ───────────────────────────────────────────── # YAML 読み込み # ───────────────────────────────────────────── def _load_yaml(path: Path) -> dict: """YAML ファイルをロードして dict を返す。""" with path.open(encoding="utf-8") as f: return yaml.safe_load(f) # ───────────────────────────────────────────── # Excel 読み込み # ───────────────────────────────────────────── def _load_excel(path: Path) -> dict: """Excel コンフィグ (.xlsx) をロードして YAML 互換の dict を返す。 期待するシート: settings : A列=キー, B列=値 (ヘッダー行は読み飛ばす) preprocess : A列=ステップ名, B列=TRUE/FALSE sections : A列=section_key, B列=section_label, C列=field_key """ wb = openpyxl.load_workbook(path, data_only=True) cfg: dict = {} # ── settings シート ────────────────────── if "settings" in wb.sheetnames: ws = wb["settings"] rows = list(ws.iter_rows(min_row=2, values_only=True)) # 1行目はヘッダー for row in rows: if not row[0]: continue key = str(row[0]).strip() val = row[1] if key == "extract_table": cfg[key] = _to_bool(val) else: cfg[key] = str(val).strip() if val is not None else "" # ── preprocess シート ──────────────────── if "preprocess" in wb.sheetnames: ws = wb["preprocess"] rows = list(ws.iter_rows(min_row=2, values_only=True)) preprocess: dict = {} for row in rows: if not row[0]: continue step = str(row[0]).strip() preprocess[step] = _to_bool(row[1]) if row[1] is not None else True cfg["preprocess"] = preprocess # ── sections シート ────────────────────── if "sections" in wb.sheetnames: ws = wb["sections"] rows = list(ws.iter_rows(min_row=2, values_only=True)) sections: dict = {} for row in rows: if not row[0]: continue sec_key = str(row[0]).strip() sec_label = str(row[1]).strip() if row[1] else sec_key field_key = str(row[2]).strip() if row[2] else None if not field_key: continue if sec_key not in sections: sections[sec_key] = {"label": sec_label, "fields": {}} sections[sec_key]["fields"][field_key] = "" cfg["sections"] = sections return cfg # ───────────────────────────────────────────── # 公開関数: コンフィグ読み込み # ───────────────────────────────────────────── def load_config(config_path: Path) -> dict: """YAML または Excel (.xlsx) のコンフィグを読み込んで dict を返す。 ファイル拡張子で自動判別する: .yaml / .yml → YAML として読み込む .xlsx → Excel として読み込む Args: config_path: コンフィグファイルのパス Returns: dict: コンフィグ辞書(YAML と同一構造) Raises: ValueError: 対応していない拡張子の場合 """ suffix = config_path.suffix.lower() if suffix in (".yaml", ".yml"): return _load_yaml(config_path) if suffix == ".xlsx": return _load_excel(config_path) raise ValueError(f"対応していないコンフィグ形式です: {suffix}(.yaml / .xlsx のみ有効)") # ───────────────────────────────────────────── # 公開関数: Excel テンプレート生成 # ───────────────────────────────────────────── # セクション一覧シートのヘッダー説明文 _SECTIONS_HEADER_NOTE = ( "section_key(変更不可)" " │ section_label(Excel出力時のシート名)" " │ field_key(変更不可)" ) def create_excel_template(cfg: dict, xlsx_path: Path) -> None: """コンフィグ dict から編集しやすい Excel テンプレートを生成する。 生成されるシート: settings … 基本設定(image / output_dir / extract_table) preprocess … 前処理ステップ ON/OFF sections … 全セクション・フィールドの一覧テーブル Args: cfg: load_config() で取得したコンフィグ dict xlsx_path: 出力先 xlsx ファイルパス """ wb = openpyxl.Workbook() # ── settings シート ────────────────────── ws_s = wb.active ws_s.title = "settings" ws_s.append(["キー", "値", "説明"]) _header_style(ws_s, 1, "2E75B6") data_s = [ ("image", cfg.get("image", ""), "対象ファイルパス(画像または PDF)"), ("output_dir", cfg.get("output_dir", "output"), "Excel 出力先ディレクトリ"), ("extract_table", cfg.get("extract_table", True), "テーブル認識を実行する(TRUE/FALSE)"), ] for i, row in enumerate(data_s, start=2): ws_s.append(list(row)) _zebra_row(ws_s, i, i % 2 == 0) _set_column_widths(ws_s, [22, 28, 44]) # ── preprocess シート ──────────────────── ws_p = wb.create_sheet("preprocess") ws_p.append(["前処理ステップ", "有効(TRUE/FALSE)", "説明"]) _header_style(ws_p, 1, "2E75B6") default_pre = {"deskew": True, "denoise": True, "enhance_contrast": True, "sharpen": True} pre_desc = { "deskew": "傾き補正(スキャン・手持ち撮影の傾きを Hough 変換で自動補正)", "denoise": "ノイズ除去(バイラテラルフィルタ、エッジを保護しながら平滑化)", "enhance_contrast": "コントラスト強調(照明ムラに有効な CLAHE)", "sharpen": "シャープ化(Unsharp Masking でぼけを補正)", } pre_cfg = cfg.get("preprocess", default_pre) for i, (step, desc) in enumerate(pre_desc.items(), start=2): ws_p.append([step, pre_cfg.get(step, True), desc]) _zebra_row(ws_p, i, i % 2 == 0) _set_column_widths(ws_p, [22, 22, 54]) # ── sections シート ────────────────────── ws_sec = wb.create_sheet("sections") ws_sec.append(["section_key", "section_label", "field_key"]) _header_style(ws_sec, 1, "2E75B6") row_idx = 2 sections = cfg.get("sections", {}) prev_sec = None for sec_key, sec_cfg in sections.items(): label = sec_cfg.get("label", sec_key) fields = sec_cfg.get("fields", {}) # セクションが変わるたびに色を切り替える is_odd = (list(sections.keys()).index(sec_key) % 2 == 0) for field_key in fields: ws_sec.append([sec_key, label, field_key]) _zebra_row(ws_sec, row_idx, is_odd) row_idx += 1 _set_column_widths(ws_sec, [18, 22, 22]) # 注釈行 ws_sec.append([]) ws_sec.append(["※ section_key と field_key はスクリプトが参照するキー名です。変更する場合は一致を確認してください。"]) note_cell = ws_sec.cell(row=row_idx + 2, column=1) note_cell.font = Font(color="888888", italic=True) xlsx_path.parent.mkdir(parents=True, exist_ok=True) wb.save(str(xlsx_path)) print(f"[OK] Excel テンプレート生成: {xlsx_path}")