Spaces:
Build error
Build error
Download app.py from Vicky009/Pricing-Engine: direct link, hf CLI and curl.
- Browser
- Download file 20.7 kB
-
https://huggingface.co/spaces/Vicky009/Pricing-Engine/resolve/main/app.py
- Command line
-
hf download hf://spaces/Vicky009/Pricing-Engine/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Vicky009/Pricing-Engine/resolve/main/app.py
20.7 kB
| """# 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"<p><b>Total Predicted Price: {total_price:.2f}</b></p>" | |
| # Create a heading | |
| output_html = "<h2>Predicted Prices Vs Actual Prices</h2>" # Add heading | |
| # Create div layout instead of table | |
| output_html += "<div class='container'>" | |
| for final_price, final_recurring_price, product_name, price in predicted_prices_with_names: | |
| output_html += f"<div class='product'>" | |
| output_html += f"<div class='product-name'>{product_name}</div>" | |
| output_html += f"<div class='final-price'>Unit Price: {final_price:.2f}</div>" | |
| output_html += f"<div class='final-price'>Recurring Unit Price: {final_recurring_price:.2f}</div>" | |
| output_html += f"<div class='final-price'>---------<b>Prediction</b>---------</div>" | |
| output_html += f"<div class='predicted-price'>Predicted Unit Price: {price[0]:.2f}</div>" | |
| output_html += f"<div class='predicted-price'>Predicted Recurring Price: {price[1]:.2f}</div>" | |
| output_html += "</div>" # Close product div | |
| output_html += "</div>" # Close container div | |
| # Add some basic CSS for styling | |
| output_html += """ | |
| <style> | |
| .container { | |
| display: flex; | |
| flex-wrap: wrap; | |
| } | |
| .product { | |
| border: 1px solid #7BC039; | |
| border-radius: 5px; | |
| padding: 10px; | |
| margin: 5px; | |
| width: 200px; /* Adjust width as needed */ | |
| } | |
| .product-name { | |
| font-weight: bold; | |
| } | |
| </style> | |
| """ | |
| 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(""" | |
| <style> | |
| @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap'); | |
| .tab-content p { /* Replace with the correct selector */ | |
| font-family: 'Roboto', sans-serif; /* Replace with your desired font - sans-serif */ | |
| } | |
| </style> | |
| <div class="tab-content"> | |
| <p><b>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:</b></p> | |
| <ul style="list-style-type: disc; padding-left: 40px;"> | |
| <li><b>Increased efficiency: </b> Sales reps can focus on selling instead of manually calculating prices. This leads to faster quote turnaround times and potentially closing deals more quickly.</li> | |
| <li><b>Improved accuracy: </b>The AI model, trained on your historical data, predicts prices with greater precision than traditional methods. This reduces errors and ensures consistent pricing across your sales organization.</li> | |
| <li><b>Enhanced profitability: </b>The system optimizes pricing strategies by considering a wide range of factors, including product costs, market dynamics, and customer behavior. This helps you identify optimal price points to maximize profit margins.</li> | |
| <li><b>Better customer experience: </b>Faster and more accurate quotes create a smoother and more satisfying buying experience for your customers.</li> | |
| <li><b>Data-driven insights: </b>The AI model provides valuable insights into pricing patterns and customer preferences, which can inform your overall sales and product strategies.</li> | |
| </ul> | |
| <br/> | |
| <p><b>Business Impact</b></p> | |
| <ul style="list-style-type: disc; padding-left: 40px;"> | |
| <li><b>Reduced sales cycle times: </b>Faster quote generation and approval processes lead to shorter sales cycles.</li> | |
| <li><b>Increased win rates: </b>Accurate and optimized pricing improves your competitiveness and increases the likelihood of closing deals.</li> | |
| <li><b>Higher profit margins: </b>The system helps you identify and implement profitable pricing strategies.</li> | |
| <li><b>Greater sales team productivity: </b>Automated pricing frees up sales reps to focus on selling and building relationships.</li> | |
| </ul> | |
| <br/> | |
| </div> | |
| """) | |
| def create_codedesc_interface(): | |
| with gr.Blocks(): | |
| with gr.Row(): | |
| gr.HTML(""" | |
| <style> | |
| @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap'); | |
| .tab-content p { /* Replace with the correct selector */ | |
| font-family: 'Roboto', sans-serif; /* Replace with your desired font - sans-serif */ | |
| } | |
| </style> | |
| <div class="tab-content"> | |
| <p><strong>Functionality:</strong></p> | |
| <p>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.</p> | |
| <p><strong>Key Steps:</strong></p> | |
| <ul style="list-style-type: disc; padding-left: 40px;"> | |
| <li><strong>Setup:-</strong> Installs required libraries (<code>gradio</code>, <code>tensorflow</code>, <code>keras-tuner</code>), etc.</li> | |
| <li><strong>CPQ Data:-</strong> Loads CPQ data, cleans it, engineers features, and splits it into training and testing sets.</li> | |
| <li><strong>Model:-</strong> Defines and trains ANN model using TensorFlow/Keras, uses <code>keras-tuner</code> to find optimal hyperparameters.</li> | |
| <li><strong>Prediction:-</strong> Predicts prices on the test data.</li> | |
| <li><strong>Saving/Loading:-</strong> Saves and loads the trained model's weights for reusability.</li> | |
| <li><strong>Finally:-</strong> Automates and optimizes the pricing process for increased efficiency and profitability.</li> | |
| </ul> | |
| </div> | |
| <br> | |
| <div class="tab-content"> | |
| <p><b>Artificial Neural Network Architecture used In the App</b></p> | |
| <!-- img src="https://huggingface.co/spaces/Vicky009/Assets/blob/main/ANN.svg"/> --> | |
| <img src="/ANN.svg"/> | |
| </div> | |
| """) | |
| 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(""" | |
| <style> | |
| @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap'); | |
| body { | |
| font-family: 'Roboto', sans-serif; | |
| } | |
| h1 { | |
| font-size: 24px; | |
| color: #7BC039; /* Example color */ | |
| } | |
| h2 { | |
| font-size: 16px; | |
| color: #7BC039; /* Example color */ | |
| background: #7BC039; | |
| padding: 5px; | |
| border-radius: 5px; | |
| text-align: center; | |
| } | |
| .container { | |
| display: flex; | |
| flex-wrap: wrap; | |
| } | |
| } | |
| </style> | |
| <div style="display: flex; align-items: center; justify-content: center;"> | |
| <img src="https://icons.iconarchive.com/icons/webalys/kameleon.pics/48/Money-Graph-icon.png" width="48" height="48" style="margin-right: 10px;"> | |
| <div> | |
| <h1>Optimal Pricing Engine - AI Powered Pricing for Perfect Quotes</h1> | |
| </div> | |
| </div> """) | |
| with gr.Row(): | |
| gr.HTML(""" | |
| <div> | |
| <h2>Leveraging AI and deep learning, quotes are optimized for intelligent pricing</h2> | |
| </div> """) | |
| 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) | |