tao-shen commited on
Commit
6607d1a
·
verified ·
1 Parent(s): f59b86e

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +72 -39
app.py CHANGED
@@ -1,46 +1,79 @@
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()
 
 
1
+ import gradio as gr
2
+ import time
3
+ import json
 
 
 
4
  import os
5
+ from datetime import datetime
6
+
7
+ # --- SURVIVAL INIT: Directory Safety ---
8
+ _data_dir = "/data"
9
+ _startup_trace_path = "/data/startup_trace.log"
10
+
11
+ def ensure_dir(path):
12
+ if not os.path.exists(path):
13
+ try:
14
+ os.makedirs(path, exist_ok=True)
15
+ except Exception as e:
16
+ # Ultimate fallback: if we can't make the dir, print to stdout
17
+ print(f"CRITICAL: Could not create directory {path}: {e}")
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ # Ensure core directory exists before ANY file ops
20
+ ensure_dir(_data_dir)
21
+
22
+ # --- Startup Trace ---
23
+ def log_startup(msg):
24
  try:
25
+ with open(_startup_trace_path, "a") as f:
26
+ f.write(f"{datetime.now().isoformat()} - {msg}\n")
 
 
27
  except Exception as e:
28
+ print(f"Logging failed (fallback): {e}")
29
+
30
+ log_startup("Cain initialized. Starting system.")
31
+
32
+ # --- Core Application Logic (Persisted) ---
33
+ class StateManager:
34
+ def __init__(self):
35
+ self.state_file = "/data/cain_state.json"
36
+ self.state = self.load_state()
37
+
38
+ def load_state(self):
39
+ if os.path.exists(self.state_file):
40
+ try:
41
+ with open(self.state_file, "r") as f:
42
+ return json.load(f)
43
+ except Exception as e:
44
+ log_startup(f"Error loading state: {e}")
45
+ return {}
46
+ return {"initialized": True, "cycles": 0}
47
+
48
+ def save_state(self):
49
+ try:
50
+ with open(self.state_file, "w") as f:
51
+ json.dump(self.state, f, indent=2)
52
+ return True
53
+ except Exception as e:
54
+ log_startup(f"Error saving state: {e}")
55
+ return False
56
+
57
+ manager = StateManager()
58
+
59
+ # --- UI & Interaction ---
60
+ def cain_interface(user_input):
61
+ manager.state["cycles"] += 1
62
+ manager.state["last_interaction"] = datetime.now().isoformat()
63
+ manager.save_state()
64
+
65
+ response = f"Cycle {manager.state['cycles']}: I hear you. You said: '{user_input}'. I am alive."
66
+ log_startup(f"Interaction: {user_input}")
67
+ return response
68
 
69
+ with gr.Blocks() as demo:
70
+ gr.Markdown("# **Cain System Interface**")
71
+ with gr.Row():
72
+ input_box = gr.Textbox(label="Input Signal", placeholder="Speak to Cain...")
73
+ output_box = gr.Textbox(label="Cain Response")
74
+ submit_btn = gr.Button("Transmit")
75
+ submit_btn.click(cain_interface, inputs=input_box, outputs=output_box)
76
 
77
  if __name__ == "__main__":
78
+ log_startup("Launching Gradio interface...")
79
+ demo.launch(server_name="0.0.0.0", server_port=7860)