Sanjayraju30 commited on
Commit
f4861ec
·
verified ·
1 Parent(s): 41226bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -51
app.py CHANGED
@@ -1,74 +1,116 @@
1
  import gradio as gr
2
- import cv2
3
- import numpy as np
 
4
  from PIL import Image
5
- import logging
6
- from ocr_engine import extract_weight_from_image
7
- from datetime import datetime
8
- import pytz
9
- import sys
10
 
11
- # Set up logging
12
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[logging.StreamHandler(sys.stdout)])
13
 
14
- def process_image(img):
 
 
 
 
 
 
 
15
  try:
16
- # Convert Gradio image (PIL) to process
17
- if img is None:
18
- return "No image provided", "", None
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- # Resize if > 5MB
21
- img_bytes = img.tobytes()
22
- size_mb = len(img_bytes) / (1024 * 1024)
23
- if size_mb > 5:
24
- scale = 0.9
25
- while size_mb > 5:
26
- w, h = img.size
27
- img = img.resize((int(w * scale), int(h * scale)), Image.Resampling.LANCZOS)
28
- img_bytes = img.tobytes()
29
- size_mb = len(img_bytes) / (1024 * 1024)
30
- scale *= 0.9
31
- logging.info(f"Resized image to {size_mb:.2f} MB")
32
-
33
- # Extract weight
34
- weight, confidence, unit = extract_weight_from_image(img)
35
 
36
- # Return results with improved feedback
37
- result = f"{weight} {unit} (Confidence: {confidence:.2f}%)" if confidence > 0 else "No weight detected"
38
- timestamp = f"Processed at {datetime.now(pytz.timezone('Asia/Kolkata')).strftime('%d-%m-%Y %I:%M:%S %p IST')}"
39
- return result, timestamp, img
40
  except Exception as e:
41
- logging.error(f"Error in process_image: {str(e)}")
42
- return f"Error: {str(e)}", "", None
 
 
43
 
44
  # Gradio interface
45
  with gr.Blocks(title="Auto Weight Logger") as demo:
46
  gr.Markdown("""
47
- # 📷 Auto Weight Logger — OCR-Based Smart Scale Reader
48
- This app detects weight from uploaded or captured images of digital balance displays. Optimized for 7-segment displays and various formats, it extracts numeric weights with high accuracy.
49
  """)
50
 
51
  with gr.Row():
52
  with gr.Column():
53
- image_input = gr.Image(source="upload", tool="select", type="pil", label="Upload Weight Display Image")
54
- webcam_input = gr.Image(source="webcam", type="pil", label="Or Capture with Webcam")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  submit_btn = gr.Button("Detect Weight")
56
-
57
  with gr.Column():
58
- output_text = gr.Textbox(label="Detected Weight", interactive=False)
59
- timestamp_text = gr.Textbox(label="Processed At", interactive=False)
60
- output_image = gr.Image(label="Processed Image")
61
-
62
- submit_btn.click(
63
- fn=process_image,
64
- inputs=[image_input],
65
- outputs=[output_text, timestamp_text, output_image]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  )
67
 
68
- webcam_input.change(
69
- fn=process_image,
70
- inputs=[webcam_input],
71
- outputs=[output_text, timestamp_text, output_image]
 
72
  )
73
 
 
74
  demo.launch()
 
1
  import gradio as gr
2
+ from weight_detector import WeightDetector
3
+ import tempfile
4
+ import os
5
  from PIL import Image
6
+ import requests
7
+ from io import BytesIO
 
 
 
8
 
9
+ # Initialize detector
10
+ detector = WeightDetector()
11
 
12
+ def process_input(image_source: str, image_upload=None, image_url: str = "") -> tuple:
13
+ """
14
+ Process image from different sources (upload, webcam, or URL)
15
+ Returns:
16
+ tuple: (detected_weight, detection_metadata, annotated_image)
17
+ """
18
+ temp_img_path = None
19
+
20
  try:
21
+ # Handle different input types
22
+ if image_source == "upload" and image_upload is not None:
23
+ img = image_upload
24
+ elif image_source == "url" and image_url:
25
+ response = requests.get(image_url)
26
+ img = Image.open(BytesIO(response.content))
27
+ else:
28
+ return None, "No valid image provided", None
29
+
30
+ # Save to temp file for processing
31
+ with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f:
32
+ temp_img_path = f.name
33
+ img.save(f.name)
34
+
35
+ # Detect weight
36
+ weight, metadata, annotated_img = detector.detect_weight(temp_img_path)
37
 
38
+ # Format result message
39
+ if weight is not None:
40
+ message = f"✅ Detected weight: {weight}g"
41
+ if len(metadata) > 1:
42
+ message += f" (from {len(metadata)} possible values)"
43
+ else:
44
+ message = "❌ No weight value detected"
45
+
46
+ return weight, message, annotated_img
 
 
 
 
 
 
47
 
 
 
 
 
48
  except Exception as e:
49
+ return None, f"Error: {str(e)}", None
50
+ finally:
51
+ if temp_img_path and os.path.exists(temp_img_path):
52
+ os.unlink(temp_img_path)
53
 
54
  # Gradio interface
55
  with gr.Blocks(title="Auto Weight Logger") as demo:
56
  gr.Markdown("""
57
+ # Auto Weight Logger
58
+ Capture or upload an image of a weight measurement to automatically detect and log the value.
59
  """)
60
 
61
  with gr.Row():
62
  with gr.Column():
63
+ image_source = gr.Radio(
64
+ ["upload", "url"],
65
+ label="Image Source",
66
+ value="upload"
67
+ )
68
+
69
+ image_upload = gr.Image(
70
+ sources=["upload"],
71
+ type="pil",
72
+ label="Upload Image"
73
+ )
74
+
75
+ image_url = gr.Textbox(
76
+ label="Image URL",
77
+ visible=False
78
+ )
79
+
80
  submit_btn = gr.Button("Detect Weight")
81
+
82
  with gr.Column():
83
+ weight_value = gr.Number(
84
+ label="Detected Weight (g)",
85
+ interactive=False
86
+ )
87
+
88
+ result_message = gr.Textbox(
89
+ label="Detection Result",
90
+ interactive=False
91
+ )
92
+
93
+ annotated_image = gr.Image(
94
+ label="Annotated Image",
95
+ interactive=False
96
+ )
97
+
98
+ # Show/hide URL input based on selection
99
+ def toggle_url_visibility(source):
100
+ return gr.Textbox(visible=source == "url")
101
+
102
+ image_source.change(
103
+ toggle_url_visibility,
104
+ inputs=image_source,
105
+ outputs=image_url
106
  )
107
 
108
+ # Process submission
109
+ submit_btn.click(
110
+ process_input,
111
+ inputs=[image_source, image_upload, image_url],
112
+ outputs=[weight_value, result_message, annotated_image]
113
  )
114
 
115
+ # For Hugging Face Spaces
116
  demo.launch()