Spaces:
Sleeping
Sleeping
| # app.py | |
| import os | |
| import streamlit as st | |
| from dotenv import load_dotenv | |
| from agents import create_research_crew | |
| from utils import format_json_output, update_progress | |
| from styles import main_styles | |
| # Load environment variables | |
| load_dotenv() | |
| # Set page config | |
| st.set_page_config( | |
| page_title="Market Research Generator", | |
| page_icon="๐", | |
| layout="wide", | |
| initial_sidebar_state="expanded" | |
| ) | |
| # Add styles | |
| st.markdown(main_styles, unsafe_allow_html=True) | |
| def get_api_keys(): | |
| """Get API keys from environment or Hugging Face Secrets""" | |
| try: | |
| serper_key = os.environ.get('SERPER_API_KEY') | |
| openai_key = os.environ.get('OPENAI_API_KEY') | |
| print("API Keys loaded successfully") | |
| return serper_key, openai_key | |
| except Exception as e: | |
| st.error(f"Error loading API keys: {str(e)}") | |
| return None, None | |
| # In app.py | |
| def run_market_research(topic: str, progress_container): | |
| """Run the market research process""" | |
| try: | |
| # Create and run the crew | |
| crew = create_research_crew(topic) | |
| # Update progress and show what's happening | |
| update_progress(progress_container, 25, "Gathering market data...") | |
| st.write("๐ Research Analyst is gathering comprehensive market data...") | |
| update_progress(progress_container, 50, "Analyzing findings...") | |
| st.write("๐ Data Analyst is processing market insights...") | |
| update_progress(progress_container, 75, "Generating report...") | |
| st.write("โ๏ธ Report Writer is creating the final document...") | |
| # Execute the crew and get result | |
| result = crew.kickoff() | |
| # Debug print | |
| st.write("Debug - Raw Result:", result) | |
| # Get raw text from result | |
| if hasattr(result, 'raw_output'): | |
| raw_text = str(result.raw_output) | |
| else: | |
| raw_text = str(result) | |
| # Debug print | |
| st.write("Debug - Raw Text:", raw_text[:500]) # Show first 500 chars | |
| # Split the text into sections | |
| sections = raw_text.split('===') | |
| # Initialize the processed report structure | |
| processed_report = { | |
| 'exec_summary': { | |
| 'summary': "Executive summary not available", | |
| 'market_highlights': "Highlights not available", | |
| 'strategic_implications': "Implications not available", | |
| 'recommendations': "Recommendations not available" | |
| }, | |
| 'market_analysis': { | |
| 'overview': "Overview not available", | |
| 'dynamics': "Industry dynamics not available", | |
| 'competitive_landscape': "Competitive analysis not available", | |
| 'strategic_analysis': "Strategic analysis not available" | |
| }, | |
| 'future_outlook': "Future outlook not available", | |
| 'sources': [] | |
| } | |
| # Process each section | |
| for section in sections: | |
| if not section.strip(): | |
| continue | |
| # Split section into title and content | |
| parts = section.strip().split('\n', 1) | |
| if len(parts) == 2: | |
| section_name = parts[0].strip().upper() | |
| content = parts[1].strip() | |
| # Debug print | |
| st.write(f"Debug - Processing section: {section_name}") | |
| if "EXECUTIVE SUMMARY" in section_name: | |
| subsections = content.split('##') | |
| processed_report['exec_summary']['summary'] = subsections[0].strip() | |
| for subsection in subsections[1:]: | |
| if 'Market Highlights' in subsection: | |
| processed_report['exec_summary']['market_highlights'] = subsection.split('\n', 1)[1].strip() | |
| elif 'Strategic Implications' in subsection: | |
| processed_report['exec_summary']['strategic_implications'] = subsection.split('\n', 1)[1].strip() | |
| elif 'Recommendations' in subsection: | |
| processed_report['exec_summary']['recommendations'] = subsection.split('\n', 1)[1].strip() | |
| elif "MARKET ANALYSIS" in section_name: | |
| subsections = content.split('##') | |
| for subsection in subsections: | |
| if 'Market Overview' in subsection: | |
| processed_report['market_analysis']['overview'] = subsection.split('\n', 1)[1].strip() | |
| elif 'Industry Dynamics' in subsection: | |
| processed_report['market_analysis']['dynamics'] = subsection.split('\n', 1)[1].strip() | |
| elif 'Competitive Landscape' in subsection: | |
| processed_report['market_analysis']['competitive_landscape'] = subsection.split('\n', 1)[1].strip() | |
| elif 'Strategic Analysis' in subsection: | |
| processed_report['market_analysis']['strategic_analysis'] = subsection.split('\n', 1)[1].strip() | |
| elif "FUTURE OUTLOOK" in section_name: | |
| processed_report['future_outlook'] = content.strip() | |
| elif "SOURCES" in section_name or "APPENDICES" in section_name: | |
| sources = [line.strip() for line in content.split('\n') | |
| if line.strip() and (line.strip().startswith('-') or | |
| line.strip().startswith('โข'))] | |
| processed_report['sources'] = sources | |
| # Debug print | |
| st.write("Debug - Processed Report Structure:", processed_report.keys()) | |
| update_progress(progress_container, 100, "Report completed!") | |
| return processed_report | |
| except Exception as e: | |
| st.error(f"Error during research: {str(e)}") | |
| print(f"Full error details: {str(e)}") # For debugging | |
| return None | |
| def main(): | |
| st.title("๐ค AI Market Research Generator") | |
| # Get API keys | |
| serper_key, openai_key = get_api_keys() | |
| if not serper_key or not openai_key: | |
| st.error("Failed to load required API keys. Please check your Hugging Face Space secrets.") | |
| return | |
| # Initialize session states | |
| if 'generating' not in st.session_state: | |
| st.session_state.generating = False | |
| # Create tabs | |
| tab1, tab2 = st.tabs(["Generate Report", "View Reports"]) | |
| with tab1: | |
| st.subheader("Enter Research Topic") | |
| topic = st.text_input( | |
| "What market would you like to research?", | |
| placeholder="e.g., Electric Vehicles Market" | |
| ) | |
| if st.session_state.generating: | |
| st.button("Generating Report...", disabled=True) | |
| else: | |
| if st.button("Generate Report", type="primary"): | |
| if not topic: | |
| st.error("Please enter a research topic") | |
| else: | |
| st.session_state.generating = True | |
| # Create progress container | |
| progress_container = st.container() | |
| try: | |
| with st.spinner("Generating comprehensive market research report..."): | |
| result = run_market_research(topic, progress_container) | |
| if result: | |
| st.session_state.current_report = result | |
| st.session_state.current_topic = topic | |
| st.success("Report generated successfully! View it in the Reports tab.") | |
| except Exception as e: | |
| st.error(f"Error generating report: {str(e)}") | |
| finally: | |
| st.session_state.generating = False | |
| with tab2: | |
| if 'current_report' in st.session_state: | |
| try: | |
| report = st.session_state.current_report | |
| topic = st.session_state.current_topic | |
| # Display AI Disclaimer | |
| st.warning("โ ๏ธ This report was generated using AI. While we strive for accuracy, please verify critical information independently.") | |
| # Report Title | |
| st.title(f"๐ Market Research Report: {topic}") | |
| # Executive Summary Section | |
| st.header("Executive Summary") | |
| st.write(report['exec_summary']['summary']) | |
| with st.expander("Key Market Highlights", expanded=True): | |
| st.write(report['exec_summary']['market_highlights']) | |
| with st.expander("Strategic Implications", expanded=True): | |
| st.write(report['exec_summary']['strategic_implications']) | |
| with st.expander("Key Recommendations", expanded=True): | |
| st.write(report['exec_summary']['recommendations']) | |
| # Market Analysis Section | |
| st.header("Market Analysis") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.subheader("Market Overview") | |
| st.write(report['market_analysis']['overview']) | |
| st.subheader("Industry Dynamics") | |
| st.write(report['market_analysis']['dynamics']) | |
| with col2: | |
| st.subheader("Competitive Landscape") | |
| st.write(report['market_analysis']['competitive_landscape']) | |
| st.subheader("Strategic Analysis") | |
| st.write(report['market_analysis']['strategic_analysis']) | |
| # Future Outlook | |
| st.header("Future Outlook") | |
| st.write(report['future_outlook']) | |
| # Sources | |
| st.header("Sources") | |
| for source in report['sources']: | |
| st.markdown(f"- {source}") | |
| # Download Report | |
| st.download_button( | |
| label="๐ฅ Download Complete Report", | |
| data=f"""# Market Research Report: {topic} | |
| ## Executive Summary | |
| {report['exec_summary']['summary']} | |
| ### Market Highlights | |
| {report['exec_summary']['market_highlights']} | |
| ### Strategic Implications | |
| {report['exec_summary']['strategic_implications']} | |
| ### Key Recommendations | |
| {report['exec_summary']['recommendations']} | |
| ## Market Analysis | |
| ### Market Overview | |
| {report['market_analysis']['overview']} | |
| ### Industry Dynamics | |
| {report['market_analysis']['dynamics']} | |
| ### Competitive Landscape | |
| {report['market_analysis']['competitive_landscape']} | |
| ### Strategic Analysis | |
| {report['market_analysis']['strategic_analysis']} | |
| ## Future Outlook | |
| {report['future_outlook']} | |
| ## Sources | |
| {chr(10).join([f"- {source}" for source in report['sources']])}""", | |
| file_name=f"{topic.lower().replace(' ', '_')}_market_research.md", | |
| mime="text/markdown", | |
| ) | |
| except Exception as e: | |
| st.error(f"Error displaying report: {str(e)}") | |
| st.write("Raw report data:", report) # Debug information | |
| if __name__ == "__main__": | |
| main() |