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
news-summary-bot
RSK World
news-summary-bot
News Summary Bot - Python + Flask + OpenAI + NewsAPI + AI Summarization + Real-time News + News Aggregation
news-summary-bot
  • __pycache__
  • static
  • templates
  • .env459 B
  • .gitignore761 B
  • GITHUB_RELEASE_SUMMARY.md3.7 KB
  • INSTALLATION.md2.7 KB
  • PROJECT_SUMMARY.md9.5 KB
  • README.md11.4 KB
  • RELEASE_NOTES_v1.0.0.md6.7 KB
  • admin.py7.6 KB
  • analytics.py11 KB
  • app.py14.1 KB
  • auth.py15 KB
  • cache.py11.1 KB
  • export.py14.2 KB
  • news_bot.py4.7 KB
  • requirements.txt286 B
  • search.py16.8 KB
  • security.py14.4 KB
app.pyinstall.batREADME.mdadmin.py
app.py
Raw Download
Find: Go to:
"""
Main Flask Application for News Summary Bot
Developer: Molla Samser
Design & Testing: Rima Khatun
Company: RSK World
Year: 2026
Website: https://rskworld.in
"""

from flask import Flask, request, jsonify, render_template, session, redirect, url_for, flash, Response
from flask_cors import CORS
from datetime import datetime
from news_bot import NewsBot
from analytics import NewsAnalytics, AdvancedNLP
from cache import cache_manager, news_cache
from auth import auth_manager, user_preferences, login_required
from search import advanced_search, SearchFilters
from security import rate_limit, security_headers
from export import data_exporter
import os
from dotenv import load_dotenv
import hashlib

load_dotenv()

app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'your-secret-key-here')
CORS(app)

# Register security headers middleware
@app.after_request
def apply_security_headers(response):
    return security_headers.add_security_headers(response)

bot = NewsBot()
analytics = NewsAnalytics()
nlp = AdvancedNLP()

# Register admin blueprint
from admin import admin_bp
app.register_blueprint(admin_bp)

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/demo')
def demo():
    return render_template('demo.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        result = auth_manager.authenticate_user(username, password)
        if result['success']:
            # Create session
            session_token = auth_manager.create_session(
                result['user_id'], 
                request.remote_addr,
                request.headers.get('User-Agent')
            )
            session['user_token'] = session_token
            session['user_id'] = result['user_id']
            session['username'] = result['username']
            
            flash('Login successful!', 'success')
            return redirect(url_for('demo'))
        else:
            flash(result['error'], 'error')
    
    return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')
        confirm_password = request.form.get('confirm_password')
        
        if password != confirm_password:
            flash('Passwords do not match!', 'error')
            return render_template('register.html')
        
        result = auth_manager.register_user(username, email, password)
        if result['success']:
            flash('Registration successful! Please log in.', 'success')
            return redirect(url_for('login'))
        else:
            flash(result['error'], 'error')
    
    return render_template('register.html')

@app.route('/logout')
def logout():
    if 'user_token' in session:
        auth_manager.invalidate_session(session['user_token'])
        session.clear()
        flash('Logged out successfully!', 'info')
    return redirect(url_for('home'))

@app.route('/api/news', methods=['GET'])
@rate_limit(limit=100, window=3600)
def get_news():
    category = request.args.get('category', 'general')
    query = request.args.get('q')
    country = request.args.get('country', 'us')
    
    # Check cache first
    cache_key_data = news_cache.get_news(category, query, country)
    if cache_key_data:
        return jsonify(cache_key_data)
    
    # Fetch fresh data
    news_data = bot.fetch_news(category=category, query=query)
    
    # Cache the results
    if 'articles' in news_data:
        news_cache.set_news(category, query, country, news_data)
        
        # Index articles for search
        for article in news_data['articles'][:10]:  # Limit to avoid overloading
            article_data = {
                'article_id': str(article.get('publishedAt', '')) + str(hash(article.get('title', ''))),
                'title': article.get('title', ''),
                'content': article.get('description', ''),
                'category': category,
                'source': article.get('source', {}).get('name', ''),
                'author': article.get('author', ''),
                'published_at': article.get('publishedAt', ''),
                'word_count': len(article.get('description', '').split())
            }
            advanced_search.index_article(article_data)
    
    return jsonify(news_data)

@app.route('/api/summarize', methods=['POST'])
@rate_limit(limit=50, window=3600)
def summarize():
    data = request.get_json()
    content = data.get('content')
    language = data.get('language', 'English')
    
    if not content:
        return jsonify({"error": "No content provided for summarization"}), 400
    
    # Generate content hash for caching
    content_hash = hashlib.md5(content.encode()).hexdigest()
    
    # Check cache first
    cached_summary = news_cache.get_summary(content_hash, language)
    if cached_summary:
        return jsonify({"summary": cached_summary, "cached": True})
    
    # Generate summary
    summary = bot.summarize_article(content, language=language)
    
    # Cache the summary
    news_cache.set_summary(content_hash, language, summary)
    
    # Track user activity if logged in
    if 'user_id' in session:
        analytics.track_user_interaction(session['user_id'], 'summarize', content_hash=content_hash)
    
    return jsonify({"summary": summary, "cached": False})

@app.route('/api/analyze', methods=['POST'])
@rate_limit(limit=50, window=3600)
def analyze():
    data = request.get_json()
    content = data.get('content')
    
    if not content:
        return jsonify({"error": "No content provided for analysis"}), 400
    
    # Generate content hash for caching
    content_hash = hashlib.md5(content.encode()).hexdigest()
    
    # Check cache first
    cached_sentiment = news_cache.get_sentiment(content_hash)
    if cached_sentiment:
        return jsonify({"sentiment": cached_sentiment, "cached": True})
    
    # Analyze sentiment
    sentiment = bot.analyze_sentiment(content)
    
    # Cache the result
    news_cache.set_sentiment(content_hash, sentiment)
    
    # Store analytics
    if 'user_id' in session:
        analytics.track_user_interaction(session['user_id'], 'analyze', content_hash=content_hash)
    
    return jsonify({"sentiment": sentiment, "cached": False})

@app.route('/api/reliability', methods=['POST'])
@rate_limit(limit=50, window=3600)
def reliability():
    data = request.get_json()
    content = data.get('content')
    
    if not content:
        return jsonify({"error": "No content provided for reliability analysis"}), 400
    
    score = bot.analyze_reliability(content)
    return jsonify({"score": score})

@app.route('/api/search', methods=['GET'])
@rate_limit(limit=200, window=3600)
def search_articles():
    query = request.args.get('q', '')
    filters = {}
    
    # Parse filters from query parameters
    if request.args.get('category'):
        filters['category'] = request.args.get('category')
    if request.args.get('sentiment'):
        filters['sentiment'] = request.args.get('sentiment')
    if request.args.get('language'):
        filters['language'] = request.args.get('language')
    if request.args.get('min_reliability'):
        filters['min_reliability'] = request.args.get('min_reliability')
    if request.args.get('date_from'):
        filters['date_from'] = request.args.get('date_from')
    if request.args.get('date_to'):
        filters['date_to'] = request.args.get('date_to')
    
    # Validate filters
    filters = SearchFilters.validate_filters(filters)
    
    # Search parameters
    sort_by = request.args.get('sort', 'relevance')
    limit = int(request.args.get('limit', 20))
    offset = int(request.args.get('offset', 0))
    
    # Perform search
    results = advanced_search.search(query, filters, sort_by, limit, offset)
    
    # Track search
    user_id = session.get('user_id') if 'user_id' in session else None
    advanced_search.track_search(user_id, query, filters, results['total_count'])
    
    return jsonify(results)

@app.route('/api/search/suggestions')
def search_suggestions():
    query = request.args.get('q', '')
    limit = int(request.args.get('limit', 10))
    
    suggestions = advanced_search.get_suggestions(query, limit)
    return jsonify({"suggestions": suggestions})

@app.route('/api/search/popular')
def popular_searches():
    limit = int(request.args.get('limit', 10))
    popular = advanced_search.get_popular_searches(limit)
    return jsonify({"popular": popular})

@app.route('/api/user/preferences', methods=['GET', 'POST'])
@login_required
def user_preferences_api():
    user_id = session['user_id']
    
    if request.method == 'POST':
        data = request.get_json()
        for pref_type, pref_value in data.items():
            user_preferences.set_preference(user_id, pref_type, pref_value)
        return jsonify({"success": True})
    
    preferences = user_preferences.get_all_preferences(user_id)
    return jsonify(preferences)

@app.route('/api/user/history')
@login_required
def reading_history():
    user_id = session['user_id']
    limit = int(request.args.get('limit', 50))
    history = user_preferences.get_reading_history(user_id, limit)
    return jsonify(history)

@app.route('/api/user/stats')
@login_required
def user_stats():
    user_id = session['user_id']
    days = int(request.args.get('days', 30))
    stats = user_preferences.get_reading_stats(user_id, days)
    return jsonify(stats)

@app.route('/api/trending')
def trending_topics():
    days = int(request.args.get('days', 7))
    
    # Check cache first
    cached_trending = news_cache.get_trending_topics(days)
    if cached_trending:
        return jsonify({"trending": cached_trending, "cached": True})
    
    # Get fresh trending data
    trending = analytics.analyze_trending_topics(days)
    
    # Cache the results
    news_cache.set_trending_topics(days, trending)
    
    return jsonify({"trending": trending, "cached": False})

@app.route('/api/analytics/overview')
def analytics_overview():
    """Public analytics endpoint."""
    days = int(request.args.get('days', 30))
    
    # Get various analytics
    sentiment_trends = analytics.get_sentiment_trends(days)
    category_analytics = analytics.get_category_analytics()
    search_analytics = advanced_search.get_search_analytics(days)
    
    return jsonify({
        "sentiment_trends": sentiment_trends,
        "category_analytics": category_analytics,
        "search_analytics": search_analytics
    })

@app.route('/api/cache/stats')
def cache_stats():
    """Cache statistics endpoint."""
    stats = cache_manager.get_stats()
    return jsonify(stats)

@app.route('/api/cache/clear', methods=['POST'])
def clear_cache():
    """Clear cache endpoint."""
    # This should be protected in production
    cache_manager.clear()
    return jsonify({"success": True, "message": "Cache cleared successfully"})

@app.route('/api/export/user-data', methods=['GET'])
@login_required
@rate_limit(limit=10, window=3600)
def export_user_data():
    """Export user data in various formats."""
    user_id = session['user_id']
    format_type = request.args.get('format', 'json').lower()
    
    try:
        data = data_exporter.export_user_data(user_id, format_type)
        
        # Set appropriate content type and filename
        content_types = {
            'json': 'application/json',
            'csv': 'text/csv',
            'xml': 'application/xml'
        }
        
        filename = f'user_data_{user_id}_{datetime.now().strftime("%Y%m%d")}.{format_type}'
        
        return Response(
            data,
            mimetype=content_types.get(format_type, 'application/octet-stream'),
            headers={'Content-Disposition': f'attachment; filename={filename}'}
        )
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/export/analytics', methods=['GET'])
@rate_limit(limit=20, window=3600)
def export_analytics():
    """Export analytics data."""
    days = int(request.args.get('days', 30))
    format_type = request.args.get('format', 'json').lower()
    
    try:
        data = data_exporter.export_analytics_data(days, format_type)
        
        content_types = {
            'json': 'application/json',
            'csv': 'text/csv',
            'xml': 'application/xml'
        }
        
        filename = f'analytics_{days}days_{datetime.now().strftime("%Y%m%d")}.{format_type}'
        
        return Response(
            data,
            mimetype=content_types.get(format_type, 'application/octet-stream'),
            headers={'Content-Disposition': f'attachment; filename={filename}'}
        )
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/export/backup', methods=['GET'])
@rate_limit(limit=5, window=3600)
def export_backup():
    """Create full system backup."""
    include_user_data = request.args.get('include_users', 'false').lower() == 'true'
    
    try:
        data = data_exporter.create_full_backup(include_user_data=include_user_data)
        filename = f'backup_{datetime.now().strftime("%Y%m%d_%H%M%S")}.zip'
        
        return Response(
            data,
            mimetype='application/zip',
            headers={'Content-Disposition': f'attachment; filename={filename}'}
        )
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    port = int(os.getenv("PORT", 5000))
    debug = os.getenv("DEBUG", "True") == "True"
    
    # Cleanup expired cache entries on startup
    cache_manager.cleanup_expired()
    
    app.run(host='0.0.0.0', port=port, debug=debug)

# Developed by Molla Samser | 2026 | RSK World
420 lines•14.1 KB
python
README.md
Raw Download

README.md

# News Summary Bot

An advanced AI-powered chatbot that fetches real-time news articles and provides concise summaries using Natural Language Processing (NLP) and OpenAI. This project includes cutting-edge features like user authentication, advanced analytics, caching, search, and comprehensive security.

## Project Details
- **Developer:** Molla Samser
- **Design & Testing:** Rima Khatun
- **Company:** RSK World
- **Website:** [rskworld.in](https://rskworld.in)
- **Contact:** +91 93305 39277 | info@rskworld.com
- **Address:** Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147
- **Year:** 2026

## 🚀 Advanced Features

### Core Functionality
- **Real-time News Fetching:** Fetches top headlines from multiple sources using NewsAPI
- **AI Article Summarization:** Generates high-quality summaries using OpenAI GPT-3.5 Turbo
- **Multi-language Support:** Summarize news in English, Hindi, Spanish, French, German
- **Voice Search:** Search news using voice commands
- **Category Filtering:** Browse news in Business, Tech, Health, Science, Sports, etc.
- **Sentiment Analysis:** Analyze the sentiment of news articles with advanced NLP
- **Reliability Scoring:** Check the reliability and objectivity of news sources
- **Mobile Responsive:** Modern glassmorphism design that works on all devices

### Advanced Features
- **User Authentication System:** Complete user registration, login, and session management
- **Personalization:** User preferences, reading history, and personalized recommendations
- **Advanced Search:** Full-text search with filters, sorting, and suggestions
- **Caching System:** Intelligent caching for improved performance and reduced API costs
- **Analytics Dashboard:** Comprehensive admin panel with real-time analytics
- **Data Export:** Export data in JSON, CSV, XML formats with backup capabilities
- **Rate Limiting:** Advanced API rate limiting and security features
- **Admin Panel:** Complete admin interface for monitoring and management

### Security Features
- **Input Validation:** Comprehensive input sanitization and validation
- **Rate Limiting:** Configurable rate limiting with exponential backoff
- **CSRF Protection:** Cross-site request forgery protection
- **Security Headers:** Complete security header implementation
- **API Key Authentication:** Secure API key validation
- **Session Management:** Secure session handling with expiration

## 🛠 Technologies Used

### Backend
- **Framework:** Python Flask
- **AI/NLP:** OpenAI API (GPT-3.5 Turbo)
- **APIs:** NewsAPI.org
- **Database:** SQLite (with full-text search)
- **Caching:** Custom caching system with SQLite backend
- **Authentication:** Custom auth system with secure password hashing
- **Security:** Rate limiting, CSRF protection, input validation

### Frontend
- **Languages:** HTML5, CSS3, JavaScript (Vanilla)
- **Styling:** Glassmorphism design with CSS animations
- **Icons:** Font Awesome 6.0
- **Charts:** Chart.js for analytics visualization
- **PDF Export:** jsPDF for document export

### Development Tools
- **Environment:** Python 3.8+
- **Package Management:** pip with requirements.txt
- **Configuration:** Environment variables with .env
- **Version Control:** Git ready

## 📁 Project Structure

```
news-summary-bot/
├── app.py # Main Flask application
├── news_bot.py # Core news fetching and processing
├── analytics.py # Advanced analytics and NLP processing
├── cache.py # Intelligent caching system
├── auth.py # User authentication and preferences
├── search.py # Advanced search functionality
├── export.py # Data export and reporting
├── security.py # Security and rate limiting
├── admin.py # Admin panel routes
├── requirements.txt # Python dependencies
├── .env # Environment variables
├── README.md # Project documentation
├── INSTALLATION.md # Detailed installation guide
├── templates/ # HTML templates
│ ├── index.html # Landing page
│ ├── demo.html # Demo interface
│ ├── login.html # User login
│ ├── register.html # User registration
│ └── admin/ # Admin panel templates
│ ├── login.html # Admin login
│ └── dashboard.html # Admin dashboard
├── static/ # Static assets
│ ├── css/
│ │ └── style.css # Custom styles
│ └── js/
│ └── script.js # JavaScript logic
└── databases/ # SQLite databases (auto-created)
├── news_analytics.db # Analytics data
├── users.db # User data
├── cache.db # Cache storage
├── search_index.db # Search index
└── rate_limits.db # Rate limiting data
```

## 🚀 Setup Instructions

### Prerequisites
- Python 3.8 or higher
- pip (Python package manager)
- Valid API keys (NewsAPI and OpenAI)

### Installation Steps

1. **Clone the repository**
```bash
git clone <repository-url>
cd news-summary-bot
```

2. **Create virtual environment**
```bash
python -m venv venv

# On Windows
venv\Scripts\activate

# On Mac/Linux
source venv/bin/activate
```

3. **Install dependencies**
```bash
pip install -r requirements.txt
```

4. **Configure environment variables**
Create a `.env` file with your configuration:
```env
# API Keys
NEWS_API_KEY=your_newsapi_org_key
OPENAI_API_KEY=your_openai_api_key

# Server Configuration
PORT=5000
DEBUG=True
SECRET_KEY=your-secret-key-here

# Admin Credentials
ADMIN_USERNAME=admin
ADMIN_PASSWORD=admin123

# Security
VALID_API_KEYS=key1,key2,key3
```

5. **Run the application**
```bash
python app.py
```

6. **Access the application**
- **Main Page:** http://localhost:5000
- **Demo Interface:** http://localhost:5000/demo
- **Admin Panel:** http://localhost:5000/admin

## 📡 API Endpoints

### News Endpoints
- `GET /api/news` - Fetch news articles (with caching)
- `POST /api/summarize` - Summarize article content
- `POST /api/analyze` - Analyze sentiment
- `POST /api/reliability` - Check reliability score

### Search Endpoints
- `GET /api/search` - Advanced search with filters
- `GET /api/search/suggestions` - Get search suggestions
- `GET /api/search/popular` - Get popular searches

### User Endpoints
- `POST /api/login` - User login
- `POST /api/register` - User registration
- `GET /api/logout` - User logout
- `GET/POST /api/user/preferences` - User preferences
- `GET /api/user/history` - Reading history
- `GET /api/user/stats` - User statistics

### Analytics Endpoints
- `GET /api/trending` - Trending topics
- `GET /api/analytics/overview` - Public analytics
- `GET /api/cache/stats` - Cache statistics

### Admin Endpoints
- `GET /admin/` - Admin dashboard
- `GET /admin/analytics` - Detailed analytics
- `GET /admin/users` - User management
- `GET /admin/settings` - System settings

## 🔧 Configuration

### Rate Limiting
Configure rate limits per endpoint:
```python
@app.route('/api/news')
@rate_limit(limit=100, window=3600) # 100 requests per hour
def get_news():
# Endpoint logic
```

### Caching
Configure cache TTL (time to live):
```python
# News cache: 5 minutes
news_cache.set_news(category, query, country, data, ttl=300)

# Summary cache: 1 hour
news_cache.set_summary(content_hash, language, summary, ttl=3600)
```

### Search Filters
Available search filters:
- `category`: News category
- `sentiment`: Positive/Negative/Neutral
- `language`: Article language
- `min_reliability`: Minimum reliability score
- `date_from/date_to`: Date range
- `sort`: relevance/date/reliability/popularity

## 📊 Analytics Features

### User Analytics
- Reading history tracking
- Category preferences
- Session duration
- Search patterns
- Summary requests

### System Analytics
- Sentiment trends over time
- Category distribution
- Popular search queries
- Cache hit rates
- API usage statistics

### Admin Dashboard
- Real-time metrics
- Interactive charts
- User management
- System monitoring
- Performance analytics

## 🔒 Security Features

### Input Validation
- Email format validation
- Password strength requirements
- XSS prevention
- SQL injection protection
- Search query validation

### Rate Limiting
- Per-IP and per-user limits
- Exponential backoff for violations
- Configurable windows and limits
- Automatic blocking for abuse

### Authentication Security
- Secure password hashing with salt
- Session management with expiration
- CSRF token protection
- API key validation

## 📤 Data Export

### Supported Formats
- **JSON:** Complete data structure
- **CSV:** Tabular data for spreadsheets
- **XML:** Structured data format
- **ZIP:** Multiple formats in one package

### Export Types
- User data export (GDPR compliant)
- Analytics data export
- News articles export
- Full system backup

## 🎯 Performance Optimization

### Caching Strategy
- Multi-level caching
- Intelligent cache invalidation
- Cache statistics and monitoring
- Automatic cleanup of expired entries

### Database Optimization
- Full-text search indexes
- Optimized queries
- Connection pooling
- Regular maintenance

### API Optimization
- Response compression
- Efficient data structures
- Minimal API calls
- Background processing

## 🐛 Troubleshooting

### Common Issues

1. **API Key Errors**
- Verify keys in `.env` file
- Check API key validity and permissions
- Ensure sufficient API credits

2. **Database Errors**
- Check file permissions for database files
- Ensure SQLite is properly installed
- Clear cache if corrupted

3. **Performance Issues**
- Check cache hit rates
- Monitor API usage limits
- Review database indexes

4. **Authentication Issues**
- Clear browser cookies
- Check session configuration
- Verify SECRET_KEY in .env

### Debug Mode
Enable debug mode for detailed error messages:
```env
DEBUG=True
```

## 📞 Support & Contact

For technical support and inquiries:
- **Email:** info@rskworld.com, support@rskworld.in
- **Phone:** +91 93305 39277
- **Website:** https://rskworld.in
- **Address:** Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147

## 📄 License

&copy; 2026 RSK World. All rights reserved.
Developed by Molla Samser | Design & Testing by Rima Khatun

---

## 🌟 Acknowledgments

This project is part of the RSK World AI Chatbots collection. Visit https://rskworld.in for more projects and resources.

### Technologies Used
- [OpenAI](https://openai.com/) - AI-powered summarization
- [NewsAPI](https://newsapi.org/) - Real-time news data
- [Flask](https://flask.palletsprojects.com/) - Web framework
- [Chart.js](https://www.chartjs.org/) - Data visualization
- [Font Awesome](https://fontawesome.com/) - Icon library

### Contributing
Contributions are welcome! Please ensure all code follows the project standards and includes proper documentation.

---

*Last updated: January 2026*
admin.py
Raw Download
Find: Go to:
"""
Admin Panel for News Summary Bot
Developer: Molla Samser
Design & Testing: Rima Khatun
Company: RSK World
Year: 2026
Website: https://rskworld.in
"""

from flask import Blueprint, render_template, request, jsonify, redirect, url_for, session, flash
from functools import wraps
import json
from datetime import datetime, timedelta
from analytics import NewsAnalytics, AdvancedNLP
import os

# Create admin blueprint
admin_bp = Blueprint('admin', __name__, url_prefix='/admin')

# Admin credentials (in production, use proper authentication)
ADMIN_USERNAME = os.getenv('ADMIN_USERNAME', 'admin')
ADMIN_PASSWORD = os.getenv('ADMIN_PASSWORD', 'admin123')

# Initialize analytics
analytics = NewsAnalytics()
nlp = AdvancedNLP()

def admin_required(f):
    """Decorator to require admin authentication."""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not session.get('admin_logged_in'):
            return redirect(url_for('admin.login'))
        return f(*args, **kwargs)
    return decorated_function

@admin_bp.route('/')
def index():
    """Redirect to dashboard if logged in, otherwise to login."""
    if session.get('admin_logged_in'):
        return redirect(url_for('admin.dashboard'))
    return redirect(url_for('admin.login'))

@admin_bp.route('/login', methods=['GET', 'POST'])
def login():
    """Admin login page."""
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        if username == ADMIN_USERNAME and password == ADMIN_PASSWORD:
            session['admin_logged_in'] = True
            session['admin_username'] = username
            flash('Login successful!', 'success')
            return redirect(url_for('admin.dashboard'))
        else:
            flash('Invalid credentials!', 'error')
    
    return render_template('admin/login.html')

@admin_bp.route('/logout')
def logout():
    """Admin logout."""
    session.clear()
    flash('Logged out successfully!', 'info')
    return redirect(url_for('admin.login'))

@admin_bp.route('/dashboard')
@admin_required
def dashboard():
    """Main admin dashboard."""
    # Get key metrics
    total_articles = get_total_articles()
    total_users = get_total_users()
    avg_reliability = get_avg_reliability()
    trending_topics = analytics.analyze_trending_topics(days=7)
    
    # Get sentiment trends for the last 30 days
    sentiment_trends = analytics.get_sentiment_trends(days=30)
    
    # Get category analytics
    category_stats = analytics.get_category_analytics()
    
    return render_template('admin/dashboard.html',
                         total_articles=total_articles,
                         total_users=total_users,
                         avg_reliability=avg_reliability,
                         trending_topics=trending_topics[:5],
                         sentiment_trends=sentiment_trends,
                         category_stats=category_stats)

@admin_bp.route('/analytics')
@admin_required
def analytics_page():
    """Detailed analytics page."""
    # Get date range from request
    days = int(request.args.get('days', 30))
    
    # Get various analytics
    trending_topics = analytics.analyze_trending_topics(days=days)
    sentiment_trends = analytics.get_sentiment_trends(days=days)
    category_analytics = analytics.get_category_analytics()
    user_activity = analytics.get_user_activity_summary(days=days)
    
    return render_template('admin/analytics.html',
                         trending_topics=trending_topics,
                         sentiment_trends=sentiment_trends,
                         category_analytics=category_analytics,
                         user_activity=user_activity,
                         days=days)

@admin_bp.route('/users')
@admin_required
def users():
    """User management page."""
    # Get user statistics
    user_activity = analytics.get_user_activity_summary()
    
    # Mock user data (in production, this would come from a database)
    users = [
        {'id': 'user1', 'name': 'John Doe', 'email': 'john@example.com', 'last_active': '2024-01-10', 'actions': 45},
        {'id': 'user2', 'name': 'Jane Smith', 'email': 'jane@example.com', 'last_active': '2024-01-09', 'actions': 32},
        {'id': 'user3', 'name': 'Bob Johnson', 'email': 'bob@example.com', 'last_active': '2024-01-08', 'actions': 28}
    ]
    
    return render_template('admin/users.html', users=users, user_activity=user_activity)

@admin_bp.route('/content')
@admin_required
def content():
    """Content management page."""
    # Get recent articles and their analysis
    # This would typically fetch from database
    articles = []  # Mock data
    
    return render_template('admin/content.html', articles=articles)

@admin_bp.route('/settings')
@admin_required
def settings():
    """Settings page."""
    # Get current settings
    settings = {
        'news_api_key': os.getenv('NEWS_API_KEY', ''),
        'openai_api_key': os.getenv('OPENAI_API_KEY', ''),
        'max_articles_per_category': os.getenv('MAX_ARTICLES', '10'),
        'cache_duration': os.getenv('CACHE_DURATION', '300'),
        'enable_analytics': os.getenv('ENABLE_ANALYTICS', 'True')
    }
    
    return render_template('admin/settings.html', settings=settings)

@admin_bp.route('/api/analytics/data')
@admin_required
def analytics_data():
    """API endpoint for analytics data."""
    days = int(request.args.get('days', 30))
    data_type = request.args.get('type', 'overview')
    
    if data_type == 'overview':
        data = {
            'total_articles': get_total_articles(),
            'total_users': get_total_users(),
            'avg_reliability': get_avg_reliability(),
            'trending_topics': analytics.analyze_trending_topics(days=days)[:10]
        }
    elif data_type == 'sentiment':
        data = analytics.get_sentiment_trends(days=days)
    elif data_type == 'categories':
        data = analytics.get_category_analytics()
    elif data_type == 'activity':
        data = analytics.get_user_activity_summary(days=days)
    else:
        data = {'error': 'Invalid data type'}
    
    return jsonify(data)

@admin_bp.route('/api/settings/update', methods=['POST'])
@admin_required
def update_settings():
    """Update application settings."""
    try:
        settings = request.get_json()
        
        # Update environment variables (in production, this would update a config file)
        for key, value in settings.items():
            if key.upper() in ['NEWS_API_KEY', 'OPENAI_API_KEY', 'MAX_ARTICLES', 'CACHE_DURATION', 'ENABLE_ANALYTICS']:
                os.environ[key.upper()] = str(value)
        
        return jsonify({'success': True, 'message': 'Settings updated successfully'})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

# Helper functions
def get_total_articles():
    """Get total number of articles processed."""
    # This would typically query a database
    return 1250  # Mock data

def get_total_users():
    """Get total number of users."""
    # This would typically query a database
    return 342  # Mock data

def get_avg_reliability():
    """Get average reliability score."""
    # This would typically calculate from database
    return 78.5  # Mock data

# Error handlers
@admin_bp.errorhandler(404)
def not_found(error):
    return render_template('admin/404.html'), 404

@admin_bp.errorhandler(500)
def internal_error(error):
    return render_template('admin/500.html'), 500

# Developer Details
# Created by Molla Samser (RSK World)
# 2026
222 lines•7.6 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