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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from prophet import Prophet
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import requests
|
| 7 |
+
|
| 8 |
+
# Securely load the API key from Hugging Face Secrets
|
| 9 |
+
API_KEY = os.environ.get("GOOGLE_API_KEY")
|
| 10 |
+
LLM_LOADED = bool(API_KEY)
|
| 11 |
+
|
| 12 |
+
def create_cases_data():
|
| 13 |
+
"""Creates a dummy CSV with customer case data."""
|
| 14 |
+
cases_data = {
|
| 15 |
+
'case_id': [101, 102],
|
| 16 |
+
'customer_name': ['Rohan Gupta', 'Priya Sharma'],
|
| 17 |
+
'customer_query': [
|
| 18 |
+
"The Leather care conditioner 500 ml I ordered (Order #404-7654321-1234567) just arrived, but the bottle is leaking. I want a replacement.",
|
| 19 |
+
"Hi, my order for the Cockpit Cleaner Matt 500 ml (Order #404-1234567-9876543) was supposed to be delivered yesterday, but the tracking says it's delayed. Where is it?"
|
| 20 |
+
],
|
| 21 |
+
'order_number': ['404-7654321-1234567', '404-1234567-9876543'],
|
| 22 |
+
'item_name': ['Leather care conditioner 500 ml', 'Cockpit Cleaner Matt 500 ml'],
|
| 23 |
+
'order_status': ['Delivered', 'Shipped']
|
| 24 |
+
}
|
| 25 |
+
df_cases = pd.DataFrame(cases_data)
|
| 26 |
+
df_cases.to_csv('customer_cases.csv', index=False)
|
| 27 |
+
|
| 28 |
+
create_cases_data()
|
| 29 |
+
|
| 30 |
+
# === USE CASE 1: Future Sales Prediction ===
|
| 31 |
+
def predict_future_sales(sku_choice):
|
| 32 |
+
if not sku_choice:
|
| 33 |
+
return "Please select a SKU."
|
| 34 |
+
|
| 35 |
+
df_sales = pd.read_csv('dummy_sales_history.csv')
|
| 36 |
+
df_sku = df_sales[df_sales['sku'] == sku_choice]
|
| 37 |
+
|
| 38 |
+
if df_sku.empty:
|
| 39 |
+
return f"No sales data could be found for '{sku_choice}'. Please check the CSV file."
|
| 40 |
+
|
| 41 |
+
df_sku = df_sku.rename(columns={'date': 'ds', 'units_sold': 'y'})
|
| 42 |
+
df_sku['ds'] = pd.to_datetime(df_sku['ds'])
|
| 43 |
+
|
| 44 |
+
model_prophet = Prophet(daily_seasonality=False, weekly_seasonality=True, yearly_seasonality=True)
|
| 45 |
+
model_prophet.fit(df_sku)
|
| 46 |
+
future = model_prophet.make_future_dataframe(periods=30)
|
| 47 |
+
forecast = model_prophet.predict(future)
|
| 48 |
+
|
| 49 |
+
thirty_day_forecast = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(30)
|
| 50 |
+
total_sales = int(thirty_day_forecast['yhat'].sum())
|
| 51 |
+
lower_bound = int(thirty_day_forecast['yhat_lower'].sum())
|
| 52 |
+
upper_bound = int(thirty_day_forecast['yhat_upper'].sum())
|
| 53 |
+
|
| 54 |
+
return f"Predicted sales for **{sku_choice}** in the next 30 days: **{total_sales} units**.\nPrediction Range: *{lower_bound} to {upper_bound} units*."
|
| 55 |
+
|
| 56 |
+
# === USE CASE 2: Automated Case Reply Generation ===
|
| 57 |
+
def get_open_cases():
|
| 58 |
+
if not os.path.exists('customer_cases.csv'):
|
| 59 |
+
return []
|
| 60 |
+
df_cases = pd.read_csv('customer_cases.csv')
|
| 61 |
+
return [f"Case {row['case_id']}: {row['customer_name']}" for index, row in df_cases.iterrows()]
|
| 62 |
+
|
| 63 |
+
def get_case_details(case_selection):
|
| 64 |
+
if not case_selection:
|
| 65 |
+
return "", "", gr.update(visible=False)
|
| 66 |
+
|
| 67 |
+
case_id = int(case_selection.split(':')[0].replace('Case', '').strip())
|
| 68 |
+
df_cases = pd.read_csv('customer_cases.csv')
|
| 69 |
+
case_data = df_cases[df_cases['case_id'] == case_id].iloc[0]
|
| 70 |
+
|
| 71 |
+
return case_data['customer_query'], case_data.to_json(), gr.update(visible=True)
|
| 72 |
+
|
| 73 |
+
def generate_case_reply(case_data_json):
|
| 74 |
+
if not LLM_LOADED:
|
| 75 |
+
return "Google API Key not loaded. Please configure it in the Space secrets."
|
| 76 |
+
|
| 77 |
+
# --- THIS IS THE CORRECTED URL ---
|
| 78 |
+
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro:generateContent?key={API_KEY}"
|
| 79 |
+
|
| 80 |
+
internal_data = json.loads(case_data_json)
|
| 81 |
+
customer_query = internal_data.pop('customer_query')
|
| 82 |
+
internal_data.pop('case_id')
|
| 83 |
+
|
| 84 |
+
system_prompt = """
|
| 85 |
+
You are an expert AI assistant for "RecoEngine", specializing in Amazon customer support... (Your prompt remains the same)
|
| 86 |
+
"""
|
| 87 |
+
user_prompt = f"### Customer Query ###\n{customer_query}\n### Internal Data ###\n{json.dumps(internal_data)}"
|
| 88 |
+
|
| 89 |
+
payload = { "contents": [{"parts": [{"text": f"{system_prompt}\n{user_prompt}"}]}] }
|
| 90 |
+
headers = {'Content-Type': 'application/json'}
|
| 91 |
+
|
| 92 |
+
try:
|
| 93 |
+
response = requests.post(url, headers=headers, json=payload)
|
| 94 |
+
response.raise_for_status()
|
| 95 |
+
result = response.json()
|
| 96 |
+
generated_text = result['candidates'][0]['content']['parts'][0]['text']
|
| 97 |
+
except requests.exceptions.RequestException as e:
|
| 98 |
+
return f"Error calling API: {e}"
|
| 99 |
+
except (KeyError, IndexError) as e:
|
| 100 |
+
return f"Error parsing API response: {e}\nRaw Response:\n{result}"
|
| 101 |
+
|
| 102 |
+
try:
|
| 103 |
+
start_index = generated_text.find('{')
|
| 104 |
+
end_index = generated_text.rfind('}') + 1
|
| 105 |
+
json_output_str = generated_text[start_index:end_index]
|
| 106 |
+
parsed_json = json.loads(json_output_str)
|
| 107 |
+
|
| 108 |
+
template = f"""
|
| 109 |
+
Subject: Regarding your recent inquiry about your order... (Your email template remains the same)
|
| 110 |
+
"""
|
| 111 |
+
return template
|
| 112 |
+
except Exception as e:
|
| 113 |
+
return f"Error parsing API output: {e}\nRaw Output:\n{generated_text}"
|
| 114 |
+
|
| 115 |
+
def send_reply(case_selection):
|
| 116 |
+
case_id = int(case_selection.split(':')[0].replace('Case', '').strip())
|
| 117 |
+
df_cases = pd.read_csv('customer_cases.csv')
|
| 118 |
+
df_cases = df_cases[df_cases['case_id'] != case_id]
|
| 119 |
+
df_cases.to_csv('customer_cases.csv', index=False)
|
| 120 |
+
return "Reply sent, case closed.", "", "", gr.update(choices=get_open_cases(), value=None), gr.update(visible=False)
|
| 121 |
+
|
| 122 |
+
# === USE CASE 3: Automated Prep Center Communication ===
|
| 123 |
+
def generate_prep_center_email(client_name, shipment_id, status, arrival_date, num_cartons, labels_provided):
|
| 124 |
+
if not LLM_LOADED:
|
| 125 |
+
return "Google API Key not loaded. Please configure it in the Space secrets."
|
| 126 |
+
|
| 127 |
+
# --- THIS IS THE CORRECTED URL ---
|
| 128 |
+
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro:generateContent?key={API_KEY}"
|
| 129 |
+
|
| 130 |
+
shipment_data = {"client_name": client_name, "shipment_id": shipment_id, "status": status, "expected_arrival_date": arrival_date, "num_cartons": num_cartons, "labels_provided": labels_provided}
|
| 131 |
+
system_prompt = "You are an expert AI operations assistant..."
|
| 132 |
+
user_prompt = f"Analyze this data and generate the JSON: {json.dumps(shipment_data)}"
|
| 133 |
+
payload = { "contents": [{"parts": [{"text": f"{system_prompt}\n{user_prompt}"}]}] }
|
| 134 |
+
headers = {'Content-Type': 'application/json'}
|
| 135 |
+
|
| 136 |
+
try:
|
| 137 |
+
response = requests.post(url, headers=headers, json=payload)
|
| 138 |
+
response.raise_for_status()
|
| 139 |
+
result = response.json()
|
| 140 |
+
generated_text = result['candidates'][0]['content']['parts'][0]['text']
|
| 141 |
+
except requests.exceptions.RequestException as e:
|
| 142 |
+
return f"Error calling API: {e}"
|
| 143 |
+
except (KeyError, IndexError) as e:
|
| 144 |
+
return f"Error parsing API response: {e}\nRaw Response:\n{result}"
|
| 145 |
+
|
| 146 |
+
try:
|
| 147 |
+
start_index = generated_text.find('{')
|
| 148 |
+
end_index = generated_text.rfind('}') + 1
|
| 149 |
+
json_output_str = generated_text[start_index:end_index]
|
| 150 |
+
parsed_json = json.loads(json_output_str)
|
| 151 |
+
template = f"""
|
| 152 |
+
Subject: {parsed_json.get('urgency_tag')} - Action Required for Your Shipment... (Your email template remains the same)
|
| 153 |
+
"""
|
| 154 |
+
return template
|
| 155 |
+
except Exception as e:
|
| 156 |
+
return f"Error parsing API output: {e}\nRaw Output:\n{generated_text}"
|
| 157 |
+
|
| 158 |
+
# === USE CASE 4: Best Warehouse Recommendation ===
|
| 159 |
+
def recommend_best_warehouse(sku_choice):
|
| 160 |
+
if not sku_choice:
|
| 161 |
+
return "Please select a SKU.", ""
|
| 162 |
+
|
| 163 |
+
df_wh = pd.read_csv('daily_sales_history.csv')
|
| 164 |
+
df_wh_sku = df_wh[df_wh['sku'] == sku_choice]
|
| 165 |
+
|
| 166 |
+
if df_wh_sku.empty:
|
| 167 |
+
return f"SKU '{sku_choice}' not found in the daily sales data.", ""
|
| 168 |
+
|
| 169 |
+
warehouse_sales = df_wh_sku.groupby('warehouse')['quantity_sold'].sum()
|
| 170 |
+
best_warehouse = warehouse_sales.idxmax()
|
| 171 |
+
recommendation = f"The best warehouse for **{sku_choice}** is **{best_warehouse}** with {warehouse_sales.max()} units sold historically."
|
| 172 |
+
|
| 173 |
+
df_wh_future = df_wh[(df_wh['sku'] == sku_choice) & (df_wh['warehouse'] == best_warehouse)]
|
| 174 |
+
df_wh_future = df_wh_future.rename(columns={'date': 'ds', 'quantity_sold': 'y'})
|
| 175 |
+
|
| 176 |
+
if len(df_wh_future) < 2:
|
| 177 |
+
return recommendation, "Not enough historical data for this specific warehouse to make a prediction."
|
| 178 |
+
|
| 179 |
+
model_prophet_wh = Prophet(daily_seasonality=False, weekly_seasonality=True, yearly_seasonality=True)
|
| 180 |
+
model_prophet_wh.fit(df_wh_future)
|
| 181 |
+
future_df = model_prophet_wh.make_future_dataframe(periods=30)
|
| 182 |
+
forecast = model_prophet_wh.predict(future_df)
|
| 183 |
+
future_sales = int(forecast['yhat'].tail(30).sum())
|
| 184 |
+
|
| 185 |
+
prediction_text = f"Predicted sales for **{sku_choice}** from **{best_warehouse}** warehouse in the next 30 days: **{future_sales} units**."
|
| 186 |
+
return recommendation, prediction_text
|
| 187 |
+
|
| 188 |
+
# --- 4. GRADIO UI CONSTRUCTION ---
|
| 189 |
+
with gr.Blocks(theme=gr.themes.Soft(text_size='lg'), title="RecoEngine Demo") as demo:
|
| 190 |
+
gr.Markdown("# RecoEngine Demo!!")
|
| 191 |
+
|
| 192 |
+
with gr.Tabs():
|
| 193 |
+
# --- TAB 1: Future Sales Prediction ---
|
| 194 |
+
with gr.TabItem("Future Sales Prediction"):
|
| 195 |
+
gr.Markdown("## Predict Next 30-Day Sales for a SKU")
|
| 196 |
+
sku_dropdown_sales = gr.Dropdown(
|
| 197 |
+
choices=['Leather care conditioner 500 ml', 'Cockpit Cleaner Matt 500 ml', 'Cockpit Cleaner Shine 500 ml'],
|
| 198 |
+
label="Select a SKU"
|
| 199 |
+
)
|
| 200 |
+
predict_button_sales = gr.Button("Generate Prediction")
|
| 201 |
+
sales_output = gr.Markdown()
|
| 202 |
+
predict_button_sales.click(predict_future_sales, inputs=sku_dropdown_sales, outputs=sales_output)
|
| 203 |
+
|
| 204 |
+
# --- TAB 2: Automated Case Reply ---
|
| 205 |
+
with gr.TabItem("Automated Case Reply"):
|
| 206 |
+
gr.Markdown("## Handle Customer Support Cases")
|
| 207 |
+
case_dropdown = gr.Dropdown(choices=get_open_cases(), label="Select an Open Case")
|
| 208 |
+
with gr.Group():
|
| 209 |
+
gr.Markdown("**Customer's Message:**")
|
| 210 |
+
customer_query_box = gr.Textbox(lines=4, interactive=False, show_label=False)
|
| 211 |
+
case_data_state = gr.State()
|
| 212 |
+
generate_reply_button = gr.Button("Generate AI Reply", visible=False)
|
| 213 |
+
with gr.Group():
|
| 214 |
+
gr.Markdown("**Generated Reply:**")
|
| 215 |
+
reply_output_box = gr.Textbox(lines=8, interactive=False, show_label=False)
|
| 216 |
+
send_reply_button = gr.Button("Send Reply & Close Case")
|
| 217 |
+
status_box = gr.Markdown()
|
| 218 |
+
case_dropdown.change(get_case_details, inputs=case_dropdown, outputs=[customer_query_box, case_data_state, generate_reply_button])
|
| 219 |
+
generate_reply_button.click(generate_case_reply, inputs=case_data_state, outputs=reply_output_box)
|
| 220 |
+
send_reply_button.click(send_reply, inputs=case_dropdown, outputs=[status_box, customer_query_box, reply_output_box, case_dropdown, generate_reply_button])
|
| 221 |
+
|
| 222 |
+
# --- TAB 3: Prep Center Communication ---
|
| 223 |
+
with gr.TabItem("Prep Center Communication"):
|
| 224 |
+
gr.Markdown("## Generate Prep Center Reminder Email")
|
| 225 |
+
with gr.Row():
|
| 226 |
+
client_name_input = gr.Textbox(label="Client Name", value="FabFurnish")
|
| 227 |
+
shipment_id_input = gr.Textbox(label="Shipment ID", value="SHP-IND-9001")
|
| 228 |
+
with gr.Row():
|
| 229 |
+
status_input = gr.Dropdown(
|
| 230 |
+
choices=["In Transit", "Awaiting Arrival", "Arrived", "Processing", "Completed"],
|
| 231 |
+
label="Status",
|
| 232 |
+
value="In Transit"
|
| 233 |
+
)
|
| 234 |
+
arrival_date_input = gr.Textbox(label="Expected Arrival Date", value="2025-09-11")
|
| 235 |
+
with gr.Row():
|
| 236 |
+
cartons_input = gr.Number(label="Number of Cartons", value=15)
|
| 237 |
+
labels_provided_input = gr.Checkbox(label="Labels Provided?", value=False)
|
| 238 |
+
generate_email_button = gr.Button("Generate Email")
|
| 239 |
+
email_output = gr.Textbox(lines=10, label="Generated Email")
|
| 240 |
+
generate_email_button.click(generate_prep_center_email, inputs=[client_name_input, shipment_id_input, status_input, arrival_date_input, cartons_input, labels_provided_input], outputs=email_output)
|
| 241 |
+
|
| 242 |
+
# --- TAB 4: Best Warehouse Recommendation ---
|
| 243 |
+
with gr.TabItem("Best Warehouse Recommendation"):
|
| 244 |
+
gr.Markdown("## Find the Best Warehouse and Predict Sales")
|
| 245 |
+
sku_dropdown_wh = gr.Dropdown(
|
| 246 |
+
choices=['Leather care conditioner 500 ml', 'Cockpit Cleaner Matt 500 ml', 'Cockpit Cleaner Shine 500 ml'],
|
| 247 |
+
label="Select a SKU"
|
| 248 |
+
)
|
| 249 |
+
recommend_button_wh = gr.Button("Get Recommendation & Prediction")
|
| 250 |
+
wh_recommendation_output = gr.Markdown()
|
| 251 |
+
wh_prediction_output = gr.Markdown()
|
| 252 |
+
recommend_button_wh.click(recommend_best_warehouse, inputs=sku_dropdown_wh, outputs=[wh_recommendation_output, wh_prediction_output])
|
| 253 |
+
|
| 254 |
+
# --- 5. LAUNCH THE APP ---
|
| 255 |
+
if __name__ == "__main__":
|
| 256 |
+
demo.launch()
|