cryogenic22 commited on
Commit
0bf80ee
·
verified ·
1 Parent(s): 68d1d67

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -91
app.py CHANGED
@@ -38,9 +38,83 @@ st.markdown("""
38
  color: white;
39
  transition: width 0.5s ease;
40
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  </style>
42
  """, unsafe_allow_html=True)
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  def update_progress(progress_container, percentage, message=""):
45
  """Update the progress bar."""
46
  progress_html = f"""
@@ -141,32 +215,56 @@ def create_research_crew(topic: str):
141
  def run_market_research(topic: str, progress_container, chat_container, log_container):
142
  """Run the market research process"""
143
  try:
 
 
 
144
  # Step 1: Initialize research team
145
  update_progress(progress_container, 0, "Initializing research team...")
146
- log_container.write("Initializing research team...")
147
  time.sleep(1)
148
 
149
  # Step 2: Gathering market data
150
  update_progress(progress_container, 25, "Gathering market data...")
151
- log_container.write("Research Analyst is gathering market data...")
 
 
 
 
 
 
 
152
  time.sleep(1)
153
 
154
  # Step 3: Analyzing findings
155
  update_progress(progress_container, 50, "Analyzing findings...")
156
- log_container.write("Data Analyst is analyzing findings...")
 
 
 
 
 
 
 
157
  time.sleep(1)
158
 
159
  # Step 4: Compiling final report
160
  update_progress(progress_container, 75, "Compiling final report...")
161
- log_container.write("Report Writer is compiling the final report...")
162
-
 
 
 
 
 
 
 
 
163
  # Create and run the crew
164
  crew = create_research_crew(topic)
165
  result = crew.kickoff()
166
 
167
- # Ensure result is a dictionary
168
- if isinstance(result, list):
169
- result = result[0]
170
 
171
  # Format and process the result
172
  report_data = format_json_output(result)
@@ -177,23 +275,27 @@ def run_market_research(topic: str, progress_container, chat_container, log_cont
177
 
178
  update_progress(progress_container, 100, "Report completed!")
179
  st.success("✨ Report generation completed! You can now view the full report.")
180
- log_container.write("Report generation completed!")
181
 
182
  # Store the report data in session state
183
  st.session_state.current_report = report_data
184
  st.session_state.current_topic = topic
185
 
186
  except Exception as e:
187
- st.error(f"Error during research: {str(e)}")
188
- log_container.write(f"Error during research: {str(e)}")
 
189
 
190
  def main():
191
  st.title("🤖 AI Market Research Generator")
192
 
193
- # Initialize session state for button control
194
  if 'generating' not in st.session_state:
195
  st.session_state.generating = False
 
 
196
 
 
197
  tab1, tab2, tab3 = st.tabs(["Generate Report", "View Reports", "Live Agent Log"])
198
 
199
  with tab1:
@@ -287,9 +389,30 @@ def main():
287
  st.markdown(f"- {source}")
288
 
289
  with tab3:
290
- st.subheader("Live Agent Log")
291
- if 'log_container' in st.session_state:
292
- st.session_state['log_container'].write("Live log will appear here...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
 
294
  def format_json_output(raw_output):
295
  """Format CrewOutput or raw string into proper JSON structure"""
@@ -322,79 +445,4 @@ def format_json_output(raw_output):
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.Scatter(
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
- if __name__ == "__main__":
400
- main()
 
38
  color: white;
39
  transition: width 0.5s ease;
40
  }
41
+
42
+ /* Agent Log Styles */
43
+ .agent-log {
44
+ background: #1a1a1a;
45
+ color: #fff;
46
+ padding: 20px;
47
+ border-radius: 10px;
48
+ font-family: 'Courier New', monospace;
49
+ height: 500px;
50
+ overflow-y: auto;
51
+ }
52
+
53
+ .log-entry {
54
+ margin: 10px 0;
55
+ padding: 8px;
56
+ border-left: 3px solid;
57
+ animation: fadeIn 0.5s ease-in;
58
+ }
59
+
60
+ .log-entry.researcher {
61
+ border-color: #4CAF50;
62
+ background: rgba(76, 175, 80, 0.1);
63
+ }
64
+
65
+ .log-entry.analyst {
66
+ border-color: #2196F3;
67
+ background: rgba(33, 150, 243, 0.1);
68
+ }
69
+
70
+ .log-entry.writer {
71
+ border-color: #FF9800;
72
+ background: rgba(255, 152, 0, 0.1);
73
+ }
74
+
75
+ .timestamp {
76
+ color: #888;
77
+ font-size: 0.8em;
78
+ }
79
+
80
+ @keyframes fadeIn {
81
+ from { opacity: 0; transform: translateY(10px); }
82
+ to { opacity: 1; transform: translateY(0); }
83
+ }
84
  </style>
85
  """, unsafe_allow_html=True)
86
 
87
+ # Initialize session state
88
+ if 'agent_logs' not in st.session_state:
89
+ st.session_state.agent_logs = []
90
+
91
+ def log_agent_activity(agent_type: str, message: str):
92
+ """Log agent activity with timestamp"""
93
+ timestamp = time.strftime("%H:%M:%S")
94
+ st.session_state.agent_logs.append({
95
+ 'timestamp': timestamp,
96
+ 'agent': agent_type,
97
+ 'message': message
98
+ })
99
+
100
+ def display_agent_logs():
101
+ """Display all agent logs"""
102
+ if not st.session_state.agent_logs:
103
+ st.info("No agent activity logs yet. Generate a report to see agents in action!")
104
+ return
105
+
106
+ st.markdown('<div class="agent-log">', unsafe_allow_html=True)
107
+
108
+ for log in st.session_state.agent_logs:
109
+ st.markdown(f"""
110
+ <div class="log-entry {log['agent'].lower()}">
111
+ <span class="timestamp">[{log['timestamp']}]</span>
112
+ <strong>{log['agent']}:</strong> {log['message']}
113
+ </div>
114
+ """, unsafe_allow_html=True)
115
+
116
+ st.markdown('</div>', unsafe_allow_html=True)
117
+
118
  def update_progress(progress_container, percentage, message=""):
119
  """Update the progress bar."""
120
  progress_html = f"""
 
215
  def run_market_research(topic: str, progress_container, chat_container, log_container):
216
  """Run the market research process"""
217
  try:
218
+ # Clear previous logs when starting new research
219
+ st.session_state.agent_logs = []
220
+
221
  # Step 1: Initialize research team
222
  update_progress(progress_container, 0, "Initializing research team...")
223
+ log_agent_activity("System", f"Starting market research for: {topic}")
224
  time.sleep(1)
225
 
226
  # Step 2: Gathering market data
227
  update_progress(progress_container, 25, "Gathering market data...")
228
+ log_agent_activity("Research Analyst", f"Beginning comprehensive research on {topic}")
229
+ display_agent_message(chat_container, "researcher",
230
+ f"Starting comprehensive research on {topic}...")
231
+ log_agent_activity("Research Analyst", "Collecting market size data...")
232
+ time.sleep(1)
233
+ log_agent_activity("Research Analyst", "Analyzing competitive landscape...")
234
+ time.sleep(1)
235
+ log_agent_activity("Research Analyst", "Gathering growth projections...")
236
  time.sleep(1)
237
 
238
  # Step 3: Analyzing findings
239
  update_progress(progress_container, 50, "Analyzing findings...")
240
+ log_agent_activity("Data Analyst", "Beginning data analysis phase")
241
+ display_agent_message(chat_container, "analyst",
242
+ "Processing research data and identifying key insights...")
243
+ log_agent_activity("Data Analyst", "Processing market size metrics...")
244
+ time.sleep(1)
245
+ log_agent_activity("Data Analyst", "Calculating growth rates...")
246
+ time.sleep(1)
247
+ log_agent_activity("Data Analyst", "Generating market share analysis...")
248
  time.sleep(1)
249
 
250
  # Step 4: Compiling final report
251
  update_progress(progress_container, 75, "Compiling final report...")
252
+ log_agent_activity("Report Writer", "Starting report compilation")
253
+ display_agent_message(chat_container, "writer",
254
+ "Compiling final report with executive summary and detailed analysis...")
255
+ log_agent_activity("Report Writer", "Creating executive summary...")
256
+ time.sleep(1)
257
+ log_agent_activity("Report Writer", "Drafting detailed analysis...")
258
+ time.sleep(1)
259
+ log_agent_activity("Report Writer", "Adding citations and sources...")
260
+ time.sleep(1)
261
+
262
  # Create and run the crew
263
  crew = create_research_crew(topic)
264
  result = crew.kickoff()
265
 
266
+ # Log completion
267
+ log_agent_activity("System", "Report generation completed successfully")
 
268
 
269
  # Format and process the result
270
  report_data = format_json_output(result)
 
275
 
276
  update_progress(progress_container, 100, "Report completed!")
277
  st.success("✨ Report generation completed! You can now view the full report.")
278
+ log_agent_activity("System", "Report generation completed!")
279
 
280
  # Store the report data in session state
281
  st.session_state.current_report = report_data
282
  st.session_state.current_topic = topic
283
 
284
  except Exception as e:
285
+ error_msg = f"Error during research: {str(e)}"
286
+ log_agent_activity("System", f"Error: {error_msg}")
287
+ st.error(error_msg)
288
 
289
  def main():
290
  st.title("🤖 AI Market Research Generator")
291
 
292
+ # Initialize session states
293
  if 'generating' not in st.session_state:
294
  st.session_state.generating = False
295
+ if 'agent_logs' not in st.session_state:
296
+ st.session_state.agent_logs = []
297
 
298
+ # Create tabs including the new Live Agent Log tab
299
  tab1, tab2, tab3 = st.tabs(["Generate Report", "View Reports", "Live Agent Log"])
300
 
301
  with tab1:
 
389
  st.markdown(f"- {source}")
390
 
391
  with tab3:
392
+ st.subheader("📋 Agent Activity Log")
393
+ st.markdown("""
394
+ This log shows the detailed activities of our AI agents as they work on your market research.
395
+ Each agent's actions are tracked and timestamped for transparency.
396
+ """)
397
+
398
+ # Add log controls
399
+ col1, col2 = st.columns([6, 1])
400
+ with col1:
401
+ if st.session_state.agent_logs:
402
+ st.download_button(
403
+ "Download Log",
404
+ data="\n".join([f"[{log['timestamp']}] {log['agent']}: {log['message']}"
405
+ for log in st.session_state.agent_logs]),
406
+ file_name="agent_activity_log.txt",
407
+ mime="text/plain"
408
+ )
409
+ with col2:
410
+ if st.button("Clear Log"):
411
+ st.session_state.agent_logs = []
412
+ st.rerun()
413
+
414
+ # Display the logs
415
+ display_agent_logs()
416
 
417
  def format_json_output(raw_output):
418
  """Format CrewOutput or raw string into proper JSON structure"""
 
445
  "metrics": {
446
  "market_size_data": [],
447
  "growth_rates": [],
448
+ "market_shares":