Download ocr_server.py from moterial/ocr: direct link, hf CLI and curl.
- Browser
- Download file 15.5 kB
-
https://huggingface.co/spaces/moterial/ocr/resolve/main/ocr_server.py
- Command line
-
hf download hf://spaces/moterial/ocr/ocr_server.py
-
curl -L -o ocr_server.py https://huggingface.co/spaces/moterial/ocr/resolve/main/ocr_server.py
15.5 kB
| """ | |
| 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] | |
| 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 | |
| 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'] | |
| def dataset_count(): | |
| """Check how many training samples have been collected.""" | |
| count = _get_dataset_count() | |
| return jsonify({'ok': True, 'count': count}) | |
| 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) | |