Sanjayraju30's picture
Update app.py
523b1ec verified
raw
history blame
1.58 kB
import gradio as gr
import numpy as np
from PIL import Image
import cv2
import re
from paddleocr import PaddleOCR
from datetime import datetime
# Initialize OCR model once
ocr = PaddleOCR(use_angle_cls=True, lang='en')
# Preprocessing: Convert to grayscale and threshold
def preprocess_image(image):
img = np.array(image.convert("RGB"))
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
return Image.fromarray(thresh)
# OCR detection + regex filtering
def extract_weight_text(image):
results = ocr.ocr(np.array(image), cls=True)
for line in results[0]:
text = line[1][0]
match = re.search(r"\d+\.\d+", text)
if match:
return match.group()
return None
# Main function
def detect_weight(image):
if image is None:
return "No image uploaded.", "", None
pre_img = preprocess_image(image)
weight = extract_weight_text(pre_img)
if weight:
return f"Detected Weight: {weight} kg", datetime.now().strftime("Captured At: %Y-%m-%d %H:%M:%S"), pre_img
else:
return "Weight Not Detected", "", pre_img
# Gradio UI
interface = gr.Interface(
fn=detect_weight,
inputs=gr.Image(type="pil", label="Upload or Capture Image"),
outputs=[
gr.Textbox(label="Weight"),
gr.Textbox(label="Timestamp"),
gr.Image(label="Preprocessed Image")
],
title="Auto Weight Logger",
description="Upload or click image of digital scale. It will detect and show the weight (kg).",
)
interface.launch()