dolphinium commited on
Commit
f4ff4c1
Β·
verified Β·
1 Parent(s): 1e79dde

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +607 -0
app.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import re
4
+ import datetime
5
+ import pandas as pd
6
+ import pysolr
7
+ import google.generativeai as genai
8
+ from sshtunnel import SSHTunnelForwarder
9
+ import matplotlib.pyplot as plt
10
+ import seaborn as sns
11
+ import io
12
+ import os
13
+ import logging
14
+ from IPython.display import display, Markdown
15
+
16
+ # --- Suppress Matplotlib Debug Logs ---
17
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
18
+
19
+ # --- SSH Tunnel Configuration ---
20
+ SSH_HOST = os.environ.get('SSH_HOST')
21
+ SSH_PORT = 5322
22
+ SSH_USER = os.environ.get('SSH_USER')
23
+ SSH_PASS = os.environ.get('SSH_PASS')
24
+
25
+ # --- Solr Configuration ---
26
+ REMOTE_SOLR_HOST = '69.167.186.48'
27
+ REMOTE_SOLR_PORT = 8983
28
+ LOCAL_BIND_PORT = 8983
29
+ SOLR_CORE_NAME = 'news'
30
+ SOLR_USER = os.environ.get('SOLR_USER')
31
+ SOLR_PASS = os.environ.get('SOLR_PASS')
32
+
33
+ # --- Google Gemini Configuration ---
34
+ try:
35
+ genai.configure(api_key=os.environ.get('GEMINI_API_KEY'))
36
+ except Exception as e:
37
+ print(f"❌ Gemini API Key Error: {e}. Please ensure 'GEMINI_API_KEY' is set in Colab Secrets.")
38
+
39
+ # --- Global Variables ---
40
+ ssh_tunnel_server = None
41
+ solr_client = None
42
+ llm_model = None
43
+ is_initialized = False
44
+
45
+ try:
46
+ # 1. Start the SSH Tunnel
47
+ ssh_tunnel_server = SSHTunnelForwarder(
48
+ (SSH_HOST, SSH_PORT),
49
+ ssh_username=SSH_USER,
50
+ ssh_password=SSH_PASS,
51
+ remote_bind_address=(REMOTE_SOLR_HOST, REMOTE_SOLR_PORT),
52
+ local_bind_address=('127.0.0.1', LOCAL_BIND_PORT)
53
+ )
54
+ ssh_tunnel_server.start()
55
+ print(f"πŸš€ SSH tunnel established: Local Port {ssh_tunnel_server.local_bind_port} -> Remote Solr.")
56
+
57
+ # 2. Initialize the pysolr client
58
+ solr_url = f'http://127.0.0.1:{ssh_tunnel_server.local_bind_port}/solr/{SOLR_CORE_NAME}'
59
+ solr_client = pysolr.Solr(solr_url, auth=(SOLR_USER, SOLR_PASS), always_commit=True)
60
+ solr_client.ping()
61
+ print(f"βœ… Solr connection successful on core '{SOLR_CORE_NAME}'.")
62
+
63
+ # 3. Initialize the LLM
64
+ llm_model = genai.GenerativeModel('gemini-2.5-flash-preview-04-17', generation_config=genai.types.GenerationConfig(temperature=0))
65
+ print(f"βœ… LLM Model '{llm_model.model_name}' initialized.")
66
+
67
+ # 4. Define available Solr fields for the LLM
68
+ # In a real app, this could be fetched dynamically from Solr's Schema API
69
+ available_fields = [
70
+ "id",
71
+ "abstract",
72
+ "date",
73
+ "date_year",
74
+ "business_model",
75
+ "news_type",
76
+ "content",
77
+ "event_type",
78
+ "source",
79
+ "source_link",
80
+ "company_name",
81
+ "company_name_s",
82
+ "territory_hq_s",
83
+ "therapeutic_category_row",
84
+ "therapeutic_category",
85
+ "therapeutic_category_hierarchy",
86
+ "therapeutic_category_s",
87
+ "compound_name",
88
+ "compound_name_s",
89
+ "generic_or_innovator",
90
+ "vaccine_or_adjuvant",
91
+ "drug_delivery_branch_row",
92
+ "drug_delivery_branch",
93
+ "drug_delivery_branch_hierarchy",
94
+ "drug_delivery_branch_s",
95
+ "route_branch_injection",
96
+ "highest_phase",
97
+ "molecule_api_group",
98
+ "conjugate_molecule_types",
99
+ "molecule_name",
100
+ "molecule_name_s",
101
+ "companies_invested_row",
102
+ "companies_invested_id_row",
103
+ "companies_invested_other_id_row",
104
+ "companies_row",
105
+ "companies_id_row",
106
+ "companies_other_id_row",
107
+ "compound_id_row",
108
+ "dd_device",
109
+ "_version_",
110
+ "discovery_technology_name",
111
+ "companies_investor_row",
112
+ "companies_investor_id_row",
113
+ "companies_investor_other_id_row",
114
+ "discovery_technology_id_row",
115
+ "route_branch",
116
+ "route_branch_s",
117
+ "route_branch_hierarchy",
118
+ "explanation",
119
+ "us_state",
120
+ "total_deal_value_in_million",
121
+ "venture_type",
122
+ "form_name_s",
123
+ "technology_name",
124
+ "technology_id_row"
125
+ ]
126
+ print("βœ… System Initialized Successfully.")
127
+ is_initialized = True
128
+
129
+ except Exception as e:
130
+ print(f"\n❌ An error occurred during setup: {e}")
131
+ if ssh_tunnel_server and ssh_tunnel_server.is_active:
132
+ ssh_tunnel_server.stop()
133
+
134
+ sample_doc = solr_client.search(q=":*",rows=1).docs
135
+
136
+ # UPDATED: This is the structured metadata you will feed into your LLM prompt.
137
+ field_metadata = [
138
+ {
139
+ "field_name": "business_model",
140
+ "type": "string (categorical)",
141
+ "example_values": ["pharma/bio", "drug delivery", "pharma services"],
142
+ "definition": "The primary business category of the company involved in the news. Use for filtering by high-level industry segments."
143
+ },
144
+ {
145
+ "field_name": "news_type",
146
+ "type": "string (categorical)",
147
+ "example_values": ["product news", "financial news", "regulatory news"],
148
+ "definition": "The category of the news article itself (e.g., financial, regulatory, acquisition). Use for filtering by the type of event being reported."
149
+ },
150
+ {
151
+ "field_name": "event_type",
152
+ "type": "string (categorical)",
153
+ "example_values": ["phase 2", "phase 1", "pre clinical", "marketed"],
154
+ "definition": "The clinical or developmental stage of a product or event discussed in the article. Essential for queries about clinical trial phases."
155
+ },
156
+ {
157
+ "field_name": "source",
158
+ "type": "string (categorical)",
159
+ "example_values": ["Press Release", "PR Newswire", "Business Wire"],
160
+ "definition": "The original source of the news article, such as a newswire or official report."
161
+ },
162
+ {
163
+ "field_name": "company_name",
164
+ "type": "string (exact match)",
165
+ "example_values": ["pfizer inc.", "astrazeneca plc", "roche"],
166
+ "definition": "The canonical, standardized name of a company. Good for comparison. For searching, prefer 'company_name_s' to catch all variations."
167
+ },
168
+ {
169
+ "field_name": "company_name_s",
170
+ "type": "string (multi-valued, for searching)",
171
+ "example_values": ["pfizer inc.", "roche", "f. hoffmann-la roche ag", "nih"],
172
+ "definition": "A field containing all known names, synonyms, and abbreviations for a company. **Use this field for all queries involving a company name** to ensure comprehensive results (e.g., searching for 'roche' will also find 'f. hoffmann-la roche ag')."
173
+ },
174
+ {
175
+ "field_name": "territory_hq_s",
176
+ "type": "string (multi-valued, hierarchical)",
177
+ "example_values": ["united states of america", "europe", "europe western"],
178
+ "definition": "The geographic location (country and continent) of a company's headquarters. It is hierarchical. Use for filtering by location."
179
+ },
180
+ {
181
+ "field_name": "therapeutic_category",
182
+ "type": "string (specific)",
183
+ "example_values": ["cancer, other", "cancer, nsclc metastatic", "alzheimer's"],
184
+ "definition": "The specific disease or therapeutic area being targeted, often in a detailed, hierarchical format. Use for very specific disease queries."
185
+ },
186
+ {
187
+ "field_name": "therapeutic_category_s",
188
+ "type": "string (multi-valued, for searching)",
189
+ "example_values": ["cancer", "oncology", "infections", "cns"],
190
+ "definition": "Broader, multi-valued therapeutic categories and their synonyms. **Use this field for broad category searches** (e.g., 'cancer', 'cns', 'immune') as it is designed for easier searching."
191
+ },
192
+ {
193
+ "field_name": "compound_name",
194
+ "type": "string (exact match)",
195
+ "example_values": ["opdivo injection solution", "keytruda injection solution"],
196
+ "definition": "The specific, full trade or development name of a drug/compound, including its formulation. For searching, prefer 'compound_name_s'."
197
+ },
198
+ {
199
+ "field_name": "compound_name_s",
200
+ "type": "string (multi-valued, for searching)",
201
+ "example_values": ["nivolumab injection solution", "opdivo injection solution", "ono-4538 injection solution"],
202
+ "definition": "A field containing all known trade names, development codes, and synonyms for a drug/compound. **Use this field for all queries involving a compound name**."
203
+ },
204
+ {
205
+ "field_name": "molecule_name",
206
+ "type": "string (exact match)",
207
+ "example_values": ["cannabidiol", "paclitaxel", "pembrolizumab"],
208
+ "definition": "The generic, non-proprietary name of the active molecule. For searching, prefer 'molecule_name_s'."
209
+ },
210
+ {
211
+ "field_name": "molecule_name_s",
212
+ "type": "string (multi-valued, for searching)",
213
+ "example_values": ["cbd", "s1-220", "a1002n5s"],
214
+ "definition": "A field containing all known generic names, development codes, and synonyms for a molecule. **Use this field for all queries involving a molecule name**."
215
+ },
216
+ {
217
+ "field_name": "highest_phase",
218
+ "type": "string (categorical)",
219
+ "example_values": ["marketed", "phase 2", "phase 1"],
220
+ "definition": "The highest stage of development a drug has ever reached. Distinct from 'event_type' which is about the event in the news."
221
+ },
222
+ {
223
+ "field_name": "drug_delivery_branch_s",
224
+ "type": "string (multi-valued, for searching)",
225
+ "example_values": ["injection", "parenteral", "oral", "injection, other", "oral, other"],
226
+ "definition": "The method of drug administration (e.g., injection, oral). **Use this for queries about route of administration** as it contains broader, search-friendly terms. contains synonyms."
227
+ },
228
+ {
229
+ "field_name": "drug_delivery_branch",
230
+ "type": "string (categorical, specific)",
231
+ "example_values": ["injection, other", "prefilled syringes", "np liposome", "oral enteric/delayed release"],
232
+ "definition": "The most specific category of drug delivery technology or formulation. This provides a detailed, granular breakdown (e.g., 'prefilled syringes', 'np liposome'). Use this field only when a user asks for very specific technologies or for detailed faceting on the technology itself."
233
+ },
234
+ {
235
+ "field_name": "route_branch",
236
+ "type": "string (categorical)",
237
+ "example_values": ["injection", "oral", "topical", "inhalation"],
238
+ "definition": "The specific, primary route of drug administration. This field is good for faceting on exact routes, for example comparing values for injection vs oral. it is usually better to use the broader 'drug_delivery_branch_s' field which contains synonyms and parent categories for search operations."
239
+ },
240
+ {
241
+ "field_name": "molecule_api_group",
242
+ "type": "string (categorical)",
243
+ "example_values": ["small molecules", "biologics", "nucleic acids"],
244
+ "definition": "High-level classification of the drug's molecular type."
245
+ },
246
+ {
247
+ "field_name": "content",
248
+ "type": "text (full-text search)",
249
+ "example_values": ["The largest study to date...", "balstilimab..."],
250
+ "definition": "The full text content of the news article. Use for keyword searches on topics not covered by other specific fields."
251
+ },
252
+ {
253
+ "field_name": "date",
254
+ "type": "date",
255
+ "example_values": ["2020-10-22T00:00:00Z"],
256
+ "definition": "The full publication date and time in ISO 8601 format. Use for precise date range queries (e.g., 'last 30 days', 'between date A and date B')."
257
+ },
258
+ {
259
+ "field_name": "date_year",
260
+ "type": "number (year)",
261
+ "example_values": [2020, 2021, 2022],
262
+ "definition": "The 4-digit year of publication. **Use this for queries involving whole years** (e.g., 'in 2023', 'last year', 'since 2020') as it is more efficient."
263
+ },
264
+ # --- EXISTING FIELD CONFIRMED ---
265
+ {
266
+ "field_name": "total_deal_value_in_million",
267
+ "type": "number (metric)",
268
+ "example_values": [50, 120.5, 176.157, 1000],
269
+ "definition": "The total value of a financial deal, in millions of USD. This is the primary numeric field for financial aggregations (sum, avg, etc.). To use this, you must also filter for news that has a deal value, e.g., 'total_deal_value_in_million:[0 TO *]'."
270
+ }
271
+ ]
272
+
273
+ # Helper function to format the metadata for the prompt
274
+ def format_metadata_for_prompt(metadata):
275
+ formatted_string = ""
276
+ for field in metadata:
277
+ formatted_string += f"- **{field['field_name']}**\n"
278
+ formatted_string += f" - **Type**: {field['type']}\n"
279
+ formatted_string += f" - **Definition**: {field['definition']}\n"
280
+ formatted_string += f" - **Examples**: {', '.join(map(str, field['example_values']))}\n\n"
281
+ return formatted_string
282
+ formatted_field_info = format_metadata_for_prompt(field_metadata)
283
+
284
+
285
+ def parse_suggestions_from_report(report_text):
286
+ """Extracts numbered suggestions from the report's markdown text."""
287
+ # This function remains useful for potentially allowing users to reference suggestions by number, even if we don't force it.
288
+ suggestions_match = re.search(r"### Suggestions for Further Exploration\s*\n(.*?)$", report_text, re.DOTALL | re.IGNORECASE)
289
+ if not suggestions_match: return []
290
+ suggestions_text = suggestions_match.group(1)
291
+ suggestions = re.findall(r"^\s*\d+\.\s*(.*)", suggestions_text, re.MULTILINE)
292
+ return [s.strip() for s in suggestions]
293
+
294
+
295
+ # NEW: Heavily revised prompt for better accuracy using a few-shot example.
296
+ def llm_generate_solr_query(natural_language_query, field_metadata):
297
+ """Generates a Solr query and facet JSON from a natural language query."""
298
+
299
+
300
+
301
+ prompt = f"""
302
+ You are an expert Solr query engineer who converts natural language questions into precise Solr JSON Facet API query objects. Your primary goal is to create a valid JSON object with `query` and `json.facet` keys.
303
+
304
+ ---
305
+ ### CONTEXT & RULES
306
+
307
+ 1. **Today's Date for Calculations**: {datetime.datetime.now().date().strftime("%Y-%m-%d")}
308
+ 2. **Field Usage**: You MUST use the fields described in the 'Field Definitions' section. Pay close attention to the definitions to select the correct field. For instance, use `company_name_s` for searching companies and `date_year` for year-based queries.
309
+ 3. **No `count(*)`**: Do NOT use functions like `count(*)`. The default facet bucket count is sufficient for counting documents.
310
+ 4. **Allowed Aggregations**: For statistical facets (`stats` or `stat` type), only use these functions: `sum`, `avg`, `min`, `max`, `unique`. The primary metric field is `total_deal_value_in_million`.
311
+ 5. **Term Facet Limits**: Every `terms` facet MUST include a `limit` key. Default to `limit: 10` unless the user specifies a different number of top results.
312
+ 6. **Output Format**: Your final output must be a single, raw JSON object and nothing else. Do not add comments, explanations, or markdown formatting like ```json.
313
+
314
+ ---
315
+ ### FIELD DEFINITIONS (Your Source of Truth)
316
+
317
+ {formatted_field_info}
318
+ ---
319
+ ### EXAMPLE
320
+
321
+ **User Query:** "What are the infection news in this year, specifically comparing deal values for injection vs oral routes?"
322
+
323
+ **Correct JSON Output:**
324
+ ```json
325
+ {{
326
+ "query": "therapeutic_category_s:infections AND date_year:{datetime.datetime.now().year} AND total_deal_value_in_million:[0 TO *]",
327
+ "json.facet": {{
328
+ "injection_deals": {{
329
+ "type": "query",
330
+ "q": "route_branch:injection",
331
+ "facet": {{
332
+ "total_deal_value": "sum(total_deal_value_in_million)"
333
+ }}
334
+ }},
335
+ "oral_deals": {{
336
+ "type": "query",
337
+ "q": "route_branch:oral",
338
+ "facet": {{
339
+ "total_deal_value": "sum(total_deal_value_in_million)"
340
+ }}
341
+ }}
342
+ }}
343
+ }}
344
+ ```
345
+ ---
346
+ ### YOUR TASK
347
+
348
+ Now, convert the following user query into a single, raw JSON object with 'query' and 'json.facet' keys, strictly following all rules and field definitions provided above.
349
+
350
+ **User Query:** "{natural_language_query}"
351
+ """
352
+ try:
353
+ # Assuming llm_model is your generative model client
354
+ response = llm_model.generate_content(prompt)
355
+ cleaned_text = re.sub(r'```json\s*|\s*```', '', response.text, flags=re.MULTILINE | re.DOTALL).strip()
356
+ return json.loads(cleaned_text)
357
+ except Exception as e:
358
+ print(f"Error in llm_generate_solr_query: {e}\nRaw Response:\n{response.text if 'response' in locals() else 'N/A'}")
359
+ return None
360
+
361
+ def llm_generate_visualization_code(query_context, facet_data):
362
+ """Generates Python code for visualization based on query and data."""
363
+ prompt = f"""
364
+ You are a Python Data Visualization expert specializing in Matplotlib and Seaborn.
365
+ Your task is to generate Python code to create a single, insightful visualization.
366
+
367
+ **Context:**
368
+ 1. **User's Analytical Goal:** "{query_context}"
369
+ 2. **Aggregated Data (from Solr Facets):**
370
+ ```json
371
+ {json.dumps(facet_data, indent=2)}
372
+ ```
373
+
374
+ **Instructions:**
375
+ 1. **Goal:** Write Python code to generate a chart that best visualizes the answer to the user's goal using the provided data.
376
+ 2. **Data Access:** The data is available in a Python dictionary named `facet_data`. Your code must parse this dictionary.
377
+ 3. **Code Requirements:**
378
+ * Start with `import matplotlib.pyplot as plt` and `import seaborn as sns`.
379
+ * Use `plt.style.use('seaborn-v0_8-whitegrid')` and `fig, ax = plt.subplots(figsize=(12, 7))`. Plot using the `ax` object.
380
+ * Always include a clear `ax.set_title(...)`, `ax.set_xlabel(...)`, and `ax.set_ylabel(...)`.
381
+ * Dynamically find the primary facet key and extract the 'buckets'.
382
+ * For each bucket, extract the 'val' (label) and the relevant metric ('count' or a nested metric).
383
+ * Use `plt.tight_layout()` and rotate x-axis labels if needed.
384
+ 4. **Output Format:** ONLY output raw Python code. Do not wrap it. Do not include `plt.show()` or any explanation.
385
+ """
386
+ try:
387
+ response = llm_model.generate_content(prompt)
388
+ code = re.sub(r'^```python\s*|\s*```$', '', response.text, flags=re.MULTILINE)
389
+ return code
390
+ except Exception as e:
391
+ print(f"Error in llm_generate_visualization_code: {e}")
392
+ return None
393
+
394
+ def execute_viz_code_and_get_path(viz_code, facet_data):
395
+ """Executes visualization code and returns the path to the saved plot image."""
396
+ if not viz_code: return None
397
+ try:
398
+ if not os.path.exists('/tmp/plots'): os.makedirs('/tmp/plots')
399
+ plot_path = f"/tmp/plots/plot_{datetime.datetime.now().timestamp()}.png"
400
+ exec_globals = {'facet_data': facet_data, 'plt': plt, 'sns': sns}
401
+ exec(viz_code, exec_globals)
402
+ fig = exec_globals.get('fig')
403
+ if fig:
404
+ fig.savefig(plot_path, bbox_inches='tight')
405
+ plt.close(fig)
406
+ return plot_path
407
+ return None
408
+ except Exception as e:
409
+ print(f"ERROR executing visualization code: {e}\n---Code---\n{viz_code}")
410
+ return None
411
+
412
+ # NEW: Enhanced prompt based on expert feedback for a more strategic and insightful report.
413
+ def llm_generate_summary_and_suggestions_stream(query_context, facet_data):
414
+ """
415
+ Yields a streaming analytical report and strategic, context-aware suggestions for further exploration.
416
+ """
417
+ prompt = f"""
418
+ You are a leading business intelligence analyst and strategist. Your audience is an executive or decision-maker who relies on you to not just present data, but to uncover its meaning and suggest smart next steps.
419
+
420
+ Your task is to analyze the provided data, deliver a concise, insightful report, and then propose logical follow-up analyses that could uncover deeper trends or causes.
421
+
422
+ **Today's Date for Context:** {datetime.datetime.now().strftime('%Y-%m-%d')}
423
+
424
+ **Analysis Context:**
425
+ * **User's Core Question:** "{query_context}"
426
+ * **Structured Data (Your Evidence):**
427
+ ```json
428
+ {json.dumps(facet_data, indent=2)}
429
+ ```
430
+
431
+ **--- INSTRUCTIONS ---**
432
+
433
+ **PART 1: THE ANALYTICAL REPORT**
434
+ Structure your report using Markdown. Your tone should be insightful, data-driven, and forward-looking.
435
+
436
+ * `## Executive Summary`: A 1-2 sentence, top-line answer to the user's core question. Get straight to the point.
437
+
438
+ * `### Key Findings & Insights`: Use bullet points. Don't just state the data; interpret it.
439
+ * Highlight the most significant figures, patterns, or anomalies.
440
+ * Where relevant, calculate key differences or growth rates (e.g., "X is 25% higher than Y").
441
+ * Pinpoint what the visualization or data reveals about the core business question.
442
+ * **Data Note:** Briefly mention any important caveats if apparent from the data (e.g., a short time frame, a small sample size).
443
+
444
+ * `### Context & Implications`: Briefly explain the "so what?" of these findings. What might this mean for our strategy, the market, or operations?
445
+
446
+ **PART 2: DEEPER DIVE: SUGGESTED FOLLOW-UP ANALYSES**
447
+ After the report, create a final section titled `### Deeper Dive: Suggested Follow-up Analyses`.
448
+
449
+ * **Think like a strategist.** Based on the findings, what would you ask next to validate a trend, understand a change, or uncover a root cause?
450
+ * **Propose 2-3 logical next questions.** These should be concise and framed as natural language questions that inspire further exploration.
451
+ * **Focus on comparative and trend analysis.** For example:
452
+ * If the user asked for "this year," suggest a comparison: *"How does this year's performance in [X] compare to last year?"*
453
+ * If a category is a clear leader, suggest breaking it down: *"What are the top sub-categories driving the growth in [Leading Category]?"*
454
+ * If there's a time-based trend, suggest exploring correlations: *"Is the decline in [Metric Z] correlated with changes in any other category during the same period?"*
455
+ * Format them as a numbered list.
456
+ * Ensure your suggestions are answerable using the available field definitions below.
457
+
458
+ ### FIELD DEFINITIONS (Your Source of Truth)
459
+ {formatted_field_info}
460
+
461
+ **--- YOUR TASK ---**
462
+ Generate the full report and the strategic suggestions based on the user's question and the data provided.
463
+ """
464
+ try:
465
+ # Assuming llm_model is your generative model client
466
+ response_stream = llm_model.generate_content(prompt, stream=True)
467
+ for chunk in response_stream:
468
+ yield chunk.text
469
+ except Exception as e:
470
+ print(f"Error in llm_generate_summary_and_suggestions_stream: {e}")
471
+ yield "Sorry, I was unable to generate a summary for this data."
472
+
473
+ # CHANGED: Reworked the entire function for a simpler, more flexible user-driven flow.
474
+ def process_analysis_flow(user_input, history, state):
475
+ """
476
+ A generator that manages the conversation and yields tuples of UI updates for Gradio.
477
+ This version treats any user input as a new query.
478
+ """
479
+ # Initialize state on the first run
480
+ if state is None:
481
+ state = {'query_count': 0, 'last_suggestions': []}
482
+
483
+ # Reset UI components for the new analysis
484
+ yield (history, state, gr.update(value=None, visible=False), gr.update(value=None, visible=False), gr.update(value=None, visible=False))
485
+
486
+ query_context = user_input.strip()
487
+ if not query_context:
488
+ history.append((user_input, "Please enter a question to analyze."))
489
+ yield (history, state, None, None, None)
490
+ return
491
+
492
+ # 1. Acknowledge and start the process
493
+ history.append((user_input, f"Analyzing: '{query_context}'\n\n*Generating Solr query...*"))
494
+ yield (history, state, None, None, None)
495
+
496
+ # 2. Generate Solr Query
497
+ llm_solr_obj = llm_generate_solr_query(query_context, field_metadata)
498
+ if not llm_solr_obj or 'query' not in llm_solr_obj or 'json.facet' not in llm_solr_obj:
499
+ history.append((None, "I'm sorry, I couldn't generate a valid Solr query for that request. Please try rephrasing your question."))
500
+ yield (history, state, None, None, None)
501
+ return
502
+
503
+ solr_q, solr_facet = llm_solr_obj.get('query'), llm_solr_obj.get('json.facet')
504
+ history.append((None, "βœ… Solr query generated!"))
505
+ formatted_query = f"**Query:**\n```\n{solr_q}\n```\n\n**Facet JSON:**\n```json\n{json.dumps(solr_facet, indent=2)}\n```"
506
+ yield (history, state, None, None, gr.update(value=formatted_query, visible=True))
507
+
508
+ # 3. Execute Query
509
+ try:
510
+ history.append((None, "*Executing query against the database...*"))
511
+ yield (history, state, None, None, gr.update(value=formatted_query, visible=True))
512
+
513
+ search_params = {"rows": 0, "json.facet": json.dumps(solr_facet)}
514
+ results = solr_client.search(q=solr_q, **search_params)
515
+ facet_data = results.raw_response.get("facets", {})
516
+
517
+ if not facet_data or facet_data.get('count', 0) == 0:
518
+ history.append((None, "No data was found for your query. Please try a different question."))
519
+ yield (history, state, None, None, gr.update(value=formatted_query, visible=True))
520
+ return
521
+
522
+ # 4. Generate Visualization
523
+ history.append((None, "βœ… Data retrieved. Generating visualization..."))
524
+ yield (history, state, None, None, gr.update(value=formatted_query, visible=True))
525
+
526
+ viz_code = llm_generate_visualization_code(query_context, facet_data)
527
+ plot_path = execute_viz_code_and_get_path(viz_code, facet_data)
528
+
529
+ output_plot = gr.update(value=plot_path, visible=True) if plot_path else gr.update(visible=False)
530
+ if not plot_path:
531
+ history.append((None, "*I was unable to generate a plot for this data.*\n"))
532
+ yield (history, state, output_plot, None, gr.update(value=formatted_query, visible=True))
533
+
534
+ # 5. Generate and Stream Report
535
+ history.append((None, "βœ… Plot created. Streaming final report..."))
536
+ output_report = gr.update(value="", visible=True) # Make it visible before streaming
537
+ yield (history, state, output_plot, output_report, gr.update(value=formatted_query, visible=True))
538
+
539
+ report_text = ""
540
+ for chunk in llm_generate_summary_and_suggestions_stream(query_context, facet_data):
541
+ report_text += chunk
542
+ yield (history, state, output_plot, report_text, gr.update(value=formatted_query, visible=True))
543
+
544
+ # 6. Finalize and prompt for next action
545
+ state['query_count'] += 1
546
+ state['last_suggestions'] = parse_suggestions_from_report(report_text)
547
+
548
+ next_prompt = "Analysis complete. What would you like to explore next? You can ask a follow-up question, pick a suggestion, or ask something new."
549
+ history.append((None, next_prompt))
550
+ yield (history, state, output_plot, report_text, gr.update(value=formatted_query, visible=True))
551
+
552
+ except Exception as e:
553
+ error_message = f"An unexpected error occurred during analysis: {e}"
554
+ history.append((None, error_message))
555
+ print(f"Error during analysis execution: {e}")
556
+ yield (history, state, None, None, gr.update(value=formatted_query, visible=True))
557
+
558
+ with gr.Blocks(theme=gr.themes.Soft(), css="footer {display: none !important}") as demo:
559
+ state = gr.State()
560
+
561
+ gr.Markdown("# πŸ’Š PharmaCircle AI Data Analyst")
562
+ # CHANGED: Updated introductory text for the new workflow.
563
+ gr.Markdown("Ask a question to begin your analysis. I will generate a Solr query, retrieve the data, create a visualization, and write a report. You can then ask follow-up questions freely.")
564
+
565
+ with gr.Row():
566
+ with gr.Column(scale=1):
567
+ chatbot = gr.Chatbot(label="Analysis Chat Log", height=700, show_copy_button=True)
568
+ # CHANGED: Updated placeholder to encourage free-form questions.
569
+ msg_textbox = gr.Textbox(placeholder="Ask a question, e.g., 'Show me the top 5 companies by total deal value in 2023'", label="Your Question", interactive=True)
570
+ with gr.Row():
571
+ # REMOVED: The "Start Initial Analysis" button.
572
+ # CHANGED: The "Clear" button is now the primary action button besides submitting text.
573
+ clear_button = gr.Button("πŸ”„ Start New Analysis", variant="primary")
574
+
575
+ with gr.Column(scale=2):
576
+ with gr.Accordion("Generated Solr Query", open=False):
577
+ solr_query_display = gr.Markdown("Query will appear here...", visible=True)
578
+ plot_display = gr.Image(label="Visualization", type="filepath", visible=False)
579
+ report_display = gr.Markdown("Report will be streamed here...", visible=False)
580
+
581
+ # --- Event Wiring ---
582
+ # REMOVED: The click handler for the old start button.
583
+
584
+ # This is now the main event handler for all user queries.
585
+ msg_textbox.submit(
586
+ fn=process_analysis_flow,
587
+ inputs=[msg_textbox, chatbot, state],
588
+ outputs=[chatbot, state, plot_display, report_display, solr_query_display]
589
+ )
590
+
591
+ def reset_all():
592
+ # This function now correctly resets the UI for a completely new session.
593
+ return (
594
+ None, # chatbot
595
+ None, # state
596
+ "", # msg_textbox
597
+ gr.update(value=None, visible=False), # plot_display
598
+ gr.update(value=None, visible=False), # report_display
599
+ gr.update(value=None, visible=False) # solr_query_display
600
+ )
601
+
602
+ clear_button.click(fn=reset_all, inputs=None, outputs=[chatbot, state, msg_textbox, plot_display, report_display, solr_query_display], queue=False)
603
+
604
+ if is_initialized:
605
+ demo.queue().launch(debug=True, share=True)
606
+ else:
607
+ print("\nSkipping Gradio launch due to initialization errors.")