Rajan Sharma commited on
Commit
48963bc
·
verified ·
1 Parent(s): 71d944b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +373 -0
app.py CHANGED
@@ -8,6 +8,26 @@ import traceback
8
  from contextlib import redirect_stdout
9
  from typing import List, Dict, Any
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  import gradio as gr
12
  import pandas as pd
13
  from datetime import datetime
@@ -24,6 +44,359 @@ from audit_log import log_event
24
  from privacy import safety_filter, refusal_reply
25
  from llm_router import cohere_chat, _co_client, cohere_embed
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  def load_markdown_text(filepath: str) -> str:
28
  try:
29
  with open(filepath, 'r', encoding='utf-8') as f:
 
8
  from contextlib import redirect_stdout
9
  from typing import List, Dict, Any
10
 
11
+ import gradio as gr
12
+ import pandas a# app.py
13
+ #
14
+ # This file defines a Gradio-based AI data analyst application with
15
+ # support for maintaining a persistent chat and assessment history.
16
+ # The history feature preserves each chat/assessment session (prompt,
17
+ # associated files, generated response, and full conversation) so that
18
+ # users can revisit past analyses without losing any existing
19
+ # functionality. A dropdown selector in the "Assessment History" tab
20
+ # allows users to select and review previous sessions, including the
21
+ # complete chat transcript.
22
+
23
+ from __future__ import annotations
24
+ import os
25
+ import io
26
+ import json
27
+ import traceback
28
+ from contextlib import redirect_stdout
29
+ from typing import List, Dict, Any
30
+
31
  import gradio as gr
32
  import pandas as pd
33
  from datetime import datetime
 
44
  from privacy import safety_filter, refusal_reply
45
  from llm_router import cohere_chat, _co_client, cohere_embed
46
 
47
+ def load_markdown_text(filepath: str) -> str:
48
+ try:
49
+ with open(filepath, 'r', encoding='utf-8') as f:
50
+ return f.read()
51
+ except FileNotFoundError:
52
+ return f"**Error:** Document `{os.path.basename(filepath)}` not found."
53
+
54
+ def _sanitize_text(s: str) -> str:
55
+ if not isinstance(s, str): return s
56
+ return re2.sub(r'[\p{C}--[\n\t]]+', '', s)
57
+
58
+ def _create_python_script(user_scenario: str, schema_context: str) -> str:
59
+ EXPERT_ANALYTICAL_GUIDELINES = """
60
+ --- EXPERT ANALYTICAL GUIDELINES ---
61
+ When writing your script, you MUST follow these expert business rules:
62
+ 1. **Linking Datasets Rule:** If you need to connect facilities to health zones when the 'zone' column is not in the facility list, you must first identify the high-priority zone from the beds data, then find the major city (by facility count) in the facility list, and *then* assess that city's capacity. Do not try to filter the facility list by a 'zone' column if it does not exist in the schema.
63
+ 2. **Prioritization Rule:** To prioritize locations, you MUST combine the most recent population data with specific high-risk health indicators to create a multi-factor risk score.
64
+ 3. **Capacity Calculation Rule:** For capacity over a 3-month window, assume **60 working days**.
65
+ 4. **Cost Calculation Rule:** Sum 'Startup cost' and 'Ongoing cost' per person before multiplying.
66
+ """
67
+
68
+ prompt_for_coder = f"""\
69
+ You are an expert Python data scientist. Your job is to write a script to extract the data needed to answer the user's request.
70
+ You have dataframes in a list `dfs`.
71
+
72
+ {EXPERT_ANALYTICAL_GUIDELINES}
73
+
74
+ --- DATA SCHEMA ---
75
+ {schema_context}
76
+ --- END DATA SCHEMA ---
77
+
78
+ CRITICAL RULES:
79
+ 1. **DO NOT READ FILES:** You MUST NOT include `pd.read_csv`. The data is ALREADY loaded in the `dfs` variable. You MUST use this variable. Failure to do so will cause a fatal error.
80
+ 2. **JSON OUTPUT ONLY:** Your script's ONLY output must be a single JSON object printed to stdout containing the raw data findings.
81
+ 3. **BE PRECISE:** Use the exact, case-sensitive column names from the schema and robustly clean strings (`re.sub()`) before converting to numbers.
82
+ 4. **JSON SERIALIZATION:** Before adding data to your final dictionary for JSON conversion, you MUST convert any pandas-specific types (like `int64`) to standard Python types using `.item()` for single values or `.tolist()` for lists.
83
+
84
+ --- USER'S SCENARIO ---
85
+ {user_scenario}
86
+
87
+ --- PYTHON SCRIPT ---
88
+ Now, write the complete Python script that performs the analysis and prints a single, serializable JSON object.
89
+ ```python
90
+ """
91
+ generated_text = cohere_chat(prompt_for_coder)
92
+ match = re2.search(r"```python\n(.*?)```", generated_text, re2.DOTALL)
93
+ if match: return match.group(1).strip()
94
+ return "print(json.dumps({'error': 'Failed to generate a valid Python script.'}))"
95
+
96
+ def _generate_long_report(prompt: str) -> str:
97
+ try:
98
+ client = _co_client()
99
+ if not client: return "Error: Cohere client not initialized."
100
+ response = client.chat(
101
+ model=COHERE_MODEL_PRIMARY,
102
+ message=prompt,
103
+ max_tokens=4096
104
+ )
105
+ return response.text
106
+ except Exception as e:
107
+ log_event("cohere_chat_error", None, {"err": str(e)})
108
+ return f"Error during final report generation: {e}"
109
+
110
+ def _generate_final_report(user_scenario: str, raw_data_json: str) -> str:
111
+ prompt_for_writer = f"""\
112
+ You are an expert management consultant and data analyst.
113
+ A data science script has run to extract key findings. You have the user's original request and the raw JSON data.
114
+
115
+ Your task is to synthesize these raw findings into a single, comprehensive, and professional report that directly answers all of the user's questions with detailed justifications.
116
+
117
+ --- USER'S ORIGINAL SCENARIO & DELIVERABLES ---
118
+ {user_scenario}
119
+ --- END SCENARIO ---
120
+
121
+ --- RAW DATA FINDINGS (JSON) ---
122
+ {raw_data_json}
123
+ --- END RAW DATA ---
124
+
125
+ Now, write the final, polished report. The report MUST:
126
+ 1. Follow the "Expected Output Format" requested by the user.
127
+ 2. Use tables, bullet points, and DETAILED narrative justifications for each recommendation.
128
+ 3. Synthesize the raw data into actionable insights. Do not just copy the raw numbers; interpret them.
129
+ 4. Ensure you fully address ALL evaluation questions, especially the final recommendations.
130
+ """
131
+ return _generate_long_report(prompt_for_writer)
132
+
133
+ def _append_msg(h: List[Dict[str, str]], r: str, c: str) -> List[Dict[str, str]]:
134
+ return (h or []) + [{"role": r, "content": c}]
135
+
136
+ def ping_cohere() -> str:
137
+ try:
138
+ cli = _co_client()
139
+ if not cli: return "Cohere client not initialized."
140
+ vecs = cohere_embed(["hello", "world"])
141
+ return f"Cohere OK ✅ (model={COHERE_MODEL_PRIMARY})" if vecs else "Cohere reachable."
142
+ except Exception as e: return f"Cohere ping failed: {e}"
143
+
144
+ def handle(user_msg: str, files: list, yield_update) -> str:
145
+ try:
146
+ safe_in, blocked_in, reason_in = safety_filter(user_msg, mode="input")
147
+ if blocked_in: return refusal_reply(reason_in)
148
+
149
+ file_paths: List[str] = [getattr(f, "name", None) or f for f in (files or [])]
150
+
151
+ if file_paths:
152
+ dataframes, schema_parts = [], []
153
+ for i, p in enumerate(file_paths):
154
+ if p.endswith('.csv'):
155
+ try: df = pd.read_csv(p)
156
+ except UnicodeDecodeError: df = pd.read_csv(p, encoding='latin1')
157
+ dataframes.append(df)
158
+ schema_parts.append(f"DataFrame `dfs[{i}]` (`{os.path.basename(p)}`):\n{df.head().to_markdown()}\n")
159
+
160
+ if not dataframes: return "Please upload at least one CSV file."
161
+
162
+ schema_context = "\n".join(schema_parts)
163
+
164
+ yield_update("```
165
+ 🧠 Generating aligned analysis script...
166
+ ```" )
167
+ analysis_script = _create_python_script(safe_in, schema_context)
168
+
169
+ yield_update("```
170
+ ⚙️ Executing script to extract raw data...
171
+ ```" )
172
+ execution_namespace = {"dfs": dataframes, "pd": pd, "re": re, "json": json}
173
+ output_buffer = io.StringIO()
174
+
175
+ try:
176
+ with redirect_stdout(output_buffer): exec(analysis_script, execution_namespace)
177
+ raw_data_output = output_buffer.getvalue()
178
+ except Exception as e:
179
+ return f"An error occurred executing the script: {e}\n\nGenerated Script:\n```python\n{analysis_script}\n```"
180
+
181
+ yield_update("```
182
+ ✍️ Synthesizing final comprehensive report...
183
+ ```" )
184
+ final_report = _generate_final_report(safe_in, raw_data_output)
185
+ return _sanitize_text(final_report)
186
+ else:
187
+ prompt = f"{GENERAL_CONVERSATION_PROMPT}\n\nUser: {safe_in}\nAssistant:"
188
+ return _sanitize_text(cohere_chat(prompt) or "How can I help further?")
189
+
190
+ except Exception as e:
191
+ tb = traceback.format_exc()
192
+ log_event("app_error", None, {"err": str(e), "tb": tb})
193
+ return f"A critical error occurred: {e}"
194
+
195
+ PRIVACY_POLICY_TEXT = load_markdown_text("privacy_policy.md")
196
+ TERMS_OF_SERVICE_TEXT = load_markdown_text("terms_of_service.md")
197
+
198
+ with gr.Blocks(theme="soft", css="style.css") as demo:
199
+ # Maintain a persistent history of past assessments or chat sessions.
200
+ # Each entry in `assessment_history` is a dictionary containing:
201
+ # - id: timestamp of the session (string)
202
+ # - prompt: the initial user prompt (string)
203
+ # - files: list of filenames uploaded by the user (list of str)
204
+ # - response: the assistant's final response text (string)
205
+ # - chat_history: the full chat transcript as a list of message dictionaries
206
+ assessment_history = gr.State([])
207
+
208
+ with gr.Group(visible=False) as privacy_modal:
209
+ with gr.Blocks():
210
+ gr.Markdown(PRIVACY_POLICY_TEXT)
211
+ close_privacy_btn = gr.Button("Close")
212
+
213
+ with gr.Group(visible=False) as terms_modal:
214
+ with gr.Blocks():
215
+ gr.Markdown(TERMS_OF_SERVICE_TEXT)
216
+ close_terms_btn = gr.Button("Close")
217
+
218
+ gr.Markdown("# Universal AI Data Analyst")
219
+ with gr.Row(variant="panel"):
220
+ with gr.Column(scale=1):
221
+ gr.Markdown("## New Assessment")
222
+ gr.Markdown("<p style='font-size:0.9rem; color: #6C757D;'>Upload CSVs for data analysis, or just enter a prompt to chat.</p>")
223
+ files_input = gr.Files(label="Upload Data Files (.csv)", file_count="multiple", type="filepath", file_types=[".csv"])
224
+ prompt_input = gr.Textbox(label="Prompt", placeholder="Paste your scenario or question here.", lines=15)
225
+ with gr.Row():
226
+ send_btn = gr.Button("▶️ Send / Run Analysis", variant="primary", scale=2)
227
+ clear_btn = gr.Button("🗑️ Clear")
228
+ ping_btn = gr.Button("Ping Cohere")
229
+ ping_out = gr.Markdown()
230
+ with gr.Column(scale=2):
231
+ with gr.Tabs():
232
+ with gr.TabItem("Current Assessment", id=0):
233
+ chat_history_output = gr.Chatbot(label="Analysis Output", type="messages", height=600)
234
+ with gr.TabItem("Assessment History", id=1):
235
+ gr.Markdown("## Review Past Assessments")
236
+ history_dropdown = gr.Dropdown(label="Select an assessment to review", choices=[])
237
+ # Use Markdown to display details of the selected assessment, including chat transcript.
238
+ history_display = gr.Markdown(label="Selected Assessment Details")
239
+ with gr.Row(): gr.Markdown("---")
240
+ with gr.Row():
241
+ privacy_link = gr.Button("Privacy Policy", variant="link")
242
+ terms_link = gr.Button("Terms of Service", variant="link")
243
+
244
+ def run_analysis_wrapper(prompt, files, chat_history_list, history_state_list):
245
+ """Handle a new user prompt and update chat and assessment history.
246
+
247
+ This wrapper manages the entire lifecycle of a chat or data analysis:
248
+ 1. Append the user's message to the ongoing conversation.
249
+ 2. Dispatch the request to the AI handler and receive a response.
250
+ 3. Construct a new session entry (with timestamp, prompt, files, response and full chat).
251
+ 4. Update the persistent history and dropdown choices.
252
+
253
+ Args:
254
+ prompt (str): The current user prompt.
255
+ files (list): List of file paths selected by the user.
256
+ chat_history_list (list): Current chat conversation as a list of message dicts.
257
+ history_state_list (list): List of past assessment/chat sessions.
258
+
259
+ Returns:
260
+ tuple: Updated chat history list, updated history list, and updated dropdown choices.
261
+ """
262
+ if not prompt:
263
+ gr.Warning("Please enter a prompt.")
264
+ yield chat_history_list, history_state_list, gr.update()
265
+ return
266
+
267
+ # Append the user's message to the existing chat history
268
+ chat_with_user_msg = _append_msg(chat_history_list, "user", prompt)
269
+
270
+ # Provide immediate feedback to the user that analysis is in progress
271
+ def dummy_update(message):
272
+ # This callback is intentionally left blank; progress messages are not streamed here
273
+ pass
274
+
275
+ thinking_message = _append_msg(chat_with_user_msg, "assistant", "```
276
+ 🧠 Generating and executing analysis... Please wait.
277
+ ```" )
278
+ # Yield intermediate state showing a thinking message
279
+ yield thinking_message, history_state_list, gr.update()
280
+
281
+ # Run the AI handler (analysis or chat) to get the assistant's response
282
+ ai_response_text = handle(prompt, files, dummy_update)
283
+
284
+ # Append the assistant's final response to the chat conversation
285
+ final_chat = _append_msg(chat_with_user_msg, "assistant", ai_response_text)
286
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
287
+
288
+ # Capture uploaded filenames (if any)
289
+ file_names: List[str] = []
290
+ if files:
291
+ file_names = [os.path.basename(f.name if hasattr(f, 'name') else f) for f in files]
292
+
293
+ # Build a new entry for the assessment/chat history
294
+ new_entry = {
295
+ "id": timestamp,
296
+ "prompt": prompt,
297
+ "files": file_names,
298
+ "response": ai_response_text,
299
+ "chat_history": final_chat,
300
+ }
301
+
302
+ # Update the history state (initialize if necessary)
303
+ updated_history: List[Dict[str, Any]] = (history_state_list or []) + [new_entry]
304
+
305
+ # Build dropdown labels showing timestamp and a snippet of the prompt
306
+ history_labels = [f"{item['id']} - {item['prompt'][:40]}..." for item in updated_history]
307
+
308
+ # Return the final chat, updated history, and updated dropdown choices
309
+ yield final_chat, updated_history, gr.update(choices=history_labels)
310
+
311
+ def view_history(selection: str, history_state_list: List[Dict[str, Any]]) -> str:
312
+ """Render the details of a selected past assessment or chat session.
313
+
314
+ The selection string contains the timestamp and prompt snippet separated by ' - '.
315
+ This function locates the corresponding history entry and returns a formatted
316
+ Markdown string with all relevant details, including the full chat transcript.
317
+
318
+ Args:
319
+ selection (str): The selected dropdown label of the form 'timestamp - prompt...'.
320
+ history_state_list (list): The list of stored history entries.
321
+
322
+ Returns:
323
+ str: Markdown-formatted details of the selected session.
324
+ """
325
+ if not selection or not history_state_list:
326
+ return ""
327
+ # Extract the unique ID (timestamp) from the dropdown label
328
+ # The dropdown label is of the form "timestamp - snippet..."
329
+ try:
330
+ selected_id = selection.split(" - ", 1)[0]
331
+ except Exception:
332
+ selected_id = selection
333
+ # Find the matching session in the history
334
+ selected_assessment = next((item for item in history_state_list if item.get("id") == selected_id), None)
335
+
336
+ if selected_assessment:
337
+ # Prepare file list display
338
+ file_list = selected_assessment.get('files', [])
339
+ file_list_md = "\n- ".join(file_list) if file_list else "*(no files uploaded)*"
340
+
341
+ # Prepare chat history display: show each role/message pair on its own line
342
+ chat_entries = selected_assessment.get("chat_history", [])
343
+ chat_md_lines = []
344
+ for msg in chat_entries:
345
+ role = msg.get("role", "").capitalize()
346
+ content = msg.get("content", "")
347
+ chat_md_lines.append(f"**{role}:** {content}")
348
+ chat_md = "\n\n".join(chat_md_lines)
349
+
350
+ return f"""### Assessment from: {selected_assessment['id']}
351
+ **Files Used:**\n- {file_list_md}
352
+ ---
353
+ **Original Prompt:**\n> {selected_assessment['prompt']}
354
+ ---
355
+ **AI Generated Response:**\n{selected_assessment['response']}
356
+ ---
357
+ **Chat Transcript:**\n{chat_md}
358
+ """
359
+ return "Could not find the selected assessment."
360
+
361
+ # Register interaction handlers
362
+ send_btn.click(
363
+ run_analysis_wrapper,
364
+ inputs=[prompt_input, files_input, chat_history_output, assessment_history],
365
+ outputs=[chat_history_output, assessment_history, history_dropdown]
366
+ )
367
+ history_dropdown.change(
368
+ view_history,
369
+ inputs=[history_dropdown, assessment_history],
370
+ outputs=[history_display]
371
+ )
372
+ clear_btn.click(
373
+ lambda: (None, None, []),
374
+ outputs=[prompt_input, files_input, chat_history_output]
375
+ )
376
+ ping_btn.click(ping_cohere, outputs=[ping_out])
377
+ privacy_link.click(lambda: gr.update(visible=True), outputs=[privacy_modal])
378
+ close_privacy_btn.click(lambda: gr.update(visible=False), outputs=[privacy_modal])
379
+ terms_link.click(lambda: gr.update(visible=True), outputs=[terms_modal])
380
+ close_terms_btn.click(lambda: gr.update(visible=False), outputs=[terms_modal])
381
+
382
+ if __name__ == "__main__":
383
+ if not os.getenv("COHERE_API_KEY"):
384
+ print("🔴 COHERE_API_KEY environment variable not set. Application may not function correctly.")
385
+ demo.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")))s pd
386
+ from datetime import datetime
387
+ import regex as re2
388
+ import re
389
+
390
+ from langchain_cohere import ChatCohere
391
+
392
+ from settings import (
393
+ GENERAL_CONVERSATION_PROMPT,
394
+ COHERE_MODEL_PRIMARY, COHERE_TIMEOUT_S, USE_OPEN_FALLBACKS
395
+ )
396
+ from audit_log import log_event
397
+ from privacy import safety_filter, refusal_reply
398
+ from llm_router import cohere_chat, _co_client, cohere_embed
399
+
400
  def load_markdown_text(filepath: str) -> str:
401
  try:
402
  with open(filepath, 'r', encoding='utf-8') as f: