vikaspal321/ocr-irctc
0
1import re2import base643import io4import time5from flask import Flask, request, jsonify6from flask_cors import CORS7from PIL import Image, ImageEnhance, ImageFilter, ImageOps8 9try:10 import pytesseract11 import os12 if os.name == 'nt':13 tess_path = r'C:\Program Files\Tesseract-OCR\tesseract.exe'14 if os.path.exists(tess_path):15 pytesseract.pytesseract.tesseract_cmd = tess_path16 else:17 print(f"!!! WARNING: Tesseract not found at {tess_path}")18except ImportError:19 print("Warning: pytesseract not installed.")20 21app = Flask(__name__)22CORS(app)23 24# The Speed Config: PSM 7 (single line) + Strict Alphanumeric Whitelist25TESSERACT_CONFIG = '--psm 7 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'26 27@app.route('/', methods=['GET'])28def home():29 return jsonify({"status": "online"}), 20030 31@app.route('/solve', methods=['POST'])32def solve_captcha():33 data = request.json34 if not data or 'image' not in data:35 return jsonify({"error": "No base64 image provided"}), 40036 37 base64_img = data['image']38 39 # Strip the data metadata40 if "," in base64_img:41 base64_img = base64_img.split(",")[1]42 43 # Padding fix in case the frontend strips trailing '=' characters44 base64_img += "=" * ((4 - len(base64_img) % 4) % 4)45 46 try:47 # Decode and load48 img_data = base64.b64decode(base64_img)49 image = Image.open(io.BytesIO(img_data)).convert('L')50 51 # 1. Scale it up FIRST to make the letters thicker and easier to preserve52 image = image.resize((image.width * 2, image.height * 2), Image.LANCZOS)53 54 # 2. Strict Binarization (Force pure Black/White). 55 image = image.point(lambda p: 255 if p > 100 else 0)56 57 # 3. Clean the noise (The MedianFilter will now eat the jagged edges and leftover dots)58 image = image.filter(ImageFilter.MedianFilter(size=3))59 60 # 4. Invert (Pure white text on pure black bg -> Pure black text on pure white bg)61 image = ImageOps.invert(image)62 63 # 5. Add breathing room (Tesseract needs white borders to understand where the word starts/ends)64 image = ImageOps.expand(image, border=20, fill='white')65 66 # --- THE MAGIC DEBUG LINE ---67 # This saves the exact image Tesseract is reading so you can view it in the Hugging Face Files tab68 image.save("debug_tesseract_view.png")69 70 try:71 # Execute OCR 72 text = pytesseract.image_to_string(image, config=TESSERACT_CONFIG).strip()73 text = re.sub(r'[^A-Za-z0-9]', '', text)74 75 # Catch empty reads76 if not text:77 text = "UNKNOWN"78 79 except NameError:80 text = "DUMMY123"81 82 app.logger.info(f"Solved Captcha: {text}")83 return jsonify({"solved_text": text}), 20084 85 except Exception as e:86 app.logger.error(f"Error decoding image: {e}")87 return jsonify({"error": str(e)}), 50088 89if __name__ == '__main__':90 app.run(port=5000, debug=True)