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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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
"""Ekstraksi kode Python dari gambar tulisan tangan via PaddleOCR."""

from __future__ import annotations

import asyncio
import logging
import os
import re
import tempfile
from typing import Any, Optional

logger = logging.getLogger(__name__)


class LayananOCRError(RuntimeError):
    """OCR tidak tersedia atau gagal memproses gambar."""


# --------------------------------------------------------------------------- #
# Lazy importers β€” backend tetap jalan tanpa Paddle / OpenCV terpasang        #
# --------------------------------------------------------------------------- #

def _import_cv2() -> Any:
    try:
        import cv2  # noqa: PLC0415
        return cv2
    except ImportError as exc:
        raise LayananOCRError(
            "opencv-python-headless belum terpasang. Jalankan: pip install opencv-python-headless"
        ) from exc


def _import_numpy() -> Any:
    try:
        import numpy as np  # noqa: PLC0415
        return np
    except ImportError as exc:
        raise LayananOCRError("numpy belum terpasang.") from exc


def _import_paddleocr() -> Any:
    try:
        from paddleocr import PaddleOCR  # noqa: PLC0415
        return PaddleOCR
    except ImportError as exc:
        raise LayananOCRError(
            "PaddleOCR belum terpasang. Jalankan: pip install -r requirements-ocr.txt"
        ) from exc


# --------------------------------------------------------------------------- #
# CodeOCRService                                                               #
# --------------------------------------------------------------------------- #

class CodeOCRService:
    """Layanan OCR yang dioptimalkan untuk kode Python tulisan tangan.

    Contoh penggunaan::

        svc = CodeOCRService()
        hasil = await asyncio.to_thread(svc.extract_code, "/path/ke/gambar.jpg")
        print(hasil["code"])
    """

    def __init__(self, lang: str = "en", debug: bool = False) -> None:
        """Inisialisasi service.

        Args:
            lang: Kode bahasa PaddleOCR (default 'en').
            debug: Jika True, simpan gambar hasil preprocess ke /tmp.
        """
        self._lang = lang
        self._debug = debug
        self._ocr: Any = None  # dibuat saat pertama kali dipakai (lazy)

    def _get_ocr(self) -> Any:
        if self._ocr is None:
            PaddleOCR = _import_paddleocr()
            self._ocr = PaddleOCR(
                use_angle_cls=True,
                lang=self._lang,
                show_log=False,
            )
        return self._ocr

    # ----------------------------------------------------------------------- #
    # Public API                                                               #
    # ----------------------------------------------------------------------- #

    def extract_code(self, image_path: str) -> dict[str, Any]:
        """Ekstrak kode Python dari gambar dan kembalikan hasil terstruktur.

        Args:
            image_path: Path absolut ke file gambar.

        Returns:
            Dict dengan kunci:
            - ``code``       : string kode hasil rekonstruksi
            - ``confidence`` : float rata-rata kepercayaan (0–1)
            - ``raw_lines``  : list dict mentah dari PaddleOCR

        Raises:
            LayananOCRError: Jika gambar tidak bisa dibaca atau OCR gagal.

        Contoh::

            hasil = svc.extract_code("/tmp/kode.jpg")
            # {'code': 'print("hello")', 'confidence': 0.97, 'raw_lines': [...]}
        """
        if not os.path.isfile(image_path):
            raise LayananOCRError(f"File tidak ditemukan: {image_path}")

        preprocessed = self.preprocess_image(image_path)

        ocr = self._get_ocr()
        try:
            hasil_ocr = ocr.ocr(preprocessed, cls=True)
        except Exception as exc:
            raise LayananOCRError(f"OCR gagal: {exc}") from exc

        if not hasil_ocr or hasil_ocr[0] is None:
            logger.warning("OCR tidak mendeteksi teks pada: %s", image_path)
            return {"code": "", "confidence": 0.0, "raw_lines": []}

        raw_lines: list[dict[str, Any]] = []
        for entri in hasil_ocr[0]:
            if not entri or len(entri) < 2:
                continue
            kotak, (teks, skor) = entri[0], entri[1]
            raw_lines.append({
                "text": teks,
                "confidence": float(skor),
                "box": kotak,
            })

        code = self.reconstruct_code(raw_lines)
        confidence = self.calculate_confidence(raw_lines)

        logger.info(
            "OCR selesai: %d baris, confidence=%.3f, path=%s",
            len(raw_lines), confidence, image_path,
        )
        return {"code": code, "confidence": confidence, "raw_lines": raw_lines}

    def preprocess_image(self, image_path: str) -> Any:
        """Terapkan pipeline preprocess agar OCR lebih akurat pada kode.

        Pipeline:
        1. Grayscale
        2. Denoising (fastNlMeansDenoising)
        3. Peningkatan kontras (equalizeHist)
        4. Binarisasi adaptif (Otsu)

        Args:
            image_path: Path ke file gambar.

        Returns:
            numpy.ndarray gambar yang sudah diproses (grayscale biner).
        """
        cv2 = _import_cv2()

        gambar = cv2.imread(image_path, cv2.IMREAD_COLOR)
        if gambar is None:
            raise LayananOCRError(
                f"Format gambar tidak dikenali atau file rusak: {image_path}"
            )

        # 1. Grayscale
        abu = cv2.cvtColor(gambar, cv2.COLOR_BGR2GRAY)

        # 2. Denoising
        bersih = cv2.fastNlMeansDenoising(abu, h=10, templateWindowSize=7, searchWindowSize=21)

        # 3. Kontras dengan equalizeHist
        kontras = cv2.equalizeHist(bersih)

        # 4. Binarisasi Otsu β€” teks hitam di latar putih
        _, biner = cv2.threshold(kontras, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

        # Pastikan teks hitam = 0, latar putih = 255 (Paddle lebih suka ini)
        if biner.mean() < 127:
            biner = cv2.bitwise_not(biner)

        if self._debug:
            nama_debug = os.path.join(
                tempfile.gettempdir(),
                f"codebuddy_preproc_{os.path.basename(image_path)}",
            )
            cv2.imwrite(nama_debug, biner)
            logger.debug("Gambar preprocess disimpan ke: %s", nama_debug)

        return biner

    def reconstruct_code(self, ocr_lines: list[dict[str, Any]]) -> str:
        """Rekonstruksi kode Python dari baris-baris OCR dengan indentasi yang benar.

        Strategi indentasi:
        - Koordinat x kiri dari bounding box menentukan level indentasi.
        - x_min global = kolom 0 (tidak ada indentasi).
        - Setiap 20px ke kanan β‰ˆ satu level indentasi (4 spasi).

        Args:
            ocr_lines: List dict dari PaddleOCR dengan kunci 'text' dan 'box'.

        Returns:
            String kode Python dengan indentasi yang telah direkonstruksi.
        """
        if not ocr_lines:
            return ""

        # Urutkan baris berdasarkan posisi vertikal (y tengah dari box)
        def _y_tengah(baris: dict[str, Any]) -> float:
            box = baris.get("box", [])
            if not box:
                return 0.0
            ys = [titik[1] for titik in box]
            return sum(ys) / len(ys)

        def _x_kiri(baris: dict[str, Any]) -> float:
            box = baris.get("box", [])
            if not box:
                return 0.0
            return min(titik[0] for titik in box)

        terurut = sorted(ocr_lines, key=_y_tengah)

        # Tentukan x minimum sebagai baseline kolom 0
        semua_x = [_x_kiri(b) for b in terurut]
        x_baseline = min(semua_x) if semua_x else 0.0
        lebar_per_indent = 20.0  # piksel per satu level indent (4 spasi)

        baris_kode: list[str] = []
        for baris in terurut:
            teks_asli = baris.get("text", "").rstrip()
            if not teks_asli:
                continue

            # Hitung level indentasi dari posisi x
            x = _x_kiri(baris)
            level = max(0, round((x - x_baseline) / lebar_per_indent))
            spasi = "    " * level  # 4 spasi per level

            teks_bersih = self._bersihkan_teks(teks_asli)
            teks_bersih = self.fix_common_ocr_errors(teks_bersih)

            baris_kode.append(spasi + teks_bersih)

        return "\n".join(baris_kode)

    def calculate_confidence(self, lines: list[dict[str, Any]]) -> float:
        """Hitung rata-rata confidence tertimbang berdasarkan panjang teks.

        Baris yang lebih panjang diberi bobot lebih tinggi karena lebih
        representatif dibanding baris pendek yang mungkin noise.

        Args:
            lines: List dict dengan kunci 'text' dan 'confidence'.

        Returns:
            Float antara 0.0 dan 1.0.
        """
        if not lines:
            return 0.0

        total_bobot = 0.0
        total_skor = 0.0
        for baris in lines:
            panjang = len(baris.get("text", ""))
            bobot = max(1, panjang)  # minimal bobot 1 agar tidak hilang
            total_skor += baris.get("confidence", 0.0) * bobot
            total_bobot += bobot

        return round(total_skor / total_bobot, 4) if total_bobot > 0 else 0.0

    # ----------------------------------------------------------------------- #
    # Helpers                                                                  #
    # ----------------------------------------------------------------------- #

    @staticmethod
    def fix_common_ocr_errors(text: str) -> str:
        """Perbaiki kesalahan OCR umum pada kode Python.

        Koreksi yang diterapkan:
        - Fungsi builtin yang sering salah dibaca (``prin(`` β†’ ``print(``)
        - Pemisah blok (``;`` β†’ ``:`` di akhir statement blok)
        - Karakter ambigu pada konteks keyword (``l`` vs ``1``, ``O`` vs ``0``)
        - Normalisasi indentasi tab β†’ 4 spasi

        Args:
            text: Satu baris teks hasil OCR.

        Returns:
            Teks yang sudah dikoreksi.
        """
        # Tab β†’ 4 spasi
        text = text.replace("\t", "    ")

        # Fungsi builtin yang sering salah baca
        text = re.sub(r"\bprin\(", "print(", text)
        text = re.sub(r"\bprintt?\(", "print(", text)
        text = re.sub(r"\binput\s*\(", "input(", text)
        text = re.sub(r"\brange\s*\(", "range(", text)
        text = re.sub(r"\blen\s*\(", "len(", text)

        # Keyword: 'def', 'class', 'return', 'import' yang sering terpotong
        text = re.sub(r"\bde f\b", "def", text)
        text = re.sub(r"\bclas s\b", "class", text)
        text = re.sub(r"\bretur n\b", "return", text)

        # Akhir baris blok: ; β†’ : (for/if/def/else/elif/while/class/try/except/with)
        _blok_pattern = r"^(\s*(?:def|class|if|elif|else|for|while|try|except|finally|with)\b.+);$"
        text = re.sub(_blok_pattern, r"\1:", text)

        # Angka ambigu dalam konteks identifier (bukan dalam string/angka):
        # 'l' β†’ '1' dan '1' β†’ 'l' sangat konteks-spesifik, hindari over-koreksi.
        # Hanya koreksi yang sangat aman:
        text = re.sub(r"\bO\b(?=\s*[+\-*/=<>])", "0", text)  # O sendirian di ekspresi
        text = re.sub(r"(?<=[=(,\[{+\-*/ ])\bI\b", "1", text)  # I setelah operator

        # Tanda baca umum: smart/curly quotes β†’ straight (U+2018/19/1C/1D β†’ U+0027/0022)
        text = text.replace("β€˜", "'").replace("’", "'")  # ' ' β†’ '
        text = text.replace("β€œ", '"').replace("”", '"')  # " " β†’ "

        return text

    @staticmethod
    def _bersihkan_teks(text: str) -> str:
        """Hapus karakter noise yang tidak mungkin ada dalam kode Python."""
        # Hapus karakter kontrol kecuali newline/tab
        text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", text)
        # Hapus karakter yang tidak mungkin di kode Python (beberapa simbol dekorasi)
        text = re.sub(r"[^\x20-\x7eΒ ]", "", text)
        return text.strip()


# --------------------------------------------------------------------------- #
# Singleton                                                                    #
# --------------------------------------------------------------------------- #

code_ocr_service = CodeOCRService()


# --------------------------------------------------------------------------- #
# Backward-compatible function (dipakai api/ocr.py)                           #
# --------------------------------------------------------------------------- #

async def ekstrak_teks_dari_gambar(
    isi_gambar: bytes,
    bahasa: str = "en",
) -> dict[str, Any]:
    """Ekstrak kode Python dari bytes gambar.

    Strategi (prioritas):
    1. Gemma 4 Vision β€” primary, tidak butuh dependensi tambahan
    2. PaddleOCR β€” fallback jika Ollama tidak berjalan

    Args:
        isi_gambar: Konten file gambar dalam bytes.
        bahasa: Kode bahasa (untuk fallback PaddleOCR).

    Returns:
        Dict dengan kunci ``text``, ``lines``, ``engine``, ``confidence``.
    """
    if not isi_gambar:
        raise LayananOCRError("Berkas gambar kosong.")

    # Simpan alasan vision gagal β€” dipakai jika fallback Paddle juga tidak jalan
    alasan_vision: Optional[str] = None

    # ── Primary: Gemma 4 Vision ───────────────────────────────────────── #
    try:
        from services.llm_service import gemma_vision_service  # noqa: PLC0415
        hasil_vision = await gemma_vision_service.ekstrak_kode(isi_gambar)
        logger.info("Gemma 4 Vision berhasil: confidence=%.2f", hasil_vision["confidence"])
        return {
            "text": hasil_vision["code"],
            "lines": [],
            "engine": "gemma4-vision",
            "confidence": hasil_vision["confidence"],
        }
    except Exception as exc:  # noqa: BLE001
        alasan_vision = str(exc)[:400]
        logger.warning("Gemma 4 Vision gagal (%s) β€” fallback ke PaddleOCR", exc)

    # ── Fallback: PaddleOCR ──────────────────────────────────────────── #
    sufiks = ".jpg"
    with tempfile.NamedTemporaryFile(suffix=sufiks, delete=False) as tmp:
        tmp.write(isi_gambar)
        tmp_path = tmp.name

    try:
        svc = CodeOCRService(lang=bahasa)
        try:
            hasil = await asyncio.to_thread(svc.extract_code, tmp_path)
        except LayananOCRError as exc_paddle:
            # Gabungkan konteks agar 503 tidak hanya menyalahkan Paddle
            vis = alasan_vision or "alasan tidak tercatat"
            raise LayananOCRError(
                f"Gemma Vision gagal ({vis}). "
                f"Paddle fallback tidak tersedia: {exc_paddle} "
                "β€” pastikan Ollama jalan + model vision (mis. gemma4:e4b), "
                "atau pasang Paddle: pip install -r requirements-ocr.txt "
                "(biasanya Python 3.10–3.12; lihat komentar di file tersebut)."
            ) from exc_paddle
    finally:
        try:
            os.unlink(tmp_path)
        except OSError:
            pass

    return {
        "text": hasil["code"],
        "lines": hasil["raw_lines"],
        "engine": "paddleocr-fallback",
        "confidence": hasil["confidence"],
    }