Spaces:
Running
Running
import gradio as gr | |
from PIL import Image, ImageEnhance, ImageOps | |
import numpy as np | |
import easyocr | |
import re | |
from datetime import datetime | |
import pytz | |
# Load EasyOCR model (no Tesseract needed) | |
reader = easyocr.Reader(['en'], gpu=False) | |
# Enhance image before OCR | |
def enhance_image(image): | |
image = image.convert("L") # Grayscale | |
image = ImageOps.invert(image) # Invert black ↔ white | |
image = ImageEnhance.Contrast(image).enhance(2.0) | |
image = ImageEnhance.Sharpness(image).enhance(2.5) | |
image = image.resize((image.width * 2, image.height * 2)) # Enlarge | |
return image | |
# Main function to extract weight | |
def detect_weight(image): | |
try: | |
# Enhance | |
processed_image = enhance_image(image) | |
# Convert to array | |
np_image = np.array(processed_image) | |
# OCR | |
result = reader.readtext(np_image, detail=0) | |
text = " ".join(result) | |
# Extract decimal weight like 52.75 | |
match = re.search(r"\d{1,4}\.\d{1,4}", text) | |
weight = match.group(0) if match else "Not detected" | |
# IST Time | |
ist = pytz.timezone("Asia/Kolkata") | |
timestamp = datetime.now(ist).strftime("%Y-%m-%d %H:%M:%S") | |
return f"Weight: {weight} kg\nCaptured At: {timestamp} (IST)", image | |
except Exception as e: | |
return f"Error: {str(e)}", image | |
# Gradio Interface | |
interface = gr.Interface( | |
fn=detect_weight, | |
inputs=gr.Image(type="pil", label="Upload or Capture Image"), | |
outputs=[ | |
gr.Textbox(label="Weight Info"), | |
gr.Image(label="Snapshot") | |
], | |
title="⚖️ Auto Weight Detector (Decimal Accurate)", | |
description="Detects exact weight including decimals (e.g., 52.75 kg) using EasyOCR. Shows IST time." | |
) | |
interface.launch() | |