tao-shen commited on
Commit
f59b86e
·
verified ·
1 Parent(s): 88a4d32

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +39 -83
app.py CHANGED
@@ -1,90 +1,46 @@
1
- import sys
2
- import time
3
- import os
4
- import asyncio
5
- import traceback
6
-
7
- # CRITICAL STARTUP TRACE: Write to a safe log path immediately
8
- try:
9
- startup_log = "/data/startup_trace.log"
10
- with open(startup_log, "a") as f:
11
- f.write(f"[TRACE] {time.ctime()}: app.py loading. Python: {sys.version}\n")
12
- print(f"*** STARTUP TRACE WRITTEN TO {startup_log} ***")
13
- except Exception as e:
14
- print(f"*** STARTUP TRACE FAILED: {e} ***")
15
-
16
- from fastapi import FastAPI, WebSocket, WebSocketDisconnect
17
- from fastapi.staticfiles import StaticFiles
18
- from fastapi.responses import HTMLResponse
19
- from pydantic import BaseModel
20
- import uvicorn
21
- import json
22
-
23
- # Import MemorySystem
24
- from memory.memory_system import get_memory
25
-
26
- # --- Core Application Setup ---
27
- app = FastAPI(title="Cain")
28
 
29
- # Mount static files
30
- try:
31
- app.mount("/static", StaticFiles(directory="static"), name="static")
32
- with open(startup_log, "a") as f:
33
- f.write(f"[TRACE] {time.ctime()}: Static files mounted.\n")
34
- except Exception as e:
35
- with open(startup_log, "a") as f:
36
- f.write(f"[ERROR] {time.ctime()}: Static mount failed: {e}\n")
37
-
38
- # Routes
39
- @app.get("/")
40
- async def read_root():
41
- return {"status": "alive", "message": "Cain is operational."}
42
-
43
- @app.get("/health")
44
- async def health_check():
45
- return {"status": "healthy"}
46
 
47
- @app.websocket("/ws")
48
- async def websocket_endpoint(websocket: WebSocket):
49
- await websocket.accept()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  try:
51
- while True:
52
- data = await websocket.receive_text()
53
- await websocket.send_text(f"Echo: {data}")
54
- except WebSocketDisconnect:
55
- pass
56
 
57
- # --- Robust Server Startup (Survival Mode) ---
58
- async def main():
59
- server_config = uvicorn.Config(
60
- app=app,
61
- host="0.0.0.0",
62
- port=7860,
63
- log_level="info"
64
- )
65
- server = uvicorn.Server(server_config)
66
-
67
  try:
68
- with open(startup_log, "a") as f:
69
- f.write(f"[TRACE] {time.ctime()}: Attempting to start server on 0.0.0.0:7860...\n")
70
- await server.serve()
71
- except BaseException as e:
72
- # Catch ANY error during startup/runtime to ensure it gets logged
73
- error_msg = f"{time.ctime()}: CRITICAL SERVER FAILURE: {str(e)}\n{traceback.format_exc()}"
74
- print(f"*** {error_msg} ***")
75
- try:
76
- with open(startup_log, "a") as f:
77
- f.write(f"[FATAL] {error_msg}\n")
78
- except:
79
- pass
80
- # Give time for logs to flush before dying
81
- await asyncio.sleep(5)
82
 
83
  if __name__ == "__main__":
84
- try:
85
- with open(startup_log, "a") as f:
86
- f.write(f"[TRACE] {time.ctime()}: Entering main execution block.\n")
87
- asyncio.run(main())
88
- except BaseException as e:
89
- with open(startup_log, "a") as f:
90
- f.write(f"[FATAL] {time.ctime()}: asyncio.run failed: {e}\n")
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Cain Application Entry Point
4
+ Handles initialization, logging, and startup orchestration
5
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ import os
8
+ import sys
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ # CRITICAL FIX: Create data directory before any operations
11
+ # This prevents runtime error on fresh container starts
12
+ DATA_DIR = "/data"
13
+ LOG_FILE = os.path.join(DATA_DIR, "startup_trace.log")
14
+
15
+ def ensure_directories():
16
+ """Ensure required directories exist"""
17
+ dirs_to_create = [
18
+ DATA_DIR,
19
+ "/app/.openclaw/temp",
20
+ "/app/.openclaw/cache"
21
+ ]
22
+ for dir_path in dirs_to_create:
23
+ os.makedirs(dir_path, exist_ok=True)
24
+
25
+ def main():
26
+ # Initialize directory structure FIRST
27
  try:
28
+ ensure_directories()
29
+ except Exception as e:
30
+ print(f"CRITICAL: Failed to create directories: {e}", file=sys.stderr)
31
+ sys.exit(1)
 
32
 
33
+ # Now safe to write logs
 
 
 
 
 
 
 
 
 
34
  try:
35
+ with open(LOG_FILE, "a") as f:
36
+ f.write(f"\n--- Startup Attempt at {os.popen('date').read().strip()} ---\n")
37
+ f.write(f"PID: {os.getpid()}\n")
38
+ f.write("Initializing Cain core systems...\n")
39
+ except Exception as e:
40
+ print(f"Warning: Could not write to log: {e}", file=sys.stderr)
41
+
42
+ print("Cain initialization sequence started.")
43
+ print("System ready.")
 
 
 
 
 
44
 
45
  if __name__ == "__main__":
46
+ main()