import cv2 import numpy as np import gradio as gr import requests import re from paddleocr import PaddleOCR # Initialize PaddleOCR with angle classification enabled ocr = PaddleOCR(use_angle_cls=True, lang='en') # Use 'en|hi' or 'en|ta' if regional scripts are needed def extract_plate_text_all(raw_texts): combined_text = ' '.join(raw_texts).upper() cleaned = re.sub(r'[^A-Z0-9 ]', '', combined_text) # Keep spaces pattern = r'[A-Z]{2}\s*\d{1,2}\s*[A-Z]{0,3}\s*\d{3,4}' match = re.search(pattern, cleaned.replace(' ', '')) if match: return match.group(0) else: return "No valid license plate detected" def detect_plate(image): if image is None: return "No image uploaded", None img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = ocr.predict(img_rgb) # Remove `cls=True` here if not results or not isinstance(results[0], list) or len(results[0]) == 0: return "License plate not detected", image # Extract all detected texts texts = [line[1][0] for line in results[0]] plate_number = extract_plate_text_all(texts) if len(plate_number) < 6: # Some threshold to check validity return "License plate not detected or low confidence", image # Find box corresponding to plate number (optional: draw box around all detected boxes) for line in results[0]: if isinstance(line[0], list) and all(isinstance(coord, (int, float)) for coord in line[0]): box = np.array(line[0]).astype(int) # Convert the coordinates to integers cv2.polylines(image, [box], isClosed=True, color=(0, 255, 0), thickness=2) else: continue # Put plate number text cv2.putText(image, plate_number, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) # Send to backend url = "https://abyssinian-heartbreaking-tuck.glitch.me/adds" try: response = requests.post(url, data={'lno': plate_number}) if response.status_code == 200: print("POST request successful") else: print(f"Request failed with status code {response.status_code}") except Exception as e: print(f"POST request failed: {e}") return f"Number plate number is: {plate_number}", image # Gradio Interface demo = gr.Interface( fn=detect_plate, inputs=gr.Image(type="numpy"), outputs=["text", "image"], title="License Plate Detector (PaddleOCR + Indian Format)" ) if __name__ == "__main__": demo.launch()