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
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
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
"""

CAPTCHA OCR server using custom trained ONNX model + ddddocr fallback.

Deployed on Hugging Face Spaces (port 7860) or locally (port 9898).



Usage (local):

    pip install ddddocr flask gunicorn pillow onnxruntime

    python ocr_server.py



Usage (HF Spaces):

    Deploy with Dockerfile — auto-starts via gunicorn on port 7860.



Endpoint:

    POST /ocr

    Body: { "image": "<base64-encoded image>" }

    Response: { "text": "ABCD12", "ok": true, "strategy": "custom_model" }

"""

import os
import io
import base64
import re
import time
import json
import hmac
import hashlib
import threading
from collections import Counter
import numpy as np
import requests
import ddddocr
from PIL import Image, ImageFilter, ImageEnhance, ImageOps
from flask import Flask, request, jsonify
from huggingface_hub import HfApi

try:
    import onnxruntime as ort
except ImportError:
    ort = None
    print("⚠️ onnxruntime not available, custom model disabled")

app = Flask(__name__)

# Initialize OCR models once at startup
ocr = ddddocr.DdddOcr(show_ad=False)
ocr_beta = ddddocr.DdddOcr(show_ad=False, beta=True)

# Custom ONNX model
MODEL_PATH = os.path.join(os.path.dirname(__file__), 'captcha_model.onnx')
custom_session = None
model_load_error = None
if ort and os.path.exists(MODEL_PATH):
    try:
        custom_session = ort.InferenceSession(MODEL_PATH)
        print(f"✅ Custom ONNX model loaded: {MODEL_PATH}")
    except Exception as e:
        model_load_error = str(e)
        print(f"⚠️ Failed to load custom model: {e}")
else:
    model_load_error = f"ort={ort is not None}, exists={os.path.exists(MODEL_PATH)}"
    print(f"⚠️ Custom model not found at {MODEL_PATH} or onnxruntime unavailable")

# Custom model config
CUSTOM_IMG_WIDTH = 160
CUSTOM_IMG_HEIGHT = 60
CUSTOM_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
CUSTOM_IDX_TO_CHAR = {i + 1: c for i, c in enumerate(CUSTOM_CHARS)}

# --- License token gate ---
# Tokens are HMAC-signed by the license server (nol-bot-license) with the shared
# OCR_TOKEN_SECRET and carry an expiry. OCR_REQUIRE_TOKEN=1 turns rejection on;
# with the secret set but requirement off, invalid/missing tokens are only logged
# (rollout mode so old legit clients keep working until they update).
OCR_TOKEN_SECRET = os.environ.get('OCR_TOKEN_SECRET', '')
OCR_REQUIRE_TOKEN = os.environ.get('OCR_REQUIRE_TOKEN', '') in ('1', 'true', 'yes')


def _b64url_decode(s):
    return base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))


def verify_ocr_token(token):
    """Returns (ok, info). info is the payload dict on success, error string on failure."""
    if not OCR_TOKEN_SECRET:
        return True, {'c': '', 'd': ''}  # gate not configured — allow all
    if not token or '.' not in token:
        return False, 'missing_token'
    try:
        payload_b64, sig = token.rsplit('.', 1)
        expected = base64.urlsafe_b64encode(
            hmac.new(OCR_TOKEN_SECRET.encode(), payload_b64.encode(), hashlib.sha256).digest()
        ).rstrip(b'=').decode()
        if not hmac.compare_digest(sig.rstrip('='), expected):
            return False, 'bad_signature'
        payload = json.loads(_b64url_decode(payload_b64))
        if payload.get('exp', 0) < time.time() * 1000:
            return False, 'expired'
        return True, payload
    except Exception:
        return False, 'malformed'


# --- Feishu rejection alerts ---
# Aggregated: first rejection notifies immediately, then at most one summary
# message per cooldown window so a hammering pirated copy can't flood the chat.
FEISHU_WEBHOOK = os.environ.get('FEISHU_WEBHOOK', '')
NOTIFY_COOLDOWN_S = int(os.environ.get('OCR_NOTIFY_COOLDOWN', '43200'))

_reject_state = {'lock': threading.Lock(), 'last_sent': 0.0, 'reasons': Counter(), 'ips': set()}


def _send_feishu(text):
    try:
        requests.post(FEISHU_WEBHOOK, json={'msg_type': 'text', 'content': {'text': text}}, timeout=10)
    except Exception as e:
        print(f"[notify] feishu error: {e}")


def notify_rejection(reason, endpoint):
    if not FEISHU_WEBHOOK:
        return
    ip = (request.headers.get('X-Forwarded-For', '') or request.remote_addr or '').split(',')[0].strip()
    with _reject_state['lock']:
        _reject_state['reasons'][f'{endpoint} {reason}'] += 1
        if ip:
            _reject_state['ips'].add(ip)
        now = time.time()
        if now - _reject_state['last_sent'] < NOTIFY_COOLDOWN_S:
            return
        reasons = dict(_reject_state['reasons'])
        ips = sorted(_reject_state['ips'])
        _reject_state['reasons'].clear()
        _reject_state['ips'].clear()
        _reject_state['last_sent'] = now
    lines = ['⚠️ OCR server 拒絕無效 token 請求' if OCR_REQUIRE_TOKEN else '⚠️ OCR server 收到無效 token 請求 (log-only 未攔截)']
    lines += [f'{k}: {v} 次' for k, v in reasons.items()]
    if ips:
        lines.append('IP: ' + ', '.join(ips[:10]) + ('…' if len(ips) > 10 else ''))
    threading.Thread(target=_send_feishu, args=('\n'.join(lines),), daemon=True).start()


def check_request_token(data):
    """Token gate for an endpoint. Returns None if allowed, or a Flask response to reject."""
    token = (data.get('token') or request.headers.get('X-OCR-Token') or '').strip()
    ok, info = verify_ocr_token(token)
    if ok:
        return None
    print(f"[token] rejected: {info} (enforce={OCR_REQUIRE_TOKEN})")
    notify_rejection(info, request.path)
    if OCR_REQUIRE_TOKEN:
        return jsonify({'ok': False, 'text': '', 'error': f'unauthorized: {info}'}), 401
    return None  # log-only rollout mode


# HF Dataset persistence
HF_TOKEN = os.environ.get('HF_TOKEN', '')
DATASET_REPO = 'moterial/captcha-training'
hf_api = HfApi(token=HF_TOKEN) if HF_TOKEN else None

# Interpark CAPTCHAs are 6 uppercase letters ONLY (no digits)
EXPECTED_LEN = 6
VALID_PATTERN = re.compile(r'^[A-Z]{4,7}$')

# Map commonly confused digits back to letters
DIGIT_TO_LETTER = {
    '0': 'O', '1': 'I', '2': 'Z', '3': 'E',
    '4': 'A', '5': 'S', '6': 'G', '7': 'T',
    '8': 'B', '9': 'G',
}

def fix_digits(text):
    """Replace any digits with their most likely letter equivalent."""
    return ''.join(DIGIT_TO_LETTER.get(c, c) for c in text)


def preprocess(image_bytes, threshold=160, contrast=2.0, invert=False, median=0, morph=False):
    """Preprocess CAPTCHA image with configurable parameters."""
    img = Image.open(io.BytesIO(image_bytes))
    img = img.convert('L')

    if invert:
        img = ImageOps.invert(img)

    # Median filter to remove noise lines
    if median > 0:
        img = img.filter(ImageFilter.MedianFilter(size=median))

    enhancer = ImageEnhance.Contrast(img)
    img = enhancer.enhance(contrast)
    img = img.filter(ImageFilter.SHARPEN)
    img = img.point(lambda p: 255 if p > threshold else 0)

    # Morphological cleanup: remove thin lines, keep thick text
    if morph:
        # Erode then dilate to remove thin noise lines
        img = img.filter(ImageFilter.MinFilter(size=3))
        img = img.filter(ImageFilter.MaxFilter(size=3))

    buf = io.BytesIO()
    img.save(buf, format='PNG')
    return buf.getvalue()


def score_result(text):
    """Score an OCR result — higher is better."""
    if not text:
        return -1
    s = 0
    # Strongly prefer exactly 6 uppercase letters
    if VALID_PATTERN.match(text) and len(text) == EXPECTED_LEN:
        s += 15
    elif VALID_PATTERN.match(text):
        s += 5
    # Heavily penalize wrong length
    s -= abs(len(text) - EXPECTED_LEN) * 3
    # Penalize very short results
    if len(text) < 4:
        s -= 10
    return s


def custom_model_ocr(image_bytes):
    """Run inference using the custom trained ONNX model."""
    if custom_session is None:
        return '', 'no_model'

    try:
        img = Image.open(io.BytesIO(image_bytes)).convert('L')
        img = img.resize((CUSTOM_IMG_WIDTH, CUSTOM_IMG_HEIGHT))
        img_arr = np.array(img, dtype=np.float32) / 255.0
        img_tensor = img_arr.reshape(1, 1, CUSTOM_IMG_HEIGHT, CUSTOM_IMG_WIDTH)

        input_name = custom_session.get_inputs()[0].name
        output = custom_session.run(None, {input_name: img_tensor})

        # CTC greedy decode
        preds = np.argmax(output[0], axis=2)  # (T, batch)
        raw = preds[:, 0].tolist()
        decoded = []
        prev = -1
        for idx in raw:
            if idx != 0 and idx != prev:
                decoded.append(idx)
            prev = idx
        text = "".join([CUSTOM_IDX_TO_CHAR.get(idx, "") for idx in decoded])
        return text, 'custom_model'
    except Exception as e:
        print(f"Custom model error: {e}")
        return '', 'custom_error'


def multi_strategy_ocr(image_bytes):
    """Run multiple preprocessing strategies and pick the best result."""
    candidates = []

    strategies = [
        {'threshold': 140, 'contrast': 2.0, 'invert': False, 'median': 0, 'morph': False, 'name': 'thresh_140'},
        {'threshold': 160, 'contrast': 2.0, 'invert': False, 'median': 0, 'morph': False, 'name': 'thresh_160'},
        {'threshold': 160, 'contrast': 2.0, 'invert': True, 'median': 0, 'morph': False, 'name': 'inverted'},
        {'threshold': 140, 'contrast': 2.0, 'invert': False, 'median': 3, 'morph': False, 'name': 'med3_140'},
        {'threshold': 160, 'contrast': 2.0, 'invert': False, 'median': 3, 'morph': False, 'name': 'med3_160'},
        {'threshold': 150, 'contrast': 2.0, 'invert': False, 'median': 3, 'morph': True, 'name': 'morph_150'},
    ]

    for strat in strategies:
        try:
            processed = preprocess(image_bytes, strat['threshold'], strat['contrast'], strat['invert'], strat['median'], strat['morph'])
            result = fix_digits(ocr.classification(processed).strip().upper())
            if result:
                candidates.append((result, strat['name'], score_result(result)))
        except:
            pass

    # Also try beta model on raw image
    try:
        result_beta = fix_digits(ocr_beta.classification(image_bytes).strip().upper())
        if result_beta:
            candidates.append((result_beta, 'beta_raw', score_result(result_beta)))
    except:
        pass

    # Also try default model on raw image
    try:
        result_raw = fix_digits(ocr.classification(image_bytes).strip().upper())
        if result_raw:
            candidates.append((result_raw, 'raw', score_result(result_raw)))
    except:
        pass

    if not candidates:
        return '', 'none'

    # Consensus bonus: if multiple strategies produce the same result, it's more likely correct
    text_counts = Counter(c[0] for c in candidates)
    scored = []
    for text, name, score in candidates:
        bonus = (text_counts[text] - 1) * 3  # +3 per additional agreement
        scored.append((text, name, score + bonus))

    scored.sort(key=lambda x: x[2], reverse=True)
    return scored[0][0], scored[0][1]



@app.route('/ocr', methods=['POST'])
def solve():
    data = request.get_json(force=True)
    rejected = check_request_token(data)
    if rejected:
        return rejected
    image_b64 = data.get('image', '')

    if not image_b64:
        return jsonify({'ok': False, 'text': '', 'error': 'Missing image'}), 400

    try:
        image_bytes = base64.b64decode(image_b64)

        # Try custom model first (fastest, trained on our data)
        custom_text, custom_strategy = custom_model_ocr(image_bytes)

        # If custom model gives valid 6-letter result, use it directly
        if custom_text and VALID_PATTERN.match(custom_text) and len(custom_text) == EXPECTED_LEN:
            return jsonify({'ok': True, 'text': custom_text, 'strategy': custom_strategy})

        # Fall back to ddddocr multi-strategy
        text, strategy = multi_strategy_ocr(image_bytes)

        # If ddddocr also has a result, compare with custom model
        if custom_text and text:
            # If custom model produced something close (5-7 chars), still consider it
            custom_score = score_result(custom_text)
            ddddocr_score = score_result(text)
            if custom_score >= ddddocr_score:
                text, strategy = custom_text, custom_strategy

        if text:
            return jsonify({'ok': True, 'text': text, 'strategy': strategy})
        elif custom_text:
            return jsonify({'ok': True, 'text': custom_text, 'strategy': custom_strategy})
        else:
            return jsonify({'ok': False, 'text': '', 'error': 'All strategies failed'}), 500
    except Exception as e:
        return jsonify({'ok': False, 'text': '', 'error': str(e)}), 500


@app.route('/feedback', methods=['POST'])
def feedback():
    """Training-data collection is finished (dataset full at 10k) — accept and discard.



    Kept as a no-op so deployed extensions calling it fire-and-forget don't error.

    """
    data = request.get_json(force=True)
    rejected = check_request_token(data)
    if rejected:
        return rejected
    return jsonify({'ok': True, 'saved': None, 'total_samples': _get_dataset_count(), 'persisted': False})


# Cached dataset count (avoid hitting HF API on every request)
_dataset_count_cache = {'count': 0, 'last_update': 0}

def _get_dataset_count():
    """Get dataset count from HF repo, cached for 60 seconds."""
    now = time.time()
    if now - _dataset_count_cache['last_update'] < 60:
        return _dataset_count_cache['count']
    try:
        if hf_api:
            files = hf_api.list_repo_files(repo_id=DATASET_REPO, repo_type='dataset')
            count = len([f for f in files if f.startswith('images/') and f.endswith('.png')])
            _dataset_count_cache['count'] = count
            _dataset_count_cache['last_update'] = now
            return count
    except Exception as e:
        print(f"HF count error: {e}")
    return _dataset_count_cache['count']


@app.route('/dataset/count', methods=['GET'])
def dataset_count():
    """Check how many training samples have been collected."""
    count = _get_dataset_count()
    return jsonify({'ok': True, 'count': count})


@app.route('/health', methods=['GET'])
@app.route('/', methods=['GET'])
def health():
    count = _get_dataset_count()
    model_size = -1
    if os.path.exists(MODEL_PATH):
        model_size = os.path.getsize(MODEL_PATH)
    return jsonify({
        'ok': True,
        'token_gate': bool(OCR_TOKEN_SECRET),
        'token_enforced': OCR_REQUIRE_TOKEN,
        'feishu_notify': bool(FEISHU_WEBHOOK),
        'engine': 'custom_onnx+ddddocr',
        'custom_model': custom_session is not None,
        'mode': 'hybrid',
        'strategies': 8,
        'dataset_samples': count,
        'persistent': bool(hf_api),
        'ort_available': ort is not None,
        'model_path': MODEL_PATH,
        'model_exists': os.path.exists(MODEL_PATH),
        'model_size': model_size,
        'model_load_error': model_load_error
    })


if __name__ == '__main__':
    port = int(os.environ.get('PORT', 7860))
    print(f'🔤 ddddocr CAPTCHA server starting on http://0.0.0.0:{port}')
    app.run(host='0.0.0.0', port=port, debug=False)