Spaces:
Runtime error
Runtime error
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781792 unmodified linesfrom PIL import Imageimport gradio as grimport numpy as npfrom simple_salesforce import Salesforceimport pandas as pdimport matplotlib.pyplot as pltfrom io import BytesIO# Initialize PaddleOCRocr = PaddleOCR(use_angle_cls=True, lang='en')# Salesforce credentialsSALESFORCE_USERNAME = "your_salesforce_username"SALESFORCE_PASSWORD = "your_salesforce_password"SALESFORCE_SECURITY_TOKEN = "your_salesforce_security_token"# Attribute mappings (readable to Salesforce API names)ATTRIBUTE_MAPPING = {"Product name": "Productname__c","Miles": "Miles__c","Colour": "Colour__c","Motortype": "Motortype__c","Frequency": "Frequency__c","Grossweight": "Grossweight__c","Ratio": "Ratio__c","MotorFrame": "Motorframe__c","Model": "Model__c","Speed": "Speed__c","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","Warranty": "Warranty__c","Brand": "Brand__c","Power": "Power__c","Miles": "Miles__c","Motorphase": "Motorphase__c","Enginetype": "Enginetype__c","Tankcapacity": "Tankcapacity__c","Head": "Head__c","Usage/Application": "Usage_Application__c",}# Product namesPRODUCT_NAMES = ["Centrifugal mono block pump", "SINGLE PHASE MOTOR STARTER", "EasyPact EZC 100","Openwell Submersible Pumpset", "Electric Motor", "Self Priming Pump","Miles-Powered Vehicle", "Miles-Electric", "Control panel for single phase submersible pumps","MOTOR", "Submersible pump set", "Fusion submersible pump set", "DCT", "Shock proof water proof","CG COMMERCIAL MOTORS", "Fusion", "5HP AV1 XL Kirloskar Pump", "Positive API 6745 hydraulic diaphragm pump"]# Function to extract text using PaddleOCRdef extract_text_from_frame(frame):if frame is None:return "No frame captured from webcam."# Extract a single frame from video input (NumPy array)pil_image = Image.fromarray(frame)# Perform OCRresult = ocr.ocr(np.array(pil_image))extracted_text = []for line in result[0]:extracted_text.append(line[1][0])return "\n".join(extracted_text)# Function to interact with Salesforcedef interact_with_salesforce(mode, entry_type):try:# Connect to Salesforcesf = Salesforce(username=SALESFORCE_USERNAME,password=SALESFORCE_PASSWORD,security_token=SALESFORCE_SECURITY_TOKEN)# Define object and fields based on mode and typeif mode == "Entry" and entry_type == "Sales":object_name = "Sales_Entry__c"elif mode == "Entry" and entry_type == "Non-Sales":object_name = "NonSales_Entry__c"elif mode == "Exit" and entry_type == "Sales":object_name = "Sales_Exit__c"elif mode == "Exit" and entry_type == "Non-Sales":object_name = "NonSales_Exit__c"else:return "Invalid mode or entry type."# Query examplequery = f"SELECT Name, Quantity__c FROM {object_name}"data = sf.query(query)["records"]# Create a DataFramedf = pd.DataFrame(data)if not df.empty:df = df.rename(columns={"Name": "Product Name", "Quantity__c": "Quantity"})return dfelse:return "No data retrieved from Salesforce."except Exception as e:return f"Error interacting with Salesforce: {str(e)}"# Function to generate a bar graph from Salesforce datadef generate_bar_graph(mode, entry_type):data = interact_with_salesforce(mode, entry_type)if isinstance(data, pd.DataFrame):plt.figure(figsize=(10, 6))plt.bar(data["Product Name"], data["Quantity"])plt.xlabel("Product Name")plt.ylabel("Quantity")plt.title(f"Product Quantity ({mode}, {entry_type})")plt.xticks(rotation=45, ha="right")plt.tight_layout()# Save the figure to a bufferbuffer = BytesIO()plt.savefig(buffer, format="png")buffer.seek(0)img = Image.open(buffer)return imgreturn None# Function to process frame and Salesforce data togetherdef process_frame_and_salesforce(frame, mode, entry_type):extracted_text = extract_text_from_frame(frame)salesforce_data = interact_with_salesforce(mode, entry_type)graph = generate_bar_graph(mode, entry_type)if isinstance(salesforce_data, pd.DataFrame):salesforce_data = salesforce_data.to_html(index=False)return extracted_text, salesforce_data, graph# Gradio Appdef create_app():return gr.Interface(fn=process_frame_and_salesforce,inputs=[gr.Video(label="Capture Webcam Video"), # Use gr.Video for webcam inputgr.Dropdown(label="Mode", choices=["Entry", "Exit"], value="Entry"),gr.Radio(label="Entry Type", choices=["Sales", "Non-Sales"], value="Sales")],outputs=["text", # Extracted textgr.HTML(label="Salesforce Data"), # Salesforce data tablegr.Image(label="Salesforce Bar Graph"), # Bar graph],live=True, # Real-time processingtitle="Webcam OCR and Salesforce Integration",description="Capture a frame from webcam video, extract text using PaddleOCR, and retrieve Salesforce data.")if __name__ == "__main__":create_app().launch(share=True)2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485862 unmodified linesfrom PIL import Imageimport gradio as grimport numpy as npfrom io import BytesIO# Initialize PaddleOCRocr = PaddleOCR(use_angle_cls=True, lang='en')# Function to extract text from an imagedef extract_text(image):if image is None:return "No image captured."# Perform OCR on the imageresult = ocr.ocr(np.array(image))extracted_text = []for line in result[0]:extracted_text.append(line[1][0])return "\n".join(extracted_text)# Custom JavaScript for handling front/rear camera togglingcustom_js = """async function captureImage(inputElement, outputElement, event) {const video = document.createElement('video');const constraints = {video: {facingMode: event.target.value === 'rear' ? { exact: 'environment' } : 'user'}};const stream = await navigator.mediaDevices.getUserMedia(constraints);video.srcObject = stream;await video.play();const canvas = document.createElement('canvas');canvas.width = video.videoWidth;canvas.height = video.videoHeight;const ctx = canvas.getContext('2d');ctx.drawImage(video, 0, 0, canvas.width, canvas.height);const dataUrl = canvas.toDataURL('image/png');outputElement.src = dataUrl;video.srcObject.getTracks().forEach(track => track.stop());inputElement.value = dataUrl;}"""# Gradio Appdef create_app():with gr.Blocks() as demo:gr.Markdown("### Capture Image from Webcam (Front/Rear Camera Toggle)")with gr.Row():with gr.Column():# Camera Selector (Front/Rear)camera_toggle = gr.Radio(choices=["front", "rear"], value="front", label="Select Camera")capture_button = gr.Button("Capture Image")with gr.Column():# Image Preview and Outputimage_output = gr.Image(type="pil", label="Captured Image")# Bind JavaScript for handling the camera capturecapture_button.click(None,inputs=[camera_toggle],outputs=image_output,_js=custom_js)# OCR Processinggr.Markdown("### Extract Text from Captured Image")ocr_button = gr.Button("Extract Text")ocr_output = gr.Textbox(label="Extracted Text")ocr_button.click(fn=extract_text,inputs=image_output,outputs=ocr_output)return demoif __name__ == "__main__":create_app().launch(share=True)
app.py+61-154