Spaces:
Paused
Paused
Update run.py
Browse files
run.py
CHANGED
|
@@ -63,13 +63,11 @@ class LegalDashboardRunner:
|
|
| 63 |
]
|
| 64 |
|
| 65 |
missing_required = []
|
| 66 |
-
missing_optional = []
|
| 67 |
|
| 68 |
# Check required modules
|
| 69 |
for module, description in required_modules:
|
| 70 |
try:
|
| 71 |
__import__(module)
|
| 72 |
-
self.logger.info(f"✅ {description}")
|
| 73 |
except ImportError:
|
| 74 |
missing_required.append((module, description))
|
| 75 |
self.logger.error(f"❌ {description} - Missing: {module}")
|
|
@@ -78,10 +76,8 @@ class LegalDashboardRunner:
|
|
| 78 |
for module, description in optional_modules:
|
| 79 |
try:
|
| 80 |
__import__(module)
|
| 81 |
-
self.logger.info(f"✅ {description}")
|
| 82 |
except ImportError:
|
| 83 |
-
|
| 84 |
-
self.logger.warning(f"⚠️ {description} - Optional: {module}")
|
| 85 |
|
| 86 |
if missing_required:
|
| 87 |
self.logger.error("❌ Missing required dependencies:")
|
|
@@ -89,42 +85,20 @@ class LegalDashboardRunner:
|
|
| 89 |
self.logger.error(f" pip install {module}")
|
| 90 |
return False
|
| 91 |
|
| 92 |
-
if missing_optional and config.is_hf_spaces:
|
| 93 |
-
# Check if gradio is available for HF Spaces
|
| 94 |
-
if any(module == "gradio" for module, _ in missing_optional):
|
| 95 |
-
self.logger.error("❌ Gradio is required for HF Spaces deployment")
|
| 96 |
-
return False
|
| 97 |
-
|
| 98 |
return True
|
| 99 |
|
| 100 |
def test_database_connection(self) -> bool:
|
| 101 |
"""Test database connectivity"""
|
| 102 |
try:
|
| 103 |
import sqlite3
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
conn = sqlite3.connect(test_db)
|
| 110 |
-
cursor = conn.cursor()
|
| 111 |
-
cursor.execute("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY)")
|
| 112 |
-
cursor.execute("INSERT INTO test (id) VALUES (1)")
|
| 113 |
-
cursor.execute("SELECT * FROM test")
|
| 114 |
-
result = cursor.fetchone()
|
| 115 |
conn.close()
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
if os.path.exists(test_db):
|
| 119 |
-
os.remove(test_db)
|
| 120 |
-
|
| 121 |
-
if result:
|
| 122 |
-
self.logger.info("✅ Database connectivity test passed")
|
| 123 |
-
return True
|
| 124 |
-
else:
|
| 125 |
-
self.logger.error("❌ Database test failed - no data returned")
|
| 126 |
-
return False
|
| 127 |
-
|
| 128 |
except Exception as e:
|
| 129 |
self.logger.error(f"❌ Database connectivity test failed: {e}")
|
| 130 |
return False
|
|
@@ -133,44 +107,35 @@ class LegalDashboardRunner:
|
|
| 133 |
"""Run Gradio interface for HF Spaces"""
|
| 134 |
try:
|
| 135 |
self.logger.info("🤗 Starting Gradio interface for HF Spaces...")
|
| 136 |
-
|
| 137 |
# Import and run Gradio app
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
else:
|
| 141 |
-
self.logger.error("❌ app.py not found for Gradio interface")
|
| 142 |
-
return False
|
| 143 |
-
|
| 144 |
except Exception as e:
|
| 145 |
self.logger.error(f"❌ Failed to start Gradio interface: {e}")
|
| 146 |
return False
|
| 147 |
|
| 148 |
def run_fastapi_server(self):
|
| 149 |
-
"""Run FastAPI server"""
|
| 150 |
try:
|
| 151 |
self.logger.info("🚀 Starting FastAPI server...")
|
| 152 |
|
| 153 |
import uvicorn
|
| 154 |
from app.main import app
|
| 155 |
|
| 156 |
-
# Server configuration
|
| 157 |
server_config = config.server_config
|
| 158 |
|
| 159 |
self.logger.info(f"🌐 Server starting on {server_config['host']}:{server_config['port']}")
|
| 160 |
self.logger.info(f"👥 Workers: {server_config['workers']}")
|
| 161 |
-
self.logger.info(f"📊 Log level: {server_config['log_level']}")
|
| 162 |
|
| 163 |
-
# Run server
|
| 164 |
uvicorn.run(
|
| 165 |
-
app,
|
| 166 |
host=server_config['host'],
|
| 167 |
port=server_config['port'],
|
| 168 |
workers=server_config['workers'],
|
| 169 |
-
log_level=server_config['log_level'],
|
| 170 |
-
access_log=server_config['access_log'],
|
| 171 |
reload=server_config['reload']
|
| 172 |
)
|
| 173 |
-
|
| 174 |
except Exception as e:
|
| 175 |
self.logger.error(f"❌ Failed to start FastAPI server: {e}")
|
| 176 |
return False
|
|
@@ -181,58 +146,43 @@ class LegalDashboardRunner:
|
|
| 181 |
print("🏛️ Legal Dashboard - Universal Runner")
|
| 182 |
print("=" * 60)
|
| 183 |
|
| 184 |
-
# Setup environment
|
| 185 |
if not setup_environment():
|
| 186 |
self.logger.error("❌ Environment setup failed")
|
| 187 |
sys.exit(1)
|
| 188 |
|
| 189 |
-
# Check dependencies
|
| 190 |
if not self.check_dependencies():
|
| 191 |
self.logger.error("❌ Dependency check failed")
|
| 192 |
sys.exit(1)
|
| 193 |
|
| 194 |
-
# Test database
|
| 195 |
if not self.test_database_connection():
|
| 196 |
self.logger.error("❌ Database test failed")
|
| 197 |
sys.exit(1)
|
| 198 |
|
| 199 |
-
# Show configuration summary
|
| 200 |
self.logger.info("📋 Configuration Summary:")
|
| 201 |
self.logger.info(f" Environment: {config.environment}")
|
| 202 |
-
self.logger.info(f" HF Spaces: {config.is_hf_spaces}")
|
| 203 |
-
self.logger.info(f" Docker: {config.is_docker}")
|
| 204 |
-
self.logger.info(f" Development: {config.is_development}")
|
| 205 |
self.logger.info(f" Data Directory: {config.directories['data']}")
|
| 206 |
-
self.logger.info(f" Cache Directory: {config.directories['cache']}")
|
| 207 |
|
| 208 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
try:
|
| 210 |
-
if
|
| 211 |
-
# HF Spaces - use Gradio interface
|
| 212 |
self.run_gradio_interface()
|
| 213 |
else:
|
| 214 |
-
# Docker/Local - use FastAPI server
|
| 215 |
self.run_fastapi_server()
|
| 216 |
|
| 217 |
except KeyboardInterrupt:
|
| 218 |
self.logger.info("🛑 Received keyboard interrupt")
|
| 219 |
-
except Exception as e:
|
| 220 |
-
self.logger.error(f"❌ Unexpected error: {e}")
|
| 221 |
-
sys.exit(1)
|
| 222 |
finally:
|
| 223 |
self.shutdown()
|
| 224 |
|
| 225 |
def shutdown(self):
|
| 226 |
"""Graceful shutdown"""
|
| 227 |
self.logger.info("🔄 Shutting down Legal Dashboard...")
|
| 228 |
-
|
| 229 |
if self.app_process:
|
| 230 |
-
|
| 231 |
-
self.app_process.terminate()
|
| 232 |
-
self.app_process.wait(timeout=10)
|
| 233 |
-
except:
|
| 234 |
-
self.app_process.kill()
|
| 235 |
-
|
| 236 |
self.logger.info("✅ Shutdown completed")
|
| 237 |
|
| 238 |
def main():
|
|
|
|
| 63 |
]
|
| 64 |
|
| 65 |
missing_required = []
|
|
|
|
| 66 |
|
| 67 |
# Check required modules
|
| 68 |
for module, description in required_modules:
|
| 69 |
try:
|
| 70 |
__import__(module)
|
|
|
|
| 71 |
except ImportError:
|
| 72 |
missing_required.append((module, description))
|
| 73 |
self.logger.error(f"❌ {description} - Missing: {module}")
|
|
|
|
| 76 |
for module, description in optional_modules:
|
| 77 |
try:
|
| 78 |
__import__(module)
|
|
|
|
| 79 |
except ImportError:
|
| 80 |
+
self.logger.warning(f"⚠️ Optional module missing: {module} ({description})")
|
|
|
|
| 81 |
|
| 82 |
if missing_required:
|
| 83 |
self.logger.error("❌ Missing required dependencies:")
|
|
|
|
| 85 |
self.logger.error(f" pip install {module}")
|
| 86 |
return False
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
return True
|
| 89 |
|
| 90 |
def test_database_connection(self) -> bool:
|
| 91 |
"""Test database connectivity"""
|
| 92 |
try:
|
| 93 |
import sqlite3
|
| 94 |
+
db_path = config.database_config["path"]
|
| 95 |
+
db_dir = os.path.dirname(db_path)
|
| 96 |
+
os.makedirs(db_dir, exist_ok=True)
|
| 97 |
+
conn = sqlite3.connect(db_path)
|
| 98 |
+
conn.execute("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY);")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
conn.close()
|
| 100 |
+
self.logger.info("✅ Database connectivity test passed")
|
| 101 |
+
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
except Exception as e:
|
| 103 |
self.logger.error(f"❌ Database connectivity test failed: {e}")
|
| 104 |
return False
|
|
|
|
| 107 |
"""Run Gradio interface for HF Spaces"""
|
| 108 |
try:
|
| 109 |
self.logger.info("🤗 Starting Gradio interface for HF Spaces...")
|
|
|
|
| 110 |
# Import and run Gradio app
|
| 111 |
+
import app # Assumes app.py at root is the Gradio entrypoint
|
| 112 |
+
self.logger.info("✅ Gradio interface started successfully from app.py")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
except Exception as e:
|
| 114 |
self.logger.error(f"❌ Failed to start Gradio interface: {e}")
|
| 115 |
return False
|
| 116 |
|
| 117 |
def run_fastapi_server(self):
|
| 118 |
+
"""Run FastAPI server for Docker, Local, or HF Docker Spaces"""
|
| 119 |
try:
|
| 120 |
self.logger.info("🚀 Starting FastAPI server...")
|
| 121 |
|
| 122 |
import uvicorn
|
| 123 |
from app.main import app
|
| 124 |
|
| 125 |
+
# Server configuration from config.py
|
| 126 |
server_config = config.server_config
|
| 127 |
|
| 128 |
self.logger.info(f"🌐 Server starting on {server_config['host']}:{server_config['port']}")
|
| 129 |
self.logger.info(f"👥 Workers: {server_config['workers']}")
|
|
|
|
| 130 |
|
|
|
|
| 131 |
uvicorn.run(
|
| 132 |
+
"app.main:app", # Use string import for reload compatibility
|
| 133 |
host=server_config['host'],
|
| 134 |
port=server_config['port'],
|
| 135 |
workers=server_config['workers'],
|
| 136 |
+
log_level=server_config['log_level'].lower(),
|
|
|
|
| 137 |
reload=server_config['reload']
|
| 138 |
)
|
|
|
|
| 139 |
except Exception as e:
|
| 140 |
self.logger.error(f"❌ Failed to start FastAPI server: {e}")
|
| 141 |
return False
|
|
|
|
| 146 |
print("🏛️ Legal Dashboard - Universal Runner")
|
| 147 |
print("=" * 60)
|
| 148 |
|
|
|
|
| 149 |
if not setup_environment():
|
| 150 |
self.logger.error("❌ Environment setup failed")
|
| 151 |
sys.exit(1)
|
| 152 |
|
|
|
|
| 153 |
if not self.check_dependencies():
|
| 154 |
self.logger.error("❌ Dependency check failed")
|
| 155 |
sys.exit(1)
|
| 156 |
|
|
|
|
| 157 |
if not self.test_database_connection():
|
| 158 |
self.logger.error("❌ Database test failed")
|
| 159 |
sys.exit(1)
|
| 160 |
|
|
|
|
| 161 |
self.logger.info("📋 Configuration Summary:")
|
| 162 |
self.logger.info(f" Environment: {config.environment}")
|
|
|
|
|
|
|
|
|
|
| 163 |
self.logger.info(f" Data Directory: {config.directories['data']}")
|
|
|
|
| 164 |
|
| 165 |
+
# --- ✅ FIX: منطق هوشمند برای تشخیص نوع اسپیس در هاگینگ فیس ---
|
| 166 |
+
# اگر در محیط هاگینگ فیس هستیم و فایل app.py (مخصوص گرادیو) وجود دارد، رابط گرادیو را اجرا کن
|
| 167 |
+
# در غیر این صورت (برای داکر، لوکال و داکر اسپیس در هاگینگ فیس) سرور اصلی FastAPI را اجرا کن
|
| 168 |
+
is_gradio_space = config.is_hf_spaces and os.path.exists("app.py")
|
| 169 |
+
|
| 170 |
try:
|
| 171 |
+
if is_gradio_space:
|
|
|
|
| 172 |
self.run_gradio_interface()
|
| 173 |
else:
|
|
|
|
| 174 |
self.run_fastapi_server()
|
| 175 |
|
| 176 |
except KeyboardInterrupt:
|
| 177 |
self.logger.info("🛑 Received keyboard interrupt")
|
|
|
|
|
|
|
|
|
|
| 178 |
finally:
|
| 179 |
self.shutdown()
|
| 180 |
|
| 181 |
def shutdown(self):
|
| 182 |
"""Graceful shutdown"""
|
| 183 |
self.logger.info("🔄 Shutting down Legal Dashboard...")
|
|
|
|
| 184 |
if self.app_process:
|
| 185 |
+
self.app_process.terminate()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
self.logger.info("✅ Shutdown completed")
|
| 187 |
|
| 188 |
def main():
|