Spaces:
Build error
Build error
Update app.py
Browse files1 unmodified line234567891011121314151617181942 unmodified lines62636465666768691 unmodified line717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711815 unmodified lines1341351361371381391401411421431441451461471481491501519 unmodified lines1611621631641651665 unmodified lines1721731741751761771 unmodified linefrom paddleocr import PaddleOCRfrom PIL import Imageimport gradio as grimport refrom simple_salesforce import Salesforceimport pandas as pdfrom fuzzywuzzy import process# Attribute mappings: readable names to Salesforce API namesATTRIBUTE_MAPPING = {"Product name": "Productname__c","Model": "Model__c","Stage": "Stage__c","H.P.": "H_p__c","Price": "Price__c"}# List of product names to match42 unmodified linesreturn attributes# Function to interact with Salesforce and fetch detailsdef fetch_salesforce_details(attributes):try:sf = Salesforce(username=SALESFORCE_USERNAME,1 unmodified linesecurity_token=SALESFORCE_SECURITY_TOKEN)object_name = "Inventory_Management__c"product_field_name = "Productname__c"model_field_name = "Model__c"stage_field_name = "Stage__c"hp_field_name = "H_p__c"price_field_name = "Price__c"# Build query conditionsquery_conditions = [f"{product_field_name} = '{attributes.get('Product name', '')}'"]if "Model" in attributes and attributes["Model"]:query_conditions.append(f"{model_field_name} = '{attributes['Model']}'")if "Stage" in attributes and attributes["Stage"]:query_conditions.append(f"{stage_field_name} = '{attributes['Stage']}'")if "H.P." in attributes and attributes["H.P."]:query_conditions.append(f"{hp_field_name} = '{attributes['H.P.']}'")# Query Salesforcequery = f"SELECT {product_field_name}, {model_field_name}, {stage_field_name}, {hp_field_name}, {price_field_name} FROM {object_name} WHERE {' AND '.join(query_conditions)} LIMIT 1"response = sf.query(query)if response["records"]:record = response["records"][0]product_name = record.get(product_field_name, "N/A")model = record.get(model_field_name, "N/A")stage = record.get(stage_field_name, "N/A")hp = record.get(hp_field_name, "N/A")price = record.get(price_field_name, "N/A")# Return details as a formatted stringreturn (f"Details:\n"f"Product Name: {product_name}\n"f"Model: {model}\n"f"Stage: {stage}\n"f"H.P.: {hp}\n"f"Price: {price}")else:return "β No matching record found in Salesforce."except Exception as e:return f"β Error fetching data from Salesforce: {str(e)}"# Function to process image, extract attributes, and allow editingdef process_image(image, mode, entry_type, quantity):15 unmodified linesdf = pd.DataFrame(list(attributes.items()), columns=["Attribute", "Value"])return f"Extracted Text:\n{extracted_text}", df, None# Function to handle edited attributes and fetch Salesforce detailsdef export_to_salesforce(mode, entry_type, quantity, edited_df):try:# Convert edited DataFrame back to dictionaryedited_attributes = dict(zip(edited_df["Attribute"], edited_df["Value"]))# Fetch details from Salesforcedetails = fetch_salesforce_details(edited_attributes)return detailsexcept Exception as e:return f"β Error exporting to Salesforce: {str(e)}"# Gradio Interfacedef app():with gr.Blocks() as demo:9 unmodified linesok_button = gr.Button("OK")result_output = gr.Text(label="π Result")# Define button actionsextract_button.click(fn=process_image,5 unmodified linesinputs=[mode_input, entry_type_input, quantity_input, editable_df_output],outputs=[result_output])return demo1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787942 unmodified lines1221231241251261271281291301311321331 unmodified line13513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819915 unmodified lines2152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273289 unmodified lines3383393403413423433443453463473483493505 unmodified lines3563573583593603613623633643653661 unmodified linefrom 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 processimport kaleido# Attribute mappings: readable names to Salesforce API namesATTRIBUTE_MAPPING = {"Product name": "Productname__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","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","H.P.": "H_p__c"}# List of product names to match42 unmodified linesreturn 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, attributes):try:sf = Salesforce(username=SALESFORCE_USERNAME,1 unmodified linesecurity_token=SALESFORCE_SECURITY_TOKEN)object_name = Nonefield_name = Nonefield_names = []product_field_name = "Productname__c"model_field_name = "Model__c"stage_field_name = "Stage__c"hp_field_name = "H_p__c"if 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"field_names = ["Quantity_Sold__c", "soldstock__c"]elif entry_type == "Non-Sales":object_name = "Un_Billable__c"field_names = ["Sold_Out__c", "soldstock__c"]if not object_name or (not field_name and not field_names):return "Invalid mode or entry type."sf_object = sf.__getattr__(object_name)schema = sf_object.describe()valid_fields = {field["name"] for field in schema["fields"]}filtered_attributes = filter_valid_attributes(attributes, valid_fields)if mode == "Exit":query_conditions = [f"{product_field_name} = '{attributes['Product name']}'"]if "Model Name" in attributes and attributes["Model Name"]:query_conditions.append(f"{model_field_name} = '{attributes['Model Name']}'")if "Stage" in attributes and attributes["Stage"] != "":query_conditions.append(f"{stage_field_name} = '{attributes['Stage']}'")if "H.P." in attributes and attributes["H.P."]:query_conditions.append(f"{hp_field_name} = '{attributes['H.P.']}'")query = f"SELECT Id, {', '.join(field_names)} FROM {object_name} WHERE {' AND '.join(query_conditions)} LIMIT 1"response = sf.query(query)if response["records"]:record_id = response["records"][0]["Id"]updated_fields = {field: quantity for field in field_names}sf_object.update(record_id, updated_fields)return f"β Updated record for product '{attributes['Product name']}' in {object_name}. Updated fields: {updated_fields}."else:return f"β No matching record found for product '{attributes['Product name']}' in {object_name}."else: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 process image, extract attributes, and allow editingdef process_image(image, mode, entry_type, quantity):15 unmodified linesdf = pd.DataFrame(list(attributes.items()), columns=["Attribute", "Value"])return f"Extracted Text:\n{extracted_text}", df, None# Function to handle edited attributes and export to Salesforcedef export_to_salesforce(mode, entry_type, quantity, edited_df):try:# Convert edited DataFrame back to dictionaryedited_attributes = dict(zip(edited_df["Attribute"], edited_df["Value"]))# Export to Salesforcemessage = interact_with_salesforce(mode, entry_type, quantity, edited_attributes)# Fetch the price from Inventory_Management__c based on attributestry:sf = Salesforce(username=SALESFORCE_USERNAME,password=SALESFORCE_PASSWORD,security_token=SALESFORCE_SECURITY_TOKEN)product_name = edited_attributes.get("Product name", "")model_name = edited_attributes.get("Model Name", "")stage = edited_attributes.get("Stage", "")# Build the queryquery_conditions = []if product_name:query_conditions.append(f"Productname__c = '{product_name}'")if model_name:query_conditions.append(f"Model__c = '{model_name}'")if stage:query_conditions.append(f"Stage__c = '{stage}'")if query_conditions:query = f"SELECT Price__c FROM Inventory_Management__c WHERE {' AND '.join(query_conditions)} LIMIT 1"response = sf.query(query)if response["records"]:price = response["records"][0].get("Price__c", None)if price:price_message = f"The estimated price for the {product_name} with {model_name} at {stage} is βΉ{price:,}."return f"{message}\n\n{price_message}"else:return f"{message}\n\nPrice information not available for the specified product."else:return f"{message}\n\nNo matching record found for the specified product."else:return f"{message}\n\nInsufficient data to fetch price information."except Exception as e:return f"{message}\n\nError fetching price information: {str(e)}"except Exception as e:return f"β Error exporting to Salesforce: {str(e)}"import pytz# Function to pull structured data from Salesforce and display as a tabledef pull_data_from_salesforce(data_type):try:sf = Salesforce(username=SALESFORCE_USERNAME,password=SALESFORCE_PASSWORD,security_token=SALESFORCE_SECURITY_TOKEN)if data_type == "Inventory":query = "SELECT Productname__c, Model__c, H_p__c, Stage__c, Current_Stocks__c, soldstock__c, Price__c FROM Inventory_Management__c LIMIT 100"else:query = "SELECT Productname__c, Model__c, H_p__c, Stage__c, Current_Stock__c, soldstock__c, Price__c FROM Un_Billable__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={"Productname__c": "Product Name","Model__c": "Model","H_p__c": "H.P","Stage__c": "Stage","Current_Stocks__c": "Current Stocks","Current_Stock__c": "Current Stocks","soldstock__c": "Sold Stock","Price__c": "Price"}, 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")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 df, excel_path, imgexcept Exception as e:return f"Error fetching data: {str(e)}", None, None, None# Gradio Interfacedef app():with gr.Blocks() as demo:9 unmodified linesok_button = gr.Button("OK")result_output = gr.Text(label="π Result")with gr.Tab("π Salesforce Data"):data_type_input = gr.Dropdown(label="Select Data Type", choices=["Inventory", "Unbilling"], value="Inventory")pull_button = gr.Button("Pull Data from Salesforce")salesforce_data_output = gr.Dataframe(label="π Salesforce Data")excel_download_output = gr.File(label="π₯ Download Excel")graph_output = gr.Image(label="π Stock Distribution Graph")# Define button actionsextract_button.click(fn=process_image,5 unmodified linesinputs=[mode_input, entry_type_input, quantity_input, editable_df_output],outputs=[result_output])pull_button.click(fn=pull_data_from_salesforce,inputs=[data_type_input],outputs=[salesforce_data_output, excel_download_output, graph_output])return demo
app.py+232-43