Spaces:
Sleeping
A newer version of the Gradio SDK is available: 6.26.0
title: Chatty - Ethics Chat
emoji: π¬
colorFrom: yellow
colorTo: purple
sdk: gradio
sdk_version: 5.0.1
app_file: app.py
pinned: false
license: mit
A secure web-based chat interface with user authentication that connects to the findEthics-Atlas API for ethical discussions and guidance.
Features
- User Authentication: Secure registration and login system
- Personalized Chat History: Each user's conversations are saved and restored
- Minimal and clean UI: Simple, responsive chat interface
- Real-time chat: Instant messaging with the ethics AI
- Security Features: CSRF protection, rate limiting, secure sessions
- Error handling: Robust error handling for API failures
- Mobile-friendly: Responsive design that works on all devices
- Loading states: Visual feedback during API calls
Technology Stack
- Backend: Flask web framework with Flask-Login
- Database: MongoDB for user accounts and chat history
- Authentication: Secure password hashing with Werkzeug
- Security: CSRF protection, rate limiting, secure sessions
- Frontend: HTML, CSS, JavaScript (ES6)
- API Integration: HTTP requests to findEthics-Atlas endpoint
- Deployment: Hugging Face Spaces, Docker, or traditional servers
Usage
First Time Setup
- Open the application in your web browser
- Register an account with your email and password
- Log in with your credentials
Using the Chat
- Access the chat interface (automatically redirected after login)
- Type your message in the chat input field
- Press Enter or click the Send button
- Wait for the response from the ethics AI
- Continue the conversation - your history is automatically saved
Account Management
- Logout: Click the logout button to securely end your session
- Session Management: Sessions automatically expire after 24 hours for security
- Chat History: Your conversations are preserved across sessions
The application connects to the findEthics-Atlas API to provide ethical guidance and responses to your questions, while maintaining your personal conversation history.
API Integration
This application uses the https://findEthics-Atlas.hf.space/chat API for generating responses.
Request Format
{
"prompt": "Your question here",
"history": []
}
Response Format
{
"response": "AI response text",
"search_results": []
}
Setup and Installation
Prerequisites
- Python 3.8 or higher
- MongoDB database (MongoDB Atlas recommended)
- Git
Local Development Setup
Clone the repository
git clone <repository-url> cd chattyCreate virtual environment
python -m venv atlas_env source atlas_env/bin/activate # On Windows: atlas_env\Scripts\activateInstall dependencies
pip install -r requirements.txtSet up environment configuration
python deploy.py setup-devThis creates a
.envfile from the template.Configure environment variables Edit
.envfile and set:SECRET_KEY=your-secret-key-here MONGODB_URL=mongodb+srv://username:password@cluster.mongodb.net/database MONGODB_DATABASE=AtlasRun the application
./start.shOr directly:
python app.pyOpen in browser Navigate to http://localhost:7860
MongoDB Setup
Option 1: MongoDB Atlas (Recommended)
- Create account at MongoDB Atlas
- Create a new cluster
- Create database user with read/write permissions
- Get connection string from Atlas dashboard
- Add connection string to
.envasMONGODB_URL
Option 2: Local MongoDB
- Install MongoDB locally
- Start MongoDB service
- Set
MONGODB_URL=mongodb://localhost:27017/chattyin.env
Project Structure
Chatty/
βββ app.py # Main Flask application
βββ config.py # Configuration management
βββ auth.py # Authentication utilities
βββ models.py # Database models (User, ChatSession)
βββ database.py # MongoDB connection utilities
βββ deploy.py # Deployment and configuration tools
βββ requirements.txt # Python dependencies
βββ .env.example # Environment variables template
βββ start.sh # Application startup script
βββ templates/
β βββ base.html # Base template with navigation
β βββ login.html # Login form
β βββ register.html # Registration form
β βββ index.html # Chat interface
β βββ errors/ # Error page templates
βββ static/
β βββ css/
β β βββ style.css # Main stylesheet
β β βββ auth.css # Authentication form styles
β βββ js/
β βββ chat.js # Frontend JavaScript
βββ Test/ # Test suite
βββ docs/
βββ PRODUCTION_DEPLOYMENT.md # Production deployment guide
Key Components
Backend Components
- Flask Routes: Authentication (
/login,/register,/logout) and chat (/,/chat,/api/chat) - User Management: Registration, login, session management
- Database Models: User accounts and chat session storage
- Security: CSRF protection, rate limiting, secure password hashing
- Configuration: Environment-based configuration management
Frontend Components
- Authentication UI: Login and registration forms
- Chat Interface: Real-time messaging with history
- Responsive Design: Mobile-first CSS architecture
- Error Handling: User-friendly error messages and validation
Security Features
- Password Security: Werkzeug password hashing (PBKDF2)
- Session Management: Flask-Login with secure cookies
- CSRF Protection: Form-based CSRF tokens
- Rate Limiting: Login attempt limiting
- Input Validation: Server and client-side validation
Configuration
Environment Variables
The application uses environment variables for configuration. Copy .env.example to .env and configure:
Required Variables
SECRET_KEY: Flask secret key (generate withpython deploy.py gen-secret)MONGODB_URL: MongoDB connection stringMONGODB_DATABASE: Database name (default: Atlas)
Optional Variables
FLASK_ENV: Environment mode (development,production,testing)SESSION_LIFETIME_HOURS: Session duration (default: 24)MAX_LOGIN_ATTEMPTS: Failed login limit (default: 5)API_TIMEOUT: External API timeout (default: 30)LOG_LEVEL: Logging level (default: INFO)
Configuration Management
Use the deployment script for configuration tasks:
# Generate secure secret key
python deploy.py gen-secret
# Set up development environment
python deploy.py setup-dev
# Check production readiness
python deploy.py check-prod
# Generate production environment template
python deploy.py gen-prod-env
Testing
Running Tests
# Install test dependencies
pip install -r Test/test_requirements.txt
# Run all tests
python Test/run_tests.py
# Run specific test categories
python -m pytest Test/test_auth_unit.py # Unit tests
python -m pytest Test/test_auth_integration.py # Integration tests
Test Categories
- Unit Tests: Individual component testing
- Integration Tests: Full authentication flow testing
- API Tests: External API integration testing
Deployment
Development Deployment
export FLASK_ENV=development
./start.sh
Production Deployment
For production deployment, see PRODUCTION_DEPLOYMENT.md for comprehensive instructions including:
- Security configuration
- Database setup
- HTTPS configuration
- Environment validation
- Monitoring and logging
Quick Production Setup
# Generate production configuration
python deploy.py gen-prod-env
# Edit .env.production with your values
# Then deploy:
export FLASK_ENV=production
./start.sh
Deployment Platforms
- Hugging Face Spaces: Direct deployment with environment variables
- Docker: Use provided Dockerfile
- Traditional Servers: systemd service configuration
- Cloud Platforms: AWS, GCP, Azure compatible
Troubleshooting
Common Issues
Database Connection Errors
# Test database connection python -c "from database import test_connection; test_connection()"Configuration Issues
# Validate configuration python config.pyAuthentication Problems
- Check
SECRET_KEYis set and secure - Verify MongoDB connection
- Ensure HTTPS in production
- Check
Session Issues
- Check cookie settings for your domain
- Verify session configuration
- Clear browser cookies
Getting Help
- Check application logs for detailed error messages
- Review configuration with
python deploy.py check-prod - Test individual components with provided test scripts
- Consult PRODUCTION_DEPLOYMENT.md for deployment issues
Security
Security Features
- Password Hashing: Secure PBKDF2 password storage
- Session Security: HTTPOnly, Secure, SameSite cookies
- CSRF Protection: Form-based CSRF tokens
- Rate Limiting: Brute force protection
- Input Validation: Server and client-side validation
- SQL Injection Prevention: MongoDB parameterized queries
Security Best Practices
- Use HTTPS in production
- Set strong
SECRET_KEY - Configure MongoDB authentication
- Regular security updates
- Monitor authentication logs
- Implement proper firewall rules
API Integration
This application integrates with the findEthics-Atlas API for AI responses.
Request Format
{
"prompt": "Your question here",
"history": [
{"message": "Previous message", "response": "Previous response"}
]
}
Response Format
{
"response": "AI response text",
"search_results": []
}
Authentication Integration
- User ID is tracked with each API request
- Chat history is maintained per user
- Session context is preserved across requests
License
MIT License - see LICENSE file for details.