import gradio as gr import numpy as np from PIL import Image import cv2 import re from paddleocr import PaddleOCR from datetime import datetime # Load OCR model ocr = PaddleOCR(use_angle_cls=True, lang='en') 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) def extract_weight_text(image): try: results = ocr.ocr(np.array(image), cls=True) texts = [] for line in results[0]: text = line[1][0] texts.append(text) match = re.search(r"\d+\.\d+", text) if match: return match.group(), texts return None, texts except Exception as e: return f"Error: {str(e)}", [] def detect_weight(image): if image is None: return "No image uploaded.", "", None, "" pre_img = preprocess_image(image) weight, texts = extract_weight_text(pre_img) if weight and "Error" not in weight: return f"Detected Weight: {weight} kg", datetime.now().strftime("Captured At: %Y-%m-%d %H:%M:%S"), pre_img, "\n".join(texts) else: return "Weight Not Detected", "", pre_img, "\n".join(texts) 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"), gr.Textbox(label="Detected Text (Debug)") ], title="Auto Weight Logger (Debug Mode)", description="Upload a clear image of a digital scale. This version shows detected text for debugging." ).launch()