Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,10 +6,27 @@ 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 |
|
| 10 |
# Load environment variables
|
| 11 |
load_dotenv()
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
# Set page config
|
| 14 |
st.set_page_config(
|
| 15 |
page_title="Market Research Generator",
|
|
@@ -87,6 +104,8 @@ st.markdown("""
|
|
| 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"""
|
|
@@ -97,8 +116,15 @@ def log_agent_activity(agent_type: str, message: str):
|
|
| 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
|
|
@@ -115,6 +141,16 @@ def display_agent_logs():
|
|
| 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"""
|
|
@@ -125,92 +161,103 @@ def update_progress(progress_container, percentage, message=""):
|
|
| 125 |
progress_container.markdown(progress_html, unsafe_allow_html=True)
|
| 126 |
|
| 127 |
def create_research_crew(topic: str):
|
| 128 |
-
"""Create the research crew with
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
verbose=True
|
| 134 |
-
)
|
| 135 |
-
|
| 136 |
-
analyst = Agent(
|
| 137 |
-
role='Data Analyst',
|
| 138 |
-
goal='Transform research data into actionable insights with visualization-ready metrics',
|
| 139 |
-
backstory="You are a skilled data analyst who excels at interpreting market research and creating data-driven insights.",
|
| 140 |
-
verbose=True
|
| 141 |
-
)
|
| 142 |
-
|
| 143 |
-
writer = Agent(
|
| 144 |
-
role='Report Writer',
|
| 145 |
-
goal='Create professional market research reports with executive summary and detailed analysis',
|
| 146 |
-
backstory="You are an expert business writer who specializes in creating clear, comprehensive market research reports.",
|
| 147 |
-
verbose=True
|
| 148 |
-
)
|
| 149 |
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
description=f"""
|
| 166 |
-
Analyze the findings and provide:
|
| 167 |
-
1. Growth projections and trends (5 years)
|
| 168 |
-
2. Market share analysis
|
| 169 |
-
3. Competitive landscape
|
| 170 |
-
4. Strategic recommendations
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
"
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
"
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
}}
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
)
|
| 207 |
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
|
|
|
|
|
|
| 214 |
|
| 215 |
def extract_section(text, section_name):
|
| 216 |
"""Extract a section from the text"""
|
|
@@ -246,6 +293,7 @@ def run_market_research(topic: str, progress_container, chat_container, log_cont
|
|
| 246 |
try:
|
| 247 |
# Clear previous logs
|
| 248 |
st.session_state.agent_logs = []
|
|
|
|
| 249 |
|
| 250 |
# Initialize research team
|
| 251 |
update_progress(progress_container, 0, "Initializing research team...")
|
|
@@ -277,6 +325,7 @@ def run_market_research(topic: str, progress_container, chat_container, log_cont
|
|
| 277 |
|
| 278 |
# Log the raw output for debugging
|
| 279 |
print("Raw output:", raw_text)
|
|
|
|
| 280 |
|
| 281 |
# Format the result
|
| 282 |
report_data = format_json_output(raw_text)
|
|
@@ -301,6 +350,21 @@ def run_market_research(topic: str, progress_container, chat_container, log_cont
|
|
| 301 |
def main():
|
| 302 |
st.title("🤖 AI Market Research Generator")
|
| 303 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
# Initialize session states
|
| 305 |
if 'generating' not in st.session_state:
|
| 306 |
st.session_state.generating = False
|
|
@@ -308,7 +372,7 @@ def main():
|
|
| 308 |
st.session_state.agent_logs = []
|
| 309 |
|
| 310 |
# Create tabs including the new Live Agent Log tab
|
| 311 |
-
tab1, tab2, tab3 = st.tabs(["Generate Report", "View Reports", "Live Agent Log"])
|
| 312 |
|
| 313 |
with tab1:
|
| 314 |
col1, col2 = st.columns([2, 3])
|
|
@@ -375,37 +439,33 @@ def main():
|
|
| 375 |
|
| 376 |
# Executive Summary Section
|
| 377 |
st.subheader("Executive Summary")
|
| 378 |
-
st.markdown("""
|
| 379 |
<div class="exec-summary">
|
| 380 |
-
|
|
|
|
| 381 |
|
| 382 |
<div class="key-findings">
|
| 383 |
<div class="finding-card">
|
| 384 |
<h4>Market Size</h4>
|
| 385 |
-
{}
|
| 386 |
</div>
|
| 387 |
<div class="finding-card">
|
| 388 |
<h4>Growth Rate</h4>
|
| 389 |
-
{}
|
| 390 |
</div>
|
| 391 |
<div class="finding-card">
|
| 392 |
<h4>Key Players</h4>
|
| 393 |
-
{}
|
| 394 |
</div>
|
| 395 |
</div>
|
| 396 |
</div>
|
| 397 |
-
"""
|
| 398 |
-
report['exec_summary']['summary'],
|
| 399 |
-
report['exec_summary']['market_size'],
|
| 400 |
-
report['exec_summary']['growth_rate'],
|
| 401 |
-
report['exec_summary']['key_players']
|
| 402 |
-
), unsafe_allow_html=True)
|
| 403 |
|
| 404 |
# Detailed Report Section
|
| 405 |
st.subheader("Detailed Report")
|
| 406 |
st.markdown(f"""
|
| 407 |
<div class="detailed-section">
|
| 408 |
-
{report['detailed_report']}
|
| 409 |
</div>
|
| 410 |
""", unsafe_allow_html=True)
|
| 411 |
|
|
@@ -440,6 +500,10 @@ def main():
|
|
| 440 |
|
| 441 |
# Display the logs
|
| 442 |
display_agent_logs()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 443 |
|
| 444 |
def format_json_output(raw_output):
|
| 445 |
"""Format CrewOutput or raw string into proper JSON structure"""
|
|
|
|
| 6 |
import plotly.graph_objects as go
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
from crewai import Agent, Crew, Process, Task
|
| 9 |
+
from crewai_tools import SerperDevTool
|
| 10 |
|
| 11 |
# Load environment variables
|
| 12 |
load_dotenv()
|
| 13 |
|
| 14 |
+
# Function to get API keys from HF secrets
|
| 15 |
+
def get_api_keys():
|
| 16 |
+
"""Get API keys from environment or Hugging Face Secrets"""
|
| 17 |
+
# Try to get from HF secrets first
|
| 18 |
+
try:
|
| 19 |
+
serper_key = os.environ.get('SERPER_API_KEY')
|
| 20 |
+
openai_key = os.environ.get('OPENAI_API_KEY')
|
| 21 |
+
|
| 22 |
+
# Log for debugging (will appear in HF Space logs)
|
| 23 |
+
print("API Keys loaded successfully")
|
| 24 |
+
|
| 25 |
+
return serper_key, openai_key
|
| 26 |
+
except Exception as e:
|
| 27 |
+
st.error(f"Error loading API keys: {str(e)}")
|
| 28 |
+
return None, None
|
| 29 |
+
|
| 30 |
# Set page config
|
| 31 |
st.set_page_config(
|
| 32 |
page_title="Market Research Generator",
|
|
|
|
| 104 |
# Initialize session state
|
| 105 |
if 'agent_logs' not in st.session_state:
|
| 106 |
st.session_state.agent_logs = []
|
| 107 |
+
if 'agent_outputs' not in st.session_state:
|
| 108 |
+
st.session_state.agent_outputs = []
|
| 109 |
|
| 110 |
def log_agent_activity(agent_type: str, message: str):
|
| 111 |
"""Log agent activity with timestamp"""
|
|
|
|
| 116 |
'message': message
|
| 117 |
})
|
| 118 |
|
| 119 |
+
def log_agent_output(agent_type: str, output: str):
|
| 120 |
+
"""Log agent outputs for transparency"""
|
| 121 |
+
st.session_state.agent_outputs.append({
|
| 122 |
+
'agent': agent_type,
|
| 123 |
+
'output': output
|
| 124 |
+
})
|
| 125 |
+
|
| 126 |
def display_agent_logs():
|
| 127 |
+
"""Display all agent logs"
|
| 128 |
if not st.session_state.agent_logs:
|
| 129 |
st.info("No agent activity logs yet. Generate a report to see agents in action!")
|
| 130 |
return
|
|
|
|
| 141 |
|
| 142 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 143 |
|
| 144 |
+
def display_agent_outputs():
|
| 145 |
+
"""Display all agent outputs"""
|
| 146 |
+
if not st.session_state.agent_outputs:
|
| 147 |
+
st.info("No agent outputs available yet. Generate a report to see agents in action!")
|
| 148 |
+
return
|
| 149 |
+
|
| 150 |
+
for output in st.session_state.agent_outputs:
|
| 151 |
+
st.markdown(f"**{output['agent']} Output:**")
|
| 152 |
+
st.code(output['output'], language='json')
|
| 153 |
+
|
| 154 |
def update_progress(progress_container, percentage, message=""):
|
| 155 |
"""Update the progress bar."""
|
| 156 |
progress_html = f"""
|
|
|
|
| 161 |
progress_container.markdown(progress_html, unsafe_allow_html=True)
|
| 162 |
|
| 163 |
def create_research_crew(topic: str):
|
| 164 |
+
"""Create the research crew with SerperDev tool integration"""
|
| 165 |
+
try:
|
| 166 |
+
# Initialize SerperDev tool
|
| 167 |
+
search_tool = SerperDevTool()
|
| 168 |
+
log_agent_activity("System", "Initialized SerperDev search tool")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
+
researcher = Agent(
|
| 171 |
+
role='Research Analyst',
|
| 172 |
+
goal=f'Conduct comprehensive market research about {topic} with detailed metrics and verifiable sources',
|
| 173 |
+
backstory="""You are an experienced market research analyst who focuses on gathering concrete data points
|
| 174 |
+
and always verifies sources using real-time market data.""",
|
| 175 |
+
tools=[search_tool],
|
| 176 |
+
verbose=True
|
| 177 |
+
)
|
| 178 |
|
| 179 |
+
analyst = Agent(
|
| 180 |
+
role='Data Analyst',
|
| 181 |
+
goal='Transform research data into actionable insights with visualization-ready metrics',
|
| 182 |
+
backstory="""You are a skilled data analyst who excels at interpreting market research and creating
|
| 183 |
+
data-driven insights from verified sources.""",
|
| 184 |
+
tools=[search_tool],
|
| 185 |
+
verbose=True
|
| 186 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
+
writer = Agent(
|
| 189 |
+
role='Report Writer',
|
| 190 |
+
goal='Create professional market research reports with executive summary and detailed analysis',
|
| 191 |
+
backstory="You are an expert business writer who specializes in creating clear, comprehensive market research reports.",
|
| 192 |
+
verbose=True
|
| 193 |
+
)
|
| 194 |
|
| 195 |
+
research_task = Task(
|
| 196 |
+
description=f"""
|
| 197 |
+
Conduct extensive market research on {topic} with:
|
| 198 |
+
1. Market Overview (market size, growth rates, projections)
|
| 199 |
+
2. Competitive Analysis (market shares, positioning)
|
| 200 |
+
3. Market Dynamics (drivers, challenges, trends)
|
| 201 |
+
|
| 202 |
+
Provide specific numerical values and sources.
|
| 203 |
+
Format data for visualization.
|
| 204 |
+
""",
|
| 205 |
+
agent=researcher,
|
| 206 |
+
expected_output="Comprehensive research data with specific metrics and sources"
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
analysis_task = Task(
|
| 210 |
+
description=f"""
|
| 211 |
+
Analyze the findings and provide:
|
| 212 |
+
1. Growth projections and trends (5 years)
|
| 213 |
+
2. Market share analysis
|
| 214 |
+
3. Competitive landscape
|
| 215 |
+
4. Strategic recommendations
|
| 216 |
+
|
| 217 |
+
Include specific numbers and percentages.
|
| 218 |
+
""",
|
| 219 |
+
agent=analyst,
|
| 220 |
+
expected_output="Detailed analysis with visualization-ready metrics",
|
| 221 |
+
context=[research_task]
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
report_task = Task(
|
| 225 |
+
description=f"""
|
| 226 |
+
Create a professional report with:
|
| 227 |
+
1. Executive Summary (2-3 pages)
|
| 228 |
+
2. Detailed Report (10+ pages)
|
| 229 |
+
3. Sources and Citations
|
| 230 |
+
|
| 231 |
+
Format as JSON:
|
| 232 |
+
{{
|
| 233 |
+
"exec_summary": {{
|
| 234 |
+
"summary": "text",
|
| 235 |
+
"market_size": "data",
|
| 236 |
+
"growth_rate": "data",
|
| 237 |
+
"key_players": "data"
|
| 238 |
+
}},
|
| 239 |
+
"detailed_report": "text",
|
| 240 |
+
"sources": ["source1", "source2"],
|
| 241 |
+
"metrics": {{
|
| 242 |
+
"market_size_data": [],
|
| 243 |
+
"growth_rates": [],
|
| 244 |
+
"market_shares": []
|
| 245 |
+
}}
|
| 246 |
}}
|
| 247 |
+
""",
|
| 248 |
+
agent=writer,
|
| 249 |
+
expected_output="JSON containing executive summary and detailed report",
|
| 250 |
+
context=[research_task, analysis_task]
|
| 251 |
+
)
|
|
|
|
| 252 |
|
| 253 |
+
return Crew(
|
| 254 |
+
agents=[researcher, analyst, writer],
|
| 255 |
+
tasks=[research_task, analysis_task, report_task],
|
| 256 |
+
verbose=True,
|
| 257 |
+
process=Process.sequential
|
| 258 |
+
)
|
| 259 |
+
except Exception as e:
|
| 260 |
+
st.error(f"Error initializing research crew: {str(e)}")
|
| 261 |
|
| 262 |
def extract_section(text, section_name):
|
| 263 |
"""Extract a section from the text"""
|
|
|
|
| 293 |
try:
|
| 294 |
# Clear previous logs
|
| 295 |
st.session_state.agent_logs = []
|
| 296 |
+
st.session_state.agent_outputs = []
|
| 297 |
|
| 298 |
# Initialize research team
|
| 299 |
update_progress(progress_container, 0, "Initializing research team...")
|
|
|
|
| 325 |
|
| 326 |
# Log the raw output for debugging
|
| 327 |
print("Raw output:", raw_text)
|
| 328 |
+
log_agent_output("Crew", raw_text)
|
| 329 |
|
| 330 |
# Format the result
|
| 331 |
report_data = format_json_output(raw_text)
|
|
|
|
| 350 |
def main():
|
| 351 |
st.title("🤖 AI Market Research Generator")
|
| 352 |
|
| 353 |
+
# Get API keys
|
| 354 |
+
serper_key, openai_key = get_api_keys()
|
| 355 |
+
|
| 356 |
+
if not serper_key or not openai_key:
|
| 357 |
+
st.error("Failed to load required API keys. Please check your Hugging Face Space secrets.")
|
| 358 |
+
return
|
| 359 |
+
|
| 360 |
+
# Initialize SerperDev tool with the key
|
| 361 |
+
try:
|
| 362 |
+
search_tool = SerperDevTool()
|
| 363 |
+
print("SerperDev tool initialized successfully") # Debug log
|
| 364 |
+
except Exception as e:
|
| 365 |
+
st.error(f"Error initializing SerperDev tool: {str(e)}")
|
| 366 |
+
return
|
| 367 |
+
|
| 368 |
# Initialize session states
|
| 369 |
if 'generating' not in st.session_state:
|
| 370 |
st.session_state.generating = False
|
|
|
|
| 372 |
st.session_state.agent_logs = []
|
| 373 |
|
| 374 |
# Create tabs including the new Live Agent Log tab
|
| 375 |
+
tab1, tab2, tab3, tab4 = st.tabs(["Generate Report", "View Reports", "Live Agent Log", "Agent Outputs"])
|
| 376 |
|
| 377 |
with tab1:
|
| 378 |
col1, col2 = st.columns([2, 3])
|
|
|
|
| 439 |
|
| 440 |
# Executive Summary Section
|
| 441 |
st.subheader("Executive Summary")
|
| 442 |
+
st.markdown(f"""
|
| 443 |
<div class="exec-summary">
|
| 444 |
+
<h4>Summary</h4>
|
| 445 |
+
{report['exec_summary']['summary']}
|
| 446 |
|
| 447 |
<div class="key-findings">
|
| 448 |
<div class="finding-card">
|
| 449 |
<h4>Market Size</h4>
|
| 450 |
+
{report['exec_summary']['market_size']}
|
| 451 |
</div>
|
| 452 |
<div class="finding-card">
|
| 453 |
<h4>Growth Rate</h4>
|
| 454 |
+
{report['exec_summary']['growth_rate']}
|
| 455 |
</div>
|
| 456 |
<div class="finding-card">
|
| 457 |
<h4>Key Players</h4>
|
| 458 |
+
{report['exec_summary']['key_players']}
|
| 459 |
</div>
|
| 460 |
</div>
|
| 461 |
</div>
|
| 462 |
+
""", unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 463 |
|
| 464 |
# Detailed Report Section
|
| 465 |
st.subheader("Detailed Report")
|
| 466 |
st.markdown(f"""
|
| 467 |
<div class="detailed-section">
|
| 468 |
+
<pre>{report['detailed_report']}</pre>
|
| 469 |
</div>
|
| 470 |
""", unsafe_allow_html=True)
|
| 471 |
|
|
|
|
| 500 |
|
| 501 |
# Display the logs
|
| 502 |
display_agent_logs()
|
| 503 |
+
|
| 504 |
+
with tab4:
|
| 505 |
+
st.subheader("Agent Outputs")
|
| 506 |
+
display_agent_outputs()
|
| 507 |
|
| 508 |
def format_json_output(raw_output):
|
| 509 |
"""Format CrewOutput or raw string into proper JSON structure"""
|