cryogenic22 commited on
Commit
246d7cd
·
verified ·
1 Parent(s): 7da1f57

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +4 -297
app.py CHANGED
@@ -1,11 +1,9 @@
1
- # app.py
2
  import os
3
  import time
4
  import json
5
  import re
6
  import streamlit as st
7
  import plotly.graph_objects as go
8
- import plotly.express as px
9
  from dotenv import load_dotenv
10
  from crewai import Agent, Crew, Process, Task
11
 
@@ -203,199 +201,6 @@ def update_progress(container, progress, message=""):
203
  """
204
  container.markdown(progress_html, unsafe_allow_html=True)
205
 
206
- def create_research_crew(topic: str):
207
- """Create the research crew with enhanced prompts"""
208
- researcher = Agent(
209
- role='Research Analyst',
210
- goal=f'Conduct comprehensive market research about {topic} with detailed metrics and verifiable sources',
211
- backstory="You are an experienced market research analyst who focuses on gathering concrete data points and always verifies sources.",
212
- verbose=True
213
- )
214
-
215
- analyst = Agent(
216
- role='Data Analyst',
217
- goal='Transform research data into actionable insights with visualization-ready metrics',
218
- backstory="You are a skilled data analyst who excels at interpreting market research and creating data-driven insights.",
219
- verbose=True
220
- )
221
-
222
- writer = Agent(
223
- role='Report Writer',
224
- goal='Create professional market research reports with executive summary and detailed analysis',
225
- backstory="You are an expert business writer who specializes in creating clear, comprehensive market research reports.",
226
- verbose=True
227
- )
228
-
229
- research_task = Task(
230
- description=f"""
231
- Conduct extensive market research on {topic} with:
232
- 1. Market Overview (market size, growth rates, projections)
233
- 2. Competitive Analysis (market shares, positioning)
234
- 3. Market Dynamics (drivers, challenges, trends)
235
-
236
- Provide specific numerical values and sources.
237
- Format data for visualization.
238
- """,
239
- agent=researcher,
240
- expected_output="Comprehensive research data with specific metrics and sources"
241
- )
242
-
243
- analysis_task = Task(
244
- description=f"""
245
- Analyze the findings and provide:
246
- 1. Growth projections and trends (5 years)
247
- 2. Market share analysis
248
- 3. Competitive landscape
249
- 4. Strategic recommendations
250
-
251
- Include specific numbers and percentages.
252
- """,
253
- agent=analyst,
254
- expected_output="Detailed analysis with visualization-ready metrics",
255
- context=[research_task]
256
- )
257
-
258
- report_task = Task(
259
- description=f"""
260
- Create a professional report with:
261
- 1. Executive Summary (2-3 pages)
262
- 2. Detailed Report (10+ pages)
263
- 3. Sources and Citations
264
-
265
- Format as JSON:
266
- {{
267
- "exec_summary": {{
268
- "summary": "text",
269
- "market_size": "data",
270
- "growth_rate": "data",
271
- "key_players": "data"
272
- }},
273
- "detailed_report": "text",
274
- "sources": ["source1", "source2"],
275
- "metrics": {{
276
- "market_size_data": [],
277
- "growth_rates": [],
278
- "market_shares": []
279
- }}
280
- }}
281
- """,
282
- agent=writer,
283
- expected_output="JSON containing executive summary and detailed report",
284
- context=[research_task, analysis_task]
285
- )
286
-
287
- return Crew(
288
- agents=[researcher, analyst, writer],
289
- tasks=[research_task, analysis_task, report_task],
290
- verbose=True,
291
- process=Process.sequential
292
- )
293
-
294
- def format_json_output(raw_output):
295
- """Format CrewOutput or raw string into proper JSON structure"""
296
- try:
297
- # Handle CrewOutput object
298
- if hasattr(raw_output, 'raw_output'):
299
- raw_text = str(raw_output.raw_output)
300
- else:
301
- raw_text = str(raw_output)
302
-
303
- # Try to find and parse JSON structure
304
- json_pattern = r"\{[\s\S]*\}"
305
- match = re.search(json_pattern, raw_text)
306
- if match:
307
- try:
308
- return json.loads(match.group())
309
- except:
310
- pass
311
-
312
- # If no JSON found, create structured format
313
- return {
314
- "exec_summary": {
315
- "summary": extract_section(raw_text, "Executive Summary"),
316
- "market_size": extract_section(raw_text, "Market Size"),
317
- "growth_rate": extract_section(raw_text, "Growth Rate"),
318
- "key_players": extract_section(raw_text, "Key Players")
319
- },
320
- "detailed_report": raw_text,
321
- "sources": extract_sources(raw_text),
322
- "metrics": {
323
- "market_size_data": [],
324
- "growth_rates": [],
325
- "market_shares": []
326
- }
327
- }
328
- except Exception as e:
329
- st.error(f"Error formatting output: {str(e)}")
330
- return {
331
- "exec_summary": {
332
- "summary": "Error formatting report",
333
- "market_size": "N/A",
334
- "growth_rate": "N/A",
335
- "key_players": "N/A"
336
- },
337
- "detailed_report": raw_text if 'raw_text' in locals() else str(raw_output),
338
- "sources": [],
339
- "metrics": {
340
- "market_size_data": [],
341
- "growth_rates": [],
342
- "market_shares": []
343
- }
344
- }
345
-
346
- def extract_section(text, section_name):
347
- """Extract a section from the text"""
348
- pattern = f"{section_name}.*?\n(.*?)(?=\n\n|$)"
349
- match = re.search(pattern, text, re.DOTALL | re.IGNORECASE)
350
- return match.group(1).strip() if match else ""
351
-
352
- def extract_sources(text):
353
- """Extract sources from the text"""
354
- sources = []
355
- source_pattern = r"Source:.*?(?:\n|$)|\[.*?\]|\(https?://.*?\)"
356
- matches = re.finditer(source_pattern, text, re.MULTILINE)
357
- return [match.group().strip() for match in matches]
358
-
359
- def generate_visualizations(data):
360
- """Generate visualizations based on the report data"""
361
- charts = []
362
-
363
- # Market Size Chart
364
- if data['metrics']['market_size_data']:
365
- fig = go.Figure(data=[
366
- go.Bar(
367
- x=['Current', 'Projected'],
368
- y=data['metrics']['market_size_data'],
369
- text=data['metrics']['market_size_data'],
370
- textposition='auto',
371
- )
372
- ])
373
- fig.update_layout(title='Market Size Projection')
374
- charts.append(fig)
375
-
376
- # Growth Rate Chart
377
- if data['metrics']['growth_rates']:
378
- fig = go.Figure(data=[
379
- go.Line(
380
- x=list(range(len(data['metrics']['growth_rates']))),
381
- y=data['metrics']['growth_rates'],
382
- mode='lines+markers'
383
- )
384
- ])
385
- fig.update_layout(title='Growth Rate Trends')
386
- charts.append(fig)
387
-
388
- # Market Share Chart
389
- if data['metrics']['market_shares']:
390
- fig = go.Figure(data=[go.Pie(
391
- labels=list(data['metrics']['market_shares'].keys()),
392
- values=list(data['metrics']['market_shares'].values())
393
- )])
394
- fig.update_layout(title='Market Share Distribution')
395
- charts.append(fig)
396
-
397
- return charts
398
-
399
  def run_market_research(topic: str, progress_container, chat_container):
400
  """Run the market research process"""
401
  try:
@@ -422,27 +227,14 @@ def run_market_research(topic: str, progress_container, chat_container):
422
  display_agent_message(chat_container, "writer",
423
  "Compiling final report with executive summary and detailed analysis...")
424
  update_progress(progress_container, 75, "Generating report...")
425
-
426
- # Create and run the crew
427
- crew = create_research_crew(topic)
428
- result = crew.kickoff()
429
-
430
- # Format and process the result
431
- report_data = format_json_output(result)
432
-
433
- # Add visualizations
434
- charts = generate_visualizations(report_data)
435
- report_data['charts'] = charts
436
 
437
  update_progress(progress_container, 100, "Report completed!")
438
  display_agent_message(chat_container, "writer",
439
  "✨ Report generation completed! You can now view the full report.")
440
 
441
- return report_data
442
-
443
  except Exception as e:
444
  st.error(f"Error during research: {str(e)}")
445
- return None
446
 
447
  def main():
448
  st.title("🤖 AI Market Research Generator")
@@ -478,97 +270,12 @@ def main():
478
  chat_container = st.container()
479
 
480
  try:
481
- result = run_market_research(topic, progress_container, chat_container)
482
-
483
- if result:
484
- st.session_state.current_report = result
485
- st.session_state.current_topic = topic
486
- st.success("Report generated successfully! View it in the Reports tab.")
487
  except Exception as e:
488
  st.error(f"Error generating report: {str(e)}")
489
  finally:
490
  st.session_state.generating = False
491
-
492
- with tab2:
493
- if hasattr(st.session_state, 'current_report'):
494
- report = st.session_state.current_report
495
- topic = st.session_state.current_topic
496
-
497
- # Display AI Disclaimer
498
- st.markdown("""
499
- <div class="report-header">
500
- <strong>⚠️ AI-Generated Report Disclaimer</strong>
501
- <p>This report was generated using AI agents for market research and analysis.
502
- While we strive for accuracy, please review all content and verify critical information
503
- independently. The analysis and recommendations provided should be used as a
504
- supplementary resource rather than the sole basis for decision-making.</p>
505
- </div>
506
- """, unsafe_allow_html=True)
507
-
508
- # Executive Summary Section
509
- st.subheader("Executive Summary")
510
- st.markdown("""
511
- <div class="exec-summary">
512
- {}
513
-
514
- <div class="key-findings">
515
- <div class="finding-card">
516
- <h4>Market Size</h4>
517
- {}
518
- </div>
519
- <div class="finding-card">
520
- <h4>Growth Rate</h4>
521
- {}
522
- </div>
523
- <div class="finding-card">
524
- <h4>Key Players</h4>
525
- {}
526
- </div>
527
- </div>
528
- </div>
529
- """.format(
530
- report['exec_summary']['summary'],
531
- report['exec_summary']['market_size'],
532
- report['exec_summary']['growth_rate'],
533
- report['exec_summary']['key_players']
534
- ), unsafe_allow_html=True)
535
-
536
- # Visualizations
537
- if 'charts' in report and report['charts']:
538
- st.subheader("Market Analysis Visualizations")
539
- for chart in report['charts']:
540
- st.plotly_chart(chart, use_container_width=True)
541
-
542
- # Detailed Report Section
543
- st.subheader("Detailed Report")
544
- st.markdown(f"""
545
- <div class="detailed-section">
546
- {report['detailed_report']}
547
- </div>
548
- """, unsafe_allow_html=True)
549
-
550
- # Sources Section
551
- if report['sources']:
552
- st.subheader("Sources")
553
- for source in report['sources']:
554
- st.markdown(f"- {source}")
555
-
556
- # Download buttons
557
- col1, col2 = st.columns(2)
558
- with col1:
559
- st.download_button(
560
- "Download Executive Summary",
561
- data=report['exec_summary']['summary'],
562
- file_name=f"{topic}_executive_summary.md",
563
- mime="text/markdown"
564
- )
565
- with col2:
566
- st.download_button(
567
- "Download Full Report",
568
- data=report['detailed_report'],
569
- file_name=f"{topic}_detailed_report.md",
570
- mime="text/markdown"
571
- )
572
 
573
  if __name__ == "__main__":
574
- main()
 
 
1
  import os
2
  import time
3
  import json
4
  import re
5
  import streamlit as st
6
  import plotly.graph_objects as go
 
7
  from dotenv import load_dotenv
8
  from crewai import Agent, Crew, Process, Task
9
 
 
201
  """
202
  container.markdown(progress_html, unsafe_allow_html=True)
203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  def run_market_research(topic: str, progress_container, chat_container):
205
  """Run the market research process"""
206
  try:
 
227
  display_agent_message(chat_container, "writer",
228
  "Compiling final report with executive summary and detailed analysis...")
229
  update_progress(progress_container, 75, "Generating report...")
230
+ time.sleep(1)
 
 
 
 
 
 
 
 
 
 
231
 
232
  update_progress(progress_container, 100, "Report completed!")
233
  display_agent_message(chat_container, "writer",
234
  "✨ Report generation completed! You can now view the full report.")
235
 
 
 
236
  except Exception as e:
237
  st.error(f"Error during research: {str(e)}")
 
238
 
239
  def main():
240
  st.title("🤖 AI Market Research Generator")
 
270
  chat_container = st.container()
271
 
272
  try:
273
+ run_market_research(topic, progress_container, chat_container)
274
+ st.success("Report generated successfully! View it in the Reports tab.")
 
 
 
 
275
  except Exception as e:
276
  st.error(f"Error generating report: {str(e)}")
277
  finally:
278
  st.session_state.generating = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
 
280
  if __name__ == "__main__":
281
+ main()