cryogenic22 commited on
Commit
7d6dd45
·
verified ·
1 Parent(s): c897b65

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -39
app.py CHANGED
@@ -1,13 +1,14 @@
1
- # app.py
2
  import os
3
  import time
4
  import json
5
  import random
 
 
 
6
  import streamlit as st
7
- from dotenv import load_dotenv
8
  from crewai import Agent, Crew, Process, Task
9
- import plotly.graph_objects as go
10
- import re
11
 
12
  # Load environment variables
13
  load_dotenv()
@@ -141,8 +142,10 @@ st.markdown("""
141
  background: linear-gradient(
142
  90deg,
143
  transparent,
144
- rgba(255, 255, 255, 0.4),
145
- transparent
 
 
146
  );
147
  animation: shimmer 2s infinite;
148
  }
@@ -184,6 +187,7 @@ st.markdown("""
184
  </style>
185
  """, unsafe_allow_html=True)
186
 
 
187
  def format_json_output(raw_output):
188
  """Format CrewOutput or raw string into proper JSON structure"""
189
  try:
@@ -199,8 +203,8 @@ def format_json_output(raw_output):
199
  if match:
200
  try:
201
  return json.loads(match.group())
202
- except:
203
- pass
204
 
205
  # If no JSON found, create structured format
206
  return {
@@ -208,7 +212,16 @@ def format_json_output(raw_output):
208
  "detailed_report": raw_text,
209
  "sources": extract_sources(raw_text)
210
  }
211
-
 
 
 
 
 
 
 
 
 
212
  def display_thinking_animation():
213
  """Display thinking animation dots"""
214
  return """
@@ -219,6 +232,7 @@ def display_thinking_animation():
219
  </div>
220
  """
221
 
 
222
  def display_agent_message(container, agent_type: str, message: str, thinking: bool = False):
223
  """Display an animated agent message"""
224
  icons = {
@@ -226,7 +240,7 @@ def display_agent_message(container, agent_type: str, message: str, thinking: bo
226
  "analyst": "📊",
227
  "writer": "✍️"
228
  }
229
-
230
  message_html = f"""
231
  <div class="agent-message">
232
  <div class="agent-avatar {agent_type}">
@@ -240,6 +254,7 @@ def display_agent_message(container, agent_type: str, message: str, thinking: bo
240
  """
241
  container.markdown(message_html, unsafe_allow_html=True)
242
 
 
243
  def update_progress(container, progress, message=""):
244
  """Update progress bar with animation"""
245
  progress_html = f"""
@@ -252,6 +267,7 @@ def update_progress(container, progress, message=""):
252
  """
253
  container.markdown(progress_html, unsafe_allow_html=True)
254
 
 
255
  def run_market_research(topic: str, progress_container, chat_container):
256
  try:
257
  researcher = Agent(
@@ -260,14 +276,14 @@ def run_market_research(topic: str, progress_container, chat_container):
260
  backstory='You are an experienced market research analyst with expertise in data analysis and trend identification.',
261
  verbose=True
262
  )
263
-
264
  analyst = Agent(
265
  role='Data Analyst',
266
  goal='Create data-driven insights with specific metrics',
267
  backstory='You are a skilled data analyst who specializes in turning research into actionable insights.',
268
  verbose=True
269
  )
270
-
271
  writer = Agent(
272
  role='Report Writer',
273
  goal='Create both executive summary and detailed reports with citations',
@@ -276,14 +292,14 @@ def run_market_research(topic: str, progress_container, chat_container):
276
  )
277
 
278
  # Research Phase
279
- display_agent_message(chat_container, "researcher",
280
- f"👋 Hello! I'll be researching the {topic} market thoroughly.", False)
281
  time.sleep(1)
282
-
283
  update_progress(progress_container, 20, "🔍 Gathering market data...")
284
  display_agent_message(chat_container, "researcher", "Processing market information...", True)
285
  time.sleep(1)
286
-
287
  research_task = Task(
288
  description=f"""
289
  Research {topic} with focus on:
@@ -292,7 +308,7 @@ def run_market_research(topic: str, progress_container, chat_container):
292
  3. Competitive analysis
293
  4. Future trends
294
  5. Include verifiable sources
295
-
296
  Format the output as clear sections with numerical data points.
297
  """,
298
  agent=researcher,
@@ -301,10 +317,10 @@ def run_market_research(topic: str, progress_container, chat_container):
301
 
302
  # Analysis Phase
303
  update_progress(progress_container, 40, "📊 Analyzing findings...")
304
- display_agent_message(chat_container, "analyst",
305
- "I've received the research data. Beginning analysis...", False)
306
  time.sleep(1)
307
-
308
  analysis_task = Task(
309
  description=f"""
310
  Analyze the research findings and provide:
@@ -312,7 +328,7 @@ def run_market_research(topic: str, progress_container, chat_container):
312
  2. Market share analysis
313
  3. Competitive landscape
314
  4. Key opportunities and challenges
315
-
316
  Include specific metrics and percentages.
317
  """,
318
  agent=analyst,
@@ -322,17 +338,17 @@ def run_market_research(topic: str, progress_container, chat_container):
322
 
323
  # Report Phase
324
  update_progress(progress_container, 70, "✍️ Generating report...")
325
- display_agent_message(chat_container, "writer",
326
- "Converting analysis into comprehensive report...", False)
327
  time.sleep(1)
328
-
329
  report_task = Task(
330
  description=f"""
331
  Create a market research report with:
332
  1. Executive Summary (2-3 paragraphs)
333
  2. Detailed Report (full analysis)
334
  3. Sources and Citations
335
-
336
  Format as a JSON with:
337
  {{
338
  "exec_summary": "summary text",
@@ -353,32 +369,31 @@ def run_market_research(topic: str, progress_container, chat_container):
353
  )
354
 
355
  result = crew.kickoff()
356
-
357
  # Update final progress
358
  update_progress(progress_container, 100, "✨ Report completed!")
359
- display_agent_message(chat_container, "writer",
360
- "Report generation completed! You can now view the full report.", False)
361
 
362
  return format_json_output(result)
363
 
364
  except Exception as e:
365
- st.error(f"Error formatting output: {str(e)}")
366
  return {
367
- "exec_summary": "Error formatting report",
368
- "detailed_report": raw_text if 'raw_text' in locals() else str(raw_output),
369
  "sources": []
370
  }
371
 
 
372
  def extract_section(text, section_name):
373
  """Extract a section from the text"""
374
- pattern = f"{section_name}.*?\n(.*?)(?=\n\n|$)"
375
- match = re.search(pattern, text, re.DOTALL | re.IGNORECASE)
376
- return match.group(1).strip() if match else ""
377
-
378
- def extract_sources(text):
379
- """Extract sources from the text"""
380
- sources = []
381
- source_pattern = r"Source:.*?(?:\n|$)|\[.*?\]|\(https?://.*?\)"
382
  matches = re.finditer(source_pattern, text, re.MULTILINE)
383
  return [match.group().strip() for match in matches]
384
 
 
1
+
2
  import os
3
  import time
4
  import json
5
  import random
6
+ import re
7
+
8
+ import plotly.graph_objects as go
9
  import streamlit as st
 
10
  from crewai import Agent, Crew, Process, Task
11
+ from dotenv import load_dotenv
 
12
 
13
  # Load environment variables
14
  load_dotenv()
 
142
  background: linear-gradient(
143
  90deg,
144
  transparent,
145
+ rgba(255, 255, 255,  
146
+ 0.4),
147
+ transparent  
148
+
149
  );
150
  animation: shimmer 2s infinite;
151
  }
 
187
  </style>
188
  """, unsafe_allow_html=True)
189
 
190
+
191
  def format_json_output(raw_output):
192
  """Format CrewOutput or raw string into proper JSON structure"""
193
  try:
 
203
  if match:
204
  try:
205
  return json.loads(match.group())
206
+ except json.JSONDecodeError:
207
+ pass # Or handle the error as needed
208
 
209
  # If no JSON found, create structured format
210
  return {
 
212
  "detailed_report": raw_text,
213
  "sources": extract_sources(raw_text)
214
  }
215
+
216
+ except Exception as e:
217
+ st.error(f"Error formatting output: {str(e)}")
218
+ return {
219
+ "exec_summary": "Error formatting report",
220
+ "detailed_report": raw_text if 'raw_text' in locals() else str(raw_output),
221
+ "sources": []
222
+ }
223
+
224
+
225
  def display_thinking_animation():
226
  """Display thinking animation dots"""
227
  return """
 
232
  </div>
233
  """
234
 
235
+
236
  def display_agent_message(container, agent_type: str, message: str, thinking: bool = False):
237
  """Display an animated agent message"""
238
  icons = {
 
240
  "analyst": "📊",
241
  "writer": "✍️"
242
  }
243
+
244
  message_html = f"""
245
  <div class="agent-message">
246
  <div class="agent-avatar {agent_type}">
 
254
  """
255
  container.markdown(message_html, unsafe_allow_html=True)
256
 
257
+
258
  def update_progress(container, progress, message=""):
259
  """Update progress bar with animation"""
260
  progress_html = f"""
 
267
  """
268
  container.markdown(progress_html, unsafe_allow_html=True)
269
 
270
+
271
  def run_market_research(topic: str, progress_container, chat_container):
272
  try:
273
  researcher = Agent(
 
276
  backstory='You are an experienced market research analyst with expertise in data analysis and trend identification.',
277
  verbose=True
278
  )
279
+
280
  analyst = Agent(
281
  role='Data Analyst',
282
  goal='Create data-driven insights with specific metrics',
283
  backstory='You are a skilled data analyst who specializes in turning research into actionable insights.',
284
  verbose=True
285
  )
286
+
287
  writer = Agent(
288
  role='Report Writer',
289
  goal='Create both executive summary and detailed reports with citations',
 
292
  )
293
 
294
  # Research Phase
295
+ display_agent_message(chat_container, "researcher",
296
+ f"👋 Hello! I'll be researching the {topic} market thoroughly.", False)
297
  time.sleep(1)
298
+
299
  update_progress(progress_container, 20, "🔍 Gathering market data...")
300
  display_agent_message(chat_container, "researcher", "Processing market information...", True)
301
  time.sleep(1)
302
+
303
  research_task = Task(
304
  description=f"""
305
  Research {topic} with focus on:
 
308
  3. Competitive analysis
309
  4. Future trends
310
  5. Include verifiable sources
311
+
312
  Format the output as clear sections with numerical data points.
313
  """,
314
  agent=researcher,
 
317
 
318
  # Analysis Phase
319
  update_progress(progress_container, 40, "📊 Analyzing findings...")
320
+ display_agent_message(chat_container, "analyst",
321
+ "I've received the research data. Beginning analysis...", False)
322
  time.sleep(1)
323
+
324
  analysis_task = Task(
325
  description=f"""
326
  Analyze the research findings and provide:
 
328
  2. Market share analysis
329
  3. Competitive landscape
330
  4. Key opportunities and challenges
331
+
332
  Include specific metrics and percentages.
333
  """,
334
  agent=analyst,
 
338
 
339
  # Report Phase
340
  update_progress(progress_container, 70, "✍️ Generating report...")
341
+ display_agent_message(chat_container, "writer",
342
+ "Converting analysis into comprehensive report...", False)
343
  time.sleep(1)
344
+
345
  report_task = Task(
346
  description=f"""
347
  Create a market research report with:
348
  1. Executive Summary (2-3 paragraphs)
349
  2. Detailed Report (full analysis)
350
  3. Sources and Citations
351
+
352
  Format as a JSON with:
353
  {{
354
  "exec_summary": "summary text",
 
369
  )
370
 
371
  result = crew.kickoff()
372
+
373
  # Update final progress
374
  update_progress(progress_container, 100, "✨ Report completed!")
375
+ display_agent_message(chat_container, "writer",
376
+ "Report generation completed! You can now view the full report.", False)
377
 
378
  return format_json_output(result)
379
 
380
  except Exception as e:
381
+ st.error(f"Error generating report: {str(e)}")
382
  return {
383
+ "exec_summary": "Error generating report",
384
+ "detailed_report": "",
385
  "sources": []
386
  }
387
 
388
+
389
  def extract_section(text, section_name):
390
  """Extract a section from the text"""
391
+ pattern = f"{section_name}.*?\n(.*?)(?=\n\n|<span class="math-inline">\)"
392
+ match \= re\.search\(pattern, text, re\.DOTALL \| re\.IGNORECASE\)
393
+ return match\.group\(1\)\.strip\(\) if match else ""
394
+ def extract\_sources\(text\)\:
395
+ """Extract sources from the text"""
396
+ source\_pattern \= r"Source\:\.\*?\(?\:\\n\|</span>)|\[.*?\]|\(https?://.*?\)"
 
 
397
  matches = re.finditer(source_pattern, text, re.MULTILINE)
398
  return [match.group().strip() for match in matches]
399