Sanjayraju30 commited on
Commit
a8e065f
Β·
verified Β·
1 Parent(s): 65ddb11

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -86
app.py CHANGED
@@ -1,92 +1,20 @@
1
  import gradio as gr
2
- from PIL import Image
3
- from datetime import datetime
4
- import pytz
5
  from ocr_engine import extract_weight
6
- from simple_salesforce import Salesforce
7
- import base64
8
- import os
9
-
10
- # Salesforce credentials
11
- SF_USERNAME = "[email protected]"
12
- SF_PASSWORD = "autoweight@32"
13
- SF_TOKEN = "UgiHKWT0aoZRX9gvTYDjAiRY"
14
-
15
- # Connect to Salesforce
16
- sf = Salesforce(username=SF_USERNAME, password=SF_PASSWORD, security_token=SF_TOKEN)
17
 
18
  def process_image(image):
19
- if image is None:
20
- return "❌ No image provided", "", None, gr.update(visible=True)
21
- try:
22
- # Extract weight using OCR (your updated function should handle any clear image)
23
- weight = extract_weight(image)
24
-
25
- ist = pytz.timezone('Asia/Kolkata')
26
- timestamp = datetime.now(ist).strftime("%Y-%m-%d %H:%M:%S IST")
27
-
28
- if not weight or "No valid" in weight:
29
- return "❌ Unable to detect. Try again with a clearer image.", "", image, gr.update(visible=True)
30
-
31
- # Save image temporarily
32
- image_path = "snapshot.jpg"
33
- image.save(image_path)
34
-
35
- # Create Weight_Log__c record
36
- record = sf.Weight_Log__c.create({
37
- "Captured_Weight__c": float(weight.replace("kg", "").strip()),
38
- "Captured_At__c": datetime.now(ist).isoformat(),
39
- "Device_ID__c": "DEVICE-001",
40
- "Status__c": "Confirmed"
41
- })
42
-
43
- # Upload image as ContentVersion
44
- with open(image_path, "rb") as f:
45
- encoded_image = base64.b64encode(f.read()).decode("utf-8")
46
-
47
- content = sf.ContentVersion.create({
48
- "Title": f"Snapshot_{timestamp}",
49
- "PathOnClient": "snapshot.jpg",
50
- "VersionData": encoded_image
51
- })
52
-
53
- content_id = sf.query(
54
- f"SELECT ContentDocumentId FROM ContentVersion WHERE Id = '{content['id']}'"
55
- )['records'][0]['ContentDocumentId']
56
-
57
- sf.ContentDocumentLink.create({
58
- "ContentDocumentId": content_id,
59
- "LinkedEntityId": record['id'],
60
- "ShareType": "V",
61
- "Visibility": "AllUsers"
62
- })
63
-
64
- return weight, timestamp, image, gr.update(visible=False)
65
- except Exception as e:
66
- return f"Error: {str(e)}", "", None, gr.update(visible=True)
67
-
68
- # Updated header: Removed "and logs it into Salesforce"
69
- with gr.Blocks(css=".gr-button {background-color: #2e7d32 !important; color: white !important;}") as demo:
70
- gr.Markdown("""
71
- <h1 style='text-align: center; color: #2e7d32;'>πŸ“· Auto Weight Logger</h1>
72
- <p style='text-align: center;'>Upload or capture a digital weight image. Detects weight using AI OCR.</p>
73
- <hr style='border: 1px solid #ddd;'/>
74
- """)
75
-
76
- with gr.Row():
77
- image_input = gr.Image(type="pil", label="πŸ“ Upload or Capture Image")
78
-
79
- detect_btn = gr.Button("πŸš€ Detect Weight")
80
-
81
- with gr.Row():
82
- weight_out = gr.Textbox(label="πŸ“¦ Detected Weight", placeholder="e.g., 97.9 kg", show_copy_button=True)
83
- time_out = gr.Textbox(label="πŸ•’ Captured At (IST)", placeholder="e.g., 2025-07-01 12:00:00")
84
-
85
- snapshot = gr.Image(label="πŸ“Έ Snapshot Preview")
86
- retake_btn = gr.Button("πŸ” Retake / Try Again", visible=False)
87
-
88
- detect_btn.click(fn=process_image, inputs=image_input, outputs=[weight_out, time_out, snapshot, retake_btn])
89
- retake_btn.click(fn=lambda: ("", "", None, gr.update(visible=False)),
90
- inputs=[], outputs=[weight_out, time_out, snapshot, retake_btn])
91
 
92
  demo.launch()
 
1
  import gradio as gr
 
 
 
2
  from ocr_engine import extract_weight
3
+ from PIL import Image
4
+ import tempfile
 
 
 
 
 
 
 
 
 
5
 
6
  def process_image(image):
7
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as f:
8
+ image.save(f.name)
9
+ result = extract_weight(f.name)
10
+ return result
11
+
12
+ demo = gr.Interface(
13
+ fn=process_image,
14
+ inputs=gr.Image(type="pil"),
15
+ outputs="text",
16
+ title="Auto Weight Detector",
17
+ description="Upload an image of a digital balance showing weight in g or kg (e.g. 52.25 g, 75.8 kg)"
18
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  demo.launch()