A Flask-based web application for analyzing financial data from small-to-medium businesses using AI-powered insights and forecasting.
- Financial Data Analysis: Upload CSV, Excel files or Google Sheets
- AI-Powered Insights: Uses LLaMA models for data extraction and dashboard generation
- Interactive Charts: Plotly-based visualizations for revenue, profit, and cost analysis
- Advanced Forecasting: Prophet-based time series forecasting and SKU performance prediction
- AI Chatbot: Ask questions about your financial data and dashboard insights
- Security: CSRF protection, rate limiting, file validation
- Production Ready: Health checks, monitoring, and deployment guides
- CSRF token protection
- Rate limiting (10 requests/minute per IP)
- File type validation
- File size limits (16MB max)
- Input sanitization
- Session management with automatic cleanup
- Environment-based configuration
The built-in AI-powered chatbot allows you to ask questions about your uploaded financial data, dashboard charts, and SKU performance. It provides:
- Context-aware answers based on your data and generated insights
- Explanations of trends, forecasts, and performance scores
- Actionable business advice in a friendly, professional tone
How to use:
- Upload your financial data (CSV, Excel, or Google Sheets)
- Go to the dashboard page
- Use the chatbot input box to ask questions like:
- "What are the main revenue trends this year?"
- "Which SKUs are underperforming and why?"
- "How can I improve my profit margin?"
- Time Series Forecasting: Uses Prophet (if available) or a fallback trend analysis to forecast revenue and other metrics.
- SKU Performance Forecasting: Each SKU is scored using a weighted formula (frequency, price, consistency) and forecasted over time, with visualizations for both performance score trends and transaction history.
- Automatic Fallback: If Prophet is not installed, the app uses a simple trend line for forecasting.
SKU Performance Scoring System:
- 40% Frequency Score: Number of transactions (normalized)
- 40% Price Score: Average transaction amount (normalized)
- 20% Consistency Score: Price stability (lower volatility = higher score)
- Scores are color-coded and SKUs are ranked for easy comparison.
GET /- Main application pagePOST /upload- Upload financial dataGET /dashboard/<session_id>- View analysis dashboardGET /api/data/<session_id>- Get session data (JSON)GET /health- Health check endpoint
- Only CSV, XLSX, and XLS files allowed
- Maximum file size: 16MB
- Files are processed in memory and immediately deleted
- 10 requests per minute per IP address
- Configurable via environment variables
- Returns HTTP 429 when exceeded
- Sessions expire after 24 hours
- Automatic cleanup of expired sessions
- Thread-safe session storage
- All POST requests require valid CSRF token
- Tokens are automatically generated and validated
curl http://localhost:5000/healthResponse:
{
"status": "healthy",
"active_sessions": 5,
"cleanup_count": 2,
"timestamp": "2024-01-15T10:30:00"
}- Application logs to stdout/stderr
- Structured logging with different levels
- Error tracking for debugging
- Python 3.9+
- Ollama with LLaMA models installed
-
Clone the repository
git clone <repository-url> cd SMB-Revenue-Cloud
-
Install dependencies
pip install -r requirements.txt
-
Set up environment variables
cp .env.example .env # Edit .env with your configuration -
Install and start Ollama
# Install Ollama (https://ollama.ai) ollama pull llama3 -
Run the application
python app.py
| Variable | Description | Default |
|---|---|---|
SECRET_KEY |
Flask secret key | dev-secret-key-change-in-production |
FLASK_DEBUG |
Debug mode | False |
RATE_LIMIT |
Requests per minute | 10 |
RATE_LIMIT_WINDOW |
Rate limit window (seconds) | 60 |
MAX_CONTENT_LENGTH |
Max file size (bytes) | 16777216 (16MB) |
OLLAMA_TIMEOUT |
Ollama request timeout | 90 |
OLLAMA_MAX_RETRIES |
Max retry attempts | 3 |
SESSION_TIMEOUT_HOURS |
Session timeout | 24 |
-
Set secure environment variables
export SECRET_KEY="your-super-secure-secret-key" export FLASK_DEBUG=False export FLASK_ENV=production
-
Run with Flask's built-in server
python wsgi.py
-
Set up reverse proxy (Nginx)
server { listen 80; server_name your-domain.com; location / { proxy_pass http://127.0.0.1:5000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }
-
Use systemd for service management
# /etc/systemd/system/smb-revenue.service [Unit] Description=SMB Revenue Cloud After=network.target [Service] User=www-data WorkingDirectory=/path/to/SMB-Revenue-Cloud Environment=PATH=/path/to/venv/bin ExecStart=/path/to/venv/bin/python wsgi.py Restart=always [Install] WantedBy=multi-user.target
-
Launch EC2 Instance
- Instance Type:
t3.mediumort3.large - OS: Ubuntu 22.04 LTS
- Security Group: Allow SSH (22) and Custom TCP (5000)
- Instance Type:
-
Connect and Install Dependencies
# Connect to your EC2 instance ssh -i your-key.pem ubuntu@your-ec2-ip # Update system sudo apt update && sudo apt upgrade -y # Install Python and dependencies sudo apt install python3 python3-pip python3-venv git curl -y # Install Ollama curl -fsSL https://ollama.ai/install.sh | sh ollama pull llama3
-
Deploy Application
# Clone your repository git clone <your-repo-url> cd SMB-Revenue-Cloud # Create virtual environment python3 -m venv venv source venv/bin/activate # Install dependencies pip install -r requirements.txt # Set up environment variables cp .env.example .env nano .env
-
Configure Environment
# Edit .env file SECRET_KEY=your-super-secret-key-for-aws FLASK_DEBUG=False FLASK_ENV=production RATE_LIMIT=10 RATE_LIMIT_WINDOW=60 MAX_CONTENT_LENGTH=16777216 OLLAMA_TIMEOUT=90 OLLAMA_MAX_RETRIES=3 SESSION_TIMEOUT_HOURS=24 -
Run with systemd Service
# Create systemd service sudo nano /etc/systemd/system/smb-revenue.serviceAdd this content:
[Unit] Description=SMB Revenue Cloud After=network.target [Service] User=ubuntu WorkingDirectory=/home/ubuntu/SMB-Revenue-Cloud Environment=PATH=/home/ubuntu/SMB-Revenue-Cloud/venv/bin ExecStart=/home/ubuntu/SMB-Revenue-Cloud/venv/bin/python wsgi.py Restart=always RestartSec=10 [Install] WantedBy=multi-user.target
# Enable and start the service sudo systemctl daemon-reload sudo systemctl enable smb-revenue sudo systemctl start smb-revenue # Check status sudo systemctl status smb-revenue
-
Access Your Application
- Direct URL:
http://your-ec2-public-ip:5000 - Health check:
http://your-ec2-public-ip:5000/health
- Direct URL:
-
Monitoring and Maintenance
# Check application logs sudo journalctl -u smb-revenue -f # Monitor system resources htop df -h free -h # Health check curl http://localhost:5000/health
-
Security Setup
# Set up firewall (UFW) sudo ufw enable sudo ufw allow ssh sudo ufw allow 5000 # Update regularly sudo apt update && sudo apt upgrade -y
If you prefer not to use systemd:
# Install screen
sudo apt install screen -y
# Start application in screen session
screen -S smb-app
python wsgi.py
# Detach from screen (Ctrl+A, then D)
# Reattach later with: screen -r smb-app# Check if Ollama is running
ollama list
# Restart Ollama if needed
sudo systemctl restart ollama
# Check application status
sudo systemctl status smb-revenue
# View recent logs
sudo journalctl -u smb-revenue --since "1 hour ago"
# Check if port 5000 is listening
sudo netstat -tlnp | grep :5000If you encounter numpy installation errors on Python 3.12:
# Check Python version
python3 --version
# If using Python 3.12, you may need to upgrade pip and setuptools first
pip install --upgrade pip setuptools wheel
# Install numpy separately first
pip install numpy==1.26.2
# Then install the rest of the requirements
pip install -r requirements.txtAlternative approach for Python 3.12:
# Use conda instead of pip (if available)
conda install numpy pandas plotly prophet flask werkzeug openpyxl python-dotenv
# Or install system packages first
sudo apt install python3-numpy python3-pandas python3-scipy
pip install -r requirements.txt --no-deps-
Ollama not found
# Install Ollama curl -fsSL https://ollama.ai/install.sh | sh ollama pull llama3
-
Permission denied on uploads
# Fix directory permissions chmod 755 uploads/ -
Memory issues with large files
- Reduce
MAX_CONTENT_LENGTHin environment - Monitor system memory usage
- Reduce
-
Rate limiting issues
- Increase
RATE_LIMITin environment - Check for multiple requests from same IP
- Increase
If you encounter numpy installation errors on Python 3.12:
# Check Python version
python3 --version
# If using Python 3.12, you may need to upgrade pip and setuptools first
pip install --upgrade pip setuptools wheel
# Install numpy separately first
pip install numpy==1.26.2
# Then install the rest of the requirements
pip install -r requirements.txtAlternative approach for Python 3.12:
# Use conda instead of pip (if available)
conda install numpy pandas plotly prophet flask werkzeug openpyxl python-dotenv
# Or install system packages first
sudo apt install python3-numpy python3-pandas python3-scipy
pip install -r requirements.txt --no-deps-
Use Redis for session storage
# Replace in-memory storage with Redis from flask_session import Session app.config['SESSION_TYPE'] = 'redis' Session(app)
-
Add caching layer
from flask_caching import Cache cache = Cache(app, config={'CACHE_TYPE': 'redis'})
-
Enable threading for concurrent requests
app.run(host='0.0.0.0', port=5000, threaded=True)