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(""" """, 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('
Source: {item["source"]} | Read Full Article
', 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('