Spaces:
Sleeping
Sleeping
Update app.py
Browse files8 unmodified lines9101112131434 unmodified lines495051525354555613 unmodified lines7071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171 unmodified line1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541 unmodified line1561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403417 unmodified lines3493503513523533543551 unmodified line3573583593603613623633643653663673683693703713723733743753763773783798 unmodified linesimport matplotlib.pyplot as pltfrom io import BytesIOfrom fuzzywuzzy import process# Attribute mappings: readable names to Salesforce API namesATTRIBUTE_MAPPING = {34 unmodified lines"GSTIN": "GSTIN__c","Totalamount": "Totalamount__c","Paymentstatus": "Paymentstatus__c","Paymentmethod": "Paymentstatus__c","Invoicedate": "Manufacturedate__c","Warranty": "Warranty__c","Brand": "Brand__c","Motorhorsepower": "Motorhorsepower__c",13 unmodified lines"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 = []1 unmodified lineextracted_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(1 unmodified linepassword=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 Interfacedef app():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_image# Rear camera HTML integration# Updated Processing Tab with Rear Camera Integrationrear_camera_html = """<h1>Camera Input</h1><video id="rear-camera" autoplay></video><button id="capture-btn">Capture</button><canvas id="camera-canvas" style="display:none;"></canvas><script>// Access the rear cameranavigator.mediaDevices.getUserMedia({video: {facingMode: "environment"}}).then(stream => {const videoElement = document.getElementById("rear-camera");videoElement.srcObject = stream;const captureBtn = document.getElementById("capture-btn");const canvas = document.getElementById("camera-canvas");const ctx = canvas.getContext("2d");captureBtn.addEventListener("click", () => {canvas.width = videoElement.videoWidth;canvas.height = videoElement.videoHeight;ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);const imageData = canvas.toDataURL("image/png");fetch("/upload-image", {method: "POST",body: JSON.stringify({ image: imageData }),headers: { "Content-Type": "application/json" }}).then(response => response.json()).then(data => console.log("Image uploaded successfully:", data)).catch(err => console.error("Error uploading image:", err));});}).catch(error => {console.error("Error accessing the rear camera:", error);alert("Unable to access the rear camera. Please check permissions.");});</script>"""7 unmodified linesgr.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),gr.HTML(rear_camera_html) # Add camera functionality directly to the Processing tab],outputs=[gr.Text(label="Image Data Viewer"),1 unmodified line],title="Salesforce Export",description="Upload an image or use the camera to process data for Salesforce.",),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)8 unmodified lines9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555634 unmodified lines919293949596979813 unmodified lines1121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691 unmodified line1711721731741751761771781791801811821831841851861871881891901911921931941951 unmodified line1971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592607 unmodified lines2682692702712722732741 unmodified line2762772782792802812822832842852868 unmodified linesimport matplotlib.pyplot as pltfrom io import BytesIOfrom fuzzywuzzy import processimport base64from flask import Flask, request, jsonify# Initialize Flask App for camera inputapp = Flask(__name__)# Salesforce credentialsSALESFORCE_USERNAME = "venkatramana@sandbox.com"SALESFORCE_PASSWORD = "Venkat12345@"SALESFORCE_SECURITY_TOKEN = "GhcJJmjBEefdnukJoz4CAQlR"# Initialize PaddleOCRocr = PaddleOCR(use_angle_cls=True, lang='en')# Product names listPRODUCT_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"]# Attribute mappings: readable names to Salesforce API namesATTRIBUTE_MAPPING = {34 unmodified lines"GSTIN": "GSTIN__c","Totalamount": "Totalamount__c","Paymentstatus": "Paymentstatus__c","Paymentmethod": "Paymentmethod__c","Invoicedate": "Invoicedate__c","Warranty": "Warranty__c","Brand": "Brand__c","Motorhorsepower": "Motorhorsepower__c",13 unmodified lines"Office": "Office__c","SRnumber": "SRnumber__c","TypeOfEndUse": "TypeOfEndUse__c","Model Name": "Model_Name__c","coolingmethod": "coolingmethod__c"}# Function to process the image and extract text@app.route('/upload-image', methods=['POST'])def upload_image():try:data = request.get_json()image_base64 = data.get('image')if not image_base64:return jsonify({"success": False, "message": "No image data received."})# Decode base64 imageimage_data = base64.b64decode(image_base64.split(",")[1])image = Image.open(BytesIO(image_data))# OCR Extractionocr_result = ocr.ocr(image)extracted_text = "\n".join([line[1][0] for line in ocr_result[0]])if not extracted_text:return jsonify({"success": False, "message": "No text extracted from the image."})return jsonify({"success": True, "result": extracted_text})except Exception as e:return jsonify({"success": False, "message": str(e)})# Function to process image using Gradio and Salesforce integrationdef process_image(image, mode, entry_type, quantity):try:# Extract text from the imageextracted_text = extract_text(image)if not extracted_text:return "No text detected in the image.", None# Match product nameproduct_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}", messageexcept Exception as e:return f"Error processing image: {str(e)}", None# Helper functions for OCR and Salesforce interactiondef extract_text(image):result = ocr.ocr(image)extracted_text = []1 unmodified lineextracted_text.append(line[1][0])return "\n".join(extracted_text)def 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 Nonedef 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 attributesdef interact_with_salesforce(mode, entry_type, quantity, extracted_text):try:sf = Salesforce(1 unmodified linepassword=SALESFORCE_PASSWORD,security_token=SALESFORCE_SECURITY_TOKEN)# Add logic for Salesforce interaction based on mode and entry_type# Simplified example:return "Successfully interacted with Salesforce."except Exception as e:return f"Error interacting with Salesforce: {str(e)}"# Gradio Interfacedef create_interface():rear_camera_html = """<h1>Camera Input</h1><video id="rear-camera" autoplay></video><button id="capture-btn">Capture</button><canvas id="camera-canvas" style="display:none;"></canvas><p id="status">Status: Ready</p><script>const statusElement = document.getElementById("status");// Access the rear cameranavigator.mediaDevices.getUserMedia({video: { facingMode: "environment" }}).then(stream => {const videoElement = document.getElementById("rear-camera");videoElement.srcObject = stream;const captureBtn = document.getElementById("capture-btn");const canvas = document.getElementById("camera-canvas");const ctx = canvas.getContext("2d");captureBtn.addEventListener("click", () => {statusElement.innerText = "Status: Capturing...";canvas.width = videoElement.videoWidth;canvas.height = videoElement.videoHeight;ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);const imageData = canvas.toDataURL("image/png");fetch("/upload-image", {method: "POST",body: JSON.stringify({ image: imageData }),headers: { "Content-Type": "application/json" }}).then(response => response.json()).then(data => {if (data.success) {statusElement.innerText = "Status: Image scanned successfully!";console.log("OCR Result:", data.result);} else {statusElement.innerText = "Status: Error in processing image.";console.error("Error:", data.message);}}).catch(err => {statusElement.innerText = "Status: Failed to upload image.";console.error("Error uploading image:", err);});});}).catch(error => {console.error("Error accessing the rear camera:", error);alert("Unable to access the rear camera. Please check permissions.");});</script>"""7 unmodified linesgr.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),gr.HTML(rear_camera_html)],outputs=[gr.Text(label="Image Data Viewer"),1 unmodified line],title="Salesforce Export",description="Upload an image or use the camera to process data for Salesforce.",)],["Processing"],)if __name__ == "__main__":create_interface().launch(share=True)app.run(debug=True)
app.py+140-233