Spaces:
Build error

File size: 12,214 Bytes
52ad3f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import streamlit as st
from langchain_openai import AzureChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain.chains import LLMChain
import requests
import json
import speech_recognition as sr
from gtts import gTTS
from io import BytesIO
import pandas as pd
from typing import List, Dict
import pyaudio
import wave
import time
from dotenv import load_dotenv
import os

# Load environment variables
load_dotenv()

# Configure environment variables
azure_config = {
    "AZURE_OPENAI_ENDPOINT": os.getenv("AZURE_OPENAI_ENDPOINT"),
    "AZURE_OPENAI_MODEL_DEPLOYMENT_NAME": os.getenv("AZURE_OPENAI_MODEL_DEPLOYMENT_NAME"),
    "AZURE_OPENAI_MODEL_NAME": os.getenv("AZURE_OPENAI_MODEL_NAME"),
    "AZURE_OPENAI_API_KEY": os.getenv("AZURE_OPENAI_API_KEY"),
    "AZURE_OPENAI_API_VERSION": os.getenv("AZURE_OPENAI_API_VERSION"),
    "SERPER_API_KEY" : os.getenv("SERPER_API_KEY")
}

# Configuration and Environment Variables
SERPER_API_KEY = azure_config["SERPER_API_KEY"]
AZURE_API_KEY = azure_config["AZURE_OPENAI_API_KEY"]
AZURE_ENDPOINT = azure_config["AZURE_OPENAI_ENDPOINT"]
AZURE_DEPLOYMENT_NAME = azure_config["AZURE_OPENAI_MODEL_DEPLOYMENT_NAME"]
AZURE_API_VERSION = azure_config["AZURE_OPENAI_API_VERSION"]

# Set Streamlit page configuration
st.set_page_config(
    page_title="News Analyzer",
    page_icon="πŸ“°",
    layout="wide"
)

# Custom CSS for better UI
st.markdown("""
    <style>
    .stApp {
    }
    .main-header {
        font-size: 2.5rem;
        color: #1E3D59;
        text-align: center;
        margin-bottom: 2rem;
    }
    .subheader {
        color: #1E3D59;
        font-size: 1.5rem;
        margin-top: 1rem;
    }
    .news-card {
        padding: 1.5rem;
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        margin-bottom: 1rem;
    }
    .source-text {
        color: #666;
        font-size: 0.9rem;
    }
    .divider {
        margin: 1.5rem 0;
        border-top: 1px solid #ddd;
    }
    </style>
    """, unsafe_allow_html=True)

# Summary template
SUMMARY_TEMPLATE = """
Please provide a concise summary of the following article in 4-5 bullet points.
Also analyze its potential impact on market perception and stock movement.
Keep the language conversational and suitable for speech.

Article: {article_text}

Please format your response as follows:
Key Points:
- Point 1
- Point 2
- Point 3
- Point 4

Market Impact:
[Your analysis of market impact]
"""

class NewsAnalyzer:
    def __init__(self):
        self.llm = AzureChatOpenAI(
            openai_api_key=AZURE_API_KEY,
            azure_endpoint=AZURE_ENDPOINT,
            deployment_name=AZURE_DEPLOYMENT_NAME,
            openai_api_version=AZURE_API_VERSION
        )
        self.output_parser = StrOutputParser()
        
    def search_news(self, query: str) -> List[Dict]:
        """Search news using Serper API"""
        url = "https://google.serper.dev/news"
        payload = json.dumps({"q": query})
        headers = {
            'X-API-KEY': SERPER_API_KEY,
            'Content-Type': 'application/json'
        }
        response = requests.request("POST", url, headers=headers, data=payload)
        return response.json().get('news', [])[:5]
    
    def analyze_sentiment(self, text: str) -> str:
        """Analyze sentiment using Azure OpenAI"""
        prompt = ChatPromptTemplate.from_messages([
            ("system", "You are a sentiment analyzer. Respond with only 'positive', 'negative', or 'neutral'."),
            ("user", "{text}")
        ])
        chain = prompt | self.llm | self.output_parser
        response = chain.invoke({"text": text})
        return response.strip().lower()
    
    def analyze_market_impact(self, text: str, sentiment: str) -> str:
        """Analyze market impact using Azure OpenAI"""
        prompt = ChatPromptTemplate.from_messages([
            ("system", "Analyze market impact and stock movement implications. Give output in 2 lines only"),
            ("user", "Based on this news with {sentiment} sentiment, analyze market impact: {text}")
        ])
        chain = prompt | self.llm | self.output_parser
        return chain.invoke({"text": text, "sentiment": sentiment})
    
    def summarize_article(self, url: str) -> Dict[str, str]:
        """Summarize article content using Azure OpenAI with new template"""
        prompt = ChatPromptTemplate.from_messages([
            ("system", "You are a news analyst."),
            ("user", SUMMARY_TEMPLATE)
        ])
        chain = prompt | self.llm | self.output_parser
        
        # Here you would typically scrape the article content
        article_content = f"Article content from {url}"
        response = chain.invoke({"article_text": article_content})
        
        # Split response into summary and market impact
        parts = response.split("Market Impact:")
        key_points = parts[0].strip()
        market_impact = parts[1].strip() if len(parts) > 1 else "Market impact analysis not available."
        
        return {
            "key_points": key_points,
            "market_impact": market_impact
        }

class AudioProcessor:
    def __init__(self):
        self.recognizer = sr.Recognizer()
        self.audio = pyaudio.PyAudio()
        
    def record_audio(self, duration=5):
        """Record audio from microphone"""
        CHUNK = 1024
        FORMAT = pyaudio.paInt16
        CHANNELS = 1
        RATE = 44100
        
        stream = self.audio.open(format=FORMAT,
                               channels=CHANNELS,
                               rate=RATE,
                               input=True,
                               frames_per_buffer=CHUNK)
        
        st.info(f"Recording for {duration} seconds...")
        frames = []
        
        for _ in range(0, int(RATE / CHUNK * duration)):
            data = stream.read(CHUNK)
            frames.append(data)
            
        st.success("Recording completed!")
        
        stream.stop_stream()
        stream.close()
        
        audio_buffer = BytesIO()
        with wave.open(audio_buffer, 'wb') as wf:
            wf.setnchannels(CHANNELS)
            wf.setsampwidth(self.audio.get_sample_size(FORMAT))
            wf.setframerate(RATE)
            wf.writeframes(b''.join(frames))
        
        audio_buffer.seek(0)
        return audio_buffer
    
    def speech_to_text(self, audio_data: BytesIO) -> str:
        """Convert speech to text"""
        try:
            with sr.AudioFile(audio_data) as source:
                audio = self.recognizer.record(source)
                text = self.recognizer.recognize_google(audio)
                return text
        except sr.UnknownValueError:
            raise Exception("Could not understand the audio")
        except sr.RequestError as e:
            raise Exception(f"Could not request results; {str(e)}")
    
    def text_to_speech(self, text: str) -> BytesIO:
        """Convert text to speech"""
        tts = gTTS(text=text, lang='en')
        fp = BytesIO()
        tts.write_to_fp(fp)
        fp.seek(0)
        return fp
    
    def create_news_summary(self, news_results: List[Dict], news_analyzer: NewsAnalyzer) -> tuple:
        """Create both text and audio summaries of news results"""
        text_summary = []
        audio_summary = "Here's your news summary.\n\n"
        
        for idx, article in enumerate(news_results, 1):
            # Text summary
            article_summary = {
                'title': article['title'],
                'source': article['source'],
                'link': article['link'],
                'summary': news_analyzer.summarize_article(article['link']),
                'sentiment': news_analyzer.analyze_sentiment(article['snippet']),
                'impact': news_analyzer.analyze_market_impact(article['snippet'], 
                                                           news_analyzer.analyze_sentiment(article['snippet']))
            }
            text_summary.append(article_summary)
            
            # Audio summary
            audio_summary += f"Article {idx} from {article['source']}.\n"
            audio_summary += f"Title: {article['title']}\n"
            audio_summary += f"Summary: {article_summary['summary']}\n"
            audio_summary += f"The sentiment is {article_summary['sentiment']}.\n"
            audio_summary += f"Market impact: {article_summary['impact']}\n\n"
        
        return text_summary, audio_summary

def display_text_summary(summary_items: List[Dict]):
    """Display formatted text summary with improved UI"""
    for item in summary_items:
        with st.container():
            st.markdown('<div class="news-card">', unsafe_allow_html=True)
            
            # Title and Source
            st.markdown(f"### {item['title']}")
            st.markdown(f'<p class="source-text">Source: {item["source"]} | <a href="{item["link"]}" target="_blank">Read Full Article</a></p>', 
                       unsafe_allow_html=True)
            
            # Sentiment Indicator
            sentiment_color = {
                "positive": "🟒",
                "negative": "πŸ”΄",
                "neutral": "βšͺ"
            }.get(item['sentiment'], "βšͺ")
            st.markdown(f"**Sentiment:** {sentiment_color} {item['sentiment'].capitalize()}")
            
            # Summary
            st.markdown("#### Key Points")
            st.markdown(item['summary']['key_points'])
            
            # Market Impact
            st.markdown("#### Market Impact")
            st.markdown(item['summary']['market_impact'])
            
            st.markdown('</div>', unsafe_allow_html=True)

def main():
    # Header
    st.markdown('<h1 class="main-header">πŸ“° News Analyzer</h1>', unsafe_allow_html=True)
    
    # Initialize classes
    news_analyzer = NewsAnalyzer()
    audio_processor = AudioProcessor()
    
    # Create two columns for input selection
    col1, col2 = st.columns(2)
    
    with col1:
        st.markdown("### Choose Input Method")
        input_mode = st.radio("", ["Text Input", "Voice Input"], key="input_mode")
    
    # Input section with better styling
    st.markdown('<div class="news-card">', unsafe_allow_html=True)
    
    query = None
    if input_mode == "Text Input":
        query = st.text_input("Enter your topic of interest:", 
                            placeholder="e.g., Tesla stock performance, Bitcoin price, Apple earnings")
    else:
        if st.button("🎀 Start Recording", key="record_button"):
            try:
                with st.spinner("πŸŽ™οΈ Recording in progress..."):
                    audio_data = audio_processor.record_audio(duration=5)
                query = audio_processor.speech_to_text(audio_data)
                st.success(f"Transcribed: {query}")
            except Exception as e:
                st.error(f"Recording Error: {str(e)}")
    
    st.markdown('</div>', unsafe_allow_html=True)
    
    # Process query and display results
    if query:
        with st.spinner("Analyzing latest news..."):
            news_results = news_analyzer.search_news(query)
            
            if input_mode == "Voice Input":
                # Create both text and audio summaries
                text_summary, audio_summary = audio_processor.create_news_summary(news_results, news_analyzer)
                
                # Audio section
                st.markdown('<div class="news-card">', unsafe_allow_html=True)
                st.markdown("### πŸ”Š Audio Summary")
                audio_fp = audio_processor.text_to_speech(audio_summary)
                st.audio(audio_fp, format='audio/mp3')
                st.markdown('</div>', unsafe_allow_html=True)
                
                # Text summary
                st.markdown("### πŸ“ Detailed Summary")
                display_text_summary(text_summary)
            else:
                # Display text results
                text_summary, _ = audio_processor.create_news_summary(news_results, news_analyzer)
                display_text_summary(text_summary)

if __name__ == "__main__":
    main()