File size: 1,799 Bytes
a481416
4e7dfd4
 
7f861bc
a481416
7f861bc
 
a481416
9b5d129
 
a481416
eff70bd
4e7dfd4
 
 
9b5d129
 
4e7dfd4
 
9b5d129
7f861bc
9b5d129
 
7f861bc
 
9b5d129
4e7dfd4
7f861bc
 
4e7dfd4
9b5d129
7f861bc
 
9b5d129
7f861bc
 
 
 
4e7dfd4
7f861bc
4e7dfd4
9b5d129
4e7dfd4
 
 
9b5d129
4e7dfd4
eff70bd
4e7dfd4
 
 
 
 
 
 
9b5d129
4e7dfd4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import gradio as gr
import cv2
import numpy as np
from paddleocr import PaddleOCR
from datetime import datetime
import re
from PIL import Image

# Initialize PaddleOCR (only once)
ocr = PaddleOCR(use_angle_cls=True, lang='en')  # Use English OCR model

def detect_weight(image):
    if image is None:
        return "No image uploaded", "N/A", None

    # Convert PIL Image to OpenCV format (NumPy array)
    image = image.convert("RGB")
    image_np = np.array(image)

    # Preprocess: Grayscale + contrast enhancement (optional)
    gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
    gray_eq = cv2.equalizeHist(gray)
    processed_image = cv2.cvtColor(gray_eq, cv2.COLOR_GRAY2RGB)  # convert back to RGB for PaddleOCR

    # Run OCR
    result = ocr.ocr(processed_image, cls=True)

    best_match = None
    best_conf = 0

    # Search for a decimal number like 25.52
    for line in result:
        for box in line:
            text, conf = box[1]
            match = re.search(r"\d+\.\d+", text)
            if match and conf > best_conf:
                best_match = match.group()
                best_conf = conf

    if best_match:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        return f"Weight: {best_match} kg (Confidence: {round(best_conf * 100, 2)}%)", now, image
    else:
        return "No weight detected kg (Confidence: 0.0%)", "N/A", image

# Gradio UI
gr.Interface(
    fn=detect_weight,
    inputs=gr.Image(type="pil", label="Upload or Capture Weight Image"),
    outputs=[
        gr.Text(label="Detected Weight"),
        gr.Text(label="Captured At (IST)"),
        gr.Image(label="Snapshot")
    ],
    title="Auto Weight Logger",
    description="Upload or capture a digital scale image. This app detects the weight automatically using AI."
).launch()