ShettyAkshay commited on
Commit
06fa28f
·
verified ·
1 Parent(s): f0957ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -40
app.py CHANGED
@@ -3,11 +3,11 @@ import pandas as pd
3
  from prophet import Prophet
4
  import json
5
  import os
6
- import requests # Use requests instead of the google library
 
7
 
8
- # --- MODIFIED: Securely load the API key from Hugging Face Secrets ---
9
  API_KEY = os.environ.get("GOOGLE_API_KEY")
10
- LLM_LOADED = bool(API_KEY) # Check if the key was loaded
11
 
12
  def create_cases_data():
13
  """Creates a dummy CSV with customer case data."""
@@ -55,14 +55,12 @@ def predict_future_sales(sku_choice):
55
 
56
  # === USE CASE 2: Automated Case Reply Generation ===
57
  def get_open_cases():
58
- """Loads open cases from the CSV and returns a list for the dropdown."""
59
  if not os.path.exists('customer_cases.csv'):
60
  return []
61
  df_cases = pd.read_csv('customer_cases.csv')
62
  return [f"Case {row['case_id']}: {row['customer_name']}" for index, row in df_cases.iterrows()]
63
 
64
  def get_case_details(case_selection):
65
- """Fetches details for a selected case."""
66
  if not case_selection:
67
  return "", "", gr.update(visible=False)
68
 
@@ -73,11 +71,11 @@ def get_case_details(case_selection):
73
  return case_data['customer_query'], case_data.to_json(), gr.update(visible=True)
74
 
75
  def generate_case_reply(case_data_json):
76
- """Generates an email reply using the Gemini API via requests."""
77
  if not LLM_LOADED:
78
  return "Google API Key not loaded. Please configure it in the Space secrets."
79
 
80
- url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={API_KEY}"
 
81
 
82
  internal_data = json.loads(case_data_json)
83
  customer_query = internal_data.pop('customer_query')
@@ -125,26 +123,26 @@ def generate_case_reply(case_data_json):
125
  Subject: Regarding your recent inquiry about your order
126
 
127
  Dear {parsed_json.get('customer_name', 'Valued Customer')},
128
-
129
  Thank you for contacting Amazon Support.
130
-
131
  I understand that you are concerned about {parsed_json.get('paraphrased_issue', 'your recent issue')}. I know how {parsed_json.get('empathy_adjective', 'concerning')} this can be, and I'm here to help you with this.
132
-
133
  After reviewing the details, I can see that {parsed_json.get('facts_statement', 'we have reviewed your case.')}.
134
-
135
  To resolve this for you, {parsed_json.get('action_taken', 'we have taken the necessary action.')}.
136
-
137
  Here is a summary of the next steps:
138
  """
139
  for i, step in enumerate(parsed_json.get('next_steps', []), 1):
140
  template += f"{i}. {step}\n"
141
  template += """
142
  If there is anything else you need assistance with, please don't hesitate to reply to this email. We're always here to help.
143
-
144
  Thank you for your patience and understanding.
145
-
146
  Best regards,
147
-
148
  Anjali
149
  Amazon.in Customer Service
150
  """
@@ -153,7 +151,6 @@ def generate_case_reply(case_data_json):
153
  return f"Error parsing API output: {e}\nRaw Output:\n{generated_text}"
154
 
155
  def send_reply(case_selection):
156
- """Simulates sending the reply by removing the case from the 'database'."""
157
  case_id = int(case_selection.split(':')[0].replace('Case', '').strip())
158
  df_cases = pd.read_csv('customer_cases.csv')
159
  df_cases = df_cases[df_cases['case_id'] != case_id]
@@ -162,26 +159,16 @@ def send_reply(case_selection):
162
 
163
  # === USE CASE 3: Automated Prep Center Communication ===
164
  def generate_prep_center_email(client_name, shipment_id, status, arrival_date, num_cartons, labels_provided):
165
- """Generates a prep center email using the Gemini API via requests."""
166
  if not LLM_LOADED:
167
  return "Google API Key not loaded. Please configure it in the Space secrets."
168
 
169
- url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={API_KEY}"
 
170
 
171
  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}
172
 
173
  system_prompt = """
174
- You are an expert AI operations assistant, specializing in e-commerce prep center communications.
175
- Your task is to analyze shipment data and generate a structured JSON object to populate a reminder email for the client.
176
- Your FINAL and ONLY output must be a single, well-formed JSON object. Do not add any text before or after the JSON.
177
- Required JSON Schema:
178
- {
179
- "urgency_tag": "string (e.g., 'Reminder', 'Urgent', 'Action Required')",
180
- "main_call_to_action": "string (A single, clear sentence summarizing what the client needs to do)",
181
- "detailed_action": "string (A more detailed explanation of the required action)",
182
- "reason_for_action": "string (Explain the impact of the action, i.e., why it is important)",
183
- "instructions": "string (Provide simple, step-by-step instructions)"
184
- }
185
  """
186
  user_prompt = f"Analyze this data and generate the JSON: {json.dumps(shipment_data)}"
187
 
@@ -207,32 +194,32 @@ def generate_prep_center_email(client_name, shipment_id, status, arrival_date, n
207
  parsed_json = json.loads(json_output_str)
208
  template = f"""
209
  Subject: {parsed_json.get('urgency_tag')} - Action Required for Your Shipment {shipment_id} - {client_name}
210
-
211
  Dear {client_name},
212
-
213
  This is an important reminder from PrepCenter India regarding your upcoming shipment.
214
-
215
  {parsed_json.get('main_call_to_action')}.
216
-
217
  **Shipment Details:**
218
  * **Shipment ID:** {shipment_id}
219
  * **Status:** {status}
220
  * **Expected Arrival Date:** {arrival_date}
221
  * **Number of Cartons:** {num_cartons}
222
-
223
  **Action Required:**
224
  {parsed_json.get('detailed_action')}
225
-
226
  **Why is this important?**
227
  {parsed_json.get('reason_for_action')}
228
-
229
  **How to complete this action:**
230
  {parsed_json.get('instructions')}
231
-
232
  If you have already completed this action, please disregard this email. If you have any questions, please reply to this message.
233
-
234
  Best regards,
235
-
236
  The PrepCenter India Team
237
  """
238
  return template
@@ -337,4 +324,4 @@ with gr.Blocks(theme=gr.themes.Soft(text_size='lg'), title="RecoEngine Demo") as
337
 
338
  # --- 5. LAUNCH THE APP ---
339
  if __name__ == "__main__":
340
- demo.launch(share=True)
 
3
  from prophet import Prophet
4
  import json
5
  import os
6
+ import requests
7
+
8
 
 
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."""
 
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
 
 
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
+ # --- FIX: Corrected model name in 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')
 
123
  Subject: Regarding your recent inquiry about your order
124
 
125
  Dear {parsed_json.get('customer_name', 'Valued Customer')},
126
+
127
  Thank you for contacting Amazon Support.
128
+
129
  I understand that you are concerned about {parsed_json.get('paraphrased_issue', 'your recent issue')}. I know how {parsed_json.get('empathy_adjective', 'concerning')} this can be, and I'm here to help you with this.
130
+
131
  After reviewing the details, I can see that {parsed_json.get('facts_statement', 'we have reviewed your case.')}.
132
+
133
  To resolve this for you, {parsed_json.get('action_taken', 'we have taken the necessary action.')}.
134
+
135
  Here is a summary of the next steps:
136
  """
137
  for i, step in enumerate(parsed_json.get('next_steps', []), 1):
138
  template += f"{i}. {step}\n"
139
  template += """
140
  If there is anything else you need assistance with, please don't hesitate to reply to this email. We're always here to help.
141
+
142
  Thank you for your patience and understanding.
143
+
144
  Best regards,
145
+
146
  Anjali
147
  Amazon.in Customer Service
148
  """
 
151
  return f"Error parsing API output: {e}\nRaw Output:\n{generated_text}"
152
 
153
  def send_reply(case_selection):
 
154
  case_id = int(case_selection.split(':')[0].replace('Case', '').strip())
155
  df_cases = pd.read_csv('customer_cases.csv')
156
  df_cases = df_cases[df_cases['case_id'] != case_id]
 
159
 
160
  # === USE CASE 3: Automated Prep Center Communication ===
161
  def generate_prep_center_email(client_name, shipment_id, status, arrival_date, num_cartons, labels_provided):
 
162
  if not LLM_LOADED:
163
  return "Google API Key not loaded. Please configure it in the Space secrets."
164
 
165
+ # --- FIX: Corrected model name in URL ---
166
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro:generateContent?key={API_KEY}"
167
 
168
  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}
169
 
170
  system_prompt = """
171
+ You are an expert AI operations assistant... (Your prompt remains the same)
 
 
 
 
 
 
 
 
 
 
172
  """
173
  user_prompt = f"Analyze this data and generate the JSON: {json.dumps(shipment_data)}"
174
 
 
194
  parsed_json = json.loads(json_output_str)
195
  template = f"""
196
  Subject: {parsed_json.get('urgency_tag')} - Action Required for Your Shipment {shipment_id} - {client_name}
197
+
198
  Dear {client_name},
199
+
200
  This is an important reminder from PrepCenter India regarding your upcoming shipment.
201
+
202
  {parsed_json.get('main_call_to_action')}.
203
+
204
  **Shipment Details:**
205
  * **Shipment ID:** {shipment_id}
206
  * **Status:** {status}
207
  * **Expected Arrival Date:** {arrival_date}
208
  * **Number of Cartons:** {num_cartons}
209
+
210
  **Action Required:**
211
  {parsed_json.get('detailed_action')}
212
+
213
  **Why is this important?**
214
  {parsed_json.get('reason_for_action')}
215
+
216
  **How to complete this action:**
217
  {parsed_json.get('instructions')}
218
+
219
  If you have already completed this action, please disregard this email. If you have any questions, please reply to this message.
220
+
221
  Best regards,
222
+
223
  The PrepCenter India Team
224
  """
225
  return template
 
324
 
325
  # --- 5. LAUNCH THE APP ---
326
  if __name__ == "__main__":
327
+ demo.launch()