help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
multi-language-chatbot
/
__pycache__
RSK World
multi-language-chatbot
Multi-language Chatbot - Python + Flask + OpenAI API + NLP + Translation + Language Detection + Cultural Adaptation
__pycache__
  • app.cpython-313.pyc23.9 KB
  • config.cpython-313.pyc5.8 KB
  • run.cpython-313.pyc4.3 KB
sentiment_analyzer.pyrun.cpython-313.pyc
modules/sentiment_analyzer.py
Raw Download
Find: Go to:
"""
Sentiment Analysis and Emotion Detection Module
Author: RSK World (https://rskworld.in)
Founder: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
Description: Advanced sentiment analysis and emotion detection with multi-language support
"""

import logging
import re
import json
from typing import Dict, List, Tuple, Optional
from textblob import TextBlob
import openai
import os

logger = logging.getLogger(__name__)

class SentimentAnalyzer:
    def __init__(self):
        self.openai_api_key = os.getenv('OPENAI_API_KEY')
        
        # Sentiment keywords for different languages
        self.sentiment_keywords = {
            'en': {
                'positive': ['good', 'great', 'excellent', 'amazing', 'wonderful', 'fantastic', 'love', 'happy', 'joy', 'perfect', 'awesome', 'brilliant'],
                'negative': ['bad', 'terrible', 'awful', 'horrible', 'hate', 'angry', 'sad', 'disappointed', 'worst', 'poor', 'disgusting'],
                'neutral': ['okay', 'fine', 'normal', 'average', 'standard', 'regular', 'typical']
            },
            'hi': {
                'positive': ['अच्छा', 'बहुत अच्छा', 'शानदार', 'बेहतरीन', 'प्यार', 'खुश', 'खुशी', 'उत्कृष्ट'],
                'negative': ['बुरा', 'बहुत बुरा', 'घटिया', 'नफरत', 'गुस्सा', 'दुखी', 'निराश'],
                'neutral': ['ठीक', 'सामान्य', 'औसत', 'रोजमर्रा']
            },
            'bn': {
                'positive': ['ভালো', 'অসাধারণ', 'চমৎকার', 'ভালোবাসা', 'খুশি', '�নন্দ', 'উৎকৃষ্ট'],
                'negative': ['খারাপ', 'ভয়ানক', 'ঘৃণা', 'রাগ', 'দুঃখ', 'নিরাশ'],
                'neutral': ['ঠিক আছে', 'স্বাভাবিক', 'গড়পড়তা']
            },
            'es': {
                'positive': ['bueno', 'excelente', 'increíble', 'amor', 'feliz', 'alegría', 'perfecto'],
                'negative': ['malo', 'terrible', 'horrible', 'odio', 'enojado', 'triste', 'decepcionado'],
                'neutral': ['ok', 'normal', 'promedio', 'regular']
            },
            'fr': {
                'positive': ['bon', 'excellent', 'incroyable', 'amour', 'heureux', 'joie', 'parfait'],
                'negative': ['mauvais', 'terrible', 'horrible', 'haine', 'en colère', 'triste', 'déçu'],
                'neutral': ['ok', 'normal', 'moyen', 'régulier']
            }
        }
        
        # Emotion keywords
        self.emotion_keywords = {
            'en': {
                'joy': ['happy', 'joy', 'excited', 'delighted', 'thrilled', 'ecstatic'],
                'sadness': ['sad', 'unhappy', 'depressed', 'melancholy', 'grief', 'sorrow'],
                'anger': ['angry', 'mad', 'furious', 'irritated', 'annoyed', 'rage'],
                'fear': ['afraid', 'scared', 'terrified', 'anxious', 'worried', 'nervous'],
                'surprise': ['surprised', 'amazed', 'astonished', 'shocked', 'stunned'],
                'disgust': ['disgusted', 'revolted', 'repulsed', 'sickened'],
                'love': ['love', 'adore', 'cherish', 'treasure', 'affection'],
                'anticipation': ['excited', 'eager', 'looking forward', 'anticipating']
            },
            'hi': {
                'joy': ['खुश', 'खुशी', 'उत्साहित', 'प्रसन्न'],
                'sadness': ['दुखी', 'उदास', 'दुख', 'परेशान'],
                'anger': ['गुस्सा', 'नाराज', 'क्रोधित', ' irritated'],
                'fear': ['डर', 'डरा हुआ', 'चिंतित', 'घबराहट'],
                'surprise': ['आश्चर्य', 'हैरान', 'चकित'],
                'disgust': ['घृणा', 'नफरत', 'विकृत'],
                'love': ['प्यार', 'प्रेम', 'स्नेह', 'आत्मीयता'],
                'anticipation': ['उत्सुकता', 'प्रत्याशा', 'इंतजार']
            }
        }
        
        # Intensity modifiers
        self.intensity_modifiers = {
            'en': {
                'very': 1.5, 'extremely': 2.0, 'slightly': 0.8, 'somewhat': 0.9,
                'really': 1.3, 'quite': 1.2, 'absolutely': 2.0, 'totally': 1.8
            },
            'hi': {
                'बहुत': 1.5, 'अत्यधिक': 2.0, 'थोड़ा': 0.8, 'काफी': 1.2,
                'वास्तव में': 1.3, 'पूरी तरह': 2.0, 'बिल्कुल': 2.0
            }
        }
    
    def analyze_sentiment(self, text: str, language: str = 'en') -> Dict:
        """
        Analyze sentiment of text
        Returns: {
            'polarity': float (-1 to 1),
            'subjectivity': float (0 to 1),
            'sentiment': str ('positive', 'negative', 'neutral'),
            'confidence': float (0 to 1)
        }
        """
        try:
            # Use TextBlob for basic sentiment analysis
            blob = TextBlob(text)
            polarity = blob.sentiment.polarity
            subjectivity = blob.sentiment.subjectivity
            
            # Determine sentiment
            if polarity > 0.1:
                sentiment = 'positive'
            elif polarity < -0.1:
                sentiment = 'negative'
            else:
                sentiment = 'neutral'
            
            # Calculate confidence
            confidence = abs(polarity)
            
            # Enhance with keyword analysis
            keyword_sentiment = self._analyze_keywords(text, language)
            if keyword_sentiment:
                # Weight the results
                final_polarity = (polarity * 0.7) + (keyword_sentiment['polarity'] * 0.3)
                final_sentiment = self._determine_sentiment(final_polarity)
                
                return {
                    'polarity': final_polarity,
                    'subjectivity': subjectivity,
                    'sentiment': final_sentiment,
                    'confidence': max(confidence, keyword_sentiment['confidence']),
                    'method': 'hybrid'
                }
            
            return {
                'polarity': polarity,
                'subjectivity': subjectivity,
                'sentiment': sentiment,
                'confidence': confidence,
                'method': 'textblob'
            }
            
        except Exception as e:
            logger.error(f"Sentiment analysis error: {str(e)}")
            return self._get_default_sentiment()
    
    def detect_emotions(self, text: str, language: str = 'en') -> Dict:
        """
        Detect emotions in text
        Returns: {
            'primary_emotion': str,
            'emotions': {emotion: score},
            'confidence': float
        }
        """
        try:
            # Keyword-based emotion detection
            emotion_scores = self._analyze_emotion_keywords(text, language)
            
            # Use OpenAI for advanced emotion detection if available
            if self.openai_api_key:
                openai_emotions = self._detect_emotions_openai(text, language)
                if openai_emotions:
                    # Combine results
                    combined_emotions = self._combine_emotion_scores(emotion_scores, openai_emotions)
                else:
                    combined_emotions = emotion_scores
            else:
                combined_emotions = emotion_scores
            
            # Find primary emotion
            if combined_emotions:
                primary_emotion = max(combined_emotions.items(), key=lambda x: x[1])
                confidence = primary_emotion[1]
                
                return {
                    'primary_emotion': primary_emotion[0],
                    'emotions': combined_emotions,
                    'confidence': confidence,
                    'method': 'hybrid' if self.openai_api_key else 'keyword'
                }
            
            return self._get_default_emotions()
            
        except Exception as e:
            logger.error(f"Emotion detection error: {str(e)}")
            return self._get_default_emotions()
    
    def _analyze_keywords(self, text: str, language: str) -> Optional[Dict]:
        """Analyze sentiment using keyword matching"""
        try:
            keywords = self.sentiment_keywords.get(language, self.sentiment_keywords['en'])
            text_lower = text.lower()
            
            scores = {'positive': 0, 'negative': 0, 'neutral': 0}
            word_count = 0
            
            for sentiment_type, words in keywords.items():
                for word in words:
                    count = len(re.findall(r'\b' + re.escape(word) + r'\b', text_lower))
                    scores[sentiment_type] += count
                    word_count += count
            
            if word_count == 0:
                return None
            
            # Calculate polarity
            total = scores['positive'] + scores['negative'] + scores['neutral']
            polarity = (scores['positive'] - scores['negative']) / max(total, 1)
            
            # Apply intensity modifiers
            intensity = self._calculate_intensity(text, language)
            polarity *= intensity
            
            return {
                'polarity': max(-1, min(1, polarity)),
                'confidence': min(word_count / 10, 1.0)
            }
            
        except Exception as e:
            logger.error(f"Keyword analysis error: {str(e)}")
            return None
    
    def _analyze_emotion_keywords(self, text: str, language: str) -> Dict:
        """Analyze emotions using keyword matching"""
        try:
            emotions = self.emotion_keywords.get(language, self.emotion_keywords['en'])
            text_lower = text.lower()
            
            emotion_scores = {}
            
            for emotion, words in emotions.items():
                score = 0
                for word in words:
                    count = len(re.findall(r'\b' + re.escape(word) + r'\b', text_lower))
                    score += count
                emotion_scores[emotion] = score
            
            # Normalize scores
            max_score = max(emotion_scores.values()) if emotion_scores.values() else 1
            if max_score > 0:
                emotion_scores = {k: v / max_score for k, v in emotion_scores.items()}
            
            return emotion_scores
            
        except Exception as e:
            logger.error(f"Emotion keyword analysis error: {str(e)}")
            return {}
    
    def _detect_emotions_openai(self, text: str, language: str) -> Optional[Dict]:
        """Detect emotions using OpenAI"""
        try:
            if not self.openai_api_key:
                return None
            
            prompt = f"""
            Analyze the emotions in the following text and provide scores for each emotion.
            Text: "{text}"
            Language: {language}
            
            Provide a JSON response with emotion scores from 0 to 1:
            {{
                "joy": 0.0,
                "sadness": 0.0,
                "anger": 0.0,
                "fear": 0.0,
                "surprise": 0.0,
                "disgust": 0.0,
                "love": 0.0,
                "anticipation": 0.0
            }}
            """
            
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "You are an expert in emotion analysis. Provide accurate emotion scores."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=200,
                temperature=0.3
            )
            
            result = response.choices[0].message.content.strip()
            emotions = json.loads(result)
            
            return emotions
            
        except Exception as e:
            logger.error(f"OpenAI emotion detection error: {str(e)}")
            return None
    
    def _combine_emotion_scores(self, keyword_scores: Dict, openai_scores: Dict) -> Dict:
        """Combine emotion scores from different methods"""
        combined = {}
        
        for emotion in set(keyword_scores.keys()) | set(openai_scores.keys()):
            keyword_score = keyword_scores.get(emotion, 0)
            openai_score = openai_scores.get(emotion, 0)
            
            # Weighted combination
            combined[emotion] = (keyword_score * 0.4) + (openai_score * 0.6)
        
        return combined
    
    def _calculate_intensity(self, text: str, language: str) -> float:
        """Calculate intensity modifier based on intensity words"""
        try:
            modifiers = self.intensity_modifiers.get(language, self.intensity_modifiers['en'])
            text_lower = text.lower()
            
            intensity = 1.0
            for word, modifier in modifiers.items():
                if word in text_lower:
                    intensity = max(intensity, modifier)
            
            return intensity
            
        except Exception as e:
            logger.error(f"Intensity calculation error: {str(e)}")
            return 1.0
    
    def _determine_sentiment(self, polarity: float) -> str:
        """Determine sentiment from polarity score"""
        if polarity > 0.1:
            return 'positive'
        elif polarity < -0.1:
            return 'negative'
        else:
            return 'neutral'
    
    def _get_default_sentiment(self) -> Dict:
        """Get default sentiment analysis result"""
        return {
            'polarity': 0.0,
            'subjectivity': 0.0,
            'sentiment': 'neutral',
            'confidence': 0.0,
            'method': 'default'
        }
    
    def _get_default_emotions(self) -> Dict:
        """Get default emotion detection result"""
        return {
            'primary_emotion': 'neutral',
            'emotions': {
                'joy': 0.0,
                'sadness': 0.0,
                'anger': 0.0,
                'fear': 0.0,
                'surprise': 0.0,
                'disgust': 0.0,
                'love': 0.0,
                'anticipation': 0.0
            },
            'confidence': 0.0,
            'method': 'default'
        }
    
    def get_sentiment_summary(self, text: str, language: str = 'en') -> str:
        """Get a human-readable sentiment summary"""
        sentiment_result = self.analyze_sentiment(text, language)
        emotion_result = self.detect_emotions(text, language)
        
        sentiment = sentiment_result['sentiment']
        confidence = sentiment_result['confidence']
        primary_emotion = emotion_result['primary_emotion']
        
        if confidence > 0.7:
            confidence_level = "high"
        elif confidence > 0.4:
            confidence_level = "moderate"
        else:
            confidence_level = "low"
        
        summary = f"The text expresses a {sentiment} sentiment with {confidence_level} confidence"
        
        if primary_emotion != 'neutral':
            summary += f" and primarily conveys {primary_emotion}"
        
        return summary
    
    def batch_analyze(self, texts: List[str], language: str = 'en') -> List[Dict]:
        """Analyze sentiment for multiple texts"""
        results = []
        for text in texts:
            result = self.analyze_sentiment(text, language)
            results.append(result)
        return results
    
    def get_emotion_trends(self, texts: List[str], language: str = 'en') -> Dict:
        """Analyze emotion trends across multiple texts"""
        all_emotions = {}
        
        for text in texts:
            emotions = self.detect_emotions(text, language)
            for emotion, score in emotions['emotions'].items():
                if emotion not in all_emotions:
                    all_emotions[emotion] = []
                all_emotions[emotion].append(score)
        
        # Calculate averages
        trends = {}
        for emotion, scores in all_emotions.items():
            if scores:
                trends[emotion] = {
                    'average': sum(scores) / len(scores),
                    'max': max(scores),
                    'min': min(scores),
                    'trend': 'increasing' if scores[-1] > scores[0] else 'decreasing' if scores[-1] < scores[0] else 'stable'
                }
        
        return trends
411 lines•16.9 KB
python
run.cpython-313.pyc

This file cannot be displayed in the browser.

Download File

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer