File size: 4,037 Bytes
63963aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- 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('<html><body style="margin:0;padding:0;">')
        f.write(svg_big)
        f.write("</body></html>")

    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)