This commit introduces major enhancements to Talk2Me: ## Database Integration - PostgreSQL support with SQLAlchemy ORM - Redis integration for caching and real-time analytics - Automated database initialization scripts - Migration support infrastructure ## User Authentication System - JWT-based API authentication - Session-based web authentication - API key authentication for programmatic access - User roles and permissions (admin/user) - Login history and session tracking - Rate limiting per user with customizable limits ## Admin Dashboard - Real-time analytics and monitoring - User management interface (create, edit, delete users) - System health monitoring - Request/error tracking - Language pair usage statistics - Performance metrics visualization ## Key Features - Dual authentication support (token + user accounts) - Graceful fallback for missing services - Non-blocking analytics middleware - Comprehensive error handling - Session management with security features ## Bug Fixes - Fixed rate limiting bypass for admin routes - Added missing email validation method - Improved error handling for missing database tables - Fixed session-based authentication for API endpoints 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
6.2 KiB
Database Integration Guide
This guide explains the Redis and PostgreSQL integration for the Talk2Me application.
Overview
The Talk2Me application now uses:
- PostgreSQL: For persistent storage of translations, transcriptions, user preferences, and analytics
- Redis: For caching, session management, and rate limiting
Architecture
PostgreSQL Database Schema
-
translations - Stores translation history
- Source and target text
- Languages
- Translation time and model used
- Session and user tracking
-
transcriptions - Stores transcription history
- Transcribed text
- Detected language
- Audio metadata
- Performance metrics
-
user_preferences - Stores user settings
- Preferred languages
- Voice preferences
- Usage statistics
-
usage_analytics - Aggregated analytics
- Hourly and daily metrics
- Service performance
- Language pair statistics
-
api_keys - API key management
- Rate limits
- Permissions
- Usage tracking
Redis Usage
-
Translation Cache
- Key:
translation:{source_lang}:{target_lang}:{text_hash}
- Expires: 24 hours
- Reduces API calls to Ollama
- Key:
-
Session Management
- Key:
session:{session_id}
- Stores session data and resources
- Expires: 1 hour (configurable)
- Key:
-
Rate Limiting
- Token bucket implementation
- Per-client and global limits
- Sliding window tracking
-
Push Subscriptions
- Set:
push_subscriptions
- Individual subscriptions:
push_subscription:{id}
- Set:
Setup Instructions
Prerequisites
-
Install PostgreSQL:
# Ubuntu/Debian sudo apt-get install postgresql postgresql-contrib # MacOS brew install postgresql
-
Install Redis:
# Ubuntu/Debian sudo apt-get install redis-server # MacOS brew install redis
-
Install Python dependencies:
pip install -r requirements.txt
Quick Setup
Run the setup script:
./setup_databases.sh
Manual Setup
-
Create PostgreSQL database:
createdb talk2me
-
Start Redis:
redis-server
-
Create .env file with database URLs:
DATABASE_URL=postgresql://username@localhost/talk2me REDIS_URL=redis://localhost:6379/0
-
Initialize database:
python database_init.py
-
Run migrations:
python migrations.py init python migrations.py create "Initial migration" python migrations.py run
Configuration
Environment Variables
# PostgreSQL
DATABASE_URL=postgresql://username:password@host:port/database
SQLALCHEMY_DATABASE_URI=${DATABASE_URL}
SQLALCHEMY_ENGINE_OPTIONS_POOL_SIZE=10
SQLALCHEMY_ENGINE_OPTIONS_POOL_RECYCLE=3600
# Redis
REDIS_URL=redis://localhost:6379/0
REDIS_DECODE_RESPONSES=false
REDIS_MAX_CONNECTIONS=50
REDIS_SOCKET_TIMEOUT=5
# Session Management
MAX_SESSION_DURATION=3600
MAX_SESSION_IDLE_TIME=900
MAX_RESOURCES_PER_SESSION=100
MAX_BYTES_PER_SESSION=104857600
Migration from In-Memory to Database
What Changed
-
Rate Limiting
- Before: In-memory dictionaries
- After: Redis sorted sets and hashes
-
Session Management
- Before: In-memory session storage
- After: Redis with automatic expiration
-
Translation Cache
- Before: Client-side IndexedDB only
- After: Server-side Redis cache + client cache
-
Analytics
- Before: No persistent analytics
- After: PostgreSQL aggregated metrics
Migration Steps
-
Backup current app.py:
cp app.py app_backup.py
-
Use the new app with database support:
cp app_with_db.py app.py
-
Update any custom configurations in the new app.py
API Changes
New Endpoints
/api/history/translations
- Get translation history/api/history/transcriptions
- Get transcription history/api/preferences
- Get/update user preferences/api/analytics
- Get usage analytics
Enhanced Features
-
Translation Caching
- Automatic server-side caching
- Reduced response time for repeated translations
-
Session Persistence
- Sessions survive server restarts
- Better resource tracking
-
Improved Rate Limiting
- Distributed rate limiting across multiple servers
- More accurate tracking
Performance Considerations
-
Database Indexes
- Indexes on session_id, user_id, languages
- Composite indexes for common queries
-
Redis Memory Usage
- Monitor with:
redis-cli info memory
- Configure maxmemory policy
- Monitor with:
-
Connection Pooling
- PostgreSQL: 10 connections default
- Redis: 50 connections default
Monitoring
PostgreSQL
-- Check database size
SELECT pg_database_size('talk2me');
-- Active connections
SELECT count(*) FROM pg_stat_activity;
-- Slow queries
SELECT * FROM pg_stat_statements ORDER BY mean_time DESC LIMIT 10;
Redis
# Memory usage
redis-cli info memory
# Connected clients
redis-cli info clients
# Monitor commands
redis-cli monitor
Troubleshooting
Common Issues
-
PostgreSQL Connection Failed
- Check if PostgreSQL is running:
sudo systemctl status postgresql
- Verify DATABASE_URL in .env
- Check pg_hba.conf for authentication
- Check if PostgreSQL is running:
-
Redis Connection Failed
- Check if Redis is running:
redis-cli ping
- Verify REDIS_URL in .env
- Check Redis logs:
sudo journalctl -u redis
- Check if Redis is running:
-
Migration Errors
- Drop and recreate database if needed
- Check migration files in
migrations/
- Run
python migrations.py init
to reinitialize
Backup and Restore
PostgreSQL Backup
# Backup
pg_dump talk2me > talk2me_backup.sql
# Restore
psql talk2me < talk2me_backup.sql
Redis Backup
# Backup (if persistence enabled)
redis-cli BGSAVE
# Copy dump.rdb file
cp /var/lib/redis/dump.rdb redis_backup.rdb
Security Notes
-
Database Credentials
- Never commit .env file
- Use strong passwords
- Limit database user permissions
-
Redis Security
- Consider enabling Redis AUTH
- Bind to localhost only
- Use SSL for remote connections
-
Data Privacy
- Translations/transcriptions contain user data
- Implement data retention policies
- Consider encryption at rest