cryogenic22 commited on
Commit
9f14bb5
·
verified ·
1 Parent(s): d5ad1fb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -631
app.py CHANGED
@@ -1,29 +1,14 @@
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
  from dotenv import load_dotenv
9
- from crewai import Agent, Crew, Process, Task
10
- from crewai_tools import SerperDevTool
 
11
 
12
  # Load environment variables
13
  load_dotenv()
14
 
15
- # Function to get API keys from HF secrets
16
- def get_api_keys():
17
- """Get API keys from environment or Hugging Face Secrets"""
18
- try:
19
- serper_key = os.environ.get('SERPER_API_KEY')
20
- openai_key = os.environ.get('OPENAI_API_KEY')
21
- print("API Keys loaded successfully")
22
- return serper_key, openai_key
23
- except Exception as e:
24
- st.error(f"Error loading API keys: {str(e)}")
25
- return None, None
26
-
27
  # Set page config
28
  st.set_page_config(
29
  page_title="Market Research Generator",
@@ -32,524 +17,40 @@ st.set_page_config(
32
  initial_sidebar_state="expanded"
33
  )
34
 
35
- # Add all CSS styles
36
- st.markdown("""
37
- <style>
38
- /* Progress Bar */
39
- .progress-container {
40
- width: 100%;
41
- background: #f0f0f0;
42
- border-radius: 8px;
43
- margin: 20px 0;
44
- }
45
-
46
- .progress-bar {
47
- height: 24px;
48
- background: linear-gradient(90deg, #4caf50, #81c784);
49
- border-radius: 8px;
50
- text-align: center;
51
- line-height: 24px;
52
- color: white;
53
- transition: width 0.5s ease;
54
- }
55
-
56
- /* Agent Log Styles */
57
- .agent-log {
58
- background: #1a1a1a;
59
- color: #fff;
60
- padding: 20px;
61
- border-radius: 10px;
62
- font-family: 'Courier New', monospace;
63
- height: 500px;
64
- overflow-y: auto;
65
- }
66
-
67
- .log-entry {
68
- margin: 10px 0;
69
- padding: 8px;
70
- border-left: 3px solid;
71
- animation: fadeIn 0.5s ease-in;
72
- }
73
-
74
- .log-entry.researcher {
75
- border-color: #4CAF50;
76
- background: rgba(76, 175, 80, 0.1);
77
- }
78
-
79
- .log-entry.analyst {
80
- border-color: #2196F3;
81
- background: rgba(33, 150, 243, 0.1);
82
- }
83
-
84
- .log-entry.writer {
85
- border-color: #FF9800;
86
- background: rgba(255, 152, 0, 0.1);
87
- }
88
-
89
- .timestamp {
90
- color: #888;
91
- font-size: 0.8em;
92
- }
93
-
94
- @keyframes fadeIn {
95
- from { opacity: 0; transform: translateY(10px); }
96
- to { opacity: 1; transform: translateY(0); }
97
- }
98
- </style>
99
- """, unsafe_allow_html=True)
100
-
101
- # Initialize session state
102
- if 'agent_logs' not in st.session_state:
103
- st.session_state.agent_logs = []
104
- if 'agent_outputs' not in st.session_state:
105
- st.session_state.agent_outputs = []
106
-
107
- def log_agent_activity(agent_type: str, message: str):
108
- """Log agent activity with timestamp"""
109
- timestamp = time.strftime("%H:%M:%S")
110
- st.session_state.agent_logs.append({
111
- 'timestamp': timestamp,
112
- 'agent': agent_type,
113
- 'message': message
114
- })
115
-
116
- def log_agent_output(agent_type: str, output: str):
117
- """Log agent outputs for transparency"""
118
- st.session_state.agent_outputs.append({
119
- 'agent': agent_type,
120
- 'output': output
121
- })
122
-
123
- def display_agent_logs():
124
- """Display all agent logs"""
125
- if not st.session_state.agent_logs:
126
- st.info("No agent activity logs yet. Generate a report to see agents in action!")
127
- return
128
-
129
- st.markdown('<div class="agent-log">', unsafe_allow_html=True)
130
-
131
- for log in st.session_state.agent_logs:
132
- st.markdown(f"""
133
- <div class="log-entry {log['agent'].lower()}">
134
- <span class="timestamp">[{log['timestamp']}]</span>
135
- <strong>{log['agent']}:</strong> {log['message']}
136
- </div>
137
- """, unsafe_allow_html=True)
138
-
139
- st.markdown('</div>', unsafe_allow_html=True)
140
-
141
- def display_agent_outputs():
142
- """Display all agent outputs"""
143
- if not st.session_state.agent_outputs:
144
- st.info("No agent outputs available yet. Generate a report to see agents in action!")
145
- return
146
-
147
- for output in st.session_state.agent_outputs:
148
- st.markdown(f"**{output['agent']} Output:**")
149
- st.code(output['output'], language='json')
150
-
151
- def update_progress(progress_container, percentage, message=""):
152
- """Update the progress bar."""
153
- progress_html = f"""
154
- <div class="progress-container">
155
- <div class="progress-bar" style="width: {percentage}%">{message}</div>
156
- </div>
157
- """
158
- progress_container.markdown(progress_html, unsafe_allow_html=True)
159
- def create_research_crew(topic: str):
160
- """Create the research crew with SerperDev tool integration"""
161
- try:
162
- # Initialize SerperDev tool
163
- search_tool = SerperDevTool()
164
- log_agent_activity("System", "Initialized SerperDev search tool")
165
-
166
- researcher = Agent(
167
- role='Research Analyst',
168
- goal=f'Conduct exhaustive market research about {topic} with comprehensive analysis and multiple data sources',
169
- backstory="""You are a senior market research analyst with 15+ years of experience in conducting
170
- detailed industry analysis. You excel at gathering in-depth market data, analyzing industry trends,
171
- and identifying market patterns through multiple verified sources. You always ensure data accuracy
172
- and provide contextual analysis alongside raw data. You're known for producing comprehensive
173
- research reports that combine quantitative data with qualitative insights.""",
174
- tools=[search_tool],
175
- verbose=True
176
- )
177
-
178
- analyst = Agent(
179
- role='Data Analyst',
180
- goal='Transform research data into profound market insights with detailed analysis and visualizations',
181
- backstory="""You are an expert data analyst and market intelligence specialist with deep expertise
182
- in converting complex market data into actionable insights. You specialize in predictive analytics,
183
- trend analysis, and creating data visualizations that tell compelling stories. You have a
184
- track record of identifying hidden market opportunities and providing nuanced analysis of market dynamics.
185
- You excel at breaking down complex market phenomena into understandable insights.""",
186
- tools=[search_tool],
187
- verbose=True
188
- )
189
-
190
- writer = Agent(
191
- role='Report Writer',
192
- goal='Create extensive, professional market research reports with compelling narratives and insights',
193
- backstory="""You are a seasoned business writer and market research expert who specializes in creating
194
- comprehensive, engaging market research reports. You excel at weaving data and insights into compelling
195
- narratives that provide deep understanding of market dynamics. You're skilled at creating well-structured,
196
- detailed reports that maintain reader engagement while delivering thorough analysis. You're known for your
197
- ability to explain complex market dynamics in clear, professional language while maintaining attention to detail.""",
198
- verbose=True
199
- )
200
-
201
- research_task = Task(
202
- description=f"""
203
- Conduct exhaustive market research on {topic} with:
204
-
205
- 1. Comprehensive Market Overview:
206
- - Detailed market size analysis (historical, current, and projected)
207
- - Growth rates and CAGR with supporting rationale
208
- - Market segmentation analysis (by type, application, region, etc.)
209
- - Value chain analysis
210
- - Pricing analysis and trends
211
- - Regional market breakdowns with specific data points
212
- - Key market metrics and KPIs
213
-
214
- 2. In-depth Competitive Analysis:
215
- - Detailed profiles of key players
216
- - Market share analysis with historical trends
217
- - Competitive strategies and positioning
218
- - Recent developments and their impact
219
- - SWOT analysis of major players
220
- - Competitive advantages and differentiators
221
- - Market concentration and fragmentation analysis
222
-
223
- 3. Extensive Market Dynamics:
224
- - Detailed analysis of growth drivers with specific examples
225
- - Comprehensive examination of market challenges
226
- - Emerging trends with supporting data
227
- - Regulatory landscape and its impact
228
- - Technology impact assessment
229
- - Patent analysis and innovation trends
230
- - Consumer behavior analysis
231
- - Supply-demand gap analysis
232
-
233
- 4. Economic and External Factors:
234
- - Macroeconomic influences
235
- - Industry-specific economic indicators
236
- - Global and regional economic impacts
237
- - Trade dynamics and supply chain analysis
238
- - Investment patterns and M&A activity
239
-
240
- Use multiple sources for verification and cross-reference all data points.
241
- Include case studies and specific examples where relevant.
242
- Provide rich context for all numerical data.
243
- Format all data to be visualization-ready.
244
- """,
245
- agent=researcher,
246
- expected_output="Exhaustive research data with comprehensive analysis and verified sources"
247
- )
248
- analysis_task = Task(
249
- description="""
250
- Perform comprehensive analysis of the research findings:
251
-
252
- 1. Strategic Market Analysis:
253
- - Detailed 5-year growth projections with scenario analysis
254
- - Market maturity assessment
255
- - Porter's Five Forces analysis
256
- - Market attractiveness analysis
257
- - Investment opportunity assessment
258
- - Risk analysis and mitigation strategies
259
-
260
- 2. Advanced Data Analysis:
261
- - Time series analysis of key metrics
262
- - Correlation analysis between market factors
263
- - Market share evolution analysis
264
- - Price sensitivity analysis
265
- - Demand forecasting models
266
- - Regional market potential assessment
267
- - Market penetration analysis
268
-
269
- 3. Competitive Intelligence:
270
- - Detailed competitor benchmarking
271
- - Market positioning matrix
272
- - Strategic group mapping
273
- - Competitive strategy analysis
274
- - Market entry barriers assessment
275
- - Future competitive scenarios
276
-
277
- 4. Trend Analysis:
278
- - Technology adoption curves
279
- - Consumer trend analysis
280
- - Innovation impact assessment
281
- - Market disruption analysis
282
- - Future market scenarios
283
- - Emerging opportunities assessment
284
-
285
- Create visualization-ready data for:
286
- - Market size and growth trends
287
- - Competitive landscape maps
288
- - Regional distribution charts
289
- - Market share evolution
290
- - Value chain analysis
291
- - Technology adoption curves
292
- - Price trend analysis
293
- - Market segmentation
294
- - Key player comparison matrices
295
-
296
- Include specific metrics, percentages, and growth rates.
297
- Provide context and implications for all analyses.
298
- Format data for multiple visualization types.
299
- """,
300
- agent=analyst,
301
- expected_output="Comprehensive analysis with visualization-ready metrics and detailed insights",
302
- context=[research_task]
303
- )
304
-
305
- report_task = Task(
306
- description="""
307
- Create an extensive professional report including:
308
 
309
- 1. Executive Summary (3-4 pages):
310
- - Key findings and insights
311
- - Critical market metrics
312
- - Major trends and developments
313
- - Strategic implications
314
- - Investment opportunities
315
- - Future outlook
316
- - Key recommendations
317
-
318
- 2. Comprehensive Market Analysis (15-20 pages):
319
- a) Market Overview
320
- - Market definition and segmentation
321
- - Market size and growth analysis
322
- - Value chain analysis
323
- - Market structure and dynamics
324
- - Regional market analysis
325
- - Pricing analysis
326
-
327
- b) Competitive Landscape
328
- - Market share analysis
329
- - Key player profiles
330
- - Competitive strategies
331
- - Market positioning
332
- - SWOT analysis
333
- - Recent developments
334
-
335
- c) Market Dynamics
336
- - Growth drivers analysis
337
- - Market challenges
338
- - Opportunity assessment
339
- - Trend analysis
340
- - Technology impact
341
- - Regulatory framework
342
-
343
- d) Future Outlook
344
- - Market forecasts
345
- - Trend projections
346
- - Scenario analysis
347
- - Strategic recommendations
348
- - Risk analysis
349
- - Success factors
350
-
351
- 3. Appendices
352
- - Detailed methodology
353
- - Data tables
354
- - Additional charts and graphs
355
- - Case studies
356
- - Glossary
357
- - Sources and citations
358
-
359
- Format as JSON:
360
- {
361
- "exec_summary": {
362
- "summary": "comprehensive executive overview",
363
- "market_size": "detailed market size analysis",
364
- "growth_rate": "detailed growth projections",
365
- "key_players": "detailed competitive analysis",
366
- "critical_insights": "key strategic insights",
367
- "recommendations": "strategic recommendations"
368
- },
369
- "detailed_report": {
370
- "market_overview": "comprehensive market analysis",
371
- "competitive_landscape": "detailed competitive analysis",
372
- "market_dynamics": "in-depth market dynamics",
373
- "future_outlook": "detailed projections and scenarios",
374
- "strategic_implications": "strategic analysis and recommendations"
375
- },
376
- "sources": ["source1", "source2"],
377
- "metrics": {
378
- "market_size_data": [],
379
- "growth_rates": [],
380
- "market_shares": {},
381
- "regional_distribution": [],
382
- "segment_analysis": [],
383
- "competitor_metrics": {},
384
- "trend_indicators": []
385
- },
386
- "visualizations": {
387
- "market_growth": "time series data",
388
- "competitive_landscape": "positioning data",
389
- "regional_analysis": "geographical data",
390
- "segment_breakdown": "segmentation data",
391
- "trend_analysis": "trend indicators"
392
- }
393
- }
394
- """,
395
- agent=writer,
396
- expected_output="Comprehensive JSON containing detailed executive summary and full report",
397
- context=[research_task, analysis_task]
398
- )
399
-
400
- return Crew(
401
- agents=[researcher, analyst, writer],
402
- tasks=[research_task, analysis_task, report_task],
403
- verbose=True,
404
- process=Process.sequential
405
- )
406
- except Exception as e:
407
- st.error(f"Error initializing research crew: {str(e)}")
408
- raise e
409
- def extract_section(text, section_name):
410
- """Extract a section from the text"""
411
- pattern = f"{section_name}.*?\n(.*?)(?=\n\n|$)"
412
- match = re.search(pattern, text, re.DOTALL | re.IGNORECASE)
413
- if match:
414
- return match.group(1).strip()
415
-
416
- # Try alternative patterns
417
- pattern2 = f"{section_name}[:\s](.*?)(?=\n\n|$)"
418
- match = re.search(pattern2, text, re.DOTALL | re.IGNORECASE)
419
- return match.group(1).strip() if match else "Information not found"
420
-
421
- def extract_sources(text):
422
- """Extract sources from the text"""
423
- sources = []
424
- patterns = [
425
- r"Source:.*?(?:\n|$)",
426
- r"\[.*?\]",
427
- r"\(https?://.*?\)",
428
- r"Reference:.*?(?:\n|$)",
429
- r"Retrieved from:.*?(?:\n|$)"
430
- ]
431
-
432
- for pattern in patterns:
433
- matches = re.finditer(pattern, text, re.MULTILINE)
434
- sources.extend([match.group().strip() for match in matches])
435
-
436
- return sources if sources else ["Sources not explicitly mentioned in the report"]
437
-
438
- def format_json_output(raw_output):
439
- """Format CrewOutput or raw string into proper JSON structure"""
440
  try:
441
- # Handle CrewOutput object
442
- if hasattr(raw_output, 'raw_output'):
443
- raw_text = str(raw_output.raw_output)
444
- else:
445
- raw_text = str(raw_output)
446
-
447
- # Try to find and parse JSON structure
448
- json_pattern = r"\{[\s\S]*\}"
449
- match = re.search(json_pattern, raw_text)
450
- if match:
451
- try:
452
- return json.loads(match.group())
453
- except:
454
- pass
455
-
456
- # If no JSON found, create structured format
457
- return {
458
- "exec_summary": {
459
- "summary": extract_section(raw_text, "Executive Summary"),
460
- "market_size": extract_section(raw_text, "Market Size"),
461
- "growth_rate": extract_section(raw_text, "Growth Rate"),
462
- "key_players": extract_section(raw_text, "Key Players")
463
- },
464
- "detailed_report": raw_text,
465
- "sources": extract_sources(raw_text),
466
- "metrics": {
467
- "market_size_data": [],
468
- "growth_rates": [],
469
- "market_shares": {},
470
- "regional_distribution": [],
471
- "segment_analysis": [],
472
- "competitor_metrics": {},
473
- "trend_indicators": []
474
- }
475
- }
476
  except Exception as e:
477
- st.error(f"Error formatting output: {str(e)}")
478
- return {
479
- "exec_summary": {
480
- "summary": "Error formatting report",
481
- "market_size": "N/A",
482
- "growth_rate": "N/A",
483
- "key_players": "N/A"
484
- },
485
- "detailed_report": raw_text if 'raw_text' in locals() else str(raw_output),
486
- "sources": [],
487
- "metrics": {
488
- "market_size_data": [],
489
- "growth_rates": [],
490
- "market_shares": {}
491
- }
492
- }
493
 
494
- def run_market_research(topic: str, progress_container, chat_container, log_container):
495
  """Run the market research process"""
496
  try:
497
- # Clear previous logs
498
- st.session_state.agent_logs = []
499
- st.session_state.agent_outputs = []
500
-
501
- # Initialize research team
502
- update_progress(progress_container, 0, "Initializing research team...")
503
- log_agent_activity("System", f"Starting market research for: {topic}")
504
-
505
  # Create and run the crew
506
  crew = create_research_crew(topic)
507
 
508
- # Research Phase
509
  update_progress(progress_container, 25, "Gathering market data...")
510
- log_agent_activity("Research Analyst", f"Beginning comprehensive research on {topic}")
511
- time.sleep(1)
512
-
513
- # Analysis Phase
514
  update_progress(progress_container, 50, "Analyzing findings...")
515
- log_agent_activity("Data Analyst", "Processing research data...")
516
- time.sleep(1)
517
-
518
- # Report Phase
519
  update_progress(progress_container, 75, "Generating report...")
520
- log_agent_activity("Report Writer", "Compiling final report...")
521
- time.sleep(1)
522
 
523
  # Execute the crew
524
  result = crew.kickoff()
525
 
526
- # Process the result
527
- if hasattr(result, 'raw_output'):
528
- raw_text = str(result.raw_output)
529
- else:
530
- raw_text = str(result)
531
-
532
- # Log the raw output for debugging
533
- print("Raw output:", raw_text)
534
- log_agent_output("Crew", raw_text)
535
-
536
- # Format the result
537
- report_data = format_json_output(raw_text)
538
-
539
- # Update progress and log completion
540
  update_progress(progress_container, 100, "Report completed!")
541
- log_agent_activity("System", "Report generation completed successfully")
542
-
543
- # Store in session state
544
- st.session_state.current_report = report_data
545
- st.session_state.current_topic = topic
546
-
547
- return report_data
548
 
549
  except Exception as e:
550
- error_msg = f"Error during research: {str(e)}"
551
- log_agent_activity("System", f"Error: {error_msg}")
552
- st.error(error_msg)
553
  print(f"Full error details: {str(e)}") # For debugging
554
  return None
555
 
@@ -568,54 +69,39 @@ def main():
568
  st.session_state.generating = False
569
 
570
  # Create tabs
571
- tab1, tab2, tab3, tab4 = st.tabs(["Generate Report", "View Reports", "Live Agent Log", "Agent Outputs"])
572
 
573
  with tab1:
574
- col1, col2 = st.columns([2, 3])
575
-
576
- with col1:
577
- st.subheader("Enter Research Topic")
578
- topic = st.text_input(
579
- "What market would you like to research?",
580
- placeholder="e.g., Electric Vehicles Market"
581
- )
582
-
583
- if st.session_state.generating:
584
- st.button("Generating Report...", disabled=True)
585
- else:
586
- if st.button("Generate Report", type="primary"):
587
- if not topic:
588
- st.error("Please enter a research topic")
589
- else:
590
- st.session_state.generating = True
591
-
592
- # Create containers
593
- progress_container = st.container()
594
- chat_container = st.container()
595
- log_container = st.container()
596
-
597
- try:
598
- with st.spinner("Generating report..."):
599
- result = run_market_research(
600
- topic,
601
- progress_container,
602
- chat_container,
603
- log_container
604
- )
605
-
606
- if result:
607
- st.success("Report generated successfully! Switch to the Reports tab to view it.")
608
- except Exception as e:
609
- st.error(f"Error generating report: {str(e)}")
610
- finally:
611
- st.session_state.generating = False
612
 
613
- # Show live agent activity in col2
614
- with col2:
615
- st.subheader("Live Agent Activity")
616
- st.markdown('<div class="agent-log">', unsafe_allow_html=True)
617
- display_agent_logs()
618
- st.markdown('</div>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
619
 
620
  with tab2:
621
  if 'current_report' in st.session_state:
@@ -623,83 +109,38 @@ def main():
623
  topic = st.session_state.current_topic
624
 
625
  # Display AI Disclaimer
626
- st.markdown("""
627
- <div class="report-header">
628
- <strong>⚠️ AI-Generated Report Disclaimer</strong>
629
- <p>This report was generated using AI agents for market research and analysis.
630
- While we strive for accuracy, please review all content and verify critical information
631
- independently. The analysis and recommendations provided should be used as a
632
- supplementary resource rather than the sole basis for decision-making.</p>
633
- </div>
634
- """, unsafe_allow_html=True)
635
 
636
- # Executive Summary Section
637
  st.subheader("Executive Summary")
638
- st.markdown(f"""
639
- <div class="exec-summary">
640
- <h4>Summary</h4>
641
- {report['exec_summary']['summary']}
642
-
643
- <div class="key-findings">
644
- <div class="finding-card">
645
- <h4>Market Size</h4>
646
- {report['exec_summary']['market_size']}
647
- </div>
648
- <div class="finding-card">
649
- <h4>Growth Rate</h4>
650
- {report['exec_summary']['growth_rate']}
651
- </div>
652
- <div class="finding-card">
653
- <h4>Key Players</h4>
654
- {report['exec_summary']['key_players']}
655
- </div>
656
- </div>
657
- </div>
658
- """, unsafe_allow_html=True)
659
 
660
- # Detailed Report Section
661
- st.subheader("Detailed Report")
662
- st.markdown(f"""
663
- <div class="detailed-section">
664
- {report['detailed_report']}
665
- </div>
666
- """, unsafe_allow_html=True)
667
 
668
- # Sources Section
669
  if report['sources']:
670
  st.subheader("Sources")
671
  for source in report['sources']:
672
  st.markdown(f"- {source}")
673
-
674
- with tab3:
675
- st.subheader("📋 Agent Activity Log")
676
- st.markdown("""
677
- This log shows the detailed activities of our AI agents as they work on your market research.
678
- Each agent's actions are tracked and timestamped for transparency.
679
- """)
680
-
681
- # Add log controls
682
- col1, col2 = st.columns([6, 1])
683
- with col1:
684
- if st.session_state.agent_logs:
685
- st.download_button(
686
- "Download Log",
687
- data="\n".join([f"[{log['timestamp']}] {log['agent']}: {log['message']}"
688
- for log in st.session_state.agent_logs]),
689
- file_name="agent_activity_log.txt",
690
- mime="text/plain"
691
- )
692
- with col2:
693
- if st.button("Clear Log"):
694
- st.session_state.agent_logs = []
695
- st.rerun()
696
-
697
- # Display the logs
698
- display_agent_logs()
699
-
700
- with tab4:
701
- st.subheader("Agent Outputs")
702
- display_agent_outputs()
703
 
704
  if __name__ == "__main__":
705
  main()
 
1
  # app.py
2
  import os
 
 
 
3
  import streamlit as st
 
4
  from dotenv import load_dotenv
5
+ from agents import create_research_crew
6
+ from utils import format_json_output, update_progress
7
+ from styles import main_styles
8
 
9
  # Load environment variables
10
  load_dotenv()
11
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  # Set page config
13
  st.set_page_config(
14
  page_title="Market Research Generator",
 
17
  initial_sidebar_state="expanded"
18
  )
19
 
20
+ # Add styles
21
+ st.markdown(main_styles, unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ def get_api_keys():
24
+ """Get API keys from environment or Hugging Face Secrets"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  try:
26
+ serper_key = os.environ.get('SERPER_API_KEY')
27
+ openai_key = os.environ.get('OPENAI_API_KEY')
28
+ print("API Keys loaded successfully")
29
+ return serper_key, openai_key
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  except Exception as e:
31
+ st.error(f"Error loading API keys: {str(e)}")
32
+ return None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
+ def run_market_research(topic: str, progress_container):
35
  """Run the market research process"""
36
  try:
 
 
 
 
 
 
 
 
37
  # Create and run the crew
38
  crew = create_research_crew(topic)
39
 
40
+ # Update progress
41
  update_progress(progress_container, 25, "Gathering market data...")
 
 
 
 
42
  update_progress(progress_container, 50, "Analyzing findings...")
 
 
 
 
43
  update_progress(progress_container, 75, "Generating report...")
 
 
44
 
45
  # Execute the crew
46
  result = crew.kickoff()
47
 
48
+ # Format and return the result
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  update_progress(progress_container, 100, "Report completed!")
50
+ return format_json_output(result)
 
 
 
 
 
 
51
 
52
  except Exception as e:
53
+ st.error(f"Error during research: {str(e)}")
 
 
54
  print(f"Full error details: {str(e)}") # For debugging
55
  return None
56
 
 
69
  st.session_state.generating = False
70
 
71
  # Create tabs
72
+ tab1, tab2 = st.tabs(["Generate Report", "View Reports"])
73
 
74
  with tab1:
75
+ st.subheader("Enter Research Topic")
76
+ topic = st.text_input(
77
+ "What market would you like to research?",
78
+ placeholder="e.g., Electric Vehicles Market"
79
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ if st.session_state.generating:
82
+ st.button("Generating Report...", disabled=True)
83
+ else:
84
+ if st.button("Generate Report", type="primary"):
85
+ if not topic:
86
+ st.error("Please enter a research topic")
87
+ else:
88
+ st.session_state.generating = True
89
+
90
+ # Create progress container
91
+ progress_container = st.container()
92
+
93
+ try:
94
+ with st.spinner("Generating comprehensive market research report..."):
95
+ result = run_market_research(topic, progress_container)
96
+
97
+ if result:
98
+ st.session_state.current_report = result
99
+ st.session_state.current_topic = topic
100
+ st.success("Report generated successfully! View it in the Reports tab.")
101
+ except Exception as e:
102
+ st.error(f"Error generating report: {str(e)}")
103
+ finally:
104
+ st.session_state.generating = False
105
 
106
  with tab2:
107
  if 'current_report' in st.session_state:
 
109
  topic = st.session_state.current_topic
110
 
111
  # Display AI Disclaimer
112
+ st.info("⚠️ This report was generated using AI. Please verify critical information independently.")
 
 
 
 
 
 
 
 
113
 
114
+ # Executive Summary
115
  st.subheader("Executive Summary")
116
+ st.write(report['exec_summary']['summary'])
117
+
118
+ # Key Metrics
119
+ col1, col2, col3 = st.columns(3)
120
+ with col1:
121
+ st.metric("Market Size", report['exec_summary']['market_size'])
122
+ with col2:
123
+ st.metric("Growth Rate", report['exec_summary']['growth_rate'])
124
+ with col3:
125
+ st.metric("Key Players", report['exec_summary']['key_players'])
 
 
 
 
 
 
 
 
 
 
 
126
 
127
+ # Detailed Report
128
+ st.subheader("Detailed Analysis")
129
+ st.write(report['detailed_report'])
 
 
 
 
130
 
131
+ # Sources
132
  if report['sources']:
133
  st.subheader("Sources")
134
  for source in report['sources']:
135
  st.markdown(f"- {source}")
136
+
137
+ # Download button
138
+ st.download_button(
139
+ "Download Report",
140
+ data=str(report['detailed_report']),
141
+ file_name=f"{topic.lower().replace(' ', '_')}_market_research.md",
142
+ mime="text/markdown"
143
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
  if __name__ == "__main__":
146
  main()