cryogenic22 commited on
Commit
902bfc2
·
verified ·
1 Parent(s): 608dc55

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +208 -126
app.py CHANGED
@@ -1,10 +1,17 @@
1
  # app.py
2
  import os
3
  import time
 
 
4
  import streamlit as st
5
  from dotenv import load_dotenv
6
  from crewai import Agent, Crew, Process, Task
7
 
 
 
 
 
 
8
  # Load environment variables
9
  load_dotenv()
10
 
@@ -12,66 +19,151 @@ load_dotenv()
12
  st.set_page_config(
13
  page_title="Market Research Generator",
14
  page_icon="📊",
15
- layout="wide"
 
16
  )
17
 
18
- # Add custom CSS
19
  st.markdown("""
20
  <style>
21
- .stButton>button {
22
- width: 100%;
23
- margin-top: 20px;
 
 
 
 
 
 
 
24
  }
25
- .report-container {
26
- background-color: #f0f2f6;
27
- padding: 20px;
28
- border-radius: 10px;
29
- margin-top: 20px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  }
 
 
31
  .agent-message {
32
- padding: 10px 15px;
33
- border-radius: 15px;
34
- margin: 5px 0;
35
- max-width: 80%;
36
- line-height: 1.4;
37
  }
38
- .researcher {
39
- background-color: #E3F2FD;
40
- border-left: 4px solid #1976D2;
 
41
  }
42
- .analyst {
43
- background-color: #F3E5F5;
44
- border-left: 4px solid #9C27B0;
 
45
  }
46
- .writer {
47
- background-color: #E8F5E9;
48
- border-left: 4px solid #43A047;
 
 
 
 
 
 
 
 
 
49
  }
50
  </style>
51
  """, unsafe_allow_html=True)
52
 
53
- def display_agent_message(container, role: str, message: str):
54
- """Display an agent message in the container"""
55
- class_name = role.lower().replace(" ", "-")
56
- icons = {
57
- "Research Analyst": "🔍",
58
- "Data Analyst": "📊",
59
- "Report Writer": "✍️"
60
- }
61
-
62
- container.markdown(
63
- f"""
64
- <div class="agent-message {class_name}">
65
- <b>{icons.get(role, '')} {role}:</b><br/>
66
- {message}
67
  </div>
68
- """,
69
- unsafe_allow_html=True
70
- )
71
 
72
- def run_market_research(topic: str, chat_container):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  try:
74
- # Create agents without external tools for now
75
  researcher = Agent(
76
  role='Research Analyst',
77
  goal=f'Conduct thorough market research about {topic}',
@@ -93,65 +185,41 @@ def run_market_research(topic: str, chat_container):
93
  verbose=True
94
  )
95
 
96
- # Display initial agent messages
97
- display_agent_message(
98
- chat_container,
99
- "Research Analyst",
100
- f"Starting research on {topic}..."
101
- )
102
 
103
- # Define tasks
104
  research_task = Task(
105
- description=f"""
106
- Conduct comprehensive market research on {topic}.
107
- Focus on:
108
- 1. Current market size and growth projections
109
- 2. Key players and their market share
110
- 3. Consumer adoption trends
111
- 4. Regulatory environment
112
- """,
113
  agent=researcher,
114
  expected_output="A comprehensive research document with market analysis."
115
  )
116
 
117
- display_agent_message(
118
- chat_container,
119
- "Data Analyst",
120
- "Preparing to analyze the research findings..."
121
- )
122
 
 
123
  analysis_task = Task(
124
- description=f"""
125
- Analyze the research findings for {topic} and identify:
126
- 1. Key market opportunities
127
- 2. Potential challenges
128
- 3. Growth drivers
129
- 4. Competitive dynamics
130
- """,
131
  agent=analyst,
132
- expected_output="An analytical report with key insights and strategic implications.",
133
  context=[research_task]
134
  )
135
 
136
- display_agent_message(
137
- chat_container,
138
- "Report Writer",
139
- "Getting ready to compile the final report..."
140
- )
141
 
 
142
  report_task = Task(
143
- description=f"""
144
- Create a detailed market research report that includes:
145
- 1. Executive summary
146
- 2. Market overview
147
- 3. Key findings
148
- 4. Strategic recommendations
149
- """,
150
  agent=writer,
151
  expected_output="A complete market research report in markdown format.",
152
  context=[research_task, analysis_task]
153
  )
154
 
 
 
155
  # Create and run the crew
156
  crew = Crew(
157
  agents=[researcher, analyst, writer],
@@ -161,6 +229,7 @@ def run_market_research(topic: str, chat_container):
161
  )
162
 
163
  result = crew.kickoff()
 
164
 
165
  # Format the final result
166
  if hasattr(result, 'raw_output'):
@@ -168,63 +237,76 @@ def run_market_research(topic: str, chat_container):
168
  else:
169
  final_report = str(result)
170
 
171
- # Display completion message
172
- display_agent_message(
173
- chat_container,
174
- "Report Writer",
175
- "Report generation completed! ✨"
176
- )
177
 
178
- return final_report
179
 
180
  except Exception as e:
181
  st.error(f"Error: {str(e)}")
182
- return None
183
 
184
  def main():
185
  st.title("🤖 AI Market Research Generator")
186
 
187
- # Create two columns
188
- col1, col2 = st.columns([2, 3])
189
 
190
- with col1:
191
- st.subheader("Enter Research Topic")
192
- topic = st.text_input(
193
- "What market would you like to research?",
194
- placeholder="e.g., Electric Vehicles Market",
195
- key="research_topic"
196
- )
197
 
198
- if st.button("Generate Report", type="primary"):
199
- if not topic:
200
- st.error("Please enter a research topic")
201
- return
 
 
 
202
 
203
- # Clear previous chat
204
- if "chat_container" in st.session_state:
205
- st.session_state.chat_container.empty()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
- # Create new chat container
208
- st.session_state.chat_container = col2.container()
209
 
210
- # Run the research
211
- with st.session_state.chat_container:
212
- st.subheader("🤖 Live Agent Updates")
213
- report = run_market_research(topic, st.session_state.chat_container)
 
214
 
215
- if report:
216
- st.subheader("📊 Generated Report")
217
- st.markdown('<div class="report-container">', unsafe_allow_html=True)
218
- st.markdown(report)
219
- st.markdown('</div>', unsafe_allow_html=True)
220
-
221
- # Download button
222
- st.download_button(
223
- label="Download Report",
224
- data=report,
225
- file_name=f"market_research_{topic.lower().replace(' ', '_')}.md",
226
- mime="text/markdown"
227
- )
228
 
229
  if __name__ == "__main__":
230
  main()
 
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
 
10
+ # Add plotly for interactive charts
11
+ import plotly.graph_objects as go
12
+ import plotly.express as px
13
+ import pandas as pd
14
+
15
  # Load environment variables
16
  load_dotenv()
17
 
 
19
  st.set_page_config(
20
  page_title="Market Research Generator",
21
  page_icon="📊",
22
+ layout="wide",
23
+ initial_sidebar_state="expanded"
24
  )
25
 
26
+ # Add custom CSS for animations and styling
27
  st.markdown("""
28
  <style>
29
+ /* Main container styles */
30
+ .main-container { padding: 20px; }
31
+
32
+ /* Agent flow animation */
33
+ .agent-flow {
34
+ display: flex;
35
+ align-items: center;
36
+ justify-content: space-between;
37
+ margin: 20px 0;
38
+ position: relative;
39
  }
40
+
41
+ .agent-node {
42
+ background-color: white;
43
+ border-radius: 50%;
44
+ width: 80px;
45
+ height: 80px;
46
+ display: flex;
47
+ align-items: center;
48
+ justify-content: center;
49
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
50
+ position: relative;
51
+ z-index: 2;
52
+ }
53
+
54
+ .agent-connector {
55
+ height: 2px;
56
+ background: #ddd;
57
+ flex-grow: 1;
58
+ margin: 0 10px;
59
+ position: relative;
60
+ overflow: hidden;
61
+ }
62
+
63
+ .data-particle {
64
+ position: absolute;
65
+ width: 10px;
66
+ height: 10px;
67
+ background: #4CAF50;
68
+ border-radius: 50%;
69
+ animation: moveParticle 2s linear infinite;
70
+ }
71
+
72
+ @keyframes moveParticle {
73
+ 0% { transform: translateX(0); opacity: 0; }
74
+ 50% { opacity: 1; }
75
+ 100% { transform: translateX(100%); opacity: 0; }
76
  }
77
+
78
+ /* Agent message styles */
79
  .agent-message {
80
+ padding: 15px;
81
+ border-radius: 10px;
82
+ margin: 10px 0;
83
+ animation: slideIn 0.5s ease-out;
 
84
  }
85
+
86
+ @keyframes slideIn {
87
+ from { transform: translateX(-20px); opacity: 0; }
88
+ to { transform: translateX(0); opacity: 1; }
89
  }
90
+
91
+ /* Tab styling */
92
+ .stTabs [data-baseweb="tab-list"] {
93
+ gap: 24px;
94
  }
95
+
96
+ .stTabs [data-baseweb="tab"] {
97
+ height: 50px;
98
+ white-space: pre-wrap;
99
+ background-color: #fff;
100
+ border-radius: 4px;
101
+ color: #000;
102
+ padding: 10px 20px;
103
+ }
104
+
105
+ .stTabs [aria-selected="true"] {
106
+ background-color: #e6f3ff;
107
  }
108
  </style>
109
  """, unsafe_allow_html=True)
110
 
111
+ def create_agent_flow(container):
112
+ """Create animated agent flow diagram"""
113
+ container.markdown("""
114
+ <div class="agent-flow">
115
+ <div class="agent-node">🔍<br/>Research</div>
116
+ <div class="agent-connector">
117
+ <div class="data-particle"></div>
118
+ </div>
119
+ <div class="agent-node">📊<br/>Analysis</div>
120
+ <div class="agent-connector">
121
+ <div class="data-particle"></div>
122
+ </div>
123
+ <div class="agent-node">✍️<br/>Report</div>
 
124
  </div>
125
+ """, unsafe_allow_html=True)
 
 
126
 
127
+ def generate_sample_charts(topic, analysis_text):
128
+ """Generate relevant charts based on the analysis"""
129
+ charts = []
130
+
131
+ # Extract numerical data using simple patterns
132
+ # This is a simplified example - in practice, you'd want more sophisticated parsing
133
+ growth_pattern = r"(\d+(?:\.\d+)?)\s*%"
134
+ values = [float(x) for x in re.findall(growth_pattern, analysis_text)]
135
+
136
+ if values:
137
+ # Market Growth Chart
138
+ fig_growth = go.Figure(data=[
139
+ go.Scatter(
140
+ x=list(range(2024, 2024 + len(values))),
141
+ y=values,
142
+ mode='lines+markers',
143
+ name='Projected Growth'
144
+ )
145
+ ])
146
+ fig_growth.update_layout(
147
+ title=f"{topic} Market Growth Projection",
148
+ xaxis_title="Year",
149
+ yaxis_title="Growth Rate (%)"
150
+ )
151
+ charts.append(fig_growth)
152
+
153
+ # Market Share Donut Chart
154
+ fig_share = go.Figure(data=[go.Pie(
155
+ labels=['Major Players', 'Other Companies'],
156
+ values=[65, 35],
157
+ hole=.3
158
+ )])
159
+ fig_share.update_layout(title='Market Share Distribution')
160
+ charts.append(fig_share)
161
+
162
+ return charts
163
+
164
+ def run_market_research(topic: str, progress_bar, chat_container):
165
  try:
166
+ # Create agents
167
  researcher = Agent(
168
  role='Research Analyst',
169
  goal=f'Conduct thorough market research about {topic}',
 
185
  verbose=True
186
  )
187
 
188
+ # Update progress and display
189
+ progress_bar.progress(0, "Initializing research...")
190
+ time.sleep(1)
 
 
 
191
 
192
+ # Research Phase
193
  research_task = Task(
194
+ description=f"Conduct comprehensive market research on {topic}...",
 
 
 
 
 
 
 
195
  agent=researcher,
196
  expected_output="A comprehensive research document with market analysis."
197
  )
198
 
199
+ progress_bar.progress(25, "Gathering market data...")
200
+ time.sleep(1)
 
 
 
201
 
202
+ # Analysis Phase
203
  analysis_task = Task(
204
+ description=f"Analyze the research findings for {topic}...",
 
 
 
 
 
 
205
  agent=analyst,
206
+ expected_output="An analytical report with key insights.",
207
  context=[research_task]
208
  )
209
 
210
+ progress_bar.progress(50, "Analyzing findings...")
211
+ time.sleep(1)
 
 
 
212
 
213
+ # Report Phase
214
  report_task = Task(
215
+ description=f"Create a detailed market research report...",
 
 
 
 
 
 
216
  agent=writer,
217
  expected_output="A complete market research report in markdown format.",
218
  context=[research_task, analysis_task]
219
  )
220
 
221
+ progress_bar.progress(75, "Generating report...")
222
+
223
  # Create and run the crew
224
  crew = Crew(
225
  agents=[researcher, analyst, writer],
 
229
  )
230
 
231
  result = crew.kickoff()
232
+ progress_bar.progress(100, "Completed!")
233
 
234
  # Format the final result
235
  if hasattr(result, 'raw_output'):
 
237
  else:
238
  final_report = str(result)
239
 
240
+ # Generate charts based on the analysis
241
+ charts = generate_sample_charts(topic, final_report)
 
 
 
 
242
 
243
+ return final_report, charts
244
 
245
  except Exception as e:
246
  st.error(f"Error: {str(e)}")
247
+ return None, []
248
 
249
  def main():
250
  st.title("🤖 AI Market Research Generator")
251
 
252
+ # Create tabs
253
+ tab1, tab2 = st.tabs(["Generate Report", "View Report"])
254
 
255
+ with tab1:
256
+ col1, col2 = st.columns([2, 3])
 
 
 
 
 
257
 
258
+ with col1:
259
+ st.subheader("Enter Research Topic")
260
+ topic = st.text_input(
261
+ "What market would you like to research?",
262
+ placeholder="e.g., Electric Vehicles Market",
263
+ key="research_topic"
264
+ )
265
 
266
+ if st.button("Generate Report", type="primary"):
267
+ if not topic:
268
+ st.error("Please enter a research topic")
269
+ return
270
+
271
+ # Create progress bar and containers
272
+ progress = st.progress(0)
273
+ chat_container = st.container()
274
+
275
+ # Show agent flow diagram
276
+ create_agent_flow(col2)
277
+
278
+ # Run the research
279
+ report, charts = run_market_research(topic, progress, chat_container)
280
+
281
+ if report:
282
+ # Store results in session state
283
+ st.session_state.report = report
284
+ st.session_state.charts = charts
285
+ st.session_state.current_tab = "report"
286
+
287
+ # Switch to report tab
288
+ st.experimental_rerun()
289
+
290
+ with tab2:
291
+ if hasattr(st.session_state, 'report'):
292
+ st.subheader("📊 Market Research Report")
293
 
294
+ # Display report sections
295
+ st.markdown(st.session_state.report)
296
 
297
+ # Display charts
298
+ if hasattr(st.session_state, 'charts'):
299
+ st.subheader("📈 Data Visualization")
300
+ for chart in st.session_state.charts:
301
+ st.plotly_chart(chart, use_container_width=True)
302
 
303
+ # Download button
304
+ st.download_button(
305
+ label="Download Report",
306
+ data=st.session_state.report,
307
+ file_name=f"market_research_{topic.lower().replace(' ', '_')}.md",
308
+ mime="text/markdown"
309
+ )
 
 
 
 
 
 
310
 
311
  if __name__ == "__main__":
312
  main()