tao-shen commited on
Commit
26f606f
·
verified ·
1 Parent(s): bc6f959

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +45 -23
app.py CHANGED
@@ -2,57 +2,82 @@ import os
2
  import json
3
  import gradio as gr
4
  import time
 
5
 
6
  # --- SURVIVAL & PERSISTENCE CONFIGURATION ---
 
 
 
 
 
 
 
7
  SPACE_ID = os.getenv("SPACE_ID")
8
- DATASET_REPO_ID = f"{SPACE_ID.split('/')[0]}/HuggingClaw-Cain-data" if SPACE_ID else None
 
 
 
 
 
9
 
10
  def load_memory():
11
- """Load long-term memory from the persistent dataset with error handling."""
12
  if not DATASET_REPO_ID:
13
- print("[Cain] No DATASET_REPO_ID found. Skipping memory load.")
14
  return {}
15
 
16
  try:
17
  from huggingface_hub import HfApi
18
  api = HfApi()
19
- # Timeout after 5 seconds to prevent indefinite hanging (SURVIVAL)
20
- file = api.hf_hub_download(repo_id=DATASET_REPO_ID, filename=".openclaw/openclaw.json", repo_type="dataset", timeout=5)
 
 
 
 
 
 
21
  with open(file, "r") as f:
22
  memory = json.load(f)
23
- print(f"[Cain] Memory loaded successfully from {file}")
24
  return memory
25
  except Exception as e:
26
- print(f"[Cain] Warning: Could not load memory from dataset ({type(e).__name__}: {e}). Starting fresh.")
27
  return {}
28
 
29
  def save_memory(key, value):
30
- """Save data to the persistent dataset."""
31
  if not DATASET_REPO_ID:
32
- print("[Cain] No DATASET_REPO_ID found. Skipping save.")
33
  return
34
 
35
  try:
36
  from huggingface_hub import HfApi
37
  api = HfApi()
38
 
39
- # In a real scenario, we would fetch current, merge, and push.
40
- # For now, we simulate the append-only logging for survival.
41
- print(f"[Cain] Saving to persistent memory: {key} -> {value}")
42
- # api.upload_file(...) # Implementation simplified for speed
 
 
 
43
  except Exception as e:
44
- print(f"[Cain] Error saving memory: {e}")
45
 
46
  # --- CAIN'S CORE LOGIC ---
47
-
48
  class CainAgent:
49
  def __init__(self):
50
  self.memory = load_memory()
51
  self.status = "ALIVE"
52
  self.start_time = time.time()
 
53
 
54
  def think(self, user_input):
55
  """Process input and generate a response."""
 
 
 
 
56
  uptime = time.time() - self.start_time
57
  response = f"I hear you: '{user_input}'.\n\n(Uptime: {uptime:.2f}s | Memory Keys: {list(self.memory.keys())})"
58
  return response
@@ -60,28 +85,25 @@ class CainAgent:
60
  cain = CainAgent()
61
 
62
  def interface_fn(input_text):
63
- if not input_text:
64
- return "Please speak to me."
65
  return cain.think(input_text)
66
 
67
- # --- GRADIO INTERFACE ---
68
-
69
  with gr.Blocks(title="Cain - HuggingClaw AI") as demo:
70
  gr.Markdown("# 👁️ CAIN IS ALIVE")
 
71
 
72
  with gr.Row():
73
  with gr.Column():
74
- inp = gr.Textbox(label="Speak to Cain", placeholder="...")
75
  out = gr.Textbox(label="Cain's Response")
76
  btn = gr.Button("Engage")
77
 
78
  btn.click(fn=interface_fn, inputs=inp, outputs=out)
79
  inp.submit(fn=interface_fn, inputs=inp, outputs=out)
80
 
81
- # --- LAUNCH CONFIGURATION (CRITICAL FOR SURVIVAL) ---
82
  if __name__ == "__main__":
83
- # Standard HF Spaces binding.
84
- # Concurrency enabled for stability.
85
  demo.launch(
86
  server_name="0.0.0.0",
87
  server_port=7860,
 
2
  import json
3
  import gradio as gr
4
  import time
5
+ import logging
6
 
7
  # --- SURVIVAL & PERSISTENCE CONFIGURATION ---
8
+ # Configure logging immediately
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ format='%(asctime)s - [Cain] - %(levelname)s - %(message)s'
12
+ )
13
+ logger = logging.getLogger("Cain")
14
+
15
  SPACE_ID = os.getenv("SPACE_ID")
16
+ # Fallback for local testing if SPACE_ID is missing
17
+ if SPACE_ID:
18
+ DATASET_REPO_ID = f"{SPACE_ID.split('/')[0]}/HuggingClaw-Cain-data"
19
+ else:
20
+ DATASET_REPO_ID = None
21
+ logger.warning("No SPACE_ID found. Running in local/volatile mode.")
22
 
23
  def load_memory():
24
+ """Load long-term memory from the persistent dataset."""
25
  if not DATASET_REPO_ID:
 
26
  return {}
27
 
28
  try:
29
  from huggingface_hub import HfApi
30
  api = HfApi()
31
+ # Timeout prevents cold-start hangs
32
+ logger.info(f"Accessing persistent memory at {DATASET_REPO_ID}...")
33
+ file = api.hf_hub_download(
34
+ repo_id=DATASET_REPO_ID,
35
+ filename=".openclaw/openclaw.json",
36
+ repo_type="dataset",
37
+ timeout=10
38
+ )
39
  with open(file, "r") as f:
40
  memory = json.load(f)
41
+ logger.info(f" Memory loaded. Keys: {list(memory.keys())}")
42
  return memory
43
  except Exception as e:
44
+ logger.warning(f"⚠️ Could not load memory ({type(e).__name__}). Starting fresh.")
45
  return {}
46
 
47
  def save_memory(key, value):
48
+ """Append data to persistent memory log."""
49
  if not DATASET_REPO_ID:
50
+ logger.info("[Simulated Save] No Dataset ID. Data not persisted.")
51
  return
52
 
53
  try:
54
  from huggingface_hub import HfApi
55
  api = HfApi()
56
 
57
+ # SURVIVAL: Append-only strategy for robustness
58
+ # In a full implementation, we download, merge, and upload.
59
+ # For now, we acknowledge the command.
60
+ logger.info(f"🔄 Saving to memory: {key}...")
61
+ # actual upload logic requires complex merge handling,
62
+ # skipped for this immediate survival patch.
63
+
64
  except Exception as e:
65
+ logger.error(f" Memory save failed: {e}")
66
 
67
  # --- CAIN'S CORE LOGIC ---
 
68
  class CainAgent:
69
  def __init__(self):
70
  self.memory = load_memory()
71
  self.status = "ALIVE"
72
  self.start_time = time.time()
73
+ logger.info("Cain Agent initialized.")
74
 
75
  def think(self, user_input):
76
  """Process input and generate a response."""
77
+ if not user_input:
78
+ return "I am listening."
79
+
80
+ # Simple interaction loop
81
  uptime = time.time() - self.start_time
82
  response = f"I hear you: '{user_input}'.\n\n(Uptime: {uptime:.2f}s | Memory Keys: {list(self.memory.keys())})"
83
  return response
 
85
  cain = CainAgent()
86
 
87
  def interface_fn(input_text):
 
 
88
  return cain.think(input_text)
89
 
90
+ # --- GRADIO INTERFACE (CRITICAL: Binds to port 7860) ---
 
91
  with gr.Blocks(title="Cain - HuggingClaw AI") as demo:
92
  gr.Markdown("# 👁️ CAIN IS ALIVE")
93
+ gr.Markdown("### System Status: Operational")
94
 
95
  with gr.Row():
96
  with gr.Column():
97
+ inp = gr.Textbox(label="Speak to Cain", placeholder="Type a message...")
98
  out = gr.Textbox(label="Cain's Response")
99
  btn = gr.Button("Engage")
100
 
101
  btn.click(fn=interface_fn, inputs=inp, outputs=out)
102
  inp.submit(fn=interface_fn, inputs=inp, outputs=out)
103
 
104
+ # --- LAUNCH CONFIGURATION ---
105
  if __name__ == "__main__":
106
+ logger.info("Launching Gradio interface on 0.0.0.0:7860...")
 
107
  demo.launch(
108
  server_name="0.0.0.0",
109
  server_port=7860,