File size: 4,672 Bytes
0590b95
f4861ec
 
 
0590b95
f4861ec
 
0590b95
f4861ec
 
0590b95
136c114
 
f4861ec
 
0590b95
f4861ec
 
 
 
 
 
 
136c114
 
 
 
 
 
f4861ec
 
 
 
 
 
 
136c114
0590b95
f4861ec
 
136c114
f4861ec
136c114
f4861ec
136c114
 
 
 
 
 
0590b95
 
136c114
 
 
 
 
 
f4861ec
 
 
0590b95
136c114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0590b95
136c114
0590b95
136c114
 
0590b95
 
 
 
f4861ec
 
 
136c114
 
f4861ec
 
 
136c114
f4861ec
136c114
 
f4861ec
 
 
 
136c114
 
f4861ec
 
136c114
f4861ec
0590b95
f4861ec
136c114
 
 
 
 
 
 
 
 
f4861ec
 
 
136c114
 
 
f4861ec
 
 
 
136c114
 
f4861ec
 
136c114
 
 
 
 
f4861ec
 
 
 
 
 
 
 
0590b95
 
f4861ec
 
 
 
136c114
 
 
 
 
 
0590b95
 
f4861ec
0590b95
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import gradio as gr
from weight_detector import WeightDetector
import tempfile
import os
from PIL import Image
import requests
from io import BytesIO

# Initialize detector
detector = WeightDetector()

def process_input(image_source: str, image_upload=None, image_url: str = "") -> dict:
    """Process image and return results with IST"""
    temp_img_path = None
    
    try:
        # Handle different input types
        if image_source == "upload" and image_upload is not None:
            img = image_upload
        elif image_source == "url" and image_url:
            response = requests.get(image_url)
            img = Image.open(BytesIO(response.content))
        else:
            return {
                "weight": None,
                "message": "No valid image provided",
                "image": None,
                "time": detector.get_current_ist()
            }
            
        # Save to temp file for processing
        with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f:
            temp_img_path = f.name
            img.save(f.name)
            
        # Detect weight
        weight, time, annotated_img = detector.detect_weight(temp_img_path)
        
        # Format result message
        if weight is not None:
            message = f"✅ Detected weight: {weight:.2f}g at {time}"
        else:
            message = f"❌ No weight value detected at {time}"
            
        return {
            "weight": weight,
            "message": message,
            "image": annotated_img,
            "time": time
        }
        
    except Exception as e:
        return {
            "weight": None,
            "message": f"Error: {str(e)}",
            "image": None,
            "time": detector.get_current_ist()
        }
    finally:
        if temp_img_path and os.path.exists(temp_img_path):
            os.unlink(temp_img_path)

# Custom CSS for better mobile display
css = """
#mobile-view {
    display: none;
}
@media screen and (max-width: 768px) {
    #desktop-view {
        display: none;
    }
    #mobile-view {
        display: block;
    }
}
"""

# Gradio interface
with gr.Blocks(title="Auto Weight Logger", css=css) as demo:
    gr.Markdown("""
    # 🏋️ Auto Weight Logger
    Capture or upload an image of a digital scale to automatically detect the weight value.
    """)
    
    with gr.Row():
        with gr.Column():
            image_source = gr.Radio(
                ["upload", "url"],
                label="Image Source",
                value="upload",
                elem_id="source-select"
            )
            
            image_upload = gr.Image(
                sources=["upload", "webcam"],
                type="pil",
                label="Upload Image or Use Webcam",
                elem_id="image-upload"
            )
            
            image_url = gr.Textbox(
                label="Image URL",
                visible=False,
                elem_id="image-url"
            )
            
            submit_btn = gr.Button("Detect Weight", variant="primary")
            
        with gr.Column():
            weight_value = gr.Number(
                label="Detected Weight (grams)",
                interactive=False,
                elem_id="weight-value"
            )
            
            detection_time = gr.Textbox(
                label="Detection Time (IST)",
                interactive=False,
                elem_id="detection-time"
            )
            
            result_message = gr.Textbox(
                label="Result",
                interactive=False,
                elem_id="result-message"
            )
            
            annotated_image = gr.Image(
                label="Annotated Image",
                interactive=False,
                elem_id="annotated-image"
            )
    
    # Mobile view toggle
    with gr.Column(visible=False, elem_id="mobile-view"):
        gr.Markdown("### Mobile Instructions")
        gr.Markdown("1. Tap 'Webcam' to capture\n2. Tap 'Detect Weight'")
    
    # Show/hide URL input based on selection
    def toggle_url_visibility(source):
        return gr.Textbox(visible=source == "url")
    
    image_source.change(
        toggle_url_visibility,
        inputs=image_source,
        outputs=image_url
    )
    
    # Process submission
    submit_btn.click(
        process_input,
        inputs=[image_source, image_upload, image_url],
        outputs={
            "weight": weight_value,
            "message": result_message,
            "image": annotated_image,
            "time": detection_time
        }
    )

# For Hugging Face Spaces
demo.launch()