Spaces:
Runtime error
π Rating Prediction System - Hugging Face Spaces Deployment
A production-ready FastAPI application for predicting product ratings from Vietnamese comments using PhoBERT. This Space uses Docker SDK for deploying heavy ML models (>500MB) with 16GB RAM.
π― Features
- π€ ML-Powered Predictions: PhoBERT-based sentiment analysis
- π Interactive Dashboard: Real-time visualizations with Chart.js
- π¬ Batch Processing: Upload CSV files for bulk predictions
- π Secure Authentication: JWT-based user management
- π Analytics: Word clouds and rating distributions
- ποΈ External Database: PostgreSQL support (Render/Neon)
π§ Configuration Required
Required Environment Variables
CRITICAL: Before deploying to Hugging Face Spaces, you MUST add these environment variables in the Settings tab:
1. DATABASE_URL (REQUIRED)
DATABASE_URL=postgresql://username:password@host:port/database
Real External Db url
DATABASE_URL=postgresql://rating_prediction_user:2p3Xv9mKFt3DDFs9OVWDrw8ARHkevTSw@dpg-d4mfq13uibrs738i6jl0-a.singapore-postgres.render.com/rating_prediction
Example from Render:
DATABASE_URL=postgresql://user:pass@dpg-xxxxx.oregon-postgres.render.com/dbname
Example from Neon:
DATABASE_URL=postgresql://user:pass@ep-xxxxx.us-east-2.aws.neon.tech/dbname?sslmode=require
β οΈ Important Notes:
- The URL MUST start with
postgresql://(NOTpostgres://) - If your provider gives you
postgres://, the app will auto-convert it - Include
?sslmode=requirefor secure connections (recommended)
2. SECRET_KEY (REQUIRED)
SECRET_KEY=your-super-secret-jwt-key-change-this-in-production-min-32-chars
Generate a secure key:
python -c "import secrets; print(secrets.token_urlsafe(32))"
Real SECRECT_KEY: nz0qzAJoIiRQ3v62SAq8g94JAFtfmf-GSU6dkluKtKA
β οΈ Security:
- NEVER commit this key to Git
- Use a cryptographically secure random string
- Minimum 32 characters recommended
π Deployment Steps
Step 1: Create a New Space
- Go to https://huggingface.co/new-space
- Choose Docker as the SDK
- Select CPU Basic (16GB RAM - Free)
- Make the Space Public or Private
Step 2: Configure Environment Variables
- Go to your Space's Settings tab
- Scroll to Repository Secrets
- Add the following secrets:
DATABASE_URLβ Your PostgreSQL connection stringSECRET_KEYβ Your JWT secret key
Step 3: Push Your Code
# Clone your Space repository
git clone https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME
cd YOUR_SPACE_NAME
# Copy your project files
cp -r /path/to/PredictRating/* .
# Commit and push
git add .
git commit -m "Initial deployment"
git push
Step 4: Wait for Build
- Hugging Face will automatically build your Docker image
- Build time: ~5-10 minutes (depending on model size)
- Check build logs in the Logs tab
Step 5: Access Your App
- Your app will be available at:
https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME - The app runs on port 7860 (handled automatically)
ποΈ Database Setup
Option A: Render PostgreSQL (Recommended)
- Create a free PostgreSQL database on Render
- Go to Dashboard β New β PostgreSQL
- Copy the External Database URL
- Add it as
DATABASE_URLin HF Spaces Settings
Option B: Neon PostgreSQL
- Create a free database on Neon
- Copy the connection string
- Ensure it includes
?sslmode=require - Add it as
DATABASE_URLin HF Spaces Settings
Database Initialization
The app automatically:
- Creates tables on first run
- Supports both SQLite (local dev) and PostgreSQL (production)
- No manual migrations needed
π³ Docker Configuration
Port Requirements
- CRITICAL: Hugging Face Spaces requires port 7860
- The Dockerfile is pre-configured correctly
- DO NOT change the port in
CMDinstruction
User Permissions
- Hugging Face runs containers as user ID 1000
- The Dockerfile creates a
useraccount - All files are owned by this user
Storage
/app/static/uploads/is writable (for word clouds)/app/database/is writable (for local SQLite fallback)- Consider using external storage (S3/Cloudinary) for production
π§ͺ Testing Locally Before Deployment
Test with Docker
# Build the Docker image
docker build -t rating-prediction .
# Run with environment variables
docker run -p 7860:7860 \
-e DATABASE_URL="postgresql://user:pass@host/db" \
-e SECRET_KEY="your-secret-key" \
rating-prediction
# Access at http://localhost:7860
Test Database Connection
# Inside container
docker exec -it <container_id> python -c "
from app.database import engine
print('β
Database connected:', engine.url)
"
π Monitoring & Logs
View Logs in Hugging Face
- Go to your Space
- Click the Logs tab
- Monitor startup and runtime logs
Expected Startup Messages
π Production Mode: Using PostgreSQL
INFO: Started server process [1]
INFO: Uvicorn running on http://0.0.0.0:7860
π Security Checklist
- β
SECRET_KEYstored as HF Secret (not in code) - β
DATABASE_URLstored as HF Secret (not in code) - β
PostgreSQL uses SSL (
sslmode=require) - β Passwords hashed with bcrypt
- β JWT tokens expire after 24 hours
- β Docker runs as non-root user
π Troubleshooting
Issue: "Application startup failed"
Solution: Check logs for database connection errors. Verify DATABASE_URL is correct.
Issue: "502 Bad Gateway"
Solution: App may be starting. Wait 2-3 minutes for heavy model loading.
Issue: "Database connection refused"
Solution: Ensure your PostgreSQL database is accessible from external IPs. Check firewall rules.
Issue: "No module named 'app'"
Solution: Ensure all files are copied correctly. Check Dockerfile WORKDIR is /app.
Issue: "Port 7860 already in use"
Solution: Only relevant for local testing. Stop other containers on that port.
π API Documentation
Once deployed, access:
- Swagger UI:
https://your-space.hf.space/docs - ReDoc:
https://your-space.hf.space/redoc
Key Endpoints
POST /api/auth/register- Create new userPOST /api/auth/login- Login and get JWT tokenPOST /api/predict/single- Predict single commentPOST /api/predict/batch- Upload CSV for batch predictionsGET /api/predict/history- View prediction history
π Support
If you encounter issues:
- Check the Logs tab in your Space
- Verify environment variables in Settings
- Test database connection from your local machine
- Review FastAPI Docs
- Check Hugging Face Spaces Docs
π License
This project is deployed under the terms specified in your Space settings.
Built with β€οΈ using FastAPI, PhoBERT, and Hugging Face Spaces