Spaces:
Build error
Build error
Download app.py from GenAI-b2l1/conversationalchatbot: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/spaces/GenAI-b2l1/conversationalchatbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/GenAI-b2l1/conversationalchatbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/GenAI-b2l1/conversationalchatbot/resolve/main/app.py
12.2 kB
| 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() |