Spaces:
Runtime error
Runtime error
Update app.py
Browse files1 unmodified line23456789101112131458 unmodified lines737475767778798081828384858687881 unmodified line9091929394954 unmodified lines1001011021031041053 unmodified lines1091101111121131141151161171 unmodified line11912012112212312423 unmodified lines1481491501511521531541551561578 unmodified lines1661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981993 unmodified lines2032042052062072081 unmodified line2102112122132142152162172185 unmodified lines2242252262272282292302312322332341 unmodified line2362372382392402412422432442452462472482492502512522534 unmodified lines2582592602612622632642655 unmodified lines2712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783791 unmodified linefrom paddleocr import PaddleOCRfrom PIL import Imageimport gradio as grimport refrom simple_salesforce import Salesforceimport pandas as pdimport matplotlib.pyplot as pltfrom io import BytesIOfrom fuzzywuzzy import processATTRIBUTE_MAPPING = {"Product name": "Productname__c","Colour": "Colour__c",58 unmodified lines"H.P.": "H_p__c"}PRODUCT_NAMES = ["Fusion", "Agroking", "CG commercial motors", "Jaguar", "Gaurav"]SALESFORCE_USERNAME = "venkataramanamotors@sales.com"SALESFORCE_PASSWORD = "Seta12345@"SALESFORCE_SECURITY_TOKEN = "2rIBKCRDlG47IkNDumDRV4jEv"ocr = PaddleOCR(use_angle_cls=True, lang='en')def 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 = 04 unmodified linesbest_score = scorereturn best_match if best_score >= 70 else Nonedef extract_attributes(extracted_text):attributes = {}for readable_attr, sf_attr in ATTRIBUTE_MAPPING.items():3 unmodified linesattributes[readable_attr] = match.group(1).strip()return attributesdef filter_valid_attributes(attributes, valid_fields):return {ATTRIBUTE_MAPPING[key]: value for key, value in attributes.items() if ATTRIBUTE_MAPPING[key] in valid_fields}def interact_with_salesforce(mode, entry_type, quantity, attributes):try:sf = Salesforce(1 unmodified linepassword=SALESFORCE_PASSWORD,security_token=SALESFORCE_SECURITY_TOKEN)object_name = Nonefield_name = Nonefield_names = []23 unmodified linessf_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"] != "":8 unmodified linesrecord_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)}"def process_image(image, mode, entry_type, quantity):extracted_text = extract_text(image)if not extracted_text:return "No text detected in the image.", None, Noneproduct_name = match_product_name(extracted_text)attributes = extract_attributes(extracted_text)if product_name:attributes["Product name"] = product_namefor fixed_attr in ["Stage", "H.P.", "Product name", "Model"]:if fixed_attr not in attributes:attributes[fixed_attr] = ""df = pd.DataFrame(list(attributes.items()), columns=["Attribute", "Value"])return f"Extracted Text:\n{extracted_text}", df, Nonedef export_to_salesforce(mode, entry_type, quantity, edited_df):try:edited_attributes = dict(zip(edited_df["Attribute"], edited_df["Value"]))message = interact_with_salesforce(mode, entry_type, quantity, edited_attributes)try:sf = Salesforce(username=SALESFORCE_USERNAME,3 unmodified linesproduct_name = edited_attributes.get("Product name", "")model_name = edited_attributes.get("Model Name", "")stage = edited_attributes.get("Stage", "")query_conditions = []if product_name:query_conditions.append(f"Productname__c = '{product_name}'")1 unmodified linequery_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:5 unmodified linesreturn 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)}"def pull_data_from_salesforce(data_type):try:sf = Salesforce(1 unmodified linepassword=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,Last_Modified_Date__c FROM Inventory_Management__c LIMIT 100"else:query = "SELECT Productname__c, Model__c, H_p__c, Stage__c, Current_Stock__c, soldstock__c, Last_Modified_Date__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')if "Last_Modified_Date__c" in df.columns:df["Last_Modified_Date__c"] = pd.to_datetime(df["Last_Modified_Date__c"]).dt.datedf.rename(columns={"Productname__c": "Product Name","Model__c": "Model",4 unmodified lines"soldstock__c": "Sold Stock","Last_Modified_Date__c": "Last Modified Date"}, inplace=True)excel_path = "salesforce_data.xlsx"df.to_excel(excel_path, index=False)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 df, excel_path, imgexcept Exception as e:return f"Error fetching data: {str(e)}", None, None, Nonedef app():with gr.Blocks(css="""body, html {background-color: #121212;color: white;font-family: Arial, sans-serif;margin: 0; padding: 20px;height: 100%;overflow: hidden;}.container {max-width: 1100px;margin: auto;background-color: #181818;padding: 25px;border-radius: 8px;height: 90vh;display: flex;flex-direction: column;}.content-area {flex-grow: 1;overflow-y: auto;padding-right: 10px;}.gr-button {background-color: #1f78b4;color: white;border-radius: 5px;border: none;padding: 10px 18px;font-weight: 600;margin-top: 15px;width: 100%;max-width: 250px;}.gr-button:hover {background-color: #145a86;}.gr-dataframe {background-color: #222;border-radius: 6px;border: 1px solid #444;padding: 10px;color: white !important;max-height: 300px;overflow-y: auto !important;}.gr-textbox textarea {font-family: monospace;background-color: #222;color: white;border-radius: 6px;border: 1px solid #444;max-height: 200px;overflow-y: auto;}.input-group {margin-bottom: 15px;}""") as demo:with gr.Column(elem_classes="container"):gr.Markdown("# π Seta Smart Inventory System")with gr.Row():with gr.Column(scale=5, min_width=350):image_input = gr.Image(type="numpy", label="π Upload Image")with gr.Column(scale=7, min_width=400):mode_input = gr.Dropdown(label="π Mode", choices=["Entry", "Exit"], value="Entry", elem_classes="input-group")entry_type_input = gr.Radio(label="π¦ Entry Type", choices=["Sales", "Non-Sales"], value="Sales", elem_classes="input-group")quantity_input = gr.Number(label="π’ Quantity", value=1, elem_classes="input-group")extract_button = gr.Button("Extract Text and Attributes")extracted_text_output = gr.Textbox(label="π Extracted Image Data", interactive=False, lines=10)editable_df_output = gr.Dataframe(label="βοΈ Edit Attributes (Key-Value Pairs)", interactive=True, wrap=True)ok_button = gr.Button("Export to Salesforce")result_output = gr.Textbox(label="π Result", interactive=False, lines=5)data_type_input = gr.Dropdown(label="Select Data Type", choices=["Inventory", "Unbilling"], value="Inventory", elem_classes="input-group")pull_button = gr.Button("Pull Data from Salesforce")salesforce_data_output = gr.Dataframe(label="π Salesforce Data", interactive=False, wrap=True)excel_download_output = gr.File(label="π₯ Download Excel")graph_output = gr.Image(label="π Stock Distribution Graph")extract_button.click(fn=process_image,inputs=[image_input, mode_input, entry_type_input, quantity_input],outputs=[extracted_text_output, editable_df_output, result_output])ok_button.click(fn=export_to_salesforce,inputs=[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 demoif __name__ == "__main__":1 unmodified line2345678910111213141516171858 unmodified lines77787980818283848586878889909192939495961 unmodified line98991001011021031044 unmodified lines1091101111121131141153 unmodified lines1191201211221231241251261271281291 unmodified line13113213313413513613723 unmodified lines1611621631641651661671681691701718 unmodified lines1801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262273 unmodified lines2312322332342352362372381 unmodified line2402412422432442452462472482492505 unmodified lines2562572582592602612622632642652662672682691 unmodified line2712722732742752762772782792802812822832842852862872882892902912922932942952964 unmodified lines3013023033043053063073083093103115 unmodified lines3173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544551 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 kaleidoimport pytz# Attribute mappings: readable names to Salesforce API namesATTRIBUTE_MAPPING = {"Product name": "Productname__c","Colour": "Colour__c",58 unmodified lines"H.P.": "H_p__c"}# List of product names to matchPRODUCT_NAMES = ["Fusion", "Agroking", "CG commercial motors", "Jaguar", "Gaurav"]# Salesforce credentialsSALESFORCE_USERNAME = "venkataramanamotors@sales.com"SALESFORCE_PASSWORD = "Seta12345@"SALESFORCE_SECURITY_TOKEN = "2rIBKCRDlG47IkNDumDRV4jEv"# 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 = 04 unmodified linesbest_score = scorereturn best_match if best_score >= 70 else None# Function to extract attributes and their valuesdef extract_attributes(extracted_text):attributes = {}for readable_attr, sf_attr in ATTRIBUTE_MAPPING.items():3 unmodified linesattributes[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, attributes):try:sf = Salesforce(1 unmodified linepassword=SALESFORCE_PASSWORD,security_token=SALESFORCE_SECURITY_TOKEN)object_name = Nonefield_name = Nonefield_names = []23 unmodified linessf_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.get('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"] != "":8 unmodified linesrecord_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.get('Product name', '')}' in {object_name}. Updated fields: {updated_fields}."else:return f"β No matching record found for product '{attributes.get('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):extracted_text = extract_text(image)if not extracted_text:return "No text detected in the image.", None, Noneproduct_name = match_product_name(extracted_text)attributes = extract_attributes(extracted_text)if product_name:attributes["Product name"] = product_name# Ensure fixed attributes are presentfor fixed_attr in ["Stage", "H.P.", "Product name", "Model"]:if fixed_attr not in attributes:attributes[fixed_attr] = ""# Convert attributes to DataFrame for editingdf = 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,3 unmodified linesproduct_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}'")1 unmodified linequery_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:5 unmodified linesreturn 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)}"# Function to pull structured data from Salesforce and display as a tabledef pull_data_from_salesforce(data_type):try:sf = Salesforce(1 unmodified linepassword=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,Last_Modified_Date__c FROM Inventory_Management__c LIMIT 100"else:query = "SELECT Productname__c, Model__c, H_p__c, Stage__c, Current_Stock__c, soldstock__c, Last_Modified_Date__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')# Format the Last_Modified_Date__c field to show only the dateif "Last_Modified_Date__c" in df.columns:df["Last_Modified_Date__c"] = pd.to_datetime(df["Last_Modified_Date__c"]).dt.date# Rename columns for better readabilitydf.rename(columns={"Productname__c": "Product Name","Model__c": "Model",4 unmodified lines"soldstock__c": "Sold Stock","Last_Modified_Date__c": "Last Modified Date"}, 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 df, excel_path, imgexcept Exception as e:return f"Error fetching data: {str(e)}", None, None, None# --- UI Components ---def inventory_ui():with gr.Row():with gr.Column(scale=1):image_input = gr.Image(type="numpy", label="π Upload Image")mode_input = gr.Dropdown(label="π Mode", choices=["Entry", "Exit"], value="Entry")entry_type_input = gr.Radio(label="π¦ Entry Type", choices=["Sales", "Non-Sales"], value="Sales")quantity_input = gr.Number(label="π’ Quantity", value=1, interactive=True)extract_button = gr.Button("Extract Text and Attributes")with gr.Column(scale=1):extracted_text_output = gr.Text(label="π Extracted Image Data")editable_df_output = gr.Dataframe(label="βοΈ Edit Attributes (Key-Value Pairs)", interactive=True)ok_button = gr.Button("OK")result_output = gr.Text(label="π Result")with gr.Row():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")# Wire up eventsextract_button.click(fn=process_image,inputs=[image_input, mode_input, entry_type_input, quantity_input],outputs=[extracted_text_output, editable_df_output, result_output])ok_button.click(fn=export_to_salesforce,inputs=[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 [image_input, mode_input, entry_type_input, quantity_input,extract_button, extracted_text_output, editable_df_output,ok_button, result_output, data_type_input, pull_button,salesforce_data_output, excel_download_output, graph_output]# Placeholders for other menu items (to be filled with your actual logic)def quote_management_ui():return gr.Markdown("## Quote Management\n\n_This section is under construction._")def quote_dashboards_ui():return gr.Markdown("## Quote Dashboards\n\n_This section is under construction._")def churn_customer_ui():return gr.Markdown("## Churn Customer\n\n_This section is under construction._")def reorder_ui():return gr.Markdown("## Reorder\n\n_This section is under construction._")def dashboards_ui():return gr.Markdown("## Dashboards\n\n_This section is under construction._")# Main app with sidebar menudef app():with gr.Blocks() as demo:with gr.Row():# Sidebar menu columnwith gr.Column(scale=1, min_width=200):menu = gr.Radio(choices=["Inventory", "Quote Management", "Quote Dashboards", "Churn Customer", "Reorder", "Dashboards"],label="π Menu",value="Inventory",interactive=True)# Content area columnwith gr.Column(scale=4):inventory_container = gr.Column(visible=True)quote_mgmt_container = gr.Column(visible=False)quote_dash_container = gr.Column(visible=False)churn_customer_container = gr.Column(visible=False)reorder_container = gr.Column(visible=False)dashboards_container = gr.Column(visible=False)# Inventory UI containerwith inventory_container:(image_input, mode_input, entry_type_input, quantity_input,extract_button, extracted_text_output, editable_df_output,ok_button, result_output, data_type_input, pull_button,salesforce_data_output, excel_download_output, graph_output) = inventory_ui()# Other UI containerswith quote_mgmt_container:quote_management_ui()with quote_dash_container:quote_dashboards_ui()with churn_customer_container:churn_customer_ui()with reorder_container:reorder_ui()with dashboards_container:dashboards_ui()# Callback to switch visible container based on menu selectiondef switch_tab(tab_name):return [tab_name == "Inventory",tab_name == "Quote Management",tab_name == "Quote Dashboards",tab_name == "Churn Customer",tab_name == "Reorder",tab_name == "Dashboards",]menu.change(fn=switch_tab,inputs=menu,outputs=[inventory_container,quote_mgmt_container,quote_dash_container,churn_customer_container,reorder_container,dashboards_container])return demoif __name__ == "__main__":
app.py+176-100