Sanjayraju30 commited on
Commit
136e7c4
·
verified ·
1 Parent(s): 5b0b2ae

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -82
app.py CHANGED
@@ -2,141 +2,104 @@ 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 = "") -> dict:
13
- """Process image and return results with IST"""
14
  temp_img_path = None
15
-
16
  try:
17
- # Handle different input types
18
- if image_source == "upload" and image_upload is not None:
 
 
19
  img = image_upload
20
  elif image_source == "url" and image_url:
 
 
21
  response = requests.get(image_url)
22
  img = Image.open(BytesIO(response.content))
23
  else:
24
  return {
25
  "weight": None,
26
- "message": "No valid image provided",
27
  "image": None,
28
  "time": detector.get_current_ist()
29
  }
30
-
31
- # Save to temp file for processing
32
  with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f:
33
  temp_img_path = f.name
34
  img.save(f.name)
35
-
36
- # Detect weight
37
- weight, time, annotated_img = detector.detect_weight(temp_img_path)
38
-
39
- # Format result message
40
- if weight is not None:
41
- message = f"✅ Detected weight: {weight:.2f}g at {time}"
42
- else:
43
- message = f"❌ No weight value detected at {time}"
44
-
45
- return {
46
- "weight": weight,
47
- "message": message,
48
- "image": annotated_img,
49
- "time": time
50
- }
51
 
 
 
 
52
  except Exception as e:
53
  return {
54
  "weight": None,
55
- "message": f"Error: {str(e)}",
56
  "image": None,
57
  "time": detector.get_current_ist()
58
  }
59
  finally:
60
  if temp_img_path and os.path.exists(temp_img_path):
61
- os.unlink(temp_img_path)
62
-
63
- # Custom CSS for better mobile display
64
- css = """
65
- #mobile-view {
66
- display: none;
67
- }
68
- @media screen and (max-width: 768px) {
69
- #desktop-view {
70
- display: none;
71
- }
72
- #mobile-view {
73
- display: block;
74
- }
75
- }
76
- """
77
 
78
- # Gradio interface
79
- with gr.Blocks(title="Auto Weight Logger", css=css) as demo:
80
  gr.Markdown("""
81
- # 🏋️ Auto Weight Logger
82
- Capture or upload an image of a digital scale to automatically detect the weight value.
 
 
 
83
  """)
84
 
85
  with gr.Row():
86
  with gr.Column():
87
  image_source = gr.Radio(
88
- ["upload", "url"],
89
- label="Image Source",
90
- value="upload",
91
- elem_id="source-select"
92
  )
93
 
94
  image_upload = gr.Image(
95
- sources=["upload", "webcam"],
96
  type="pil",
97
- label="Upload Image or Use Webcam",
98
- elem_id="image-upload"
99
  )
100
 
101
  image_url = gr.Textbox(
102
- label="Image URL",
103
- visible=False,
104
- elem_id="image-url"
105
  )
106
 
107
  submit_btn = gr.Button("Detect Weight", variant="primary")
108
-
109
  with gr.Column():
110
  weight_value = gr.Number(
111
- label="Detected Weight (grams)",
112
- interactive=False,
113
- elem_id="weight-value"
114
  )
115
 
116
  detection_time = gr.Textbox(
117
  label="Detection Time (IST)",
118
- interactive=False,
119
- elem_id="detection-time"
120
  )
121
 
122
  result_message = gr.Textbox(
123
  label="Result",
124
- interactive=False,
125
- elem_id="result-message"
126
  )
127
 
128
  annotated_image = gr.Image(
129
  label="Annotated Image",
130
- interactive=False,
131
- elem_id="annotated-image"
132
  )
133
 
134
- # Mobile view toggle
135
- with gr.Column(visible=False, elem_id="mobile-view"):
136
- gr.Markdown("### Mobile Instructions")
137
- gr.Markdown("1. Tap 'Webcam' to capture\n2. Tap 'Detect Weight'")
138
-
139
- # Show/hide URL input based on selection
140
  def toggle_url_visibility(source):
141
  return gr.Textbox(visible=source == "url")
142
 
@@ -146,17 +109,11 @@ with gr.Blocks(title="Auto Weight Logger", css=css) as demo:
146
  outputs=image_url
147
  )
148
 
149
- # Process submission
150
  submit_btn.click(
151
  process_input,
152
  inputs=[image_source, image_upload, image_url],
153
- outputs={
154
- "weight": weight_value,
155
- "message": result_message,
156
- "image": annotated_image,
157
- "time": detection_time
158
- }
159
  )
160
 
161
- # For Hugging Face Spaces
162
  demo.launch()
 
2
  from weight_detector import WeightDetector
3
  import tempfile
4
  import os
 
 
 
5
 
 
6
  detector = WeightDetector()
7
 
8
  def process_input(image_source: str, image_upload=None, image_url: str = "") -> dict:
9
+ """Process webcam/image and return weight + IST time"""
10
  temp_img_path = None
 
11
  try:
12
+ # Handle webcam/image upload
13
+ if image_source == "webcam" and image_upload is not None:
14
+ img = image_upload
15
+ elif image_source == "upload" and image_upload is not None:
16
  img = image_upload
17
  elif image_source == "url" and image_url:
18
+ import requests
19
+ from io import BytesIO
20
  response = requests.get(image_url)
21
  img = Image.open(BytesIO(response.content))
22
  else:
23
  return {
24
  "weight": None,
25
+ "message": "⚠️ No image provided!",
26
  "image": None,
27
  "time": detector.get_current_ist()
28
  }
29
+
30
+ # Save to temp file
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
+ return detector.detect_weight(temp_img_path)
37
+
38
  except Exception as e:
39
  return {
40
  "weight": None,
41
+ "message": f"⚠️ Error: {str(e)}",
42
  "image": None,
43
  "time": detector.get_current_ist()
44
  }
45
  finally:
46
  if temp_img_path and os.path.exists(temp_img_path):
47
+ os.remove(temp_img_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ # Gradio UI
50
+ with gr.Blocks(title="Auto Weight Logger") as demo:
51
  gr.Markdown("""
52
+ # **⚖️ Auto Weight Logger (7-Segment OCR)**
53
+ **Capture weight from digital balances using a webcam or image upload.**
54
+ - ✅ Optimized for **7-segment displays** (e.g., lab balances)
55
+ - 📅 Logs **IST time** automatically
56
+ - 🚫 Detects **blurry/glare** images
57
  """)
58
 
59
  with gr.Row():
60
  with gr.Column():
61
  image_source = gr.Radio(
62
+ ["webcam", "upload", "url"],
63
+ label="Input Source",
64
+ value="webcam"
 
65
  )
66
 
67
  image_upload = gr.Image(
68
+ sources=["webcam", "upload"],
69
  type="pil",
70
+ label="Capture/Upload Image",
71
+ interactive=True
72
  )
73
 
74
  image_url = gr.Textbox(
75
+ label="Image URL (if selected)",
76
+ visible=False
 
77
  )
78
 
79
  submit_btn = gr.Button("Detect Weight", variant="primary")
80
+
81
  with gr.Column():
82
  weight_value = gr.Number(
83
+ label="Detected Weight (g)",
84
+ interactive=False
 
85
  )
86
 
87
  detection_time = gr.Textbox(
88
  label="Detection Time (IST)",
89
+ interactive=False
 
90
  )
91
 
92
  result_message = gr.Textbox(
93
  label="Result",
94
+ interactive=False
 
95
  )
96
 
97
  annotated_image = gr.Image(
98
  label="Annotated Image",
99
+ interactive=False
 
100
  )
101
 
102
+ # Show/hide URL input
 
 
 
 
 
103
  def toggle_url_visibility(source):
104
  return gr.Textbox(visible=source == "url")
105
 
 
109
  outputs=image_url
110
  )
111
 
112
+ # Process input
113
  submit_btn.click(
114
  process_input,
115
  inputs=[image_source, image_upload, image_url],
116
+ outputs=[weight_value, detection_time, result_message, annotated_image]
 
 
 
 
 
117
  )
118
 
 
119
  demo.launch()