"""# Importing the libraries""" import numpy as np import pandas as pd import tensorflow as tf from sklearn.preprocessing import LabelEncoder import matplotlib.pyplot as plt import gradio as gr import keras_tuner as kt """# Declaring Constants""" """# Importing the dataset""" # Load the CPQ data df = pd.read_csv('cpq_sample_output_extended.csv') """# Selecting Features And Target Variable""" # MISSING PARAM 1: One-Time Methodology (Price Based / Margin Based) | Values = {Price,Margin} - may require label encoding # MISSING PARAM 2: Recurring Methodology (Price Based / Margin Based) | Values = {Price/Margin} - may require label encoding # MISSING PARAM 3: Amortization Enabled | Values = {Yes,No} - may require label encoding # Convert date columns to datetime df['QuoteDate'] = pd.to_datetime(df['QuoteDate'], format='%d/%m/%Y') df['ExpirationDate'] = pd.to_datetime(df['ExpirationDate'], format='%d/%m/%Y') # Handle missing values (if any) df = df.dropna() # Create additional features (e.g., quote duration) df['QuoteDuration'] = (df['ExpirationDate'] - df['QuoteDate']).dt.days df['BillingFrequencyID'] = df['BillingFrequencyID'].astype(int) # Select features and target variable features = df[['ProductID', 'Quantity', 'UnitCost', 'Recurring Cost', 'DiscountPerc', 'SalesTaxPerc', 'LocationID', 'QuoteDuration', 'BillingFrequencyID']] #le = LabelEncoder() #features['BillingFrequency'] = le.fit_transform(features['BillingFrequency']) target = df[['UnitPrice', 'Recurring Price']] # Two target variables # Convert percentages to numeric features['DiscountPerc'] = features['DiscountPerc'].str.rstrip('%').astype('float') / 100.0 features['SalesTaxPerc'] = features['SalesTaxPerc'].str.rstrip('%').astype('float') / 100.0 """# Splitting the dataset into the Training set and Test set""" from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(features, target, test_size = 0.2, random_state = 10) """# Feature Scaling""" from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) """# Loading the Model + Weights""" # Recreate the same model, including its weights and the optimizer ann = tf.keras.models.load_model('my_model.keras') ann.build() """# Predict""" y_pred = ann.predict(X_test) # Retrieve QuoteIDs quote_ids = df.iloc[y_test.index]['QuoteID'].values # Create a DataFrame with actual and predicted prices results_df = pd.DataFrame({'QuoteID': quote_ids, 'ProductID': df.iloc[y_test.index]['ProductID'], 'Actual Price': y_test.iloc[:,0].values, 'Pricing Engine Price': y_pred[:, 0].flatten(), 'Actual Recurring Price': y_test.iloc[:,1].values, 'Pricing Engine Recurring Price': y_pred[:, 1].flatten()}) # Create a CSV file results_df.to_csv('actual_vs_predicted_prices.csv', index=False) def add_product(product_id, quantity, unit_cost, unit_price, recurring_cost, recurring_price, discount_pc, salestax_pc, location, quote_duration, billing_freq, products): """ Adds a product to the list of products. Args: product_id: product_id, quantity: quantity, unit_cost: unit_cost, unit_price: unit_price, recurring_cost: recurring_cost, recurring_price: recurring_price, discount_pc: discount_pc, salestax_pc: salestax_pc, location: location, quote_duration: quote_duration, billing_freq: billing_freq, products: products Returns: products: list of dictionaries containing product information """ products.append({ "productid": product_id, "quantity": quantity, "unit_cost": unit_cost, "unit_price": unit_price, "recurring_cost": recurring_cost, "recurring_price": recurring_price, "discount_pc": discount_pc, "salestax_pc": salestax_pc, "location": location, "quote_duration": quote_duration, "billing_freq": billing_freq }) return products def predict_price(products): """ Predicts the price of a product based on the input features. Args: products: list of dictionaries containing product information Returns: str: A predicted price """ total_price = 0 predicted_prices_with_names = [] # List to store predicted prices with names all_input_data = [] # List to store all input data for product in products: # Extract individual product information product_id = product["productid"] quantity = product["quantity"] unit_cost = product["unit_cost"] unit_price = product["unit_price"] recurring_cost = product["recurring_cost"] recurring_price = product["recurring_price"] discount_pc = product["discount_pc"] salestax_pc = product["salestax_pc"] loc_id = product["location"] quote_duration = product["quote_duration"] billing_freq_id = product["billing_freq"] discount_pc = discount_pc / 100 salestax_pc = salestax_pc / 100 # Create input features as a DataFrame input_data = pd.DataFrame({ 'ProductID': [product_dict[product_id]], 'Quantity': [quantity], 'UnitCost': [unit_cost], #'UnitPrice': [unit_price], 'Recurring Cost': [recurring_cost], #'Recurring Price': [recurring_price], 'DiscountPerc': [discount_pc], 'SalesTaxPerc': [salestax_pc], 'LocationID': [location_dict[loc_id]], 'QuoteDuration': quote_duration_dict[quote_duration], 'BillingFrequencyID': [billingfreq_dict[billing_freq_id]] }) final_price = unit_price * quantity final_recurring_price = recurring_price * quantity # Apply feature scaling input_data = sc.transform(input_data) # Make the prediction for the individual product individual_predicted_prices = ann.predict(input_data)[0] unit_price_pred = individual_predicted_prices[0] # Access UnitPrice prediction recurring_price_pred = individual_predicted_prices[1] # Access Recurring Price prediction # Get the product name product_name = product["productid"] # "productid" stores the name # Store predicted price with product name predicted_prices_with_names.append((final_price, final_recurring_price, product_name, individual_predicted_prices)) # Add to the total price (You can use individual_predicted_price or final_price here) - Can be Quote price #total_price += individual_predicted_price # Create output string with individual and total prices #output_html = f"

Total Predicted Price: {total_price:.2f}

" # Create a heading output_html = "

Predicted Prices Vs Actual Prices

" # Add heading # Create div layout instead of table output_html += "
" for final_price, final_recurring_price, product_name, price in predicted_prices_with_names: output_html += f"
" output_html += f"
{product_name}
" output_html += f"
Unit Price: {final_price:.2f}
" output_html += f"
Recurring Unit Price: {final_recurring_price:.2f}
" output_html += f"
---------Prediction---------
" output_html += f"
Predicted Unit Price: {price[0]:.2f}
" output_html += f"
Predicted Recurring Price: {price[1]:.2f}
" output_html += "
" # Close product div output_html += "
" # Close container div # Add some basic CSS for styling output_html += """ """ return output_html product_dict = dict(zip(df['ProductName'], df['ProductID'])) product_options = sorted(list(product_dict.keys())) location_dict = dict(zip(df['Location'], df['LocationID'])) location_options = sorted(list(location_dict.keys())) # Display names in the dropdown billingfreq_dict = dict(zip(df['BillingFrequency'], df['BillingFrequencyID'])) billingfreq_options = sorted(list(billingfreq_dict.keys())) #quote_duration_options_list = sorted(df['QuoteDuration'].unique().tolist()) #quote_duration_options = {str(duration) + " days": duration for duration in quote_duration_options_list} quote_duration_dict = dict(zip(df['QuoteDuration'], df['QuoteDuration'])) quote_duration_options = sorted(list(quote_duration_dict.keys())) def validate_quantity(quantity): """Ensures quantity is non-negative.""" if quantity < 0: return gr.update(value=0, visible=True) # Reset to 0 if negative else: return gr.update(visible=True) # No change if non-negative #description interface def create_desc_interface(): with gr.Blocks(): with gr.Row(): gr.HTML("""

This app delivers an AI-powered pricing engine that automates and optimizes your CPQ (Configure, Price, Quote) process. It empowers your sales teams to generate accurate and profitable quotes quickly, leading to:


Business Impact


""") def create_codedesc_interface(): with gr.Blocks(): with gr.Row(): gr.HTML("""

Functionality:

The code builds an AI-powered pricing engine for CPQ (Configure, Price, Quote) processes, using an Artificial Neural Network (ANN) to predict optimal product prices.

Key Steps:


Artificial Neural Network Architecture used In the App

""") with gr.Row(): # Format the 'Pricing Engine Price' column formatted_results_df = results_df.copy() # Create a copy to avoid modifying the original DataFrame formatted_results_df['Pricing Engine Price'] = formatted_results_df['Pricing Engine Price'].apply(lambda x: f'{x:.2f}') #Sort the dateframe formatted_results_df = formatted_results_df.sort_values(by=['QuoteID']) # Display the DataFrame as a Gradio table gr.DataFrame(value=formatted_results_df, headers=formatted_results_df.columns.tolist(), label="Prediced Results On Training Data") #pricing interface def create_pricing_interface(): with gr.Blocks(): # State variable to store the products products = gr.State([]) with gr.Row(): with gr.Column(): # Display static Quote Number gr.Textbox(label="Quote Number", value="QUO-007873-06") with gr.Row(): with gr.Column(): # Product selection and input fields product_dropdown_input = gr.Dropdown(choices=product_options, label="Product", value=product_options[0]) quantity_input = gr.Number(label="Quantity", value=1, interactive=False) unit_cost_input = gr.Number(label="Unit Cost", value=100) unit_price_input = gr.Number(label="Unit Price", value=110) recurring_cost_input = gr.Number(label="Recurring Cost", value=200) recurring_price_input = gr.Number(label="Recurring Price", value=250) discount_perc_input = gr.Slider(minimum=0, maximum=100, step=1, label="Discount %", value=10) salestax_perc_input = gr.Slider(minimum=0, maximum=100, step=1, label="Sales Tax %", value=10) location_input = gr.Dropdown(choices=location_options, label="Quote Location",value=location_options[0]) quoteduration_input = gr.Dropdown(choices=quote_duration_options, label="Quote Duration", value=quote_duration_options[0]) billfreq_input = gr.Dropdown(choices=billingfreq_options, label="Billing Frequency",value=billingfreq_options[0]) # Button to add the product to the list add_btn = gr.Button("Add Product") with gr.Column(): # Display the products as a JSON or a custom component products_display = gr.JSON(label="Selected Product(s)") # Or use a custom component # Button to trigger prediction predict_btn = gr.Button("Predict Price(s)") # Output component for predicted prices (placed below the button) predicted_prices_output = gr.HTML(label="Predicted Prices") # Event handler for adding a product add_btn.click( add_product, inputs=[product_dropdown_input, quantity_input, unit_cost_input, unit_price_input, recurring_cost_input, recurring_price_input, discount_perc_input, salestax_perc_input, location_input, quoteduration_input, billfreq_input, products], outputs=products, # Update 'products' state ) # Event handler for prediction predict_btn.click( predict_price, inputs=products, outputs=predicted_prices_output, ) # Event handler to update the products display products.change( fn=lambda x: x, # Identity function to pass the updated products inputs=products, outputs=products_display, ) # Create the main Blocks for the entire interface with gr.Blocks() as demo: with gr.Row(): gr.HTML("""

Optimal Pricing Engine - AI Powered Pricing for Perfect Quotes

""") with gr.Row(): gr.HTML("""

Leveraging AI and deep learning, quotes are optimized for intelligent pricing

""") with gr.Row(): with gr.Tabs(): # Details tab with gr.TabItem("About App"): # Call the function to create the pricing interface iface_desc = create_desc_interface() # Details tab with gr.TabItem("Technical Summary"): # Call the function to create the code desc interface iface_codedesc = create_codedesc_interface() # AI Pricing tab with gr.TabItem("AI Pricing"): # Content for the AI Pricing tab (iface_pricing) iface_pricing = create_pricing_interface() # Assuming you have the create_pricing_interface function """# Run Gradio App Demo""" demo.title = "Optimal Pricing Engine - AI-Powered Pricing for Perfect Quotes" #demo.launch(favicon_path='https://www.iconarchive.com/download/i99476/webalys/kameleon.pics/Money-Graph.ico') if __name__ == "__main__": demo.launch(theme="lone17/kotaemon", mcp_server=True)