Spaces:
Sleeping
Sleeping
Update app.py
Browse files8 unmodified lines9101112131464 unmodified lines7980818283848575 unmodified lines16116216316416516616716816917017117217317417517617717817918018118218318418514 unmodified lines2002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582595 unmodified lines26526626726826927027127227314 unmodified lines2882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293308 unmodified linesimport matplotlib.pyplot as pltfrom io import BytesIOfrom fuzzywuzzy import process# Attribute mappings: readable names to Salesforce API namesATTRIBUTE_MAPPING = {64 unmodified lines"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 COMMERCIALMOTORS", "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",75 unmodified linesobject_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:14 unmodified linesattributes["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")5 unmodified linesplt.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):14 unmodified lines# 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_imagereturn gr.TabbedInterface([gr.Interface(fn=process_image,inputs=[gr.Image(type="numpy", label="Upload Image"),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="Upload an image, select Entry/Exit mode and Sales/Non-Sales type, and specify quantity."),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 lines910111213141564 unmodified lines8081828384858675 unmodified lines16216316416516616716816917017117217317417517617717817918018118214 unmodified lines1971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512525 unmodified lines25825926026126226326426526626714 unmodified lines2822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153168 unmodified linesimport matplotlib.pyplot as pltfrom io import BytesIOfrom fuzzywuzzy import processimport kaleido # Ensure kaleido is imported# Attribute mappings: readable names to Salesforce API namesATTRIBUTE_MAPPING = {64 unmodified lines"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",75 unmodified linesobject_name = Nonefield_name = Noneproduct_field_name = "Product_Name__c" # Correct field for product name in the objectmodel_field_name = "Model_Name__c" # Correct field for model name in the objectif mode == "Entry":if entry_type == "Sales":object_name = "Inventory__c"field_name = "Stock_Quantity__c"elif entry_type == "Non-Sales":object_name = "Unbilled_Inventory__c"field_name = "Unbilled_Quantity__c"elif mode == "Exit":if entry_type == "Sales":object_name = "Inventory__c"field_name = "Sold_Quantity__c"elif entry_type == "Non-Sales":object_name = "Unbilled_Inventory__c"field_name = "Sold_Out__c"if not object_name or not field_name:14 unmodified linesattributes["Product name"] = product_nameif mode == "Exit":query = f"SELECT Id, {field_name}, Stock_Quantity__c 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"]current_stock = response["records"][0].get("Stock_Quantity__c", 0)updated_quantity = current_stock - quantity # Deduct sold quantitysf_object.update(record_id, {field_name: quantity, "Stock_Quantity__c": updated_quantity})return f"Updated record for product '{product_name}' in {object_name}. New {field_name}: {quantity}, Updated Stock: {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 structured data from Salesforce and display as a tabledef pull_data_from_salesforce():try:sf = Salesforce(username=SALESFORCE_USERNAME,password=SALESFORCE_PASSWORD,security_token=SALESFORCE_SECURITY_TOKEN)query = "SELECT Product_Name__c, Model_Name__c, Stock_Quantity__c FROM Inventory__c LIMIT 100"response = sf.query_all(query)records = response.get("records", [])if not records:return "No data found in Salesforce.", None, None, Nonedf = pd.DataFrame(records)df = df.drop(columns=['attributes'], errors='ignore')# Rename columns for better readabilitydf.rename(columns={"Product_Name__c": "Product Name","Model_Name__c": "Model Name","Stock_Quantity__c": "Current Stocks"}, inplace=True)excel_path = "salesforce_data.xlsx"df.to_excel(excel_path, index=False)# Generate interactive vertical bar graph using Matplotlibfig, 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")5 unmodified linesplt.savefig(buffer, format="png")buffer.seek(0)img = Image.open(buffer)return "Data successfully retrieved.", df, excel_path, imgexcept Exception as e:return f"Error fetching data: {str(e)}", None, None, None# Unified function to handle image processing and Salesforce interactiondef process_image(image, mode, entry_type, quantity):14 unmodified lines# Gradio Interfacedef app():return gr.TabbedInterface([gr.Interface(fn=process_image,inputs=[gr.Image(type="numpy", label="π Upload Image"),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="π Extracted Image Data"),gr.Text(label="π Result")],title="π’ Inventory Management",description="π¦ Inventory Management System"),gr.Interface(fn=pull_data_from_salesforce,inputs=[],outputs=[gr.Text(label="Status"),gr.Dataframe(label="π¦ Salesforce Data Table"),gr.File(label="Download Salesforce Data"),gr.Image(label="π Stock Distribution Bar Graph")],title="π Salesforce Data Export",description="View, visualize (zoom-in/out), and download Salesforce data (Product Name, Model Name, Current Stocks).")], ["π₯ OCR Processing", "π Salesforce Data Export"])if __name__ == "__main__":app().launch(share=True)
app.py+61-75