# -*- coding: utf-8 -*- """ decoder.py Module giai ma captcha dang SVG (6 chu so) thanh chuoi text. Pipeline: SVG (raw text) -> render ra anh raster (PNG) bang wkhtmltoimage -> cat 6 vung co dinh (moi vung 1 chu so) -> phan loai tung vung bang model RandomForest (sklearn) -> ghep lai thanh chuoi ket qua Yeu cau he thong: lenh `wkhtmltoimage` phai co san (cai qua apt: sudo apt-get install -y wkhtmltopdf goi cai dat nay cung cap luon binary wkhtmltoimage). """ import os import re import subprocess import tempfile import uuid import numpy as np from PIL import Image import joblib BASE_DIR = os.path.dirname(os.path.abspath(__file__)) MODEL_PATH = os.path.join(BASE_DIR, "digit_classifier.pkl") # Toa do tam 6 vi tri chu so trong he toa do goc cua SVG (width=192, height=24) SLOT_CENTERS = [26.3, 53.6, 80.9, 108.2, 135.5, 162.8] SLOT_HALF_WIDTH = 14 # trong he toa do goc (192x24) RENDER_SCALE = 5 # render anh lon gap 5 lan de cat chinh xac hon RENDER_W = 192 * RENDER_SCALE RENDER_H = 24 * RENDER_SCALE _model_bundle = None def _load_model(): global _model_bundle if _model_bundle is None: _model_bundle = joblib.load(MODEL_PATH) return _model_bundle def _ensure_viewbox(svg_text: str) -> str: """Dam bao SVG co viewBox de render phong to dung ty le.""" if "viewBox" in svg_text: # da co viewBox, chi can doi width/height svg_text = re.sub(r'width="[\d.]+"', f'width="{RENDER_W}"', svg_text, count=1) svg_text = re.sub(r'height="[\d.]+"', f'height="{RENDER_H}"', svg_text, count=1) return svg_text # them viewBox dua tren width/height goc, roi phong to m = re.search(r'width="([\d.]+)"\s+height="([\d.]+)"', svg_text) if not m: raise ValueError("Khong tim thay width/height trong SVG") w, h = m.group(1), m.group(2) svg_text = svg_text.replace( f'width="{w}" height="{h}"', f'width="{RENDER_W}" height="{RENDER_H}" viewBox="0 0 {w} {h}"', 1, ) return svg_text def render_svg_to_image(svg_text: str) -> Image.Image: """Render chuoi SVG thanh PIL.Image bang wkhtmltoimage (qua subprocess).""" svg_big = _ensure_viewbox(svg_text) tmp_id = uuid.uuid4().hex html_path = os.path.join(tempfile.gettempdir(), f"giaianh_{tmp_id}.html") png_path = os.path.join(tempfile.gettempdir(), f"giaianh_{tmp_id}.png") with open(html_path, "w", encoding="utf-8") as f: f.write('') f.write(svg_big) f.write("") try: result = subprocess.run( ["wkhtmltoimage", "--width", str(RENDER_W), "--height", str(RENDER_H), html_path, png_path], capture_output=True, text=True, timeout=15, ) if not os.path.exists(png_path): raise RuntimeError(f"wkhtmltoimage that bai: {result.stderr}") img = Image.open(png_path).convert("L") img.load() # dam bao doc het du lieu truoc khi xoa file return img finally: for p in (html_path, png_path): if os.path.exists(p): os.remove(p) def crop_slots(img: Image.Image): """Cat anh raster (RENDER_W x RENDER_H) thanh 6 vung chu so.""" crops = [] for cx in SLOT_CENTERS: left = int((cx - SLOT_HALF_WIDTH) * RENDER_SCALE) right = int((cx + SLOT_HALF_WIDTH) * RENDER_SCALE) crops.append(img.crop((left, 0, right, RENDER_H))) return crops def decode_svg(svg_text: str) -> str: """Ham chinh: nhan chuoi SVG, tra ve chuoi 6 chu so da giai ma.""" bundle = _load_model() model = bundle["model"] size = bundle["size"] # (w, h) img = render_svg_to_image(svg_text) crops = crop_slots(img) feats = [] for c in crops: c = c.resize(size) arr = np.asarray(c, dtype=np.float32).flatten() / 255.0 feats.append(arr) feats = np.array(feats) preds = model.predict(feats) return "".join(preds)