Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567891011121314151617181920217 unmodified lines2930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194from flask import Flask, request, jsonify, render_template_stringfrom paddleocr import PaddleOCRfrom PIL import Imageimport refrom io import BytesIOimport base64from fuzzywuzzy import processfrom simple_salesforce import Salesforce# Initialize PaddleOCRocr = PaddleOCR(use_angle_cls=True, lang='en')# Salesforce credentialsSALESFORCE_USERNAME = "your_username"SALESFORCE_PASSWORD = "your_password"SALESFORCE_SECURITY_TOKEN = "your_security_token"# Attribute mappings and product namesATTRIBUTE_MAPPING = {"Product name": "Productname__c","Colour": "Colour__c",7 unmodified lines"Quantity": "Quantity__c","Voltage": "Voltage__c","Material": "Material__c",}PRODUCT_NAMES = ["Centrifugal mono block pump", "Electric Motor", "Self Priming Pump","Submersible pump set", "Havells open well Submersible pump"]# Decode Base64 imagedef decode_base64_image(base64_image):try:image_data = re.sub('^data:image/.+;base64,', '', base64_image)image = Image.open(BytesIO(base64.b64decode(image_data)))print("Decoded image successfully.")return imageexcept Exception as e:print(f"Error decoding image: {e}")return None# Extract text using PaddleOCRdef extract_text(image):try:result = ocr.ocr(image)extracted_text = []for line in result[0]:extracted_text.append(line[1][0])return "\n".join(extracted_text)except Exception as e:print(f"Error during OCR processing: {e}")return "Error processing the image."# Match product namesdef match_product_name(extracted_text):best_match = Nonebest_score = 0for line in extracted_text.split("\n"):match, score = process.extractOne(line, PRODUCT_NAMES)if score > best_score:best_match = matchbest_score = scorereturn best_match if best_score >= 70 else None# Extract attributesdef extract_attributes(extracted_text):attributes = {}for readable_attr, sf_attr in ATTRIBUTE_MAPPING.items():pattern = rf"{re.escape(readable_attr)}[:\-]?\s*(.+)"match = re.search(pattern, extracted_text, re.IGNORECASE)if match:attributes[readable_attr] = match.group(1).strip()return attributes# Interact with Salesforcedef interact_with_salesforce(attributes, mode, entry_type):try:sf = Salesforce(username=SALESFORCE_USERNAME,password=SALESFORCE_PASSWORD,security_token=SALESFORCE_SECURITY_TOKEN)print("Connected to Salesforce successfully.")# Add Salesforce logic herereturn "Data successfully sent to Salesforce."except Exception as e:print(f"Error interacting with Salesforce: {e}")return "Failed to interact with Salesforce."# Flask Appapp = Flask(__name__)# HTML Template for Camera InterfaceHTML_TEMPLATE = """<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Camera Integration</title></head><body><div style="text-align: center;"><h1>Camera Image Capture</h1><video id="video" autoplay playsinline style="width: 80%; border: 1px solid black;"></video><canvas id="canvas" style="display: none;"></canvas><br><button id="captureButton" style="padding: 10px 20px;">Capture</button><div id="output" style="margin-top: 20px; font-size: 1.2em;"></div></div><script>const videoElement = document.querySelector("#video");const canvasElement = document.querySelector("#canvas");const captureButton = document.querySelector("#captureButton");const outputDiv = document.querySelector("#output");navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } }).then((stream) => {videoElement.srcObject = stream;}).catch((err) => console.error("Error accessing camera:", err));captureButton.addEventListener("click", () => {const context = canvasElement.getContext("2d");canvasElement.width = videoElement.videoWidth;canvasElement.height = videoElement.videoHeight;context.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);const imageData = canvasElement.toDataURL("image/png");console.log("Captured Image Data:", imageData); // Debug captured image data// Send image to backendfetch("/process-image", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ image: imageData }),}).then((response) => response.json()).then((data) => {console.log("Backend Response:", data);outputDiv.innerHTML = `<strong>Extracted Text:</strong> ${data["Extracted Text"]}<br><strong>Matched Product Name:</strong> ${data["Matched Product Name"]}<br><strong>Attributes:</strong> ${JSON.stringify(data["Extracted Attributes"])}<br><strong>Salesforce Message:</strong> ${data["Salesforce Message"]}`;}).catch((err) => {console.error("Error sending image to backend:", err);outputDiv.textContent = "Error processing image.";});});</script></body></html>"""@app.route("/")def index():return render_template_string(HTML_TEMPLATE)@app.route("/process-image", methods=["POST"])def process_image():data = request.jsonbase64_image = data.get("image")if not base64_image:return jsonify({"error": "No image data provided."}), 400image = decode_base64_image(base64_image)if image is None:return jsonify({"error": "Invalid image data."}), 400extracted_text = extract_text(image)product_name = match_product_name(extracted_text)attributes = extract_attributes(extracted_text)sf_message = interact_with_salesforce(attributes, mode="Entry", entry_type="Sales")return jsonify({"Extracted Text": extracted_text,"Matched Product Name": product_name or "No matching product found.","Extracted Attributes": attributes,"Salesforce Message": sf_message,})if __name__ == "__main__":app.run(host="0.0.0.0", port=5000, debug=True)123456789101112131415167 unmodified lines24252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362import osfrom paddleocr import PaddleOCRfrom PIL import Imageimport gradio as grimport requestsimport refrom simple_salesforce import Salesforceimport pandas as pdimport matplotlib.pyplot as pltfrom io import BytesIOfrom fuzzywuzzy import process# Attribute mappings: readable names to Salesforce API namesATTRIBUTE_MAPPING = {"Product name": "Productname__c","Colour": "Colour__c",7 unmodified lines"Quantity": "Quantity__c","Voltage": "Voltage__c","Material": "Material__c","Type": "Type__c","Horsepower": "Horsepower__c","Consignee": "Consignee__c","LOT": "LOT__c","Stage": "Stage__c","Outlet": "Outlet__c","Serialnumber": "Serialnumber__c","HeadSize": "Headsize__c","Deliverysize": "Deliverysize__c","Phase": "Phase__c","Size": "Size__c","MRP": "MRP__c","Usebefore": "Usebefore__c","Height": "Height__c","MaximumDischarge Flow": "Maximumdischargeflow__c","DischargeRange": "Dischargeflow__c","Assembledby": "Manufacturer__c","Manufacturedate": "Manufacturedate__c","Companyname": "Companyname__c","Customercarenumber": "Customercarenumber__c","SellerAddress": "Selleraddress__c","Selleremail": "Selleremail__c","GSTIN": "GSTIN__c","Totalamount": "Totalamount__c","Paymentstatus": "Paymentstatus__c","Paymentmethod": "Paymentstatus__c","Invoicedate": "Manufacturedate__c","Warranty": "Warranty__c","Brand": "Brand__c","Motorhorsepower": "Motorhorsepower__c","Power": "Power__c","Motorphase": "Motorphase__c","Enginetype": "Enginetype__c","Tankcapacity": "Tankcapacity__c","Head": "Head__c","Usage/Application": "Usage_Application__c","Volts": "volts__c","Hertz": "Hertz__c","Frame": "frame__c","Mounting": "Mounting__c","Tollfreenumber": "Tollfreenumber__c","Pipesize": "Pipesize__c","Manufacturer": "Manufacturer__c","Office": "Office__c","SRnumber": "SRnumber__c","TypeOfEndUse": "TypeOfEndUse__c","Model Name": "Model_Name_Number__c","coolingmethod": "coolingmethod__c"}# List of product names to matchPRODUCT_NAMES = ["Centrifugal mono block pump", "SINGLE PHASE MOTOR STARTER", "EasyPact EZC 100","Openwell Submersible Pumpset", "Electric Motor", "Self Priming Pump","Control panel for single phase submersible pumps", "MOTOR", "Submersible pump set","Fusion submersible pump set", "DCT", "Shock proof water proof", "CG COMMERCIAL MOTORS", "Fusion","control panel for single phase submerisible pumps","single phase digital starter dry run and timer panel", "5HP AV1 XL Kirloskar Pump","Phase stainless steel submersible pump", "Submersible pump", "WB15X","Vtype self priming pump", "SP SHINE DISC", "havells submersible pump","Havells open well Submersible pump", "Bertolini pump CK3 90pp","WPA 772 Water Pump Assy", "bertolini TTL triplex high pressure plunger pumps","Generic plunger high pressure pump", "Apple Normal, Banana","Cast Iron KSb centrifugal pump", "5.5kw Water Pump","KSB reliable i line centrifuged pumps", "Apple Normal, Orange, Banana","Positive API 6745 hydraulic diaphragm pump", "1/2 inch Fuel Hose Pipe", "Kirloskar Water Pump","Rotodel motor pump", "PVC Electrical Insulation Materials","Electric kirloskar domestic water pump", "Electrical Insulation Materials","sellowell motor pump", "bhupathi submersible pump set","Flowshine Submersible pump set", "Index submersible pump","Wintoss Plastic Electric Switch Board", "Electric 18 watt ujagar cooler pump","Generator Service", "LG WM FHT1207ZWL, LG REF GL-S292RSCY","Water tank, Filters, Water Pump", "MS Control Submersible Panel","Centrifugal Monoblock Pumps", "Electric Motor with Pump BodyBlue and White","Various Repair and Maintenance Parts", "Earthmax Pump","Water Tank, Filters, Water Pump", "Centrifugal Water Pump for Agriculture","mono block pumps"]# Salesforce credentialsSALESFORCE_USERNAME = "venkatramana@sandbox.com"SALESFORCE_PASSWORD = "Venkat12345@"SALESFORCE_SECURITY_TOKEN = "GhcJJmjBEefdnukJoz4CAQlR"# Initialize PaddleOCRocr = PaddleOCR(use_angle_cls=True, lang='en')# Function to extract text using PaddleOCRdef extract_text(image):result = ocr.ocr(image)extracted_text = []for line in result[0]:extracted_text.append(line[1][0])return "\n".join(extracted_text)# Function to match product name using fuzzy matchingdef match_product_name(extracted_text):best_match = Nonebest_score = 0for line in extracted_text.split("\n"):match, score = process.extractOne(line, PRODUCT_NAMES)if score > best_score:best_match = matchbest_score = scorereturn best_match if best_score >= 70 else None # Threshold of 70 for a match# Function to extract attributes and their valuesdef extract_attributes(extracted_text):attributes = {}for readable_attr, sf_attr in ATTRIBUTE_MAPPING.items():pattern = rf"{re.escape(readable_attr)}[:\-]?\s*(.+)"match = re.search(pattern, extracted_text, re.IGNORECASE)if match:attributes[readable_attr] = match.group(1).strip()return attributes# Function to filter attributes for valid Salesforce fieldsdef filter_valid_attributes(attributes, valid_fields):return {ATTRIBUTE_MAPPING[key]: value for key, value in attributes.items() if ATTRIBUTE_MAPPING[key] in valid_fields}# Function to interact with Salesforce based on mode and typedef interact_with_salesforce(mode, entry_type, quantity, extracted_text):try:sf = Salesforce(username=SALESFORCE_USERNAME,password=SALESFORCE_PASSWORD,security_token=SALESFORCE_SECURITY_TOKEN)# Mapping mode and entry_type to Salesforce object and fieldobject_name = Nonefield_name = Noneproduct_field_name = "Product_Name__c" # Correct field for product name in the objectmodel_field_name = "Modal_Name__c" # Correct field for model name in the objectif mode == "Entry":if entry_type == "Sales":object_name = "VENKATA_RAMANA_MOTORS__c"field_name = "Quantity__c"elif entry_type == "Non-Sales":object_name = "UNBILLING_DATA__c"field_name = "TotalQuantity__c"elif mode == "Exit":if entry_type == "Sales":object_name = "Inventory_Management__c"product_field_name = "Product_Name__c"model_field_name = "Modal_Name__c"field_name = "Quantity_Sold__c"elif entry_type == "Non-Sales":object_name = "Un_Billable__c"product_field_name = "Product_Name__c"model_field_name = "Model_Name__c"field_name = "Sold_Out__c"if not object_name or not field_name:return "Invalid mode or entry type."# Get valid fields for the specified Salesforce objectsf_object = sf.__getattr__(object_name)schema = sf_object.describe()valid_fields = {field["name"] for field in schema["fields"]}# Extract product name or model numberproduct_name = match_product_name(extracted_text)attributes = extract_attributes(extracted_text)if not product_name:return "Product name could not be matched from the extracted text."attributes["Product name"] = product_nameif mode == "Exit":query = f"SELECT Id, {field_name} FROM {object_name} WHERE {product_field_name} = '{product_name}' OR {model_field_name} = '{attributes.get('Model Name', '')}' LIMIT 1"response = sf.query(query)if response["records"]:record_id = response["records"][0]["Id"]updated_quantity = quantity # Overwrite the quantity, don't addsf_object.update(record_id, {field_name: updated_quantity})return f"Updated record for product '{product_name}' in {object_name}. New {field_name}: {updated_quantity}."else:return f"No matching record found for product '{product_name}' in {object_name}."else:filtered_attributes = filter_valid_attributes(attributes, valid_fields)filtered_attributes[field_name] = quantitysf_object.create(filtered_attributes)return f"Data successfully exported to Salesforce object {object_name}."except Exception as e:return f"Error interacting with Salesforce: {str(e)}"# Function to pull data from Salesforce MotorDataAPIdef pull_data_from_motor_api():try:sf = Salesforce(username=SALESFORCE_USERNAME,password=SALESFORCE_PASSWORD,security_token=SALESFORCE_SECURITY_TOKEN)motor_data = sf.apexecute("MotorDataAPI/", method="GET")return motor_data # API returns the list of recordsexcept Exception as e:return f"Error pulling data from MotorDataAPI: {str(e)}"# Function to format Salesforce data into a DataFrame with readable headersdef format_salesforce_data():try:data = pull_data_from_motor_api()if isinstance(data, list):df = pd.DataFrame(data)df = df.rename(columns={"Product_Name__c": "Product Name","Modal_Name__c": "Model Name","Current_Stocks__c": "Current Stocks"})# Remove unnecessary columnsdf = df[["Product Name", "Model Name", "Current Stocks"]]return dfelse:return Noneexcept Exception as e:return None# Function to generate a bar graph from Salesforce datadef generate_bar_graph(df):try:fig, ax = plt.subplots(figsize=(12, 8))df.plot(kind='bar', x="Product Name", y="Current Stocks", ax=ax, legend=False)ax.set_title("Stock Distribution by Product Name")ax.set_xlabel("Product Name")ax.set_ylabel("Current Stocks")plt.xticks(rotation=45, ha="right", fontsize=10)plt.tight_layout()buffer = BytesIO()plt.savefig(buffer, format="png")buffer.seek(0)img = Image.open(buffer)return imgexcept Exception as e:return None# Unified function to handle image processing and Salesforce interactiondef process_image(image, mode, entry_type, quantity):extracted_text = extract_text(image)if not extracted_text:return "No text detected in the image.", Noneproduct_name = match_product_name(extracted_text)attributes = extract_attributes(extracted_text)if product_name:attributes["Product name"] = product_name# Interact with Salesforcemessage = interact_with_salesforce(mode, entry_type, quantity, extracted_text)numbered_output = "\n".join([f"{key}: {value}" for key, value in attributes.items()])return f"Extracted Text:\n{extracted_text}\n\nAttributes and Values:\n{numbered_output}", message# Gradio Interface with JavaScript camera functionalitydef app():camera_js = """<script>async function captureImage() {const video = document.createElement('video');video.style.display = 'none';document.body.appendChild(video);const canvas = document.createElement('canvas');document.body.appendChild(canvas);const stream = await navigator.mediaDevices.getUserMedia({ video: true });video.srcObject = stream;await video.play();canvas.width = video.videoWidth;canvas.height = video.videoHeight;const context = canvas.getContext('2d');context.drawImage(video, 0, 0, canvas.width, canvas.height);const imageData = canvas.toDataURL('image/png');document.body.removeChild(video);document.body.removeChild(canvas);stream.getTracks().forEach(track => track.stop());const base64Image = imageData.split(',')[1];return base64Image;}</script>"""df = format_salesforce_data()table_component = Nonebar_graph_component = Noneif df is not None:table_component = df.to_html(index=False)bar_graph_image = generate_bar_graph(df)if bar_graph_image:bar_graph_component = bar_graph_imagereturn gr.TabbedInterface([gr.Interface(fn=process_image,inputs=[gr.Text(label="Upload Image (Base64)"),gr.Dropdown(label="Mode", choices=["Entry", "Exit"], value="Entry"),gr.Radio(label="Entry Type", choices=["Sales", "Non-Sales"], value="Sales"),gr.Number(label="Quantity", value=1, interactive=True),],outputs=[gr.Text(label="Image Data Viewer"),gr.Text(label="Result")],title="Salesforce Export",description="Capture an image using JavaScript or upload Base64 and process."),gr.Interface(fn=lambda: (table_component, bar_graph_component),inputs=[],outputs=[gr.HTML(label="Salesforce Data Table"),gr.Image(type="pil", label="Stock Distribution Bar Graph")],title="Salesforce Data",description="View structured Salesforce data as a table and bar graph.")], ["Processing", "Salesforce Data"])if __name__ == "__main__":app().launch(share=True)
app.py+301-133