amauricunha commited on
Commit
3a1532f
·
verified ·
1 Parent(s): 134121f

Delete hf_app.py

Browse files
Files changed (1) hide show
  1. hf_app.py +0 -143
hf_app.py DELETED
@@ -1,143 +0,0 @@
1
- #!/usr/bin/env python3
2
- # hf_app.py - Hugging Face Spaces optimized entry point
3
-
4
- import os
5
- import sys
6
- import signal
7
- import threading
8
- import time
9
- from pathlib import Path
10
-
11
- # Add current directory to Python path
12
- sys.path.insert(0, str(Path(__file__).parent))
13
-
14
- # Import the main Flask app
15
- from app import app
16
- from database import init_db
17
-
18
- def setup_huggingface_environment():
19
- """Setup environment variables for Hugging Face Spaces"""
20
-
21
- # Set default configurations for HF Spaces
22
- os.environ.setdefault('FLASK_ENV', 'production')
23
- os.environ.setdefault('HOST', '0.0.0.0')
24
- os.environ.setdefault('PORT', '7860')
25
-
26
- # Ensure data directory exists
27
- data_dir = Path(__file__).parent / 'data'
28
- data_dir.mkdir(exist_ok=True)
29
-
30
- print("🚀 English Helper - Hugging Face Spaces Setup")
31
- print("=" * 50)
32
-
33
- # Check required environment variables
34
- required_vars = ['GROQ_API_KEY', 'GEMINI_API_KEY']
35
- optional_vars = ['SMTP_SERVER', 'ADMIN_USERNAME', 'SECRET_KEY']
36
-
37
- print("🔑 Checking API Keys:")
38
- for var in required_vars:
39
- if os.environ.get(var):
40
- print(f" ✅ {var}: Configured")
41
- else:
42
- print(f" ❌ {var}: Missing (required for full functionality)")
43
-
44
- print("\n📧 Checking Optional Configuration:")
45
- for var in optional_vars:
46
- if os.environ.get(var):
47
- print(f" ✅ {var}: Configured")
48
- else:
49
- print(f" ⚠️ {var}: Not configured (optional)")
50
-
51
- # Generate secret key if not provided
52
- if not os.environ.get('SECRET_KEY'):
53
- import secrets
54
- secret_key = secrets.token_urlsafe(32)
55
- os.environ['SECRET_KEY'] = secret_key
56
- print(f" 🔐 Generated temporary SECRET_KEY")
57
-
58
- print("=" * 50)
59
-
60
- def initialize_database():
61
- """Initialize database with error handling"""
62
- try:
63
- print("🗄️ Initializing database...")
64
- init_db()
65
- print("✅ Database initialized successfully")
66
- return True
67
- except Exception as e:
68
- print(f"❌ Database initialization failed: {e}")
69
- return False
70
-
71
- def health_check():
72
- """Simple health check endpoint"""
73
- @app.route('/health')
74
- def health():
75
- return {'status': 'healthy', 'app': 'English Helper'}, 200
76
-
77
- def setup_signal_handlers():
78
- """Setup graceful shutdown handlers"""
79
- def signal_handler(signum, frame):
80
- print(f"\n🛑 Received signal {signum}, shutting down gracefully...")
81
- sys.exit(0)
82
-
83
- signal.signal(signal.SIGINT, signal_handler)
84
- signal.signal(signal.SIGTERM, signal_handler)
85
-
86
- def run_flask_app():
87
- """Run the Flask application"""
88
- host = os.environ.get('HOST', '0.0.0.0')
89
- port = int(os.environ.get('PORT', 7860))
90
- debug = os.environ.get('FLASK_DEBUG', 'false').lower() == 'true'
91
-
92
- print(f"🌐 Starting server on http://{host}:{port}")
93
- print(f"🎯 Debug mode: {'ON' if debug else 'OFF'}")
94
- print(f"📱 Access your app at: http://{host}:{port}")
95
- print(f"🔐 Admin panel at: http://{host}:{port}/admin")
96
- print("\n" + "=" * 50)
97
-
98
- try:
99
- app.run(
100
- host=host,
101
- port=port,
102
- debug=debug,
103
- threaded=True,
104
- use_reloader=False # Disable reloader in production
105
- )
106
- except Exception as e:
107
- print(f"❌ Failed to start server: {e}")
108
- return False
109
-
110
- return True
111
-
112
- def main():
113
- """Main entry point for Hugging Face Spaces"""
114
- try:
115
- # Setup environment
116
- setup_huggingface_environment()
117
-
118
- # Setup signal handlers
119
- setup_signal_handlers()
120
-
121
- # Add health check
122
- health_check()
123
-
124
- # Initialize database
125
- if not initialize_database():
126
- print("⚠️ Database initialization failed, but continuing...")
127
-
128
- print("🎓 English Helper is ready!")
129
- print("✨ Enjoy learning English with AI assistance!")
130
- print("=" * 50)
131
-
132
- # Run the Flask app
133
- return run_flask_app()
134
-
135
- except KeyboardInterrupt:
136
- print("\n👋 Goodbye! Thanks for using English Helper!")
137
- except Exception as e:
138
- print(f"❌ Fatal error: {e}")
139
- return False
140
-
141
- if __name__ == "__main__":
142
- success = main()
143
- sys.exit(0 if success else 1)