Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,49 +1,272 @@
|
|
| 1 |
-
from flask import Flask, request, jsonify
|
| 2 |
-
from transformers import pipeline
|
| 3 |
-
import base64
|
| 4 |
-
from PIL import Image
|
| 5 |
-
import io
|
| 6 |
import os
|
| 7 |
-
import
|
| 8 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
# Initialize Flask
|
| 11 |
app = Flask(__name__)
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
|
|
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
model = pipeline("image-classification", model=model_path, device=device) # Load from absolute path
|
| 23 |
-
print(f"Model loaded in {time.time() - start_time:.2f} seconds")
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
try:
|
| 28 |
-
#
|
| 29 |
-
|
| 30 |
-
if not
|
| 31 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
except Exception as e:
|
| 46 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
if __name__ ==
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
from paddleocr import PaddleOCR
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import requests
|
| 6 |
+
import re
|
| 7 |
+
from simple_salesforce import Salesforce
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
from io import BytesIO
|
| 11 |
+
from fuzzywuzzy import process
|
| 12 |
+
import base64
|
| 13 |
+
from flask import Flask, request, jsonify
|
| 14 |
|
| 15 |
+
# Initialize Flask App for camera input
|
| 16 |
app = Flask(__name__)
|
| 17 |
|
| 18 |
+
# Salesforce credentials
|
| 19 |
+
SALESFORCE_USERNAME = "venkatramana@sandbox.com"
|
| 20 |
+
SALESFORCE_PASSWORD = "Venkat12345@"
|
| 21 |
+
SALESFORCE_SECURITY_TOKEN = "GhcJJmjBEefdnukJoz4CAQlR"
|
| 22 |
+
|
| 23 |
+
# Initialize PaddleOCR
|
| 24 |
+
ocr = PaddleOCR(use_angle_cls=True, lang='en')
|
| 25 |
+
|
| 26 |
+
# Product names list
|
| 27 |
+
PRODUCT_NAMES = [
|
| 28 |
+
"Centrifugal mono block pump", "SINGLE PHASE MOTOR STARTER", "EasyPact EZC 100",
|
| 29 |
+
"Openwell Submersible Pumpset", "Electric Motor", "Self Priming Pump",
|
| 30 |
+
"Control panel for single phase submersible pumps", "MOTOR", "Submersible pump set",
|
| 31 |
+
"Fusion submersible pump set", "DCT", "Shock proof water proof", "CG COMMERCIAL MOTORS", "Fusion",
|
| 32 |
+
"control panel for single phase submerisible pumps",
|
| 33 |
+
"single phase digital starter dry run and timer panel", "5HP AV1 XL Kirloskar Pump",
|
| 34 |
+
"Phase stainless steel submersible pump", "Submersible pump", "WB15X",
|
| 35 |
+
"Vtype self priming pump", "SP SHINE DISC", "havells submersible pump",
|
| 36 |
+
"Havells open well Submersible pump", "Bertolini pump CK3 90pp",
|
| 37 |
+
"WPA 772 Water Pump Assy", "bertolini TTL triplex high pressure plunger pumps",
|
| 38 |
+
"Generic plunger high pressure pump", "Apple Normal, Banana",
|
| 39 |
+
"Cast Iron KSb centrifugal pump", "5.5kw Water Pump",
|
| 40 |
+
"KSB reliable i line centrifuged pumps", "Apple Normal, Orange, Banana",
|
| 41 |
+
"Positive API 6745 hydraulic diaphragm pump", "1/2 inch Fuel Hose Pipe", "Kirloskar Water Pump",
|
| 42 |
+
"Rotodel motor pump", "PVC Electrical Insulation Materials",
|
| 43 |
+
"Electric kirloskar domestic water pump", "Electrical Insulation Materials",
|
| 44 |
+
"sellowell motor pump", "bhupathi submersible pump set",
|
| 45 |
+
"Flowshine Submersible pump set", "Index submersible pump",
|
| 46 |
+
"Wintoss Plastic Electric Switch Board", "Electric 18 watt ujagar cooler pump",
|
| 47 |
+
"Generator Service", "LG WM FHT1207ZWL, LG REF GL-S292RSCY",
|
| 48 |
+
"Water tank, Filters, Water Pump", "MS Control Submersible Panel",
|
| 49 |
+
"Centrifugal Monoblock Pumps", "Electric Motor with Pump BodyBlue and White",
|
| 50 |
+
"Various Repair and Maintenance Parts", "Earthmax Pump",
|
| 51 |
+
"Water Tank, Filters, Water Pump", "Centrifugal Water Pump for Agriculture",
|
| 52 |
+
"mono block pumps"
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
# Attribute mappings: readable names to Salesforce API names
|
| 56 |
+
ATTRIBUTE_MAPPING = {
|
| 57 |
+
"Product name": "Productname__c",
|
| 58 |
+
"Colour": "Colour__c",
|
| 59 |
+
"Motortype": "Motortype__c",
|
| 60 |
+
"Frequency": "Frequency__c",
|
| 61 |
+
"Grossweight": "Grossweight__c",
|
| 62 |
+
"Ratio": "Ratio__c",
|
| 63 |
+
"MotorFrame": "Motorframe__c",
|
| 64 |
+
"Model": "Model__c",
|
| 65 |
+
"Speed": "Speed__c",
|
| 66 |
+
"Quantity": "Quantity__c",
|
| 67 |
+
"Voltage": "Voltage__c",
|
| 68 |
+
"Material": "Material__c",
|
| 69 |
+
"Type": "Type__c",
|
| 70 |
+
"Horsepower": "Horsepower__c",
|
| 71 |
+
"Consignee": "Consignee__c",
|
| 72 |
+
"LOT": "LOT__c",
|
| 73 |
+
"Stage": "Stage__c",
|
| 74 |
+
"Outlet": "Outlet__c",
|
| 75 |
+
"Serialnumber": "Serialnumber__c",
|
| 76 |
+
"HeadSize": "Headsize__c",
|
| 77 |
+
"Deliverysize": "Deliverysize__c",
|
| 78 |
+
"Phase": "Phase__c",
|
| 79 |
+
"Size": "Size__c",
|
| 80 |
+
"MRP": "MRP__c",
|
| 81 |
+
"Usebefore": "Usebefore__c",
|
| 82 |
+
"Height": "Height__c",
|
| 83 |
+
"MaximumDischarge Flow": "Maximumdischargeflow__c",
|
| 84 |
+
"DischargeRange": "Dischargeflow__c",
|
| 85 |
+
"Assembledby": "Manufacturer__c",
|
| 86 |
+
"Manufacturedate": "Manufacturedate__c",
|
| 87 |
+
"Companyname": "Companyname__c",
|
| 88 |
+
"Customercarenumber": "Customercarenumber__c",
|
| 89 |
+
"SellerAddress": "Selleraddress__c",
|
| 90 |
+
"Selleremail": "Selleremail__c",
|
| 91 |
+
"GSTIN": "GSTIN__c",
|
| 92 |
+
"Totalamount": "Totalamount__c",
|
| 93 |
+
"Paymentstatus": "Paymentstatus__c",
|
| 94 |
+
"Paymentmethod": "Paymentmethod__c",
|
| 95 |
+
"Invoicedate": "Invoicedate__c",
|
| 96 |
+
"Warranty": "Warranty__c",
|
| 97 |
+
"Brand": "Brand__c",
|
| 98 |
+
"Motorhorsepower": "Motorhorsepower__c",
|
| 99 |
+
"Power": "Power__c",
|
| 100 |
+
"Motorphase": "Motorphase__c",
|
| 101 |
+
"Enginetype": "Enginetype__c",
|
| 102 |
+
"Tankcapacity": "Tankcapacity__c",
|
| 103 |
+
"Head": "Head__c",
|
| 104 |
+
"Usage/Application": "Usage_Application__c",
|
| 105 |
+
"Volts": "volts__c",
|
| 106 |
+
"Hertz": "Hertz__c",
|
| 107 |
+
"Frame": "frame__c",
|
| 108 |
+
"Mounting": "Mounting__c",
|
| 109 |
+
"Tollfreenumber": "Tollfreenumber__c",
|
| 110 |
+
"Pipesize": "Pipesize__c",
|
| 111 |
+
"Manufacturer": "Manufacturer__c",
|
| 112 |
+
"Office": "Office__c",
|
| 113 |
+
"SRnumber": "SRnumber__c",
|
| 114 |
+
"TypeOfEndUse": "TypeOfEndUse__c",
|
| 115 |
+
"Model Name": "Model_Name__c",
|
| 116 |
+
"coolingmethod": "coolingmethod__c"
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
# Function to process the image and extract text
|
| 120 |
+
@app.route('/upload-image', methods=['POST'])
|
| 121 |
+
def upload_image():
|
| 122 |
+
try:
|
| 123 |
+
data = request.get_json()
|
| 124 |
+
image_base64 = data.get('image')
|
| 125 |
+
|
| 126 |
+
if not image_base64:
|
| 127 |
+
return jsonify({"success": False, "message": "No image data received."})
|
| 128 |
|
| 129 |
+
# Decode base64 image
|
| 130 |
+
image_data = base64.b64decode(image_base64.split(",")[1])
|
| 131 |
+
image = Image.open(BytesIO(image_data))
|
| 132 |
|
| 133 |
+
# OCR Extraction
|
| 134 |
+
ocr_result = ocr.ocr(image)
|
| 135 |
+
extracted_text = "\n".join([line[1][0] for line in ocr_result[0]])
|
|
|
|
|
|
|
| 136 |
|
| 137 |
+
if not extracted_text:
|
| 138 |
+
return jsonify({"success": False, "message": "No text extracted from the image."})
|
| 139 |
+
|
| 140 |
+
return jsonify({"success": True, "result": extracted_text})
|
| 141 |
+
except Exception as e:
|
| 142 |
+
return jsonify({"success": False, "message": str(e)})
|
| 143 |
+
|
| 144 |
+
# Function to process image using Gradio and Salesforce integration
|
| 145 |
+
def process_image(image, mode, entry_type, quantity):
|
| 146 |
try:
|
| 147 |
+
# Extract text from the image
|
| 148 |
+
extracted_text = extract_text(image)
|
| 149 |
+
if not extracted_text:
|
| 150 |
+
return "No text detected in the image.", None
|
| 151 |
+
|
| 152 |
+
# Match product name
|
| 153 |
+
product_name = match_product_name(extracted_text)
|
| 154 |
+
attributes = extract_attributes(extracted_text)
|
| 155 |
+
if product_name:
|
| 156 |
+
attributes["Product name"] = product_name
|
| 157 |
+
|
| 158 |
+
# Interact with Salesforce
|
| 159 |
+
message = interact_with_salesforce(mode, entry_type, quantity, extracted_text)
|
| 160 |
+
|
| 161 |
+
numbered_output = "\n".join([f"{key}: {value}" for key, value in attributes.items()])
|
| 162 |
+
return f"Extracted Text:\n{extracted_text}\n\nAttributes and Values:\n{numbered_output}", message
|
| 163 |
+
except Exception as e:
|
| 164 |
+
return f"Error processing image: {str(e)}", None
|
| 165 |
|
| 166 |
+
# Helper functions for OCR and Salesforce interaction
|
| 167 |
+
def extract_text(image):
|
| 168 |
+
result = ocr.ocr(image)
|
| 169 |
+
extracted_text = []
|
| 170 |
+
for line in result[0]:
|
| 171 |
+
extracted_text.append(line[1][0])
|
| 172 |
+
return "\n".join(extracted_text)
|
| 173 |
|
| 174 |
+
def match_product_name(extracted_text):
|
| 175 |
+
best_match = None
|
| 176 |
+
best_score = 0
|
| 177 |
+
for line in extracted_text.split("\n"):
|
| 178 |
+
match, score = process.extractOne(line, PRODUCT_NAMES)
|
| 179 |
+
if score > best_score:
|
| 180 |
+
best_match = match
|
| 181 |
+
best_score = score
|
| 182 |
+
return best_match if best_score >= 70 else None
|
| 183 |
|
| 184 |
+
def extract_attributes(extracted_text):
|
| 185 |
+
attributes = {}
|
| 186 |
+
for readable_attr, sf_attr in ATTRIBUTE_MAPPING.items():
|
| 187 |
+
pattern = rf"{re.escape(readable_attr)}[:\-]?\s*(.+)"
|
| 188 |
+
match = re.search(pattern, extracted_text, re.IGNORECASE)
|
| 189 |
+
if match:
|
| 190 |
+
attributes[readable_attr] = match.group(1).strip()
|
| 191 |
+
return attributes
|
| 192 |
|
| 193 |
+
def interact_with_salesforce(mode, entry_type, quantity, extracted_text):
|
| 194 |
+
try:
|
| 195 |
+
sf = Salesforce(
|
| 196 |
+
username=SALESFORCE_USERNAME,
|
| 197 |
+
password=SALESFORCE_PASSWORD,
|
| 198 |
+
security_token=SALESFORCE_SECURITY_TOKEN
|
| 199 |
+
)
|
| 200 |
+
# Add logic for Salesforce interaction based on mode and entry_type
|
| 201 |
+
# Simplified example:
|
| 202 |
+
return "Successfully interacted with Salesforce."
|
| 203 |
except Exception as e:
|
| 204 |
+
return f"Error interacting with Salesforce: {str(e)}"
|
| 205 |
+
|
| 206 |
+
# Gradio Interface
|
| 207 |
+
|
| 208 |
+
def create_interface():
|
| 209 |
+
return gr.Interface(
|
| 210 |
+
fn=process_image,
|
| 211 |
+
inputs=[
|
| 212 |
+
gr.HTML("""
|
| 213 |
+
<h1>Camera Input</h1>
|
| 214 |
+
<video id=\"rear-camera\" autoplay></video>
|
| 215 |
+
<button id=\"capture-btn\">Capture</button>
|
| 216 |
+
<canvas id=\"camera-canvas\" style=\"display:none;\"></canvas>
|
| 217 |
+
<p id=\"status\">Status: Ready</p>
|
| 218 |
+
<script>
|
| 219 |
+
const statusElement = document.getElementById(\"status\");
|
| 220 |
+
navigator.mediaDevices.getUserMedia({
|
| 221 |
+
video: { facingMode: \"environment\" }
|
| 222 |
+
}).then(stream => {
|
| 223 |
+
const videoElement = document.getElementById(\"rear-camera\");
|
| 224 |
+
videoElement.srcObject = stream;
|
| 225 |
+
const captureBtn = document.getElementById(\"capture-btn\");
|
| 226 |
+
const canvas = document.getElementById(\"camera-canvas\");
|
| 227 |
+
const ctx = canvas.getContext(\"2d\");
|
| 228 |
+
|
| 229 |
+
captureBtn.addEventListener(\"click\", () => {
|
| 230 |
+
statusElement.innerText = \"Status: Capturing...\";
|
| 231 |
+
canvas.width = videoElement.videoWidth;
|
| 232 |
+
canvas.height = videoElement.videoHeight;
|
| 233 |
+
ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
|
| 234 |
+
|
| 235 |
+
const imageData = canvas.toDataURL(\"image/png\");
|
| 236 |
+
fetch(\"/upload-image\", {
|
| 237 |
+
method: \"POST\",
|
| 238 |
+
body: JSON.stringify({ image: imageData }),
|
| 239 |
+
headers: { \"Content-Type\": \"application/json\" }
|
| 240 |
+
}).then(response => response.json()).then(data => {
|
| 241 |
+
if (data.success) {
|
| 242 |
+
statusElement.innerText = \"Status: Image scanned successfully!\";
|
| 243 |
+
console.log(\"OCR Result:\", data.result);
|
| 244 |
+
} else {
|
| 245 |
+
statusElement.innerText = \"Status: Error in processing image.\";
|
| 246 |
+
console.error(\"Error:\", data.message);
|
| 247 |
+
}
|
| 248 |
+
}).catch(err => {
|
| 249 |
+
statusElement.innerText = \"Status: Failed to upload image.\";
|
| 250 |
+
console.error(\"Error uploading image:\", err);
|
| 251 |
+
});
|
| 252 |
+
});
|
| 253 |
+
}).catch(error => {
|
| 254 |
+
console.error(\"Error accessing the rear camera:\", error);
|
| 255 |
+
alert(\"Unable to access the rear camera. Please check permissions.\");
|
| 256 |
+
});
|
| 257 |
+
</script>
|
| 258 |
+
"""),
|
| 259 |
+
gr.Dropdown(label="Mode", choices=["Entry", "Exit"], value="Entry"),
|
| 260 |
+
gr.Radio(label="Entry Type", choices=["Sales", "Non-Sales"], value="Sales"),
|
| 261 |
+
gr.Number(label="Quantity", value=1, interactive=True)
|
| 262 |
+
],
|
| 263 |
+
outputs=[
|
| 264 |
+
gr.Text(label="Extracted Text and Attributes"),
|
| 265 |
+
gr.Text(label="Salesforce Interaction Result")
|
| 266 |
+
],
|
| 267 |
+
title="Salesforce Export",
|
| 268 |
+
description="Use your camera to scan an image and process data for Salesforce.")
|
| 269 |
|
| 270 |
+
if __name__ == "__main__":
|
| 271 |
+
create_interface().launch(share=True)
|
| 272 |
+
app.run(debug=True)
|