Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import easyocr | |
| import cv2 | |
| import numpy as np | |
| from PIL import Image | |
| import requests | |
| from io import BytesIO | |
| import json | |
| # Initialize EasyOCR once | |
| reader = easyocr.Reader(['en']) | |
| def detect_digits(image_url): | |
| try: | |
| # Download the image | |
| response = requests.get(image_url) | |
| response.raise_for_status() | |
| # Convert to OpenCV format | |
| image = Image.open(BytesIO(response.content)).convert('RGB') | |
| img_np = np.array(image) | |
| img_cv = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR) | |
| # Perform text detection | |
| results = reader.readtext(img_cv) | |
| # Process results | |
| output = [] | |
| for bbox, text, conf in results: | |
| if any(c.isdigit() for c in text): | |
| # Extract coordinates | |
| tl = tuple(map(int, bbox[0])) | |
| br = tuple(map(int, bbox[2])) | |
| output.append({ | |
| "text": text, | |
| "confidence": float(conf), | |
| "coordinates": { | |
| "x_min": tl[0], | |
| "y_min": tl[1], | |
| "x_max": br[0], | |
| "y_max": br[1] | |
| } | |
| }) | |
| return json.dumps(output, indent=2, ensure_ascii=False) | |
| except Exception as e: | |
| return json.dumps({"error": str(e)}) | |
| # Create Gradio interface | |
| interface = gr.Interface( | |
| fn=detect_digits, | |
| inputs=gr.Textbox( | |
| label="Image URL", | |
| placeholder="Enter image URL here..." | |
| ), | |
| outputs=gr.JSON(label="Detection Results"), | |
| title="Digit Region Detection", | |
| description="Upload an image URL to detect regions containing numbers", | |
| allow_flagging="never" | |
| ) | |
| interface.launch() |