import gradio as gr import cv2 import numpy as np import tensorflow as tf import os # ───────────────────────────────────────────────────────────────────────────── # 1. LOAD MODEL # ───────────────────────────────────────────────────────────────────────────── MODEL = None def load_model(): global MODEL paths = [ "best_cnn_model/best_cnn_model(1).keras", "best_cnn_model/best_cnn_model.keras", ] for path in paths: if os.path.exists(path): MODEL = tf.keras.models.load_model(path) print(f"✅ Model loaded: {path}") return print("❌ Model not found!") load_model() # ───────────────────────────────────────────────────────────────────────────── # 2. DETECTION LOGIC # ───────────────────────────────────────────────────────────────────────────── def detect(frame): if MODEL is None or frame is None: return frame # Gradio sends RGB, OpenCV needs BGR img = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if np.mean(gray) > 127: gray = cv2.bitwise_not(gray) small = cv2.resize(gray, (224, 224)) _, thresh = cv2.threshold(small, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if contours: cnt = max(contours, key=cv2.contourArea) x, y, w, h = cv2.boundingRect(cnt) if w > 20 and h > 20: scale_x = img.shape[1] / 224 scale_y = img.shape[0] / 224 # Draw Box start_pt = (int(x * scale_x), int(y * scale_y)) end_pt = (int((x + w) * scale_x), int((y + h) * scale_y)) cv2.rectangle(img, start_pt, end_pt, (0, 255, 0), 3) # Predict pad = 20 y1, y2 = max(0, y - pad), min(224, y + h + pad) x1, x2 = max(0, x - pad), min(224, x + w + pad) crop = small[y1:y2, x1:x2] digit_img = cv2.resize(crop, (28, 28)) tensor = (digit_img / 255.0).reshape(1, 28, 28, 1).astype(np.float32) preds = MODEL.predict(tensor, verbose=0)[0] digit = int(np.argmax(preds)) conf = float(np.max(preds)) * 100 # Draw Label label = f"{digit} ({conf:.0f}%)" cv2.putText(img, label, (start_pt[0], start_pt[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # ───────────────────────────────────────────────────────────────────────────── # 3. UI (Gradio 6 Native Streaming) # ───────────────────────────────────────────────────────────────────────────── with gr.Blocks(title="Digit Detector") as demo: gr.Markdown("# 📱 Real-Time Digit Detection") gr.Markdown("Point your camera at a number.") # Native streaming component (Replaces gr.WebRTC) video = gr.Image( sources=["webcam"], streaming=True, type="numpy", label="Live Feed" ) video.stream( fn=detect, inputs=[video], outputs=[video], time_limit=60 ) if __name__ == "__main__": demo.launch()