Spaces:
Sleeping
Sleeping
Donne120 commited on
Commit ·
efee20b
1
Parent(s): b9dc1ee
main updated
Browse files- Dockerfile +10 -23
- main.py +126 -9
- render.yaml +4 -9
- render_check.py +58 -0
Dockerfile
CHANGED
|
@@ -1,31 +1,18 @@
|
|
| 1 |
-
FROM python:3.
|
| 2 |
|
| 3 |
WORKDIR /app
|
| 4 |
|
| 5 |
-
#
|
| 6 |
-
ENV PYTHONUNBUFFERED=1 \
|
| 7 |
-
PYTHONDONTWRITEBYTECODE=1 \
|
| 8 |
-
PIP_NO_CACHE_DIR=off \
|
| 9 |
-
PIP_DISABLE_PIP_VERSION_CHECK=on
|
| 10 |
-
|
| 11 |
-
# Install dependencies using a single layer to reduce image size
|
| 12 |
COPY requirements.txt .
|
| 13 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 14 |
|
| 15 |
-
# Copy
|
| 16 |
-
COPY . .
|
| 17 |
-
|
| 18 |
-
# Copy only necessary application files
|
| 19 |
-
COPY alu_brain ./alu_brain
|
| 20 |
-
COPY prompt_engine ./prompt_engine
|
| 21 |
-
COPY document_processor.py retrieval_engine.py retrieval_engine_extended.py main.py ./
|
| 22 |
-
|
| 23 |
-
# Create necessary directories with proper permissions
|
| 24 |
-
RUN mkdir -p data/uploads data/documents data/vector_index && \
|
| 25 |
-
chmod -R 777 data
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
#
|
| 31 |
-
CMD ["
|
|
|
|
| 1 |
+
FROM python:3.9-slim
|
| 2 |
|
| 3 |
WORKDIR /app
|
| 4 |
|
| 5 |
+
# Copy requirements
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
COPY requirements.txt .
|
| 7 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 8 |
|
| 9 |
+
# Copy application code
|
| 10 |
+
COPY . .
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
# Set environment variables similar to Render
|
| 13 |
+
ENV PORT=10000
|
| 14 |
+
ENV PYTHONUNBUFFERED=1
|
| 15 |
+
ENV CORS_ALLOWED_ORIGINS="http://localhost:3000,http://localhost:3001,https://alu-student-companion.onrender.com"
|
| 16 |
|
| 17 |
+
# Start the application
|
| 18 |
+
CMD ["python", "server.py"]
|
main.py
CHANGED
|
@@ -19,6 +19,55 @@ import platform
|
|
| 19 |
import signal
|
| 20 |
import threading
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
# Set environment variables to reduce memory usage
|
| 23 |
os.environ["OMP_NUM_THREADS"] = "1"
|
| 24 |
os.environ["MKL_NUM_THREADS"] = "1"
|
|
@@ -29,12 +78,6 @@ if torch.cuda.is_available():
|
|
| 29 |
torch.cuda.empty_cache()
|
| 30 |
torch.set_num_threads(1)
|
| 31 |
|
| 32 |
-
# Add a memory cleanup function
|
| 33 |
-
def cleanup_memory():
|
| 34 |
-
gc.collect()
|
| 35 |
-
if torch.cuda.is_available():
|
| 36 |
-
torch.cuda.empty_cache()
|
| 37 |
-
|
| 38 |
logging.basicConfig(
|
| 39 |
level=logging.INFO,
|
| 40 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
@@ -49,6 +92,32 @@ from prompt_engine.nyptho_integration import NypthoIntegration
|
|
| 49 |
from enhanced_capabilities.capability_router import handle_question, is_school_related
|
| 50 |
from enhanced_capabilities.conversation_memory import ConversationMemory
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
# Create FastAPI app
|
| 53 |
app = FastAPI(title="ALU Chatbot Backend")
|
| 54 |
|
|
@@ -159,8 +228,27 @@ async def health():
|
|
| 159 |
"timestamp": datetime.now().isoformat()
|
| 160 |
}
|
| 161 |
|
| 162 |
-
@app.
|
| 163 |
-
async def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
user_message = request.message
|
| 165 |
user_id = request.options.get("user_id", "anonymous") if request.options else "anonymous"
|
| 166 |
conversation_id = request.options.get("conversation_id") if request.options else None
|
|
@@ -269,4 +357,33 @@ async def process_chat(request: ChatRequest):
|
|
| 269 |
except Exception as e:
|
| 270 |
print(f"Error processing chat: {e}")
|
| 271 |
cleanup_memory()
|
| 272 |
-
return {"response": "I'm sorry, I couldn't process your request due to a technical error."}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
import signal
|
| 20 |
import threading
|
| 21 |
|
| 22 |
+
# Cross-platform imports and utilities
|
| 23 |
+
if platform.system() != "Windows":
|
| 24 |
+
# Linux-specific imports
|
| 25 |
+
import resource
|
| 26 |
+
|
| 27 |
+
# Linux memory limit function
|
| 28 |
+
def limit_memory(max_gb=2):
|
| 29 |
+
"""Limit memory usage on Linux"""
|
| 30 |
+
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
|
| 31 |
+
# Set to max_gb GB or keep hard limit if lower
|
| 32 |
+
max_bytes = max_gb * 1024 * 1024 * 1024
|
| 33 |
+
resource.setrlimit(resource.RLIMIT_AS, (min(max_bytes, hard), hard))
|
| 34 |
+
print(f"✅ Memory limited to {max_gb}GB on Linux")
|
| 35 |
+
|
| 36 |
+
# Linux timeout handler using SIGALRM
|
| 37 |
+
def timeout_handler(signum, frame):
|
| 38 |
+
"""Handle timeouts on Linux"""
|
| 39 |
+
raise TimeoutError("Function call timed out")
|
| 40 |
+
else:
|
| 41 |
+
# Windows mock implementations
|
| 42 |
+
def limit_memory(max_gb=2):
|
| 43 |
+
"""Mock memory limit function for Windows"""
|
| 44 |
+
print(f"ℹ️ Memory limiting not available on Windows (would be {max_gb}GB on Linux)")
|
| 45 |
+
|
| 46 |
+
# Windows timeout handler (no SIGALRM)
|
| 47 |
+
def timeout_handler(signum, frame):
|
| 48 |
+
"""Mock timeout handler for Windows"""
|
| 49 |
+
pass # Windows can't use this signal mechanism
|
| 50 |
+
|
| 51 |
+
# More aggressive memory management for Render
|
| 52 |
+
def cleanup_memory():
|
| 53 |
+
"""Cross-platform memory cleanup"""
|
| 54 |
+
import gc
|
| 55 |
+
gc.collect()
|
| 56 |
+
|
| 57 |
+
if torch.cuda.is_available():
|
| 58 |
+
torch.cuda.empty_cache()
|
| 59 |
+
|
| 60 |
+
# Linux-specific memory release
|
| 61 |
+
if platform.system() != "Windows":
|
| 62 |
+
try:
|
| 63 |
+
import ctypes
|
| 64 |
+
libc = ctypes.CDLL("libc.so.6")
|
| 65 |
+
# Return memory to OS
|
| 66 |
+
libc.malloc_trim(0)
|
| 67 |
+
print("✅ Released memory back to OS (Linux)")
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print(f"⚠️ Error releasing memory to OS: {e}")
|
| 70 |
+
|
| 71 |
# Set environment variables to reduce memory usage
|
| 72 |
os.environ["OMP_NUM_THREADS"] = "1"
|
| 73 |
os.environ["MKL_NUM_THREADS"] = "1"
|
|
|
|
| 78 |
torch.cuda.empty_cache()
|
| 79 |
torch.set_num_threads(1)
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
logging.basicConfig(
|
| 82 |
level=logging.INFO,
|
| 83 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
|
|
| 92 |
from enhanced_capabilities.capability_router import handle_question, is_school_related
|
| 93 |
from enhanced_capabilities.conversation_memory import ConversationMemory
|
| 94 |
|
| 95 |
+
# Timeout execution utility
|
| 96 |
+
def execute_with_timeout(func, timeout_seconds=30, *args, **kwargs):
|
| 97 |
+
"""
|
| 98 |
+
Run a function with a timeout, works on both Windows and Linux
|
| 99 |
+
Returns tuple (result, error)
|
| 100 |
+
"""
|
| 101 |
+
result = [None]
|
| 102 |
+
exception = [None]
|
| 103 |
+
|
| 104 |
+
def worker():
|
| 105 |
+
try:
|
| 106 |
+
result[0] = func(*args, **kwargs)
|
| 107 |
+
except Exception as e:
|
| 108 |
+
exception[0] = e
|
| 109 |
+
|
| 110 |
+
thread = threading.Thread(target=worker)
|
| 111 |
+
thread.daemon = True
|
| 112 |
+
thread.start()
|
| 113 |
+
thread.join(timeout_seconds)
|
| 114 |
+
|
| 115 |
+
if thread.is_alive():
|
| 116 |
+
return None, TimeoutError(f"Function timed out after {timeout_seconds} seconds")
|
| 117 |
+
if exception[0]:
|
| 118 |
+
return None, exception[0]
|
| 119 |
+
return result[0], None
|
| 120 |
+
|
| 121 |
# Create FastAPI app
|
| 122 |
app = FastAPI(title="ALU Chatbot Backend")
|
| 123 |
|
|
|
|
| 228 |
"timestamp": datetime.now().isoformat()
|
| 229 |
}
|
| 230 |
|
| 231 |
+
@app.get("/debug")
|
| 232 |
+
async def debug_info():
|
| 233 |
+
"""Debug endpoint with detailed system info"""
|
| 234 |
+
import sys
|
| 235 |
+
import psutil
|
| 236 |
+
process = psutil.Process()
|
| 237 |
+
|
| 238 |
+
return {
|
| 239 |
+
"status": "running",
|
| 240 |
+
"python_version": sys.version,
|
| 241 |
+
"platform": platform.system(),
|
| 242 |
+
"memory_usage_mb": process.memory_info().rss / (1024 * 1024),
|
| 243 |
+
"components_loaded": {
|
| 244 |
+
"document_processor": document_processor is not None,
|
| 245 |
+
"retrieval_engine": retrieval_engine is not None,
|
| 246 |
+
"prompt_engine": prompt_engine is not None,
|
| 247 |
+
"conversation_memory": conversation_memory is not None
|
| 248 |
+
}
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
def process_chat_internal(request: ChatRequest):
|
| 252 |
user_message = request.message
|
| 253 |
user_id = request.options.get("user_id", "anonymous") if request.options else "anonymous"
|
| 254 |
conversation_id = request.options.get("conversation_id") if request.options else None
|
|
|
|
| 357 |
except Exception as e:
|
| 358 |
print(f"Error processing chat: {e}")
|
| 359 |
cleanup_memory()
|
| 360 |
+
return {"response": "I'm sorry, I couldn't process your request due to a technical error."}
|
| 361 |
+
|
| 362 |
+
@app.post("/api/chat")
|
| 363 |
+
async def process_chat(request: ChatRequest):
|
| 364 |
+
try:
|
| 365 |
+
# Use cross-platform timeout for processing
|
| 366 |
+
result, error = execute_with_timeout(
|
| 367 |
+
process_chat_internal,
|
| 368 |
+
timeout_seconds=30,
|
| 369 |
+
request=request
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
if error:
|
| 373 |
+
if isinstance(error, TimeoutError):
|
| 374 |
+
return {
|
| 375 |
+
"response": "I'm sorry, processing your request took too long. Please try a simpler question.",
|
| 376 |
+
"error_type": "timeout"
|
| 377 |
+
}
|
| 378 |
+
return {
|
| 379 |
+
"response": "I'm sorry, I encountered an error processing your request.",
|
| 380 |
+
"error_type": "processing_error"
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
return result
|
| 384 |
+
except Exception as e:
|
| 385 |
+
logger.error(f"Error in process_chat: {str(e)}")
|
| 386 |
+
return {
|
| 387 |
+
"response": "I'm sorry, I encountered an unexpected error.",
|
| 388 |
+
"error_type": "general_error"
|
| 389 |
+
}
|
render.yaml
CHANGED
|
@@ -2,15 +2,10 @@ services:
|
|
| 2 |
- type: web
|
| 3 |
name: alu-chatbot-backend
|
| 4 |
env: python
|
| 5 |
-
buildCommand:
|
| 6 |
-
pip install -r requirements.txt
|
| 7 |
-
python cache_models.py
|
| 8 |
startCommand: python server.py
|
| 9 |
envVars:
|
| 10 |
-
- key:
|
| 11 |
-
value:
|
| 12 |
- key: CORS_ALLOWED_ORIGINS
|
| 13 |
-
value: https://
|
| 14 |
-
- key: TRANSFORMERS_OFFLINE
|
| 15 |
-
value: "1"
|
| 16 |
-
healthCheckPath: /health
|
|
|
|
| 2 |
- type: web
|
| 3 |
name: alu-chatbot-backend
|
| 4 |
env: python
|
| 5 |
+
buildCommand: pip install -r requirements.txt
|
|
|
|
|
|
|
| 6 |
startCommand: python server.py
|
| 7 |
envVars:
|
| 8 |
+
- key: PYTHONUNBUFFERED
|
| 9 |
+
value: 1
|
| 10 |
- key: CORS_ALLOWED_ORIGINS
|
| 11 |
+
value: http://localhost:3000,http://localhost:3001,https://alu-student-companion.onrender.com
|
|
|
|
|
|
|
|
|
render_check.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import platform
|
| 4 |
+
import importlib
|
| 5 |
+
|
| 6 |
+
def check_render_compatibility():
|
| 7 |
+
"""Check for common issues that might cause problems on Render"""
|
| 8 |
+
issues = []
|
| 9 |
+
|
| 10 |
+
# Check platform-specific code
|
| 11 |
+
if platform.system() == "Windows":
|
| 12 |
+
print("⚠️ Running on Windows - Render uses Linux")
|
| 13 |
+
|
| 14 |
+
# Check for Linux-only modules
|
| 15 |
+
try:
|
| 16 |
+
import resource
|
| 17 |
+
print("✅ Resource module available")
|
| 18 |
+
except ImportError:
|
| 19 |
+
issues.append("❌ Resource module not available on Windows but used on Linux")
|
| 20 |
+
|
| 21 |
+
# Check for signal handling
|
| 22 |
+
import signal
|
| 23 |
+
if not hasattr(signal, 'SIGALRM'):
|
| 24 |
+
issues.append("❌ SIGALRM not available on Windows but might be used in your code")
|
| 25 |
+
|
| 26 |
+
# Check for ctypes and libc
|
| 27 |
+
if platform.system() == "Windows":
|
| 28 |
+
issues.append("⚠️ Linux-specific memory management with libc.so.6 won't work on Windows")
|
| 29 |
+
|
| 30 |
+
# Check that all imports will work
|
| 31 |
+
modules_to_check = [
|
| 32 |
+
"document_processor",
|
| 33 |
+
"retrieval_engine_extended",
|
| 34 |
+
"prompt_engine",
|
| 35 |
+
"enhanced_capabilities.capability_router",
|
| 36 |
+
"enhanced_capabilities.conversation_memory"
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
for module in modules_to_check:
|
| 40 |
+
try:
|
| 41 |
+
importlib.import_module(module)
|
| 42 |
+
print(f"✅ Module {module} importable")
|
| 43 |
+
except ImportError as e:
|
| 44 |
+
issues.append(f"❌ Module {module} import error: {str(e)}")
|
| 45 |
+
|
| 46 |
+
return issues
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
print("=== Checking Render Compatibility ===")
|
| 50 |
+
issues = check_render_compatibility()
|
| 51 |
+
|
| 52 |
+
if issues:
|
| 53 |
+
print("\n=== Potential Render Deployment Issues ===")
|
| 54 |
+
for issue in issues:
|
| 55 |
+
print(issue)
|
| 56 |
+
print("\nFix these issues before deploying to Render")
|
| 57 |
+
else:
|
| 58 |
+
print("\n✅ No obvious compatibility issues detected")
|