File size: 11,322 Bytes
d5ad1fb
ec07c78
 
7d6dd45
9f14bb5
 
 
4925c76
ec07c78
 
 
 
 
 
5c001ed
902bfc2
 
ec07c78
 
9f14bb5
 
a10143f
9f14bb5
 
d5ad1fb
9f14bb5
 
 
 
d5ad1fb
9f14bb5
 
d5ad1fb
699d379
 
9f14bb5
7da1f57
03bc604
df45ab2
 
 
5da984d
 
699d379
 
5da984d
699d379
 
5da984d
699d379
df45ab2
5da984d
40fb758
 
5da984d
 
 
699d379
 
 
 
 
 
5da984d
 
 
 
699d379
5da984d
 
44fed4e
 
5da984d
 
 
 
44fed4e
 
5da984d
 
 
 
44fed4e
5da984d
44fed4e
 
699d379
44fed4e
699d379
 
 
 
5da984d
699d379
 
5da984d
 
44fed4e
5da984d
 
44fed4e
5da984d
44fed4e
5da984d
 
44fed4e
5da984d
 
 
 
 
 
44fed4e
5da984d
 
 
 
 
 
 
 
 
 
 
44fed4e
5da984d
 
 
 
 
 
 
44fed4e
5da984d
 
 
699d379
982e3fa
44fed4e
df45ab2
03bc604
9f14bb5
df45ab2
5da984d
 
ec07c78
 
0d48b65
31fe386
 
0d48b65
31fe386
 
 
0d48b65
0bf80ee
c897b65
 
0d48b65
d5ad1fb
9f14bb5
0d48b65
902bfc2
9f14bb5
 
 
 
 
0d48b65
9f14bb5
 
 
 
 
 
 
 
0d48b65
9f14bb5
 
0d48b65
9f14bb5
 
 
0d48b65
 
 
 
 
9f14bb5
 
 
 
0d48b65
0495c3a
 
3ae0511
 
 
0d48b65
b54644d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ae0511
b54644d
3ae0511
0d48b65
 
44fed4e
0d48b65
 
44fed4e
0d48b65
 
44fed4e
0d48b65
 
44fed4e
0d48b65
44fed4e
0d48b65
 
44fed4e
0d48b65
 
44fed4e
0d48b65
 
44fed4e
0d48b65
 
44fed4e
0d48b65
 
44fed4e
0d48b65
 
b54644d
3ae0511
 
 
 
c144ee0
 
0d48b65
b54644d
5c001ed
75f8517
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# 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()