File size: 3,660 Bytes
a3a81c9
f76d417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d55b56b
d5ceb6c
 
 
 
f50878a
d5ceb6c
 
 
 
325b9a0
 
d5ceb6c
a3a81c9
f50878a
325b9a0
f50878a
 
 
 
d5ceb6c
 
 
 
f50878a
10cd160
d5ceb6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f76d417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py
import gradio as gr
from PIL import Image
from datetime import datetime
import pytz
from ocr_engine import extract_weight
from simple_salesforce import Salesforce
import base64
import re
import os

# Salesforce credentials
SF_USERNAME = "[email protected]"
SF_PASSWORD = "autoweight@32"
SF_TOKEN = "UgiHKWT0aoZRX9gvTYDjAiRY"

# Connect to Salesforce
sf = Salesforce(username=SF_USERNAME, password=SF_PASSWORD, security_token=SF_TOKEN)

def process_image(image):
    if image is None:
        return "❌ No image provided", "", None, gr.update(visible=True)
    try:
        weight = extract_weight(image)
        print("🧠 Final OCR Result:", weight)

        ist = pytz.timezone('Asia/Kolkata')
        timestamp = datetime.now(ist).strftime("%Y-%m-%d %H:%M:%S IST")

        if not weight or weight.startswith("Error"):
            return f"❌ OCR Error: {weight}", "", image, gr.update(visible=True)

        numeric_match = re.search(r'\d{1,5}(\.\d{1,3})?', weight)
        if not numeric_match:
            return f"❌ Could not extract number | OCR: {weight}", "", image, gr.update(visible=True)

        numeric_value = float(numeric_match.group())
        unit = "kg" if "kg" in weight.lower() else "g"

        image_path = "snapshot.jpg"
        image.save(image_path)

        record = sf.Weight_Log__c.create({
            "Captured_Weight__c": numeric_value,
            "Captured_Unit__c": unit,
            "Captured_At__c": datetime.now(ist).isoformat(),
            "Device_ID__c": "DEVICE-001",
            "Status__c": "Confirmed"
        })

        with open(image_path, "rb") as f:
            encoded_image = base64.b64encode(f.read()).decode("utf-8")

        content = sf.ContentVersion.create({
            "Title": f"Snapshot_{timestamp}",
            "PathOnClient": "snapshot.jpg",
            "VersionData": encoded_image
        })

        content_id = sf.query(
            f"SELECT ContentDocumentId FROM ContentVersion WHERE Id = '{content['id']}'"
        )['records'][0]['ContentDocumentId']

        sf.ContentDocumentLink.create({
            "ContentDocumentId": content_id,
            "LinkedEntityId": record['id'],
            "ShareType": "V",
            "Visibility": "AllUsers"
        })

        return weight, timestamp, image, gr.update(visible=False)
    except Exception as e:
        return f"Error: {str(e)}", "", None, gr.update(visible=True)

with gr.Blocks(css=".gr-button {background-color: #2e7d32 !important; color: white !important;}") as demo:
    gr.Markdown("""
    <h1 style='text-align: center; color: #2e7d32;'>πŸ“· Auto Weight Logger</h1>
    <p style='text-align: center;'>Upload or capture a digital weight image. Detects weight using AI OCR and logs it into Salesforce.</p>
    <hr style='border: 1px solid #ddd;' />
    """)

    with gr.Row():
        image_input = gr.Image(type="pil", label="πŸ“ Upload or Capture Image")

    detect_btn = gr.Button("πŸš€ Detect Weight")

    with gr.Row():
        weight_out = gr.Textbox(label="πŸ“¦ Detected Weight", placeholder="e.g., 75.5 kg", show_copy_button=True)
        time_out = gr.Textbox(label="πŸ•’ Captured At (IST)", placeholder="e.g., 2025-07-01 12:00:00")

    snapshot = gr.Image(label="πŸ“Έ Snapshot Preview")
    retake_btn = gr.Button("πŸ” Retake / Try Again", visible=False)

    detect_btn.click(fn=process_image, inputs=image_input, outputs=[weight_out, time_out, snapshot, retake_btn])
    retake_btn.click(fn=lambda: ("", "", None, gr.update(visible=False)),
                     inputs=[], outputs=[weight_out, time_out, snapshot, retake_btn])

if __name__ == "__main__":
    demo.launch()