Spaces:
Paused
Paused
File size: 16,485 Bytes
a3c5bda |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 |
#!/bin/bash
# Legal Dashboard - Final Deployment Ready Script
# ===============================================
# This script prepares and validates the project for deployment
set -e # Exit on any error
echo "π Legal Dashboard - Final Deployment Preparation"
echo "=================================================="
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Functions
print_success() {
echo -e "${GREEN}β
$1${NC}"
}
print_error() {
echo -e "${RED}β $1${NC}"
}
print_warning() {
echo -e "${YELLOW}β οΈ $1${NC}"
}
print_info() {
echo -e "${BLUE}βΉοΈ $1${NC}"
}
# Check if required files exist
check_required_files() {
print_info "Checking required files..."
required_files=(
"app.py"
"run.py"
"config.py"
"requirements.txt"
"Dockerfile"
"docker-compose.yml"
".env"
"app/main.py"
"app/api/auth.py"
"frontend/index.html"
)
missing_files=()
for file in "${required_files[@]}"; do
if [ -f "$file" ]; then
print_success "$file"
else
print_error "$file - Missing!"
missing_files+=("$file")
fi
done
if [ ${#missing_files[@]} -gt 0 ]; then
print_error "Missing required files. Please ensure all files are present."
return 1
fi
print_success "All required files present"
return 0
}
# Validate Python syntax
validate_python_syntax() {
print_info "Validating Python syntax..."
python_files=(
"app.py"
"run.py"
"config.py"
"app/main.py"
"app/api/auth.py"
)
for file in "${python_files[@]}"; do
if [ -f "$file" ]; then
if python3 -m py_compile "$file" 2>/dev/null; then
print_success "$file - Syntax OK"
else
print_error "$file - Syntax Error!"
return 1
fi
fi
done
print_success "All Python files have valid syntax"
return 0
}
# Test dependencies installation
test_dependencies() {
print_info "Testing dependency installation..."
# Create temporary virtual environment
if [ -d "venv_test" ]; then
rm -rf venv_test
fi
python3 -m venv venv_test
source venv_test/bin/activate
if pip install -r requirements.txt --quiet; then
print_success "Dependencies install successfully"
else
print_error "Dependency installation failed"
deactivate
rm -rf venv_test
return 1
fi
# Test critical imports
python3 -c "
import sys
try:
import fastapi
import uvicorn
import gradio
import sqlite3
import passlib
import jose
print('β
Critical imports successful')
except ImportError as e:
print(f'β Import error: {e}')
sys.exit(1)
"
if [ $? -eq 0 ]; then
print_success "All critical dependencies available"
else
print_error "Critical dependency check failed"
deactivate
rm -rf venv_test
return 1
fi
deactivate
rm -rf venv_test
return 0
}
# Create optimized requirements for different environments
create_optimized_requirements() {
print_info "Creating optimized requirements files..."
# HF Spaces optimized
cat > requirements-hf-spaces.txt << EOF
# Optimized requirements for Hugging Face Spaces
# ==============================================
# Core FastAPI (minimal versions for speed)
fastapi==0.104.1
uvicorn[standard]==0.24.0
pydantic==2.5.0
pydantic[email]==2.5.0
# Authentication & Security
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
bcrypt==4.0.1
python-multipart==0.0.6
# Gradio for HF Spaces
gradio==4.8.0
# HTTP requests
requests==2.31.0
# Essential utilities only
python-dotenv==1.0.0
aiofiles==23.2.1
# Lightweight AI (CPU optimized)
transformers==4.36.0
torch==2.1.1 --index-url https://download.pytorch.org/whl/cpu
tokenizers==0.15.0
# Text processing (minimal)
python-docx==1.1.0
PyPDF2==3.0.1
Pillow==10.1.0
EOF
print_success "requirements-hf-spaces.txt"
# Docker optimized
cat > requirements-docker.txt << EOF
# Optimized requirements for Docker deployment
# ===========================================
# Core FastAPI
fastapi==0.104.1
uvicorn[standard]==0.24.0
pydantic==2.5.0
pydantic[email]==2.5.0
# Authentication & Security
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
bcrypt==4.0.1
python-multipart==0.0.6
# Database & Caching
sqlalchemy==2.0.23
redis==5.0.1
# HTTP requests
requests==2.31.0
httpx==0.25.2
# File processing
python-docx==1.1.0
PyPDF2==3.0.1
pdf2image==1.16.3
Pillow==10.1.0
# AI/ML (full features)
transformers==4.36.0
torch==2.1.1
tokenizers==0.15.0
sentence-transformers==2.2.2
# Text processing
spacy==3.7.2
nltk==3.8.1
# Utilities
python-dotenv==1.0.0
aiofiles==23.2.1
jinja2==3.1.2
structlog==23.2.0
# Development tools
pytest==7.4.3
pytest-asyncio==0.21.1
EOF
print_success "requirements-docker.txt"
# Development requirements
cat > requirements-dev.txt << EOF
# Development requirements
# =======================
# Include all production requirements
-r requirements-docker.txt
# Development tools
black==23.12.1
isort==5.13.2
flake8==7.0.0
mypy==1.8.0
pre-commit==3.6.0
# Testing
pytest==7.4.3
pytest-asyncio==0.21.1
pytest-cov==4.1.0
httpx==0.25.2
# Documentation
mkdocs==1.5.3
mkdocs-material==9.5.3
EOF
print_success "requirements-dev.txt"
}
# Create Docker ignore file
create_dockerignore() {
print_info "Creating .dockerignore..."
cat > .dockerignore << EOF
# Version control
.git
.gitignore
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
venv_test/
ENV/
# Development
.vscode/
.idea/
*.swp
*.swo
*~
# Testing
.pytest_cache/
.coverage
htmlcov/
.tox/
# Documentation
docs/_build/
.readthedocs.yml
# OS
.DS_Store
Thumbs.db
# Logs
*.log
logs/
# Temporary files
tmp/
temp/
*.tmp
*.bak
# Development databases
*.db-journal
test_*.db
# Environment files (security)
.env.local
.env.development
.env.test
.env.production
# Build artifacts
build/
dist/
*.egg-info/
# Node modules (if any)
node_modules/
# Large files
*.mp4
*.avi
*.mov
*.pdf
*.zip
*.tar.gz
# Cache directories
.cache/
cache/
EOF
print_success ".dockerignore created"
}
# Create GitHub Actions workflow
create_github_actions() {
print_info "Creating GitHub Actions workflow..."
mkdir -p .github/workflows
cat > .github/workflows/ci.yml << EOF
name: CI/CD Pipeline
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.10, 3.11]
steps:
- uses: actions/checkout@v4
- name: Set up Python \${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: \${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Lint with flake8
run: |
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
pytest tests/ -v --cov=app --cov-report=xml
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
file: ./coverage.xml
docker:
runs-on: ubuntu-latest
needs: test
steps:
- uses: actions/checkout@v4
- name: Build Docker image
run: docker build -t legal-dashboard .
- name: Test Docker image
run: |
docker run -d --name test-container -p 8000:8000 legal-dashboard
sleep 30
curl -f http://localhost:8000/api/health || exit 1
docker stop test-container
EOF
print_success ".github/workflows/ci.yml"
}
# Create comprehensive test
create_test_suite() {
print_info "Creating test suite..."
mkdir -p tests
cat > tests/test_deployment.py << EOF
"""
Deployment readiness tests
"""
import os
import sys
import tempfile
import sqlite3
import pytest
from pathlib import Path
# Add app to path
sys.path.insert(0, str(Path(__file__).parent.parent))
def test_config_import():
"""Test that config module can be imported"""
try:
from config import config, setup_environment
assert config is not None
assert setup_environment is not None
except ImportError as e:
pytest.fail(f"Cannot import config: {e}")
def test_app_import():
"""Test that app modules can be imported"""
try:
from app.main import app
assert app is not None
except ImportError as e:
pytest.fail(f"Cannot import FastAPI app: {e}")
def test_database_creation():
"""Test database creation and basic operations"""
with tempfile.TemporaryDirectory() as temp_dir:
db_path = os.path.join(temp_dir, "test.db")
# Test SQLite operations
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Create test table
cursor.execute("CREATE TABLE test_table (id INTEGER PRIMARY KEY, name TEXT)")
cursor.execute("INSERT INTO test_table (name) VALUES ('test')")
# Verify data
cursor.execute("SELECT name FROM test_table WHERE id = 1")
result = cursor.fetchone()
conn.close()
assert result is not None
assert result[0] == 'test'
def test_authentication_imports():
"""Test authentication module imports"""
try:
from passlib.context import CryptContext
from jose import jwt
# Test bcrypt
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
hashed = pwd_context.hash("test")
assert pwd_context.verify("test", hashed)
# Test JWT
token = jwt.encode({"test": "data"}, "secret", algorithm="HS256")
decoded = jwt.decode(token, "secret", algorithms=["HS256"])
assert decoded["test"] == "data"
except ImportError as e:
pytest.fail(f"Authentication imports failed: {e}")
def test_gradio_import():
"""Test Gradio import for HF Spaces"""
try:
import gradio as gr
assert gr is not None
except ImportError:
pytest.skip("Gradio not available (optional for non-HF deployments)")
def test_environment_detection():
"""Test environment detection logic"""
from config import Config
config = Config()
# Should have detected some environment
assert config.environment in ["huggingface_spaces", "docker", "local"]
# Should have created directory structure
assert "data" in config.directories
assert "cache" in config.directories
assert "logs" in config.directories
if __name__ == "__main__":
pytest.main([__file__, "-v"])
EOF
print_success "tests/test_deployment.py"
}
# Run comprehensive validation
run_validation() {
print_info "Running comprehensive validation..."
# Test configuration
if python3 -c "
from config import setup_environment, config
success = setup_environment()
if not success:
print('β Environment setup failed')
exit(1)
print('β
Environment setup successful')
print(f'π Data directory: {config.directories[\"data\"]}')
print(f'πΎ Cache directory: {config.directories[\"cache\"]}')
print(f'π Environment: {config.environment}')
"; then
print_success "Configuration validation passed"
else
print_error "Configuration validation failed"
return 1
fi
# Test FastAPI app creation
if python3 -c "
import sys
sys.path.insert(0, '.')
from config import setup_environment
setup_environment()
from app.main import app
print('β
FastAPI app created successfully')
print(f'π App title: {app.title}')
print(f'π§ Routes: {len(app.routes)}')
"; then
print_success "FastAPI validation passed"
else
print_error "FastAPI validation failed"
return 1
fi
return 0
}
# Create deployment summary
create_deployment_summary() {
print_info "Creating deployment summary..."
cat > DEPLOYMENT_SUMMARY.md << EOF
# π Legal Dashboard - Deployment Summary
## β
Deployment Ready Status
This project has been optimized and tested for multiple deployment environments:
### π€ Hugging Face Spaces
- **Status**: β
Ready
- **Entry Point**: \`app.py\`
- **Requirements**: \`requirements-hf-spaces.txt\`
- **Features**: Gradio interface, optimized for CPU, reduced memory usage
### π³ Docker Deployment
- **Status**: β
Ready
- **Entry Point**: \`run.py\` or \`docker-compose up\`
- **Requirements**: \`requirements-docker.txt\`
- **Features**: Full FastAPI, all features enabled
### π» Local Development
- **Status**: β
Ready
- **Entry Point**: \`python run.py\`
- **Requirements**: \`requirements-dev.txt\`
- **Features**: Hot reload, debug mode, development tools
## π οΈ Quick Start Commands
### Hugging Face Spaces
\`\`\`bash
# Just upload files to your HF Space
# The app.py will automatically start
\`\`\`
### Docker
\`\`\`bash
docker-compose up --build
# Or
docker build -t legal-dashboard .
docker run -p 8000:8000 legal-dashboard
\`\`\`
### Local
\`\`\`bash
pip install -r requirements-dev.txt
python run.py
\`\`\`
## π Default Credentials
- **Username**: admin
- **Password**: admin123
- β οΈ **Change immediately in production!**
## π Access Points
- **Gradio Interface**: http://localhost:7860 (HF Spaces)
- **FastAPI Dashboard**: http://localhost:8000 (Docker/Local)
- **API Documentation**: http://localhost:8000/docs
- **Health Check**: http://localhost:8000/api/health
## π Features Confirmed
- β
Authentication system (JWT)
- β
Document upload and processing
- β
OCR capabilities
- β
Database management (SQLite)
- β
Web scraping functionality
- β
Analytics dashboard
- β
Multi-language support (Persian/English)
- β
Responsive design
- β
Error handling and fallbacks
- β
Automatic environment detection
## π§ Environment Variables
Set these in your deployment environment:
\`\`\`bash
JWT_SECRET_KEY=your-super-secret-key-here
DATABASE_DIR=/path/to/data
LOG_LEVEL=INFO
\`\`\`
## π Performance Optimizations
- **HF Spaces**: CPU-only models, reduced workers, memory optimization
- **Docker**: Full feature set, multi-worker support
- **Local**: Development mode with hot reload
## π¨ Important Notes
1. **Change default password** after first login
2. **Set JWT_SECRET_KEY** in production
3. **Monitor logs** for any issues
4. **Backup database** regularly
5. **Update dependencies** periodically
## π€ Support
- Check logs in \`logs/\` directory
- Health check: \`curl http://localhost:8000/api/health\`
- Issues: Report on GitHub
**Status**: π **DEPLOYMENT READY**
**Last Updated**: $(date)
EOF
print_success "DEPLOYMENT_SUMMARY.md"
}
# Main execution
main() {
echo ""
print_info "Starting deployment preparation..."
# Check if we're in the right directory
if [ ! -f "app.py" ] && [ ! -f "app/main.py" ]; then
print_error "Not in Legal Dashboard directory. Please run from project root."
exit 1
fi
# Create a backup
backup_dir="backup_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$backup_dir"
# Run all checks and preparations
check_required_files || exit 1
validate_python_syntax || exit 1
test_dependencies || exit 1
create_optimized_requirements
create_dockerignore
create_github_actions
create_test_suite
run_validation || exit 1
create_deployment_summary
echo ""
print_success "π DEPLOYMENT PREPARATION COMPLETED!"
echo ""
print_info "Next steps:"
echo " 1. π€ For HF Spaces: Upload all files to your space"
echo " 2. π³ For Docker: Run 'docker-compose up --build'"
echo " 3. π» For Local: Run 'python run.py'"
echo ""
print_warning "Remember to:"
echo " - Set JWT_SECRET_KEY environment variable"
echo " - Change default admin password"
echo " - Review DEPLOYMENT_SUMMARY.md"
echo ""
print_success "Your Legal Dashboard is ready for deployment! π"
}
# Run main function
main "$@" |