Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,6 +5,7 @@ import time
|
|
| 5 |
import logging
|
| 6 |
import psutil
|
| 7 |
import asyncio
|
|
|
|
| 8 |
from datetime import datetime
|
| 9 |
from typing import List, Dict, Optional, Any
|
| 10 |
import requests
|
|
@@ -40,15 +41,19 @@ logging.basicConfig(
|
|
| 40 |
)
|
| 41 |
logger = logging.getLogger(__name__)
|
| 42 |
|
|
|
|
| 43 |
supabase_integration = None
|
| 44 |
security_system = None
|
| 45 |
monitor = None
|
| 46 |
ai_system = None
|
|
|
|
|
|
|
| 47 |
|
| 48 |
def initialize_systems():
|
| 49 |
-
|
|
|
|
| 50 |
|
| 51 |
-
logger.info("🚀
|
| 52 |
|
| 53 |
try:
|
| 54 |
supabase_integration = AdvancedSupabaseIntegration(
|
|
@@ -72,87 +77,44 @@ def initialize_systems():
|
|
| 72 |
)
|
| 73 |
logger.info("✅ AI system initialized")
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
return True
|
| 76 |
|
| 77 |
except Exception as e:
|
| 78 |
logger.error(f"❌ Failed to initialize systems: {e}")
|
|
|
|
| 79 |
return False
|
| 80 |
|
| 81 |
-
def
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
client_host = getattr(request, "client", None)
|
| 87 |
-
if client_host:
|
| 88 |
-
user_ip = client_host.host
|
| 89 |
-
else:
|
| 90 |
-
user_ip = "unknown"
|
| 91 |
-
user_id = f"gradio_user_{user_ip}"
|
| 92 |
-
|
| 93 |
-
security_result = security_system.check_request(message, user_id)
|
| 94 |
-
if security_result["is_suspicious"]:
|
| 95 |
-
logger.warning(f"Suspicious request blocked from {user_ip}: {message}")
|
| 96 |
-
return "Your request has been blocked for security reasons. Please try a different question."
|
| 97 |
-
|
| 98 |
-
start_time = time.time()
|
| 99 |
-
response = ai_system.process_query(message, user_id)
|
| 100 |
-
processing_time = time.time() - start_time
|
| 101 |
-
|
| 102 |
-
formatted_response = f"{response}\n\n_Generated in {processing_time:.1f}s_"
|
| 103 |
-
|
| 104 |
-
logger.info(f"Chat processed: {message[:50]}... -> {processing_time:.2f}s")
|
| 105 |
-
|
| 106 |
-
return formatted_response
|
| 107 |
-
|
| 108 |
-
except Exception as e:
|
| 109 |
-
logger.error(f"Chat error: {e}")
|
| 110 |
-
return "I apologize, but I'm experiencing technical difficulties. Please try again later."
|
| 111 |
-
|
| 112 |
-
def get_system_status() -> Dict[str, Any]:
|
| 113 |
-
if not all([supabase_integration, security_system, monitor, ai_system]):
|
| 114 |
-
return {"status": "initializing", "details": "Systems are starting up..."}
|
| 115 |
-
|
| 116 |
-
try:
|
| 117 |
-
return {
|
| 118 |
-
"status": "healthy",
|
| 119 |
-
"timestamp": datetime.now().isoformat(),
|
| 120 |
-
"systems": {
|
| 121 |
-
"supabase": supabase_integration.is_connected(),
|
| 122 |
-
"security": True,
|
| 123 |
-
"monitoring": True,
|
| 124 |
-
"ai_system": ai_system.is_healthy()
|
| 125 |
-
},
|
| 126 |
-
"resources": {
|
| 127 |
-
"cpu_percent": psutil.cpu_percent(),
|
| 128 |
-
"memory_percent": psutil.virtual_memory().percent,
|
| 129 |
-
"disk_percent": psutil.disk_usage('/').percent
|
| 130 |
-
},
|
| 131 |
-
"performance": {
|
| 132 |
-
"total_requests": len(monitor.inference_metrics),
|
| 133 |
-
"avg_response_time": monitor.get_average_response_time(),
|
| 134 |
-
"error_rate": monitor.get_error_rate()
|
| 135 |
-
}
|
| 136 |
-
}
|
| 137 |
-
except Exception as e:
|
| 138 |
-
return {"status": "error", "error": str(e)}
|
| 139 |
-
|
| 140 |
-
class ChatRequest(BaseModel):
|
| 141 |
-
message: str
|
| 142 |
-
user_id: Optional[str] = "anonymous"
|
| 143 |
-
conversation_id: Optional[str] = None
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
processing_time: float
|
| 148 |
-
conversation_id: str
|
| 149 |
-
timestamp: str
|
| 150 |
-
model_used: str
|
| 151 |
|
|
|
|
| 152 |
fastapi_app = FastAPI(title="Saem's Tunes AI API", version="1.0.0")
|
| 153 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
@fastapi_app.get("/api/health")
|
| 155 |
def api_health():
|
|
|
|
| 156 |
try:
|
| 157 |
status_data = get_system_status()
|
| 158 |
return status_data
|
|
@@ -197,6 +159,9 @@ def api_chat(request: ChatRequest):
|
|
| 197 |
if not request.message.strip():
|
| 198 |
raise HTTPException(status_code=400, detail="Message cannot be empty")
|
| 199 |
|
|
|
|
|
|
|
|
|
|
| 200 |
security_result = security_system.check_request(request.message, request.user_id)
|
| 201 |
if security_result["is_suspicious"]:
|
| 202 |
raise HTTPException(status_code=429, detail="Request blocked for security reasons")
|
|
@@ -219,6 +184,94 @@ def api_chat(request: ChatRequest):
|
|
| 219 |
logger.error(f"API chat error: {e}")
|
| 220 |
raise HTTPException(status_code=500, detail="Internal server error")
|
| 221 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
def create_gradio_interface():
|
| 223 |
custom_css = """
|
| 224 |
.gradio-container {
|
|
@@ -382,6 +435,8 @@ def create_gradio_interface():
|
|
| 382 |
Memory: {resources.get('memory_percent', 0):.1f}%
|
| 383 |
</small>
|
| 384 |
"""
|
|
|
|
|
|
|
| 385 |
else:
|
| 386 |
html = f"<div class='status-indicator {status_class}'></div>{status.get('details', 'Unknown status')}"
|
| 387 |
|
|
@@ -440,16 +495,20 @@ def create_gradio_interface():
|
|
| 440 |
|
| 441 |
return demo
|
| 442 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 443 |
if __name__ == "__main__":
|
| 444 |
-
logger.info("🎵 Starting Saem's Tunes AI
|
| 445 |
-
|
| 446 |
-
if not initialize_systems():
|
| 447 |
-
logger.error("Failed to initialize systems. Exiting.")
|
| 448 |
-
exit(1)
|
| 449 |
-
|
| 450 |
-
demo = create_gradio_interface()
|
| 451 |
|
| 452 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
|
| 454 |
import uvicorn
|
| 455 |
uvicorn.run(
|
|
|
|
| 5 |
import logging
|
| 6 |
import psutil
|
| 7 |
import asyncio
|
| 8 |
+
import threading
|
| 9 |
from datetime import datetime
|
| 10 |
from typing import List, Dict, Optional, Any
|
| 11 |
import requests
|
|
|
|
| 41 |
)
|
| 42 |
logger = logging.getLogger(__name__)
|
| 43 |
|
| 44 |
+
# Global systems and initialization state
|
| 45 |
supabase_integration = None
|
| 46 |
security_system = None
|
| 47 |
monitor = None
|
| 48 |
ai_system = None
|
| 49 |
+
systems_ready = False
|
| 50 |
+
initialization_complete = False
|
| 51 |
|
| 52 |
def initialize_systems():
|
| 53 |
+
"""Initialize systems in background thread"""
|
| 54 |
+
global supabase_integration, security_system, monitor, ai_system, systems_ready, initialization_complete
|
| 55 |
|
| 56 |
+
logger.info("🚀 Starting background system initialization...")
|
| 57 |
|
| 58 |
try:
|
| 59 |
supabase_integration = AdvancedSupabaseIntegration(
|
|
|
|
| 77 |
)
|
| 78 |
logger.info("✅ AI system initialized")
|
| 79 |
|
| 80 |
+
systems_ready = True
|
| 81 |
+
initialization_complete = True
|
| 82 |
+
logger.info("🎉 All systems ready!")
|
| 83 |
+
|
| 84 |
return True
|
| 85 |
|
| 86 |
except Exception as e:
|
| 87 |
logger.error(f"❌ Failed to initialize systems: {e}")
|
| 88 |
+
initialization_complete = True
|
| 89 |
return False
|
| 90 |
|
| 91 |
+
def start_initialization():
|
| 92 |
+
"""Start system initialization in background thread"""
|
| 93 |
+
thread = threading.Thread(target=initialize_systems, daemon=True)
|
| 94 |
+
thread.start()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
# Start initialization immediately when module loads
|
| 97 |
+
start_initialization()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
+
# Create FastAPI app at MODULE LEVEL (required by Hugging Face)
|
| 100 |
fastapi_app = FastAPI(title="Saem's Tunes AI API", version="1.0.0")
|
| 101 |
|
| 102 |
+
# ADD ROOT ROUTE - Hugging Face checks this!
|
| 103 |
+
@fastapi_app.get("/")
|
| 104 |
+
def root():
|
| 105 |
+
"""Root endpoint for Hugging Face health checks"""
|
| 106 |
+
return {
|
| 107 |
+
"status": "healthy" if systems_ready else "initializing",
|
| 108 |
+
"message": "Saem's Tunes AI API is running",
|
| 109 |
+
"timestamp": datetime.now().isoformat(),
|
| 110 |
+
"version": "1.0.0",
|
| 111 |
+
"systems_ready": systems_ready,
|
| 112 |
+
"initialization_complete": initialization_complete
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
@fastapi_app.get("/api/health")
|
| 116 |
def api_health():
|
| 117 |
+
"""Health check endpoint"""
|
| 118 |
try:
|
| 119 |
status_data = get_system_status()
|
| 120 |
return status_data
|
|
|
|
| 159 |
if not request.message.strip():
|
| 160 |
raise HTTPException(status_code=400, detail="Message cannot be empty")
|
| 161 |
|
| 162 |
+
if not systems_ready:
|
| 163 |
+
raise HTTPException(status_code=503, detail="System is still initializing. Please try again in a moment.")
|
| 164 |
+
|
| 165 |
security_result = security_system.check_request(request.message, request.user_id)
|
| 166 |
if security_result["is_suspicious"]:
|
| 167 |
raise HTTPException(status_code=429, detail="Request blocked for security reasons")
|
|
|
|
| 184 |
logger.error(f"API chat error: {e}")
|
| 185 |
raise HTTPException(status_code=500, detail="Internal server error")
|
| 186 |
|
| 187 |
+
class ChatRequest(BaseModel):
|
| 188 |
+
message: str
|
| 189 |
+
user_id: Optional[str] = "anonymous"
|
| 190 |
+
conversation_id: Optional[str] = None
|
| 191 |
+
|
| 192 |
+
class ChatResponse(BaseModel):
|
| 193 |
+
response: str
|
| 194 |
+
processing_time: float
|
| 195 |
+
conversation_id: str
|
| 196 |
+
timestamp: str
|
| 197 |
+
model_used: str
|
| 198 |
+
|
| 199 |
+
def chat_interface(message: str, history: List[List[str]], request: gr.Request) -> str:
|
| 200 |
+
try:
|
| 201 |
+
if not message.strip():
|
| 202 |
+
return "Please ask me anything about Saem's Tunes!"
|
| 203 |
+
|
| 204 |
+
if not systems_ready:
|
| 205 |
+
return "🔄 System is still initializing. Please wait a moment and try again..."
|
| 206 |
+
|
| 207 |
+
client_host = getattr(request, "client", None)
|
| 208 |
+
if client_host:
|
| 209 |
+
user_ip = client_host.host
|
| 210 |
+
else:
|
| 211 |
+
user_ip = "unknown"
|
| 212 |
+
user_id = f"gradio_user_{user_ip}"
|
| 213 |
+
|
| 214 |
+
security_result = security_system.check_request(message, user_id)
|
| 215 |
+
if security_result["is_suspicious"]:
|
| 216 |
+
logger.warning(f"Suspicious request blocked from {user_ip}: {message}")
|
| 217 |
+
return "Your request has been blocked for security reasons. Please try a different question."
|
| 218 |
+
|
| 219 |
+
start_time = time.time()
|
| 220 |
+
response = ai_system.process_query(message, user_id)
|
| 221 |
+
processing_time = time.time() - start_time
|
| 222 |
+
|
| 223 |
+
formatted_response = f"{response}\n\n_Generated in {processing_time:.1f}s_"
|
| 224 |
+
|
| 225 |
+
logger.info(f"Chat processed: {message[:50]}... -> {processing_time:.2f}s")
|
| 226 |
+
|
| 227 |
+
return formatted_response
|
| 228 |
+
|
| 229 |
+
except Exception as e:
|
| 230 |
+
logger.error(f"Chat error: {e}")
|
| 231 |
+
return "I apologize, but I'm experiencing technical difficulties. Please try again later."
|
| 232 |
+
|
| 233 |
+
def get_system_status() -> Dict[str, Any]:
|
| 234 |
+
if not initialization_complete:
|
| 235 |
+
return {
|
| 236 |
+
"status": "initializing",
|
| 237 |
+
"details": "Systems are starting up...",
|
| 238 |
+
"systems_ready": systems_ready,
|
| 239 |
+
"timestamp": datetime.now().isoformat()
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
if not systems_ready:
|
| 243 |
+
return {
|
| 244 |
+
"status": "degraded",
|
| 245 |
+
"details": "Systems initialized but not ready",
|
| 246 |
+
"systems_ready": systems_ready,
|
| 247 |
+
"timestamp": datetime.now().isoformat()
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
try:
|
| 251 |
+
return {
|
| 252 |
+
"status": "healthy",
|
| 253 |
+
"timestamp": datetime.now().isoformat(),
|
| 254 |
+
"systems": {
|
| 255 |
+
"supabase": supabase_integration.is_connected() if supabase_integration else False,
|
| 256 |
+
"security": True,
|
| 257 |
+
"monitoring": True,
|
| 258 |
+
"ai_system": ai_system.is_healthy() if ai_system else False
|
| 259 |
+
},
|
| 260 |
+
"resources": {
|
| 261 |
+
"cpu_percent": psutil.cpu_percent(),
|
| 262 |
+
"memory_percent": psutil.virtual_memory().percent,
|
| 263 |
+
"disk_percent": psutil.disk_usage('/').percent
|
| 264 |
+
},
|
| 265 |
+
"performance": {
|
| 266 |
+
"total_requests": len(monitor.inference_metrics),
|
| 267 |
+
"avg_response_time": monitor.get_average_response_time(),
|
| 268 |
+
"error_rate": monitor.get_error_rate()
|
| 269 |
+
},
|
| 270 |
+
"systems_ready": systems_ready
|
| 271 |
+
}
|
| 272 |
+
except Exception as e:
|
| 273 |
+
return {"status": "error", "error": str(e)}
|
| 274 |
+
|
| 275 |
def create_gradio_interface():
|
| 276 |
custom_css = """
|
| 277 |
.gradio-container {
|
|
|
|
| 435 |
Memory: {resources.get('memory_percent', 0):.1f}%
|
| 436 |
</small>
|
| 437 |
"""
|
| 438 |
+
elif status_text == "initializing":
|
| 439 |
+
html = f"<div class='status-indicator {status_class}'></div>Systems initializing... (This may take a few minutes)"
|
| 440 |
else:
|
| 441 |
html = f"<div class='status-indicator {status_class}'></div>{status.get('details', 'Unknown status')}"
|
| 442 |
|
|
|
|
| 495 |
|
| 496 |
return demo
|
| 497 |
|
| 498 |
+
# Create Gradio interface and mount to FastAPI at MODULE LEVEL
|
| 499 |
+
demo = create_gradio_interface()
|
| 500 |
+
app = gr.mount_gradio_app(fastapi_app, demo, path="/")
|
| 501 |
+
|
| 502 |
if __name__ == "__main__":
|
| 503 |
+
logger.info("🎵 Starting Saem's Tunes AI locally...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
|
| 505 |
+
# For local development, wait for initialization
|
| 506 |
+
if not initialization_complete:
|
| 507 |
+
logger.info("⏳ Waiting for system initialization...")
|
| 508 |
+
for i in range(30): # Wait up to 30 seconds
|
| 509 |
+
if initialization_complete:
|
| 510 |
+
break
|
| 511 |
+
time.sleep(1)
|
| 512 |
|
| 513 |
import uvicorn
|
| 514 |
uvicorn.run(
|