Spaces:
Running
Running
Donne120 commited on
Commit ·
efee20b
1
Parent(s): b9dc1ee
main updated
Browse filesFiles changed (4)
- Dockerfile+10-23
- main.py+126-9
- render.yaml+4-9
- render_check.pyAdded+58
12345678910111213141516171819202122232425262728293031FROM python:3.10-slim-bookwormWORKDIR /app# Set environment variables to optimize Python performanceENV PYTHONUNBUFFERED=1 \PYTHONDONTWRITEBYTECODE=1 \PIP_NO_CACHE_DIR=off \PIP_DISABLE_PIP_VERSION_CHECK=on# Install dependencies using a single layer to reduce image sizeCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt# Copy ALL application code and directoriesCOPY . .# Copy only necessary application filesCOPY alu_brain ./alu_brainCOPY prompt_engine ./prompt_engineCOPY document_processor.py retrieval_engine.py retrieval_engine_extended.py main.py ./# Create necessary directories with proper permissionsRUN mkdir -p data/uploads data/documents data/vector_index && \chmod -R 777 data# Expose the port the app runs onEXPOSE 8080# Command to run the application with optimized settingsCMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]123456789101112131415161718FROM python:3.9-slimWORKDIR /app# Copy requirementsCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt# Copy application codeCOPY . .# Set environment variables similar to RenderENV PORT=10000ENV PYTHONUNBUFFERED=1ENV CORS_ALLOWED_ORIGINS="http://localhost:3000,http://localhost:3001,https://alu-student-companion.onrender.com"# Start the applicationCMD ["python", "server.py"]
18 unmodified lines1920212223244 unmodified lines2930313233343536373839408 unmodified lines495051525354104 unmodified lines159160161162163164165166102 unmodified lines26927027127218 unmodified linesimport signalimport threading# Set environment variables to reduce memory usageos.environ["OMP_NUM_THREADS"] = "1"os.environ["MKL_NUM_THREADS"] = "1"4 unmodified linestorch.cuda.empty_cache()torch.set_num_threads(1)# Add a memory cleanup functiondef cleanup_memory():gc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'8 unmodified linesfrom enhanced_capabilities.capability_router import handle_question, is_school_relatedfrom enhanced_capabilities.conversation_memory import ConversationMemory# Create FastAPI appapp = FastAPI(title="ALU Chatbot Backend")104 unmodified lines"timestamp": datetime.now().isoformat()}@app.post("/api/chat")async def process_chat(request: ChatRequest):user_message = request.messageuser_id = request.options.get("user_id", "anonymous") if request.options else "anonymous"conversation_id = request.options.get("conversation_id") if request.options else None102 unmodified linesexcept Exception as e:print(f"Error processing chat: {e}")cleanup_memory()return {"response": "I'm sorry, I couldn't process your request due to a technical error."}18 unmodified lines192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172734 unmodified lines7879808182838 unmodified lines9293949596979899100101102103104105106107108109110111112113114115116117118119120121122123104 unmodified lines228229230231232233234235236237238239240241242243244245246247248249250251252253254102 unmodified lines35735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838918 unmodified linesimport signalimport threading# Cross-platform imports and utilitiesif platform.system() != "Windows":# Linux-specific importsimport resource# Linux memory limit functiondef limit_memory(max_gb=2):"""Limit memory usage on Linux"""soft, hard = resource.getrlimit(resource.RLIMIT_AS)# Set to max_gb GB or keep hard limit if lowermax_bytes = max_gb * 1024 * 1024 * 1024resource.setrlimit(resource.RLIMIT_AS, (min(max_bytes, hard), hard))print(f"✅ Memory limited to {max_gb}GB on Linux")# Linux timeout handler using SIGALRMdef timeout_handler(signum, frame):"""Handle timeouts on Linux"""raise TimeoutError("Function call timed out")else:# Windows mock implementationsdef limit_memory(max_gb=2):"""Mock memory limit function for Windows"""print(f"ℹ️ Memory limiting not available on Windows (would be {max_gb}GB on Linux)")# Windows timeout handler (no SIGALRM)def timeout_handler(signum, frame):"""Mock timeout handler for Windows"""pass # Windows can't use this signal mechanism# More aggressive memory management for Renderdef cleanup_memory():"""Cross-platform memory cleanup"""import gcgc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()# Linux-specific memory releaseif platform.system() != "Windows":try:import ctypeslibc = ctypes.CDLL("libc.so.6")# Return memory to OSlibc.malloc_trim(0)print("✅ Released memory back to OS (Linux)")except Exception as e:print(f"⚠️ Error releasing memory to OS: {e}")# Set environment variables to reduce memory usageos.environ["OMP_NUM_THREADS"] = "1"os.environ["MKL_NUM_THREADS"] = "1"4 unmodified linestorch.cuda.empty_cache()torch.set_num_threads(1)logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'8 unmodified linesfrom enhanced_capabilities.capability_router import handle_question, is_school_relatedfrom enhanced_capabilities.conversation_memory import ConversationMemory# Timeout execution utilitydef execute_with_timeout(func, timeout_seconds=30, *args, **kwargs):"""Run a function with a timeout, works on both Windows and LinuxReturns tuple (result, error)"""result = [None]exception = [None]def worker():try:result[0] = func(*args, **kwargs)except Exception as e:exception[0] = ethread = threading.Thread(target=worker)thread.daemon = Truethread.start()thread.join(timeout_seconds)if thread.is_alive():return None, TimeoutError(f"Function timed out after {timeout_seconds} seconds")if exception[0]:return None, exception[0]return result[0], None# Create FastAPI appapp = FastAPI(title="ALU Chatbot Backend")104 unmodified lines"timestamp": datetime.now().isoformat()}@app.get("/debug")async def debug_info():"""Debug endpoint with detailed system info"""import sysimport psutilprocess = psutil.Process()return {"status": "running","python_version": sys.version,"platform": platform.system(),"memory_usage_mb": process.memory_info().rss / (1024 * 1024),"components_loaded": {"document_processor": document_processor is not None,"retrieval_engine": retrieval_engine is not None,"prompt_engine": prompt_engine is not None,"conversation_memory": conversation_memory is not None}}def process_chat_internal(request: ChatRequest):user_message = request.messageuser_id = request.options.get("user_id", "anonymous") if request.options else "anonymous"conversation_id = request.options.get("conversation_id") if request.options else None102 unmodified linesexcept Exception as e:print(f"Error processing chat: {e}")cleanup_memory()return {"response": "I'm sorry, I couldn't process your request due to a technical error."}@app.post("/api/chat")async def process_chat(request: ChatRequest):try:# Use cross-platform timeout for processingresult, error = execute_with_timeout(process_chat_internal,timeout_seconds=30,request=request)if error:if isinstance(error, TimeoutError):return {"response": "I'm sorry, processing your request took too long. Please try a simpler question.","error_type": "timeout"}return {"response": "I'm sorry, I encountered an error processing your request.","error_type": "processing_error"}return resultexcept Exception as e:logger.error(f"Error in process_chat: {str(e)}")return {"response": "I'm sorry, I encountered an unexpected error.","error_type": "general_error"}
1 unmodified line23456789101112131415161 unmodified line- type: webname: alu-chatbot-backendenv: pythonbuildCommand: |pip install -r requirements.txtpython cache_models.pystartCommand: python server.pyenvVars:- key: DEPLOYMENT_ENVvalue: render- key: CORS_ALLOWED_ORIGINSvalue: https://your-frontend-domain.com- key: TRANSFORMERS_OFFLINEvalue: "1"healthCheckPath: /health1 unmodified line2345678910111 unmodified line- type: webname: alu-chatbot-backendenv: pythonbuildCommand: pip install -r requirements.txtstartCommand: python server.pyenvVars:- key: PYTHONUNBUFFEREDvalue: 1- key: CORS_ALLOWED_ORIGINSvalue: http://localhost:3000,http://localhost:3001,https://alu-student-companion.onrender.com
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import osimport sysimport platformimport importlib
def check_render_compatibility(): """Check for common issues that might cause problems on Render""" issues = [] # Check platform-specific code if platform.system() == "Windows": print("⚠️ Running on Windows - Render uses Linux") # Check for Linux-only modules try: import resource print("✅ Resource module available") except ImportError: issues.append("❌ Resource module not available on Windows but used on Linux") # Check for signal handling import signal if not hasattr(signal, 'SIGALRM'): issues.append("❌ SIGALRM not available on Windows but might be used in your code") # Check for ctypes and libc if platform.system() == "Windows": issues.append("⚠️ Linux-specific memory management with libc.so.6 won't work on Windows") # Check that all imports will work modules_to_check = [ "document_processor", "retrieval_engine_extended", "prompt_engine", "enhanced_capabilities.capability_router", "enhanced_capabilities.conversation_memory" ] for module in modules_to_check: try: importlib.import_module(module) print(f"✅ Module {module} importable") except ImportError as e: issues.append(f"❌ Module {module} import error: {str(e)}") return issues
if __name__ == "__main__": print("=== Checking Render Compatibility ===") issues = check_render_compatibility() if issues: print("\n=== Potential Render Deployment Issues ===") for issue in issues: print(issue) print("\nFix these issues before deploying to Render") else: print("\n✅ No obvious compatibility issues detected")Dockerfile+10-23
main.py+126-9
render.yaml+4-9
render_check.pyAdded+58