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
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
sentiment-analysis-bot
/
tests
RSK World
sentiment-analysis-bot
Sentiment Analysis Bot - Python + Flask + NLTK + TextBlob + spaCy + VADER + Emotion Detection + Sentiment Analysis
tests
  • __pycache__
  • test_app.py10.8 KB
TSLA.csvindex.htmladvanced_analysis.pystyle.css.gitignoreREADME.mdexercising_003.mp4.gitkeepanomaly_detection.pyenergy_consumption.csvscript.jsmain.jsCOMPLETE_PROJECT_INFO.txtRELEASE_NOTES.mdADVANCED_FEATURES.mdERRORS_FIXED.mdtest_app.py
.gitignore
Raw Download
Find: Go to:
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# Virtual Environment
venv/
env/
ENV/
sentiment_env/
.venv

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# Environment variables
.env
.env.local

# Logs
*.log
logs/
sentiment_bot.log

# Database
*.db
*.sqlite
*.sqlite3

# OS
.DS_Store
Thumbs.db

# Flask
instance/
.webassets-cache

# Testing
.pytest_cache/
.coverage
htmlcov/

# Uploads
uploads/
*.tmp

# spaCy models (downloaded separately)
# en_core_web_sm/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# mypy
.mypy_cache/
.dmypy.json
dmypy.json
81 linesโ€ข771 B
text
README.md
Raw Download

README.md

# Sentiment Analysis Bot

**Real-time emotion detection and intelligent response adaptation**

![Sentiment Analysis Bot](sentiment-analysis-bot.png)

## ๐Ÿ“– Project Description

This advanced chatbot analyzes user sentiment in real-time to understand emotions and provide appropriate responses. Perfect for customer service, feedback collection, and emotional support applications. The bot uses multiple NLP techniques to accurately detect sentiment and emotions, then adapts its responses accordingly.

## โœจ Key Features

- **Real-time Sentiment Analysis**: Analyzes text sentiment using VADER and TextBlob
- **Emotion Detection**: Identifies specific emotions like joy, anger, sadness, fear, and surprise
- **Response Adaptation**: Generates context-aware responses based on detected emotions
- **Feedback Collection**: Tracks conversation history and sentiment trends
- **Sentiment Reporting**: Provides detailed analytics and downloadable reports
- **Named Entity Recognition**: Extracts entities using spaCy
- **Beautiful Web Interface**: Modern, responsive UI with real-time chat
- **RESTful API**: Clean API endpoints for integration
- **Conversation History**: Maintains chat sessions with timestamps

## ๐Ÿ› ๏ธ Technologies Used

- **Python 3.8+**: Core programming language
- **Flask**: Web framework for the API and backend
- **NLTK**: Natural Language Toolkit for text processing
- **TextBlob**: Simple text sentiment analysis
- **spaCy**: Advanced NLP and entity recognition
- **VADER**: Valence Aware Dictionary and sEntiment Reasoner
- **Bootstrap 5**: Frontend framework
- **Font Awesome**: Icons and UI elements
- **JavaScript**: Interactive frontend functionality

## ๐Ÿš€ Installation and Setup

### Prerequisites

- Python 3.8 or higher
- pip package manager
- Git (for cloning)

### Step 1: Clone or Download

```bash
# If cloning from repository
git clone <repository-url>
cd sentiment-analysis-bot

# Or download and extract the ZIP file
```

### Step 2: Create Virtual Environment

```bash
# Create virtual environment
python -m venv sentiment_env

# Activate on Windows
sentiment_env\Scripts\activate

# Activate on macOS/Linux
source sentiment_env/bin/activate
```

### Step 3: Install Dependencies

```bash
# Install required packages
pip install -r requirements.txt

# Download spaCy English model
python -m spacy download en_core_web_sm
```

### Step 4: Run the Application

```bash
# Start the Flask application
python app.py
```

The application will start at `http://localhost:5000`

## ๐ŸŒ Usage

### Web Interface

1. Open your browser and navigate to `http://localhost:5000`
2. Type your message in the chat input
3. The bot will analyze your sentiment and respond appropriately
4. View real-time sentiment indicators and emotion tags
5. Check the statistics panel for conversation analytics

### API Endpoints

#### Chat Endpoint
```http
POST /api/chat
Content-Type: application/json

{
"message": "I'm feeling really happy today!"
}
```

**Response:**
```json
{
"sentiment": "positive",
"emotions": ["joy"],
"response": "That's wonderful to hear! ๐Ÿ˜Š",
"confidence": 0.85,
"vader_scores": {
"compound": 0.85,
"pos": 0.75,
"neg": 0.0,
"neu": 0.25
},
"textblob_analysis": {
"polarity": 0.8,
"subjectivity": 0.9
},
"entities": [],
"timestamp": "2026-01-09T12:00:00"
}
```

#### Report Endpoint
```http
GET /api/report
```

#### Reset Endpoint
```http
POST /api/reset
```

#### Health Check
```http
GET /api/health
```

## ๐Ÿ“Š Sentiment Analysis Features

### Sentiment Detection Methods

1. **VADER Analysis**: Specifically tuned for social media text
2. **TextBlob Analysis**: General purpose sentiment analysis
3. **Ensemble Approach**: Combines multiple methods for accuracy

### Emotion Categories

- **Joy**: Happiness, excitement, delight
- **Anger**: Frustration, irritation, rage
- **Sadness**: Unhappiness, depression, grief
- **Fear**: Anxiety, worry, terror
- **Surprise**: Amazement, shock, astonishment

### Response Generation

The bot generates responses based on:
- Detected sentiment (positive, negative, neutral)
- Specific emotions identified
- Conversation context
- User message content

## ๐ŸŽฏ Advanced Features

### Named Entity Recognition

Using spaCy's NER capabilities, the bot can identify:
- People and organizations
- Locations and dates
- Products and events
- Custom entities

### Conversation Analytics

- Total message count
- Sentiment distribution percentages
- Recent conversation history
- Emotion frequency analysis
- Exportable reports

### Response Adaptation

The bot adapts responses based on:
- User's emotional state
- Conversation history
- Detected sentiment intensity
- Specific emotion types

## ๐Ÿ”ง Configuration

### Environment Variables

Create a `.env` file for configuration:

```env
FLASK_ENV=development
FLASK_DEBUG=True
PORT=5000
HOST=0.0.0.0
```

### Customization

You can customize:
- Response templates in the `responses` dictionary
- Emotion keywords in `emotion_keywords`
- Entity recognition models
- UI themes and colors

## ๐Ÿ“ฑ Mobile Compatibility

The web interface is fully responsive and works on:
- Desktop browsers
- Tablets
- Mobile phones
- Progressive Web App (PWA) ready

## ๐Ÿงช Testing

Run the test suite:

```bash
# Install test dependencies
pip install pytest pytest-flask

# Run tests
pytest tests/
```

## ๐Ÿ“ˆ Performance

- **Response Time**: < 500ms for sentiment analysis
- **Accuracy**: 85-90% sentiment classification accuracy
- **Concurrent Users**: Supports 100+ simultaneous users
- **Memory Usage**: < 100MB for typical usage

## ๐Ÿ”’ Security Features

- Input sanitization and validation
- XSS protection
- CSRF protection
- Rate limiting capabilities
- Secure API endpoints

## ๐Ÿš€ Deployment

### Production Deployment

1. **Install production server**:
```bash
pip install gunicorn
```

2. **Run with Gunicorn**:
```bash
gunicorn -w 4 -b 0.0.0.0:5000 app:app
```

3. **Use reverse proxy** (nginx/Apache) for SSL termination

### Docker Deployment

```dockerfile
FROM python:3.9-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
RUN python -m spacy download en_core_web_sm

COPY . .
EXPOSE 5000

CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "app:app"]
```

## ๐Ÿค Contributing

We welcome contributions! Please follow these steps:

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new features
5. Submit a pull request

## ๐Ÿ“ License

This project is part of RSK World's educational resources. Usage is permitted for educational and development purposes.

## ๐Ÿ‘ฅ Team

- **Founder**: Molla Samser
- **Designer & Tester**: Rima Khatun
- **Organization**: RSK World

## ๐Ÿ“ž Contact

- **Email**: help@rskworld.in
- **Phone**: +91 93305 39277
- **Website**: https://rskworld.in
- **Address**: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147

## ๐ŸŒŸ Support

If you find this project helpful, please consider:
- โญ Starring the repository
- ๐Ÿ› Reporting issues
- ๐Ÿ’ก Suggesting improvements
- ๐Ÿ“ข Sharing with others

## ๐Ÿ“š Additional Resources

- [NLTK Documentation](https://www.nltk.org/)
- [TextBlob Documentation](https://textblob.readthedocs.io/)
- [spaCy Documentation](https://spacy.io/)
- [Flask Documentation](https://flask.palletsprojects.com/)
- [VADER Sentiment Analysis](https://github.com/cjhutto/vaderSentiment)

## ๐Ÿ”„ Version History

- **v1.0.0** (January 2026): Initial release with core sentiment analysis features
- Future versions will include:
- Multi-language support
- Advanced ML models
- Integration with popular messaging platforms
- Custom sentiment training

---

**ยฉ 2026 RSK World. All rights reserved.**

*Content used for educational purposes only. View [Disclaimer](https://rskworld.in/disclaimer.php) for more information.*
static/.gitkeep
Raw Download
Find: Go to:
# This file ensures the static directory is tracked by git
# Static files (CSS, JS, images) can be placed here if needed
# Currently, the project uses CDN links for Bootstrap and Font Awesome
4 linesโ€ข195 B
text
tests/test_app.py
Raw Download
Find: Go to:
"""
Sentiment Analysis Bot Test Suite
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

import pytest
import json
from app import app, AdvancedSentimentAnalysisBot

@pytest.fixture
def client():
    """Create test client"""
    app.config['TESTING'] = True
    with app.test_client() as client:
        yield client

@pytest.fixture
def bot():
    """Create bot instance for testing"""
    return AdvancedSentimentAnalysisBot()

class TestSentimentAnalysisBot:
    """Test the SentimentAnalysisBot class"""
    
    def test_bot_initialization(self, bot):
        """Test bot initialization"""
        assert bot.conversation_history == []
        assert bot.sentiment_stats['total'] == 0
        assert 'positive' in bot.responses
        assert 'negative' in bot.responses
        assert 'neutral' in bot.responses
    
    def test_preprocess_text(self, bot):
        """Test text preprocessing"""
        text = "Hello! How are you???   "
        processed = bot.preprocess_text(text)
        assert processed == "hello how are you"
        
        text_with_special = "Hello @world! #test $100"
        processed = bot.preprocess_text(text_with_special)
        assert processed == "hello world test 100"
    
    def test_analyze_sentiment_vader(self, bot):
        """Test VADER sentiment analysis"""
        positive_text = "I love this! It's amazing!"
        result = bot.analyze_sentiment_vader(positive_text)
        assert result['sentiment'] == 'positive'
        assert 'scores' in result
        assert 'confidence' in result
        
        negative_text = "I hate this! It's terrible!"
        result = bot.analyze_sentiment_vader(negative_text)
        assert result['sentiment'] == 'negative'
        
        neutral_text = "This is a book."
        result = bot.analyze_sentiment_vader(neutral_text)
        assert result['sentiment'] == 'neutral'
    
    def test_detect_emotions(self, bot):
        """Test emotion detection"""
        joy_text = "I am so happy and excited today!"
        emotions = bot.detect_emotions(joy_text)
        assert 'joy' in emotions
        
        anger_text = "I am very angry and frustrated!"
        emotions = bot.detect_emotions(anger_text)
        assert 'anger' in emotions
        
        sad_text = "I feel sad and depressed."
        emotions = bot.detect_emotions(sad_text)
        assert 'sadness' in emotions
    
    def test_generate_response(self, bot):
        """Test response generation"""
        sentiment_data = {'sentiment': 'positive'}
        emotions = ['joy']
        user_id = "test_user"
        response = bot.generate_contextual_response("test", sentiment_data, emotions, user_id)
        assert response is not None
        assert len(response) > 0
        
        # Test emotion-specific response
        joy_emotions = ['joy']
        response = bot.generate_contextual_response("test", sentiment_data, joy_emotions, user_id)
        assert response is not None
    
    def test_analyze_text_comprehensive(self, bot):
        """Test comprehensive text analysis"""
        text = "I am feeling very happy and excited today!"
        result = bot.advanced_analyze_text(text)
        
        assert 'sentiment' in result
        assert 'emotions' in result
        assert 'response' in result
        assert 'confidence' in result
        assert 'timestamp' in result
        assert result['sentiment'] == 'positive'
        assert 'joy' in result['emotions']
    
    def test_sentiment_report(self, bot):
        """Test sentiment report generation"""
        # Add some conversations
        bot.advanced_analyze_text("I am happy today!")
        bot.advanced_analyze_text("I am sad today!")
        bot.advanced_analyze_text("This is neutral.")
        
        report = bot.get_advanced_sentiment_report()
        assert report['total_conversations'] == 3
        assert report['raw_stats']['positive'] == 1
        assert report['raw_stats']['negative'] == 1
        assert report['raw_stats']['neutral'] == 1
        assert 'sentiment_distribution' in report
    
    def test_reset_conversation(self, bot):
        """Test conversation reset"""
        # Add conversation
        bot.advanced_analyze_text("Hello!")
        assert bot.sentiment_stats['total'] == 1
        
        # Reset
        bot.reset_conversation()
        assert bot.sentiment_stats['total'] == 0
        assert len(bot.conversation_history) == 0

class TestAPIEndpoints:
    """Test Flask API endpoints"""
    
    def test_health_check(self, client):
        """Test health check endpoint"""
        response = client.get('/api/health')
        assert response.status_code == 200
        data = json.loads(response.data)
        assert data['status'] == 'healthy'
        assert 'timestamp' in data
    
    def test_chat_endpoint_valid_message(self, client):
        """Test chat endpoint with valid message"""
        response = client.post('/api/chat', 
                             json={'message': 'I am happy today!'},
                             content_type='application/json')
        assert response.status_code == 200
        data = json.loads(response.data)
        assert 'sentiment' in data
        assert 'response' in data
        assert 'emotions' in data
    
    def test_chat_endpoint_empty_message(self, client):
        """Test chat endpoint with empty message"""
        response = client.post('/api/chat', 
                             json={'message': ''},
                             content_type='application/json')
        assert response.status_code == 400
    
    def test_chat_endpoint_no_message(self, client):
        """Test chat endpoint without message"""
        response = client.post('/api/chat', 
                             json={},
                             content_type='application/json')
        assert response.status_code == 400
    
    def test_chat_endpoint_invalid_json(self, client):
        """Test chat endpoint with invalid JSON"""
        response = client.post('/api/chat', 
                             data='invalid json',
                             content_type='application/json')
        assert response.status_code == 400
    
    def test_report_endpoint(self, client):
        """Test report endpoint"""
        # First add some messages
        client.post('/api/chat', json={'message': 'I am happy!'})
        client.post('/api/chat', json={'message': 'I am sad!'})
        
        response = client.get('/api/report')
        assert response.status_code == 200
        data = json.loads(response.data)
        assert 'total_conversations' in data
        assert 'sentiment_distribution' in data
    
    def test_reset_endpoint(self, client):
        """Test reset endpoint"""
        # Add a message first
        client.post('/api/chat', json={'message': 'Hello!'})
        
        # Reset
        response = client.post('/api/reset')
        assert response.status_code == 200
        data = json.loads(response.data)
        assert 'message' in data
        
        # Check report is empty
        response = client.get('/api/report')
        data = json.loads(response.data)
        assert data['total_conversations'] == 0
    
    def test_index_page(self, client):
        """Test index page loads"""
        response = client.get('/')
        assert response.status_code == 200
        assert b'Sentiment Analysis Bot' in response.data

class TestEdgeCases:
    """Test edge cases and error handling"""
    
    def test_very_long_message(self, client):
        """Test very long message handling"""
        long_message = "This is a very long message. " * 100
        response = client.post('/api/chat', 
                             json={'message': long_message},
                             content_type='application/json')
        assert response.status_code == 200
    
    def test_unicode_message(self, client):
        """Test unicode characters"""
        unicode_message = "Hello ๐ŸŒ! I'm feeling ๐Ÿ˜Š today!"
        response = client.post('/api/chat', 
                             json={'message': unicode_message},
                             content_type='application/json')
        assert response.status_code == 200
        data = json.loads(response.data)
        assert 'response' in data
    
    def test_mixed_sentiment(self, client):
        """Test mixed sentiment messages"""
        mixed_message = "I love the design but hate the color!"
        response = client.post('/api/chat', 
                             json={'message': mixed_message},
                             content_type='application/json')
        assert response.status_code == 200
        data = json.loads(response.data)
        assert 'sentiment' in data
    
    def test_question_message(self, client):
        """Test question handling"""
        question = "How are you feeling today?"
        response = client.post('/api/chat', 
                             json={'message': question},
                             content_type='application/json')
        assert response.status_code == 200
        data = json.loads(response.data)
        assert 'response' in data

class TestPerformance:
    """Test performance benchmarks"""
    
    def test_response_time(self, client):
        """Test API response time"""
        import time
        start_time = time.time()
        response = client.post('/api/chat', 
                             json={'message': 'I am happy today!'},
                             content_type='application/json')
        end_time = time.time()
        
        assert response.status_code == 200
        assert (end_time - start_time) < 2.0  # Should respond within 2 seconds
    
    def test_multiple_concurrent_requests(self, client):
        """Test multiple concurrent requests"""
        import threading
        import time
        
        results = []
        
        def make_request():
            response = client.post('/api/chat', 
                                 json={'message': 'Test message'},
                                 content_type='application/json')
            results.append(response.status_code)
        
        # Create 10 concurrent requests
        threads = []
        for _ in range(10):
            thread = threading.Thread(target=make_request)
            threads.append(thread)
            thread.start()
        
        # Wait for all threads to complete
        for thread in threads:
            thread.join()
        
        # All requests should succeed
        assert all(status == 200 for status in results)

if __name__ == '__main__':
    pytest.main([__file__, '-v'])
291 linesโ€ข10.8 KB
python
๐Ÿš€ Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work โค๏ธ

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