# app.py import gradio as gr import pandas as pd from yahoo_finance_scraper import YahooFinanceScraper from sentiment_analyzer import SentimentAnalyzer # --- 1. โหลดโมเดลและ Scraper --- try: scraper = YahooFinanceScraper() analyzer = SentimentAnalyzer() print("Scraper and Analyzer are ready.") except Exception as e: print(f"Error loading models: {e}") scraper = None analyzer = None # --- 2. ฟังก์ชันหลัก (แก้ไข: กลับไปใช้ search_news) --- def process_keyword_search(keyword): # <--- เปลี่ยนชื่อกลับ """ ค้นหาข่าวด้วย Keyword -> วิเคราะห์ Sentiment -> สร้าง Markdown 2 ส่วน """ if not scraper or not analyzer: return "Models failed to load. Check logs.", "" # คืนค่า 2 ส่วน if not keyword: return "Please enter a keyword or symbol.", "" print(f"Searching for keyword: {keyword}") # <--- 3. กลับไปใช้ search_news (Google) ที่หาข่าวตรงประเด็น --- news_list = scraper.search_news(keyword, max_articles=10) if not news_list: return f"No recent news found for: {keyword}", "" # คืนค่า 2 ส่วน # <--- 4. วิเคราะห์ Sentiment --- analyzed_list = analyzer.analyze_batch(news_list) # --- 5. สร้าง สรุป Sentiment (ส่วนบน) --- df = pd.DataFrame(analyzed_list) total_articles = len(df) summary_lines = ["📊 **Overall Sentiment Summary**", "---"] sentiment_counts = df['sentiment'].value_counts() for sentiment, count in sentiment_counts.items(): percentage = (count / total_articles) * 100 summary_lines.append(f"**{sentiment.capitalize()}**: {percentage:.1f}% ({count}/{total_articles})") summary_text = " \n".join(summary_lines) # --- 6. สร้าง ข่าวแต่ละชิ้น (ส่วนล่าง) --- markdown_output_lines = [] for item in analyzed_list: try: date_str = pd.to_datetime(item['published']).strftime("%Y-%m-%d %H:%M") except: date_str = "N/A" markdown_output_lines.append(f"### 📰 {item['title']}") markdown_output_lines.append(f"*(Published: {date_str})*") # <--- 7. เพิ่ม Sentiment (FinBERT วิเคราะห์จากหัวข้อข่าว) --- sentiment_label = item['sentiment'].capitalize() sentiment_score = item['score'] * 100 markdown_output_lines.append(f"\n**Sentiment: {sentiment_label}** ({sentiment_score:.1f}%)") # --- (เราไม่แสดง item['summary'] เพราะมันคือหัวข้อข่าวซ้ำ) --- markdown_output_lines.append(f"\n[Read Full Article]({item['link']})") markdown_output_lines.append("\n---") main_output_text = "\n".join(markdown_output_lines) return summary_text, main_output_text # --- 3. สร้างหน้าเว็บ Gradio (แก้ไข) --- with gr.Blocks(theme=gr.themes.Soft()) as app: # <--- แก้ไข: เปลี่ยนคำอธิบาย --- gr.Markdown( """ # 📈 Stock News Sentiment Analyzer Enter a keyword or stock symbol (e.g., 'AAPL', 'TSLA', 'Inflation') to get recent news and analyze its sentiment using FinBERT. """ ) # --- ส่วน Input (แก้ไข) --- with gr.Row(): keyword_input = gr.Textbox( label="Enter Keyword or Symbol", placeholder="e.g., AAPL, NVIDIA, Inflation...", scale=3 ) search_button = gr.Button("Analyze Sentiment", variant="primary", scale=1) # --- ส่วน Output (เหมือนเดิม 2 ส่วน) --- summary_output = gr.Markdown( label="Overall Sentiment Summary" ) output_markdown = gr.Markdown( label="News Analysis Results" ) # --- 4. เชื่อมปุ่มกับฟังก์ชัน (แก้ไข) --- search_button.click( fn=process_keyword_search, # <--- เรียกฟังก์ชัน Keyword inputs=[keyword_input], outputs=[summary_output, output_markdown] # <--- ชี้ไปที่ 2 Output ) # --- 5. สั่งรันแอป (เหมือนเดิม) --- if __name__ == "__main__": app.launch()