File size: 10,896 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 | """
ใณใณใใฃใฐ่ชญใฟ่พผใฟใป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}")
|