Spaces:
Build error
Build error
Update app.py
Browse files9 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106131415161711111211311411511611711811918192021223 unmodified lines26272812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815929303132333435361661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372383738240241242243244394024624724841424344252253254255256257258259260261262263264265266267268269270271272273274275276277278454647280484950515253545556575859606162636465666768697071288289290291292293294295296297298299300301302303727374753063077677787931031180818283314315843173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324338586874364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834848889909192939495969798991001011021031041051061071081091101111121131141151161171181194874884894901209 unmodified linesfrom io import BytesIOfrom fuzzywuzzy import process
#π 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"}
# 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 credentials# Salesforce credentialsSALESFORCE_USERNAME = "venkatramana@sandbox.com"SALESFORCE_PASSWORD = "Venkat12345@"SALESFORCE_SECURITY_TOKEN = "GhcJJmjBEefdnukJoz4CAQlR"
#π§ Initialize PaddleOCRocr = PaddleOCR( use_angle_cls=False, # Disable angle classification to reduce memory lang='en', det_model_dir=None, rec_model_dir=None, cls_model_dir=None)
# Initialize PaddleOCRocr = PaddleOCR(use_angle_cls=True, lang='en')
# Function to extract text using PaddleOCRdef extract_text(image):3 unmodified lines extracted_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 = None best_score = 0
for line in extracted_text.split("\n"): match, score = process.extractOne(line, PRODUCT_NAMES) if score > best_score: best_match = match best_score = score
return 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):# Function to fetch data from Salesforce and format it into a DataFramedef fetch_salesforce_data(): try: sf = Salesforce( username=SALESFORCE_USERNAME, password=SALESFORCE_PASSWORD, security_token=SALESFORCE_SECURITY_TOKEN )
# Mapping mode and entry_type to Salesforce object and field object_name = None field_name = None product_field_name = "Product_Name__c" # Correct field for product name in the object model_field_name = "Modal_Name__c" # Correct field for model name in the object
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" 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 object sf_object = sf.__getattr__(object_name) schema = sf_object.describe() valid_fields = {field["name"] for field in schema["fields"]}
# Extract product name or model number product_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_name
if 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 add sf_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] = quantity sf_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 Salesforcedef pull_data_from_salesforce(): try: sf = Salesforce( username=SALESFORCE_USERNAME, password=SALESFORCE_PASSWORD, security_token=SALESFORCE_SECURITY_TOKEN ) query = "SELECT Product_Name__c, Modal_Name__c, Current_Stocks__c FROM Inventory_Management__c LIMIT 100" query = "SELECT Product_Name__c, Modal_Name__c, Current_Stocks__c FROM MotorDataAPI__c" response = sf.query_all(query) records = response.get("records", []) if not records: return "No data found in Salesforce.", None, None, None records = response["records"] df = pd.DataFrame(records) df = df.drop(columns=['attributes'], errors='ignore') df.rename(columns={ df = df.rename(columns={ "Product_Name__c": "Product Name", "Modal_Name__c": "Model Name", "Current_Stocks__c": "Current Stocks" }, inplace=True) excel_path = "salesforce_data.xlsx" df.to_excel(excel_path, index=False) # Generate interactive bar graph using Plotly fig = go.Figure() fig.add_trace(go.Bar( x=df['Product Name'], y=df['Current Stocks'], marker=dict(color='blue'), hoverinfo='x+y', hovertemplate='<b>Product Name:</b> %{x}<br><b>Current Stocks:</b> %{y}<extra></extra>', text=df['Current Stocks'], textposition='outside' )) fig.update_layout( title="Current Stocks of Products", xaxis=dict(title="Product Name", tickangle=-45), yaxis=dict(title="Stock Quantity"), hovermode='x', dragmode='zoom', showlegend=False ) return "Data successfully retrieved.", df, excel_path, fig }) return df[["Product Name", "Model Name", "Current Stocks"]] except Exception as e: return f"Error fetching data: {str(e)}", None, None, None return None
# Function to generate a bar graph from Salesforce datadef generate_salesforce_bar_chart(df): try: plt.figure(figsize=(12, 6)) df.plot(kind='bar', x="Product Name", y="Current Stocks", legend=False) plt.title("Stock Distribution by Product Name") plt.xlabel("Product Name") plt.ylabel("Current Stocks") plt.xticks(rotation=45, ha="right") plt.tight_layout() buffer = BytesIO() plt.savefig(buffer, format="png") buffer.seek(0) return Image.open(buffer) except 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.", None
product_name = match_product_name(extracted_text) attributes = extract_attributes(extracted_text) if product_name: attributes["Product name"] = product_name
# Interact with Salesforce message = 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
import gradio as grimport numpy as npfrom PIL import Image return f"Extracted Text:\n{extracted_text}\n\nProcessing Completed.", None
# Function to fetch and return Salesforce datadef generate_salesforce_data(): df = format_salesforce_data()def get_salesforce_visualization(): df = fetch_salesforce_data() if df is not None: table_component = df.to_html(index=False) bar_graph_image = generate_bar_graph(df) return table_component, bar_graph_image bar_chart_image = generate_salesforce_bar_chart(df) return table_component, bar_chart_image return "<p>No Data Available</p>", None
import gradio as gr
def app(): with gr.Blocks(css=""" /* General Styling */ .gradio-container { background: #0b0f29; /* Deep Dark Blue */ font-family: 'Poppins', sans-serif; color: white; padding: 10px; }
h1, h2, h3 { text-align: center; color: white; font-weight: bold; text-shadow: 0px 0px 10px rgba(255,255,255,0.8); }
/* Cards & Elements */ .card { background: rgba(255, 255, 255, 0.1); border-radius: 15px; padding: 20px; width: 100%; max-width: 900px; margin: auto; box-shadow: 0px 0px 25px rgba(0, 255, 255, 0.6); transition: 0.3s; }
.card:hover { box-shadow: 0px 0px 30px rgba(0, 255, 255, 0.9); }
/* Buttons */ .gradio-button { background: linear-gradient(to right, #ff416c, #ff4b2b); color: white !important; border-radius: 10px !important; font-weight: bold; padding: 12px; transition: all 0.3s ease-in-out; box-shadow: 0px 0px 20px rgba(255, 0, 255, 0.6); }
.gradio-button:hover { background: linear-gradient(to right, #ff4b2b, #ff416c); box-shadow: 0px 0px 30px rgba(255, 0, 255, 0.9); }
/* Tabs */ .gradio-tab { font-size: 16px; color: white; font-weight: bold; text-shadow: 0px 0px 10px rgba(255, 255, 255, 0.6); }
/* Scrollable Table */ .table-container { width: 100%; max-width: 900px; max-height: 400px; overflow-y: auto; overflow-x: auto; display: flex; justify-content: center; margin: auto; }
table { width: 100%; border-collapse: collapse; background: rgba(255, 255, 255, 0.1); color: white; min-width: 600px; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid rgba(255, 255, 255, 0.2); font-size: 14px; }
th { background: rgba(0, 255, 255, 0.2); }
/* Mobile View */ @media (max-width: 768px) { .gradio-container { padding: 10px; }
.card { width: 100%; max-width: 100%; padding: 10px; }
.table-container { max-height: 350px; overflow-y: scroll; }
table { width: 100%; min-width: 100%; }
th, td { font-size: 12px; padding: 8px; } }
""") as interface:
with gr.Blocks() as interface: gr.Markdown("<h1>π’ VENKATARAMANA MOTORS</h1>")
# Tabbed Interface interface = gr.TabbedInterface( [ # Tab 1: Stock Entry & Processing gr.Interface( fn=process_image, # Replace with your actual function inputs=[ gr.Image(type="numpy", label="π Upload Image", elem_classes="card"), gr.Dropdown(label="π Mode", choices=["Entry", "Exit"], value="Entry", elem_classes="card"), gr.Radio(label="π¦ Entry Type", choices=["Sales", "Non-Sales"], value="Sales", elem_classes="card"), gr.Number(label="π’ Quantity", value=1, interactive=True, elem_classes="card"), ], outputs=[ gr.Text(label="π Image Data Viewer", interactive=False, elem_classes="card"), gr.Text(label="π Processed Result", interactive=False, elem_classes="card"), ], title="Stock Entry & Processing", description="Upload an image to extract product details and update Salesforce." ),
# Tab 2: Salesforce Data Visualization gr.Interface( fn=pull_data_from_salesforce, # Replace with your actual function inputs=[], outputs=[ gr.Text(label="Status", elem_classes="card"), gr.Dataframe(label="Sales Data Table", elem_classes="card"), gr.File(label="Download Salesforce Data", elem_classes="card"), gr.Plot(label="Stock Distribution Bar Graph", elem_classes="card"), ], title="Salesforce Data Visualization", description="View, visualize, and download Salesforce data (Product Name, Model Name, Current Stocks)." ) ], ["Stock Entry & Processing", "Salesforce Data Visualization"] )
return interfaceimport gradio as gr
def sample_function(input_text): return f"Processed: {input_text}"
with gr.Blocks() as app: gr.Markdown("## My Gradio App") input_box = gr.Textbox(label="Enter something") output_box = gr.Textbox(label="Output") button = gr.Button("Submit") button.click(sample_function, inputs=input_box, outputs=output_box) with gr.Tab("π₯ Stock Entry & Processing"): with gr.Row(): with gr.Column(): gr.Markdown("<h3>π Upload & Process</h3>") image_input = gr.Image(type="numpy", label="π Upload Image") mode_dropdown = gr.Dropdown(label="π Mode", choices=["Entry", "Exit"], value="Entry") entry_type_radio = gr.Radio(label="π¦ Entry Type", choices=["Sales", "Non-Sales"], value="Sales") quantity_input = gr.Number(label="π’ Quantity", value=1, interactive=True) with gr.Column(): gr.Markdown("<h3>π Processed Data</h3>") image_view = gr.Text(label="π Image Data Viewer", interactive=False) result_output = gr.Text(label="π Processed Result", interactive=False) submit_button = gr.Button("π Process Image")
with gr.Tab("π Salesforce Data Overview"): gr.Markdown("<h3>π Stock Table</h3>") with gr.Row(): salesforce_table = gr.HTML(label="π¦ Salesforce Data Table")
gr.Markdown("<h3>π Inventory Analytics</h3>") with gr.Row(): salesforce_graph = gr.Image(type="pil", label="π Stock Distribution Bar Graph") generate_button = gr.Button("β‘ Generate Data")
generate_button.click(fn=get_salesforce_visualization, inputs=[], outputs=[salesforce_table, salesforce_graph]) submit_button.click(fn=process_image, inputs=[image_input, mode_dropdown, entry_type_radio, quantity_input], outputs=[image_view, result_output]) return interface
if __name__ == "__main__": app.launch(server_name="0.0.0.0", server_port=7860, share=True)
app().launch(share=True)app.py+65-435