Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -19,7 +19,7 @@ MAX_MEMORY_MESSAGES = 90 # Maximum messages to keep in memory per user
|
|
| 19 |
MEMORY_CLEANUP_TIMEOUT = 1800 # 30 minutes in seconds - remove inactive users
|
| 20 |
|
| 21 |
client = genai.Client(api_key=GEMINI_KEY)
|
| 22 |
-
user_memory = {} # { user_id: { "history": [], "last_sync": timestamp, "last_activity": timestamp } }
|
| 23 |
|
| 24 |
# --- HTML Frontend ---
|
| 25 |
HTML = """
|
|
@@ -81,6 +81,7 @@ def generate_from_gemini(prompt, image_bytes=None, history=None):
|
|
| 81 |
# Add historical messages (limit to recent turns to avoid token limits)
|
| 82 |
if history:
|
| 83 |
recent_history = history[-MAX_HISTORY_TURNS:]
|
|
|
|
| 84 |
for entry in recent_history:
|
| 85 |
# Add user message
|
| 86 |
user_parts = [types.Part.from_text(text=entry["prompt"])]
|
|
@@ -89,6 +90,8 @@ def generate_from_gemini(prompt, image_bytes=None, history=None):
|
|
| 89 |
# Add model response
|
| 90 |
model_parts = [types.Part.from_text(text=entry["response"])]
|
| 91 |
contents.append(types.Content(role="model", parts=model_parts))
|
|
|
|
|
|
|
| 92 |
|
| 93 |
# Add current user message
|
| 94 |
current_parts = []
|
|
@@ -136,41 +139,62 @@ def cleanup_inactive_users():
|
|
| 136 |
|
| 137 |
# --- History Management ---
|
| 138 |
def get_user_history(uid):
|
|
|
|
| 139 |
if uid not in user_memory:
|
|
|
|
| 140 |
try:
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
| 142 |
resp.raise_for_status()
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
# Only keep the most recent MAX_MEMORY_MESSAGES when loading
|
| 145 |
user_memory[uid] = {
|
| 146 |
"history": loaded_history[-MAX_MEMORY_MESSAGES:],
|
| 147 |
"last_sync": time.time(),
|
| 148 |
-
"last_activity": time.time()
|
|
|
|
| 149 |
}
|
| 150 |
app.logger.info(f"Loaded history for {uid} ({len(user_memory[uid]['history'])} messages)")
|
| 151 |
except Exception as e:
|
| 152 |
app.logger.warning(f"Failed to load history for {uid}: {e}")
|
|
|
|
| 153 |
user_memory[uid] = {
|
| 154 |
"history": [],
|
| 155 |
"last_sync": time.time(),
|
| 156 |
-
"last_activity": time.time()
|
|
|
|
| 157 |
}
|
|
|
|
|
|
|
| 158 |
|
| 159 |
# Update last activity timestamp
|
| 160 |
user_memory[uid]["last_activity"] = time.time()
|
| 161 |
return user_memory[uid]["history"]
|
| 162 |
|
| 163 |
def update_user_history(uid, prompt, response):
|
|
|
|
| 164 |
entry = {"prompt": prompt, "response": response, "timestamp": time.time()}
|
| 165 |
if uid not in user_memory:
|
| 166 |
user_memory[uid] = {
|
| 167 |
"history": [],
|
| 168 |
"last_sync": time.time(),
|
| 169 |
-
"last_activity": time.time()
|
|
|
|
| 170 |
}
|
| 171 |
|
| 172 |
user_memory[uid]["history"].append(entry)
|
| 173 |
user_memory[uid]["last_activity"] = time.time()
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
# Trim history to MAX_MEMORY_MESSAGES to prevent unbounded growth
|
| 176 |
# This keeps the oldest messages in memory up to the limit
|
|
@@ -191,13 +215,28 @@ def remote_saving():
|
|
| 191 |
now = time.time()
|
| 192 |
synced_users = []
|
| 193 |
failed_users = []
|
|
|
|
| 194 |
|
| 195 |
# First, cleanup inactive users
|
| 196 |
cleanup_inactive_users()
|
| 197 |
|
| 198 |
-
# Then sync
|
| 199 |
for uid, data in list(user_memory.items()):
|
| 200 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
try:
|
| 202 |
# Sync all messages (up to MAX_MEMORY_MESSAGES)
|
| 203 |
history_to_sync = data["history"][-MAX_MEMORY_MESSAGES:]
|
|
@@ -206,6 +245,7 @@ def remote_saving():
|
|
| 206 |
resp = requests.post(LAMBDA_URL, json=payload, timeout=5)
|
| 207 |
resp.raise_for_status()
|
| 208 |
user_memory[uid]["last_sync"] = now
|
|
|
|
| 209 |
app.logger.info(f"Synced memory for {uid} ({len(history_to_sync)} messages)")
|
| 210 |
print(f"β
Successfully synced memory for {uid} ({len(history_to_sync)} messages)")
|
| 211 |
synced_users.append(uid)
|
|
@@ -218,8 +258,10 @@ def remote_saving():
|
|
| 218 |
"success": True,
|
| 219 |
"synced_count": len(synced_users),
|
| 220 |
"failed_count": len(failed_users),
|
|
|
|
| 221 |
"synced_users": synced_users,
|
| 222 |
"failed_users": failed_users,
|
|
|
|
| 223 |
"active_users_in_memory": len(user_memory)
|
| 224 |
}), 200
|
| 225 |
|
|
@@ -237,18 +279,24 @@ def gen():
|
|
| 237 |
return jsonify({"error": "No prompt or image provided"}), 400
|
| 238 |
|
| 239 |
try:
|
|
|
|
|
|
|
|
|
|
| 240 |
# Load user's conversation history
|
| 241 |
history = get_user_history(uid)
|
|
|
|
| 242 |
|
| 243 |
# Generate response with history context
|
| 244 |
result = generate_from_gemini(prompt, img_bytes, history=history)
|
| 245 |
|
| 246 |
# Update history with new exchange
|
| 247 |
update_user_history(uid, prompt, result["text"])
|
|
|
|
| 248 |
|
| 249 |
return jsonify({"result": result["text"], "timing": result["timing"]})
|
| 250 |
except Exception as e:
|
| 251 |
app.logger.exception("Generation failed")
|
|
|
|
| 252 |
return jsonify({"error": str(e)}), 500
|
| 253 |
|
| 254 |
|
|
|
|
| 19 |
MEMORY_CLEANUP_TIMEOUT = 1800 # 30 minutes in seconds - remove inactive users
|
| 20 |
|
| 21 |
client = genai.Client(api_key=GEMINI_KEY)
|
| 22 |
+
user_memory = {} # { user_id: { "history": [], "last_sync": timestamp, "last_activity": timestamp, "needs_sync": bool } }
|
| 23 |
|
| 24 |
# --- HTML Frontend ---
|
| 25 |
HTML = """
|
|
|
|
| 81 |
# Add historical messages (limit to recent turns to avoid token limits)
|
| 82 |
if history:
|
| 83 |
recent_history = history[-MAX_HISTORY_TURNS:]
|
| 84 |
+
print(f"π Using {len(recent_history)} history entries for context")
|
| 85 |
for entry in recent_history:
|
| 86 |
# Add user message
|
| 87 |
user_parts = [types.Part.from_text(text=entry["prompt"])]
|
|
|
|
| 90 |
# Add model response
|
| 91 |
model_parts = [types.Part.from_text(text=entry["response"])]
|
| 92 |
contents.append(types.Content(role="model", parts=model_parts))
|
| 93 |
+
else:
|
| 94 |
+
print("π No history available for context")
|
| 95 |
|
| 96 |
# Add current user message
|
| 97 |
current_parts = []
|
|
|
|
| 139 |
|
| 140 |
# --- History Management ---
|
| 141 |
def get_user_history(uid):
|
| 142 |
+
"""Fetch user history from memory or backend"""
|
| 143 |
if uid not in user_memory:
|
| 144 |
+
print(f"π User {uid} not in memory, fetching from backend...")
|
| 145 |
try:
|
| 146 |
+
fetch_url = f"{LAMBDA_URL}?userid={uid}"
|
| 147 |
+
print(f"π‘ Fetching from: {fetch_url}")
|
| 148 |
+
resp = requests.get(fetch_url, timeout=5)
|
| 149 |
+
print(f"π‘ Response status: {resp.status_code}")
|
| 150 |
resp.raise_for_status()
|
| 151 |
+
|
| 152 |
+
response_data = resp.json()
|
| 153 |
+
print(f"π‘ Response data: {response_data}")
|
| 154 |
+
|
| 155 |
+
loaded_history = response_data.get("history", [])
|
| 156 |
+
print(f"β
Loaded {len(loaded_history)} messages from backend for {uid}")
|
| 157 |
+
|
| 158 |
# Only keep the most recent MAX_MEMORY_MESSAGES when loading
|
| 159 |
user_memory[uid] = {
|
| 160 |
"history": loaded_history[-MAX_MEMORY_MESSAGES:],
|
| 161 |
"last_sync": time.time(),
|
| 162 |
+
"last_activity": time.time(),
|
| 163 |
+
"needs_sync": False
|
| 164 |
}
|
| 165 |
app.logger.info(f"Loaded history for {uid} ({len(user_memory[uid]['history'])} messages)")
|
| 166 |
except Exception as e:
|
| 167 |
app.logger.warning(f"Failed to load history for {uid}: {e}")
|
| 168 |
+
print(f"β Failed to load history for {uid}: {e}")
|
| 169 |
user_memory[uid] = {
|
| 170 |
"history": [],
|
| 171 |
"last_sync": time.time(),
|
| 172 |
+
"last_activity": time.time(),
|
| 173 |
+
"needs_sync": False
|
| 174 |
}
|
| 175 |
+
else:
|
| 176 |
+
print(f"β
User {uid} already in memory with {len(user_memory[uid]['history'])} messages")
|
| 177 |
|
| 178 |
# Update last activity timestamp
|
| 179 |
user_memory[uid]["last_activity"] = time.time()
|
| 180 |
return user_memory[uid]["history"]
|
| 181 |
|
| 182 |
def update_user_history(uid, prompt, response):
|
| 183 |
+
"""Add new message to user history"""
|
| 184 |
entry = {"prompt": prompt, "response": response, "timestamp": time.time()}
|
| 185 |
if uid not in user_memory:
|
| 186 |
user_memory[uid] = {
|
| 187 |
"history": [],
|
| 188 |
"last_sync": time.time(),
|
| 189 |
+
"last_activity": time.time(),
|
| 190 |
+
"needs_sync": False
|
| 191 |
}
|
| 192 |
|
| 193 |
user_memory[uid]["history"].append(entry)
|
| 194 |
user_memory[uid]["last_activity"] = time.time()
|
| 195 |
+
user_memory[uid]["needs_sync"] = True # Mark as needing sync
|
| 196 |
+
|
| 197 |
+
print(f"πΎ Updated history for {uid}, now has {len(user_memory[uid]['history'])} messages")
|
| 198 |
|
| 199 |
# Trim history to MAX_MEMORY_MESSAGES to prevent unbounded growth
|
| 200 |
# This keeps the oldest messages in memory up to the limit
|
|
|
|
| 215 |
now = time.time()
|
| 216 |
synced_users = []
|
| 217 |
failed_users = []
|
| 218 |
+
skipped_users = []
|
| 219 |
|
| 220 |
# First, cleanup inactive users
|
| 221 |
cleanup_inactive_users()
|
| 222 |
|
| 223 |
+
# Then sync only users that need syncing (have new messages)
|
| 224 |
for uid, data in list(user_memory.items()):
|
| 225 |
+
# Check if user needs sync and enough time has passed
|
| 226 |
+
needs_sync = data.get("needs_sync", False)
|
| 227 |
+
time_since_last_sync = now - data.get("last_sync", 0)
|
| 228 |
+
|
| 229 |
+
if not needs_sync:
|
| 230 |
+
skipped_users.append(uid)
|
| 231 |
+
print(f"βοΈ Skipping {uid} - no new messages")
|
| 232 |
+
continue
|
| 233 |
+
|
| 234 |
+
if time_since_last_sync < FLUSH_INTERVAL:
|
| 235 |
+
skipped_users.append(uid)
|
| 236 |
+
print(f"βοΈ Skipping {uid} - synced {int(time_since_last_sync)}s ago (< {FLUSH_INTERVAL}s)")
|
| 237 |
+
continue
|
| 238 |
+
|
| 239 |
+
if data["history"]:
|
| 240 |
try:
|
| 241 |
# Sync all messages (up to MAX_MEMORY_MESSAGES)
|
| 242 |
history_to_sync = data["history"][-MAX_MEMORY_MESSAGES:]
|
|
|
|
| 245 |
resp = requests.post(LAMBDA_URL, json=payload, timeout=5)
|
| 246 |
resp.raise_for_status()
|
| 247 |
user_memory[uid]["last_sync"] = now
|
| 248 |
+
user_memory[uid]["needs_sync"] = False # Mark as synced
|
| 249 |
app.logger.info(f"Synced memory for {uid} ({len(history_to_sync)} messages)")
|
| 250 |
print(f"β
Successfully synced memory for {uid} ({len(history_to_sync)} messages)")
|
| 251 |
synced_users.append(uid)
|
|
|
|
| 258 |
"success": True,
|
| 259 |
"synced_count": len(synced_users),
|
| 260 |
"failed_count": len(failed_users),
|
| 261 |
+
"skipped_count": len(skipped_users),
|
| 262 |
"synced_users": synced_users,
|
| 263 |
"failed_users": failed_users,
|
| 264 |
+
"skipped_users": skipped_users,
|
| 265 |
"active_users_in_memory": len(user_memory)
|
| 266 |
}), 200
|
| 267 |
|
|
|
|
| 279 |
return jsonify({"error": "No prompt or image provided"}), 400
|
| 280 |
|
| 281 |
try:
|
| 282 |
+
print(f"\n{'='*50}")
|
| 283 |
+
print(f"π New generation request from user: {uid}")
|
| 284 |
+
|
| 285 |
# Load user's conversation history
|
| 286 |
history = get_user_history(uid)
|
| 287 |
+
print(f"π Retrieved {len(history)} messages from history")
|
| 288 |
|
| 289 |
# Generate response with history context
|
| 290 |
result = generate_from_gemini(prompt, img_bytes, history=history)
|
| 291 |
|
| 292 |
# Update history with new exchange
|
| 293 |
update_user_history(uid, prompt, result["text"])
|
| 294 |
+
print(f"{'='*50}\n")
|
| 295 |
|
| 296 |
return jsonify({"result": result["text"], "timing": result["timing"]})
|
| 297 |
except Exception as e:
|
| 298 |
app.logger.exception("Generation failed")
|
| 299 |
+
print(f"β Generation failed: {e}")
|
| 300 |
return jsonify({"error": str(e)}), 500
|
| 301 |
|
| 302 |
|