File size: 2,164 Bytes
d55b56b
d5ceb6c
 
 
 
f50878a
d5ceb6c
 
 
 
10cd160
f50878a
d5ceb6c
 
c042a27
f50878a
 
 
 
 
 
 
7ebef67
d5ceb6c
 
 
10cd160
d5ceb6c
f50878a
10cd160
d5ceb6c
 
 
 
 
10cd160
d5ceb6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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")

        # Handle fallback errors
        if not weight or ("No valid" in weight and "OCR:" not in weight):
            return "❌ Unable to detect. Try again with a clearer image.", "", image, gr.update(visible=True)

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

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

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

        # Create Salesforce record
        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"
        })

        # Upload image to Salesforce
        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)