# sentiment_analyzer.py from transformers import pipeline import torch class SentimentAnalyzer: def __init__(self): """ Initialize the FinBERT Sentiment Analysis pipeline """ print("Initializing FinBERT Sentiment model (project-aps/finbert-finetune)...") self.device = 0 if torch.cuda.is_available() else -1 print(f"Using device: {'cuda' if self.device == 0 else 'cpu'}") try: # FinBERT เป็นโมเดล text-classification self.sentiment_pipeline = pipeline( "text-classification", model="project-aps/finbert-finetune", device=self.device ) print("Model loaded successfully!") except Exception as e: print(f"Fatal error loading model: {e}") self.sentiment_pipeline = None def analyze_sentiment(self, text): """ วิเคราะห์ Sentiment ของข้อความ 1 ชิ้น """ if not self.sentiment_pipeline: return "N/A", 0.0 if not text or len(text.strip()) == 0: return "N/A", 0.0 try: # โมเดล FinBERT นี้มี label 3 แบบ: 'positive', 'negative', 'neutral' result = self.sentiment_pipeline(text[:512])[0] return result['label'], result['score'] except Exception as e: print(f"Error in sentiment analysis: {e}") return "N/A", 0.0 def analyze_batch(self, news_list): """ วิเคราะห์ Sentiment ของข่าวหลายรายการ """ results = [] for news in news_list: # เราจะใช้ 'title' และ 'summary' ที่ได้จาก RSS combined_text = f"{news.get('title', '')}. {news.get('summary', '')}" # เรียกใช้การวิเคราะห์ label, score = self.analyze_sentiment(combined_text) news['sentiment'] = label news['score'] = score results.append(news) return results