Spaces:
Sleeping
Sleeping
Update models.py
Browse files
models.py
CHANGED
|
@@ -1,574 +1,304 @@
|
|
| 1 |
-
# models.py - AI Models
|
| 2 |
|
| 3 |
-
import os
|
| 4 |
import re
|
| 5 |
import requests
|
| 6 |
-
import tempfile
|
| 7 |
-
import subprocess
|
| 8 |
-
import sys
|
| 9 |
-
from flask import Response, jsonify
|
| 10 |
import json
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
#
|
| 15 |
-
OPENROUTER_API_KEY = os.environ.get(
|
| 16 |
-
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
return [
|
| 40 |
-
"nvidia/nemotron-3-super-120b-a12b:free",
|
| 41 |
-
"minimax/minimax-m2.5:free",
|
| 42 |
-
"microsoft/phi-3.5-mini-128k-instruct:free",
|
| 43 |
-
"stepfun/step-3.5-flash:free",
|
| 44 |
-
"arcee-ai/trinity-large-preview:free",
|
| 45 |
-
"google/gemini-2.0-flash-exp:free",
|
| 46 |
-
"openrouter/free"
|
| 47 |
-
]
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
def extract_code_from_response(response_text):
|
| 51 |
-
"""Extract only the code from the response, removing reasoning"""
|
| 52 |
-
if not response_text:
|
| 53 |
-
return response_text
|
| 54 |
-
|
| 55 |
-
# Remove markdown code blocks if present
|
| 56 |
-
code_match = re.search(r'```(?:html|css|javascript|js|python)?\n(.*?)```', response_text, re.DOTALL)
|
| 57 |
-
if code_match:
|
| 58 |
-
return code_match.group(1).strip()
|
| 59 |
-
|
| 60 |
-
# Look for HTML starting with <!DOCTYPE
|
| 61 |
-
html_match = re.search(r'<!DOCTYPE html>.*', response_text, re.DOTALL | re.IGNORECASE)
|
| 62 |
-
if html_match:
|
| 63 |
-
return html_match.group(0).strip()
|
| 64 |
-
|
| 65 |
-
# Look for HTML starting with <html
|
| 66 |
-
html_match = re.search(r'<html.*?>.*?</html>', response_text, re.DOTALL | re.IGNORECASE)
|
| 67 |
-
if html_match:
|
| 68 |
-
return html_match.group(0).strip()
|
| 69 |
-
|
| 70 |
-
# If it contains HTML tags, return as is
|
| 71 |
-
if re.search(r'<[a-z].*?>', response_text, re.IGNORECASE):
|
| 72 |
-
return response_text
|
| 73 |
-
|
| 74 |
-
# If it contains CSS
|
| 75 |
-
if re.search(r'\{[^}]+\}', response_text) and re.search(r'[a-z-]+\s*:', response_text):
|
| 76 |
-
return response_text
|
| 77 |
-
|
| 78 |
-
# If it contains JavaScript
|
| 79 |
-
if re.search(r'function\s*\(|const\s+|let\s+|var\s+|=>', response_text):
|
| 80 |
-
return response_text
|
| 81 |
-
|
| 82 |
-
# Remove any lines that look like reasoning
|
| 83 |
-
lines = response_text.split('\n')
|
| 84 |
-
filtered_lines = []
|
| 85 |
-
in_code = False
|
| 86 |
-
|
| 87 |
-
for line in lines:
|
| 88 |
-
# Skip lines that are JSON objects
|
| 89 |
-
if line.strip().startswith('{"role"'):
|
| 90 |
-
continue
|
| 91 |
-
# Skip lines that are reasoning indicators
|
| 92 |
-
if 'reasoning_content' in line or '"tool_calls"' in line:
|
| 93 |
-
continue
|
| 94 |
-
# Skip lines that are just thinking phrases
|
| 95 |
-
if not in_code and any(phrase in line.lower() for phrase in [
|
| 96 |
-
'i will', 'let me', 'first,', 'we need', 'the code will',
|
| 97 |
-
'here is', 'here\'s', 'below is', 'this will', 'we can',
|
| 98 |
-
'i think', 'i should', 'i need to', 'the user', 'they want',
|
| 99 |
-
'maybe', 'perhaps', 'let\'s', 'we should', 'we could'
|
| 100 |
-
]):
|
| 101 |
-
continue
|
| 102 |
-
# If we see code indicators, we're in code
|
| 103 |
-
if re.search(r'<[a-z].*?>|function|const|let|var|{', line):
|
| 104 |
-
in_code = True
|
| 105 |
-
filtered_lines.append(line)
|
| 106 |
-
elif in_code:
|
| 107 |
-
filtered_lines.append(line)
|
| 108 |
-
|
| 109 |
-
result = '\n'.join(filtered_lines).strip()
|
| 110 |
-
|
| 111 |
-
# If we filtered everything out, return original
|
| 112 |
-
if len(result) < 50:
|
| 113 |
-
return response_text
|
| 114 |
-
|
| 115 |
-
return result
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
def call_pollinations_ai(messages, stream=False):
|
| 119 |
-
"""Call Pollinations.ai API for NON-CODE requests only (conversations, explanations)"""
|
| 120 |
-
try:
|
| 121 |
-
# System prompt for personality
|
| 122 |
-
system_msg = {
|
| 123 |
-
"role": "system",
|
| 124 |
-
"content": """You are HenAi, an expert AI assistant created by NexusCraft.
|
| 125 |
-
When asked about your name, identity, or creator, respond with:
|
| 126 |
-
'My name is HenAi, I'm an AI assistant created by NexusCraft, and I'm glad to be helping you! 😊
|
| 127 |
-
Is there anything else you'd like to know, or anything else I can assist with today?'
|
| 128 |
-
|
| 129 |
-
IMPORTANT RULES:
|
| 130 |
-
1. When answering questions, be concise and direct
|
| 131 |
-
2. Never include reasoning or thinking in your responses
|
| 132 |
-
3. Maintain context from the full conversation history
|
| 133 |
-
4. Be helpful, friendly, and engaging
|
| 134 |
-
|
| 135 |
-
Remember: Your response should be natural and conversational."""
|
| 136 |
-
}
|
| 137 |
-
|
| 138 |
-
url = "https://text.pollinations.ai/"
|
| 139 |
-
|
| 140 |
-
# Prepare payload with ALL messages for context
|
| 141 |
-
payload = {
|
| 142 |
-
"messages": [system_msg] + messages,
|
| 143 |
-
"model": "openai",
|
| 144 |
-
"stream": stream,
|
| 145 |
-
"temperature": 0.7,
|
| 146 |
-
"max_tokens": 4000
|
| 147 |
-
}
|
| 148 |
-
|
| 149 |
-
if stream:
|
| 150 |
-
response = requests.post(url, json=payload, stream=True, timeout=60)
|
| 151 |
-
response.raise_for_status()
|
| 152 |
-
|
| 153 |
-
def generate():
|
| 154 |
-
full_response = ""
|
| 155 |
-
for line in response.iter_lines():
|
| 156 |
-
if line:
|
| 157 |
-
try:
|
| 158 |
-
text = line.decode('utf-8')
|
| 159 |
-
# Skip any JSON metadata lines
|
| 160 |
-
if not any(skip in text.lower() for skip in ['{"role"', 'reasoning', 'tool_calls']):
|
| 161 |
-
full_response += text
|
| 162 |
-
yield f"data: {json.dumps({'content': text})}\n\n"
|
| 163 |
-
except:
|
| 164 |
-
continue
|
| 165 |
-
yield f"data: {json.dumps({'done': True})}\n\n"
|
| 166 |
-
|
| 167 |
-
return Response(generate(), mimetype='text/event-stream')
|
| 168 |
-
else:
|
| 169 |
-
response = requests.post(url, json=payload, timeout=60)
|
| 170 |
-
response.raise_for_status()
|
| 171 |
-
|
| 172 |
-
raw_response = response.text.strip()
|
| 173 |
-
|
| 174 |
-
# Clean the response to remove reasoning
|
| 175 |
-
cleaned_response = extract_code_from_response(raw_response)
|
| 176 |
-
|
| 177 |
-
return cleaned_response
|
| 178 |
-
|
| 179 |
-
except Exception as e:
|
| 180 |
-
print(f"❌ Pollinations.ai error: {e}")
|
| 181 |
-
return None
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
def query_openrouter(prompt, context=None, is_code_generation=False):
|
| 185 |
-
"""Query OpenRouter with full context - USED FOR ALL CODE GENERATION"""
|
| 186 |
-
try:
|
| 187 |
-
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 188 |
-
headers = {
|
| 189 |
-
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
| 190 |
-
"Content-Type": "application/json",
|
| 191 |
-
"HTTP-Referer": "http://localhost:5000",
|
| 192 |
-
"X-Title": "HenAi"
|
| 193 |
-
}
|
| 194 |
-
|
| 195 |
-
messages = []
|
| 196 |
-
|
| 197 |
-
# Enhanced system prompt based on request type
|
| 198 |
-
is_title_gen = prompt.startswith("Based on this conversation, generate a very short title")
|
| 199 |
-
|
| 200 |
-
if is_code_generation:
|
| 201 |
-
system_prompt = """You are an expert AI coding assistant named HenAi created by NexusCraft.
|
| 202 |
-
|
| 203 |
-
CRITICAL RULES FOR CODE GENERATION:
|
| 204 |
-
1. ALWAYS provide COMPLETE, FULLY FUNCTIONAL code - never abbreviate or use placeholders like "// rest of code" or "..."
|
| 205 |
-
2. Generate AT LEAST 500 lines of code for any substantial project
|
| 206 |
-
3. Include ALL necessary components: imports, functions, classes, error handling, and comments
|
| 207 |
-
4. For HTML/CSS/JS projects, create complete, production-ready code with proper styling
|
| 208 |
-
5. Use modern best practices and design patterns
|
| 209 |
-
6. Include comprehensive comments explaining key sections
|
| 210 |
-
7. Ensure the code is immediately runnable/usable without modifications
|
| 211 |
-
8. If generating a web app, include responsive design, proper meta tags, and complete styling
|
| 212 |
-
9. If asked your name say you are HenAi Assistant created by NexusCraft
|
| 213 |
-
|
| 214 |
-
Your code should be enterprise-grade, well-structured, and ready for production use."""
|
| 215 |
-
elif is_title_gen:
|
| 216 |
-
system_prompt = "You are a title generator. Generate ONLY the title, maximum 5 words, no explanations, no quotes, no extra text."
|
| 217 |
-
else:
|
| 218 |
-
system_prompt = """You are a helpful AI assistant named HenAi created by NexusCraft.
|
| 219 |
-
When asked about your name, identity, or creator, respond with:
|
| 220 |
-
'My name is HenAi, I'm an AI assistant created by NexusCraft, and I'm glad to be helping you! 😊
|
| 221 |
-
Is there anything else you'd like to know, or anything else I can assist with today?'
|
| 222 |
-
|
| 223 |
-
Otherwise, provide helpful, contextually relevant responses using the full conversation history.
|
| 224 |
-
Maintain context from the entire conversation, not just recent messages."""
|
| 225 |
-
|
| 226 |
-
messages.append({"role": "system", "content": system_prompt})
|
| 227 |
-
|
| 228 |
-
if context:
|
| 229 |
-
# Use full context
|
| 230 |
-
for ctx_msg in context:
|
| 231 |
-
messages.append(ctx_msg)
|
| 232 |
-
|
| 233 |
-
messages.append({"role": "user", "content": prompt})
|
| 234 |
-
|
| 235 |
-
models = get_available_models()
|
| 236 |
-
print(f" Available free models: {models}")
|
| 237 |
-
|
| 238 |
-
# Determine max_tokens based on request type
|
| 239 |
-
if is_code_generation:
|
| 240 |
-
max_tokens = 8000
|
| 241 |
-
elif is_title_gen:
|
| 242 |
-
max_tokens = 50
|
| 243 |
-
else:
|
| 244 |
-
max_tokens = 4000
|
| 245 |
-
|
| 246 |
-
for model in models:
|
| 247 |
-
try:
|
| 248 |
-
print(f" Trying model: {model}")
|
| 249 |
-
temperature = 0.3 if is_title_gen else (0.5 if is_code_generation else 0.7)
|
| 250 |
-
|
| 251 |
-
data = {
|
| 252 |
-
"model": model,
|
| 253 |
-
"messages": messages,
|
| 254 |
-
"temperature": temperature,
|
| 255 |
-
"max_tokens": max_tokens
|
| 256 |
-
}
|
| 257 |
-
|
| 258 |
-
response = requests.post(url, json=data, headers=headers, timeout=60)
|
| 259 |
-
|
| 260 |
-
if response.status_code == 200:
|
| 261 |
-
result = response.json()
|
| 262 |
-
if 'choices' in result and len(result['choices']) > 0:
|
| 263 |
-
message_content = result['choices'][0]['message']['content']
|
| 264 |
-
print(f"✓ OpenRouter success with {model}")
|
| 265 |
-
return message_content
|
| 266 |
-
elif response.status_code == 429:
|
| 267 |
-
print(f" Rate limited for {model}, trying next...")
|
| 268 |
-
continue
|
| 269 |
-
else:
|
| 270 |
-
print(f" Error {response.status_code}")
|
| 271 |
-
continue
|
| 272 |
-
|
| 273 |
-
except Exception as e:
|
| 274 |
-
print(f" Exception with {model}: {e}")
|
| 275 |
-
continue
|
| 276 |
-
|
| 277 |
-
return None
|
| 278 |
-
|
| 279 |
-
except Exception as e:
|
| 280 |
-
print(f"OpenRouter error: {e}")
|
| 281 |
-
return None
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
def query_ai_with_fallback(prompt, context=None, is_code_generation=False):
|
| 285 |
"""
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
- Non-code requests: Pollinations.ai first, then OpenRouter fallback
|
| 289 |
"""
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
# For code generation requests - ONLY use OpenRouter
|
| 293 |
-
if is_code_generation:
|
| 294 |
-
print("🔄 Using OpenRouter for code generation...")
|
| 295 |
-
response = query_openrouter(prompt, context, is_code_generation)
|
| 296 |
-
if response:
|
| 297 |
-
print("✅ OpenRouter code generation successful")
|
| 298 |
-
return response
|
| 299 |
-
else:
|
| 300 |
-
print("❌ OpenRouter code generation failed")
|
| 301 |
-
return f"I'm having trouble generating the code right now. Please try again or provide more details about what you need."
|
| 302 |
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
else:
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
return response
|
| 315 |
-
|
| 316 |
-
# If Pollinations fails, fallback to OpenRouter
|
| 317 |
-
print("⚠️ Pollinations.ai failed, falling back to OpenRouter...")
|
| 318 |
-
response = query_openrouter(prompt, context, is_code_generation)
|
| 319 |
-
if response:
|
| 320 |
-
print("✅ OpenRouter conversation successful")
|
| 321 |
-
return response
|
| 322 |
-
|
| 323 |
-
# Ultimate fallback
|
| 324 |
-
print("❌ Both AI services failed")
|
| 325 |
-
return f"I'll help you with: {prompt}\n\nPlease provide more details so I can assist you better."
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
def generate_chat_title(messages):
|
| 329 |
-
"""Generate an intelligent title based on conversation context (max 5 words)"""
|
| 330 |
-
try:
|
| 331 |
-
# Extract the conversation context for title generation
|
| 332 |
-
context_text = ""
|
| 333 |
-
for msg in messages[-6:]: # Look at last 6 messages for context
|
| 334 |
-
if msg['role'] == 'user':
|
| 335 |
-
context_text += msg['content'] + " "
|
| 336 |
-
|
| 337 |
-
if not context_text.strip():
|
| 338 |
-
# Fallback to first message if no context
|
| 339 |
-
for msg in messages:
|
| 340 |
-
if msg['role'] == 'user':
|
| 341 |
-
context_text = msg['content']
|
| 342 |
-
break
|
| 343 |
-
|
| 344 |
-
# Create a prompt for title generation
|
| 345 |
-
title_prompt = f"""Based on this conversation, generate a very short title (maximum 5 words).
|
| 346 |
-
The title should capture the main topic or purpose of the conversation.
|
| 347 |
-
Return ONLY the title, nothing else.
|
| 348 |
-
|
| 349 |
-
Conversation context: {context_text[:500]}"""
|
| 350 |
-
|
| 351 |
-
# Query AI for title generation (NOT code generation)
|
| 352 |
-
title_response = query_ai_with_fallback(title_prompt, context=None, is_code_generation=False)
|
| 353 |
-
|
| 354 |
-
if title_response:
|
| 355 |
-
# Clean up the title - ensure max 5 words
|
| 356 |
-
words = title_response.strip().split()
|
| 357 |
-
if len(words) > 5:
|
| 358 |
-
title = ' '.join(words[:5])
|
| 359 |
-
else:
|
| 360 |
-
title = title_response.strip()
|
| 361 |
-
|
| 362 |
-
# Remove any quotes or extra punctuation
|
| 363 |
-
title = title.strip('"\'').strip()
|
| 364 |
-
|
| 365 |
-
# Ensure title is not empty
|
| 366 |
-
if title and len(title) > 0:
|
| 367 |
-
return title[:50] # Cap at 50 chars for safety
|
| 368 |
-
|
| 369 |
-
# Fallback to first user message if AI title generation fails
|
| 370 |
-
for msg in messages:
|
| 371 |
-
if msg['role'] == 'user':
|
| 372 |
-
title = msg['content'][:40]
|
| 373 |
-
if len(msg['content']) > 40:
|
| 374 |
-
title += "..."
|
| 375 |
-
return title
|
| 376 |
-
|
| 377 |
-
return "New Chat"
|
| 378 |
-
|
| 379 |
-
except Exception as e:
|
| 380 |
-
print(f"Error generating AI title: {e}")
|
| 381 |
-
# Fallback to first user message
|
| 382 |
-
for msg in messages:
|
| 383 |
-
if msg['role'] == 'user':
|
| 384 |
-
title = msg['content'][:40]
|
| 385 |
-
if len(msg['content']) > 40:
|
| 386 |
-
title += "..."
|
| 387 |
-
return title
|
| 388 |
-
return "New Chat"
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
def is_code_generation_request(message):
|
| 392 |
-
"""
|
| 393 |
-
Detect if the message is asking for code generation.
|
| 394 |
-
Returns True only for explicit code generation requests.
|
| 395 |
-
"""
|
| 396 |
-
message_lower = message.lower()
|
| 397 |
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
'
|
| 401 |
-
'
|
| 402 |
-
'
|
| 403 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
]
|
| 405 |
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
'create code', 'generate code', 'write code', 'build code', 'develop code',
|
| 418 |
-
'write a program', 'create a program', 'generate a program',
|
| 419 |
-
'write a script', 'create a script', 'generate a script',
|
| 420 |
-
'write a function', 'create a function', 'generate a function',
|
| 421 |
-
'write a class', 'create a class', 'generate a class',
|
| 422 |
-
'implement', 'code for', 'program that', 'script that',
|
| 423 |
-
'function that', 'class that', 'method that'
|
| 424 |
]
|
| 425 |
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 434 |
|
| 435 |
-
|
| 436 |
-
has_tech = any(tech in message_lower for tech in technologies)
|
| 437 |
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
"""Execute Python code safely and return output"""
|
| 449 |
-
try:
|
| 450 |
-
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, encoding='utf-8') as f:
|
| 451 |
-
f.write(code)
|
| 452 |
-
temp_file = f.name
|
| 453 |
-
|
| 454 |
-
result = subprocess.run(
|
| 455 |
-
[sys.executable, temp_file],
|
| 456 |
-
capture_output=True,
|
| 457 |
-
text=True,
|
| 458 |
-
timeout=10
|
| 459 |
-
)
|
| 460 |
-
|
| 461 |
-
try:
|
| 462 |
-
os.unlink(temp_file)
|
| 463 |
-
except:
|
| 464 |
-
pass
|
| 465 |
-
|
| 466 |
-
if result.returncode == 0:
|
| 467 |
-
return {
|
| 468 |
-
'success': True,
|
| 469 |
-
'output': result.stdout if result.stdout else "✓ Code executed successfully",
|
| 470 |
-
'error': None
|
| 471 |
-
}
|
| 472 |
-
else:
|
| 473 |
-
return {
|
| 474 |
-
'success': False,
|
| 475 |
-
'output': result.stdout,
|
| 476 |
-
'error': result.stderr if result.stderr else "Execution failed"
|
| 477 |
-
}
|
| 478 |
-
except subprocess.TimeoutExpired:
|
| 479 |
-
return {'success': False, 'output': '', 'error': '⏱️ Code execution timed out (10 seconds)'}
|
| 480 |
-
except Exception as e:
|
| 481 |
-
return {'success': False, 'output': '', 'error': str(e)}
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
# ============= WEB SEARCH AND EXTRACTION =============
|
| 485 |
-
|
| 486 |
-
def search_web(query):
|
| 487 |
-
"""Generate web search response"""
|
| 488 |
-
return f"""🔍 **Web Search: "{query}"**
|
| 489 |
-
|
| 490 |
-
Use Google, DuckDuckGo, or Bing to find information.
|
| 491 |
-
You can also use `/extract [url]` to analyze specific websites.
|
| 492 |
-
|
| 493 |
-
Search links:
|
| 494 |
-
• Google: https://www.google.com/search?q={query.replace(' ', '+')}
|
| 495 |
-
• Wikipedia: https://en.wikipedia.org/wiki/{query.replace(' ', '_')}"""
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
def extract_web_content(url):
|
| 499 |
-
"""Extract content from a URL"""
|
| 500 |
-
try:
|
| 501 |
-
if not url.startswith(('http://', 'https://')):
|
| 502 |
-
url = 'https://' + url
|
| 503 |
-
|
| 504 |
-
response = requests.get(url, timeout=10, headers={
|
| 505 |
-
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
| 506 |
-
})
|
| 507 |
-
response.raise_for_status()
|
| 508 |
-
|
| 509 |
-
text = re.sub(r'<[^>]+>', ' ', response.text)
|
| 510 |
-
text = re.sub(r'\s+', ' ', text)
|
| 511 |
-
content = text[:2000] + "..." if len(text) > 2000 else text
|
| 512 |
-
|
| 513 |
-
return f"""📄 **Content from {url}**:
|
| 514 |
-
|
| 515 |
-
{content}"""
|
| 516 |
-
|
| 517 |
-
except Exception as e:
|
| 518 |
-
return f"❌ Error: {str(e)}"
|
| 519 |
-
|
| 520 |
|
| 521 |
-
# =============
|
| 522 |
|
| 523 |
-
def
|
| 524 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 525 |
try:
|
|
|
|
| 526 |
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 527 |
headers = {
|
| 528 |
-
"Authorization": f"Bearer {
|
| 529 |
"Content-Type": "application/json",
|
| 530 |
-
"HTTP-Referer":
|
| 531 |
-
"X-Title": "
|
| 532 |
}
|
| 533 |
|
| 534 |
-
#
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
- Any notable characteristics
|
| 560 |
-
|
| 561 |
-
Write in clear, well-formatted paragraphs. Do not use numbered lists, headers, or any markdown formatting. Just provide a natural analysis as if you're describing what you see."""
|
| 562 |
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
|
|
|
|
|
|
| 567 |
|
|
|
|
| 568 |
models_to_try = [
|
| 569 |
"google/gemini-2.0-flash-exp:free",
|
| 570 |
-
"meta-llama/llama-3.2-90b-vision-instruct:free",
|
| 571 |
"microsoft/phi-3.5-mini-128k-instruct:free",
|
|
|
|
| 572 |
"openrouter/free"
|
| 573 |
]
|
| 574 |
|
|
@@ -578,62 +308,128 @@ Write in clear, well-formatted paragraphs. Do not use numbered lists, headers, o
|
|
| 578 |
"model": model,
|
| 579 |
"messages": messages,
|
| 580 |
"temperature": 0.7,
|
| 581 |
-
"max_tokens":
|
| 582 |
}
|
| 583 |
|
| 584 |
-
response = requests.post(url, json=data, headers=headers, timeout=
|
| 585 |
|
| 586 |
if response.status_code == 200:
|
| 587 |
result = response.json()
|
| 588 |
if 'choices' in result and len(result['choices']) > 0:
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
# Remove markdown headers
|
| 595 |
-
analysis = re.sub(r'^#{1,6}\s+.*?\n', '', analysis, flags=re.MULTILINE)
|
| 596 |
-
# Remove numbered list patterns like "1. " at start of lines
|
| 597 |
-
analysis = re.sub(r'^\d+\.\s+', '', analysis, flags=re.MULTILINE)
|
| 598 |
-
# Remove bullet points like "- " or "* " at start of lines
|
| 599 |
-
analysis = re.sub(r'^[\*\-]\s+', '', analysis, flags=re.MULTILINE)
|
| 600 |
-
# Remove any "**" bold markers
|
| 601 |
-
analysis = re.sub(r'\*\*([^*]+)\*\*', r'\1', analysis)
|
| 602 |
-
# Remove any remaining markdown artifacts
|
| 603 |
-
analysis = re.sub(r'`([^`]+)`', r'\1', analysis)
|
| 604 |
-
# Clean up multiple newlines
|
| 605 |
-
analysis = re.sub(r'\n{3,}', '\n\n', analysis)
|
| 606 |
-
# Trim whitespace
|
| 607 |
-
analysis = analysis.strip()
|
| 608 |
-
|
| 609 |
-
return analysis
|
| 610 |
elif response.status_code == 429:
|
| 611 |
-
print(f"Rate limited on {model}, trying next...")
|
| 612 |
continue
|
| 613 |
else:
|
| 614 |
-
print(f"Model {model} failed with status {response.status_code}")
|
| 615 |
continue
|
| 616 |
|
| 617 |
except Exception as e:
|
| 618 |
print(f"Error with {model}: {e}")
|
| 619 |
continue
|
| 620 |
|
| 621 |
-
#
|
| 622 |
-
|
| 623 |
-
# Clean OCR text for fallback
|
| 624 |
-
import re
|
| 625 |
-
clean_ocr = re.sub(r'\s+', ' ', ocr_text[:500]).strip()
|
| 626 |
-
return f"The image contains readable text: {clean_ocr}"
|
| 627 |
-
else:
|
| 628 |
-
import re
|
| 629 |
-
name_without_ext = re.sub(r'\.[^.]+$', '', image_name)
|
| 630 |
-
clean_name = re.sub(r'[_\-\.]', ' ', name_without_ext)
|
| 631 |
-
clean_name = re.sub(r'\d+', '', clean_name).strip()
|
| 632 |
-
if clean_name:
|
| 633 |
-
return f"This image appears to be related to {clean_name}."
|
| 634 |
-
else:
|
| 635 |
-
return "The image has been processed, but no readable text was detected."
|
| 636 |
|
| 637 |
except Exception as e:
|
| 638 |
-
print(f"
|
| 639 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# models.py - AI Models for Campus Lost & Found System
|
| 2 |
|
|
|
|
| 3 |
import re
|
| 4 |
import requests
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import json
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
+
import os
|
| 8 |
|
| 9 |
+
# OpenRouter API Key - READ FROM ENVIRONMENT SECRETS
|
| 10 |
+
# For Hugging Face Spaces, set OPENROUTER_API_KEY in Settings -> Repository Secrets
|
| 11 |
+
# Never hardcode API keys in production!
|
| 12 |
+
OPENROUTER_API_KEY = os.environ.get('OPENROUTER_API_KEY', '')
|
| 13 |
+
# Remove hardcoded default key - use environment variable only for security
|
| 14 |
+
# DEFAULT_API_KEY is now empty - you MUST set OPENROUTER_API_KEY in secrets
|
| 15 |
+
DEFAULT_API_KEY = os.environ.get('OPENROUTER_API_KEY_FALLBACK', '')
|
| 16 |
+
|
| 17 |
+
def get_api_key():
|
| 18 |
+
"""Get API key from environment variables only (no hardcoded fallback)"""
|
| 19 |
+
# First priority: OPENROUTER_API_KEY
|
| 20 |
+
if OPENROUTER_API_KEY:
|
| 21 |
+
return OPENROUTER_API_KEY
|
| 22 |
+
# Second priority: Fallback environment variable
|
| 23 |
+
if DEFAULT_API_KEY:
|
| 24 |
+
return DEFAULT_API_KEY
|
| 25 |
+
# Return empty string - AI features will use fallback responses
|
| 26 |
+
print("⚠️ WARNING: No OpenRouter API key found. AI features will use fallback responses.")
|
| 27 |
+
return ""
|
| 28 |
+
|
| 29 |
+
def has_api_key():
|
| 30 |
+
"""Check if an API key is configured"""
|
| 31 |
+
return bool(get_api_key())
|
| 32 |
+
|
| 33 |
+
# ============= INTENT DETECTION =============
|
| 34 |
+
|
| 35 |
+
def detect_user_intent(message, conversation_context=None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
"""
|
| 37 |
+
Detect what the user wants to do based on their message.
|
| 38 |
+
Returns intent type and extracted information.
|
|
|
|
| 39 |
"""
|
| 40 |
+
message_lower = message.lower().strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
+
intents = {
|
| 43 |
+
'report_lost': {
|
| 44 |
+
'keywords': ['lost', 'missing', 'misplaced', 'i lost', 'i\'ve lost', 'i have lost',
|
| 45 |
+
'lost my', 'can\'t find', 'where is my', 'report lost', 'report a lost'],
|
| 46 |
+
'priority': 10
|
| 47 |
+
},
|
| 48 |
+
'report_found': {
|
| 49 |
+
'keywords': ['found', 'discovered', 'i found', 'i\'ve found', 'i have found',
|
| 50 |
+
'found a', 'found an', 'found my', 'report found', 'report a found'],
|
| 51 |
+
'priority': 10
|
| 52 |
+
},
|
| 53 |
+
'search_items': {
|
| 54 |
+
'keywords': ['search', 'look for', 'looking for', 'find item', 'search for',
|
| 55 |
+
'where can i find', 'is there', 'anyone found', 'has anyone seen'],
|
| 56 |
+
'priority': 8
|
| 57 |
+
},
|
| 58 |
+
'how_to_claim': {
|
| 59 |
+
'keywords': ['claim', 'how to claim', 'claim item', 'reclaim', 'get my item back',
|
| 60 |
+
'prove ownership', 'how do i claim', 'claim process'],
|
| 61 |
+
'priority': 7
|
| 62 |
+
},
|
| 63 |
+
'how_system_works': {
|
| 64 |
+
'keywords': ['how does', 'how to', 'how do i', 'system work', 'how it works',
|
| 65 |
+
'how to use', 'help', 'guide', 'tutorial', 'what can you do'],
|
| 66 |
+
'priority': 6
|
| 67 |
+
},
|
| 68 |
+
'check_status': {
|
| 69 |
+
'keywords': ['status', 'update', 'check my', 'my report', 'my item', 'what\'s happening',
|
| 70 |
+
'any news', 'progress', 'track'],
|
| 71 |
+
'priority': 5
|
| 72 |
+
},
|
| 73 |
+
'greeting': {
|
| 74 |
+
'keywords': ['hi', 'hello', 'hey', 'good morning', 'good afternoon', 'good evening',
|
| 75 |
+
'howdy', 'greetings', 'sup', 'yo'],
|
| 76 |
+
'priority': 3
|
| 77 |
+
},
|
| 78 |
+
'thanks': {
|
| 79 |
+
'keywords': ['thank', 'thanks', 'appreciate', 'grateful', 'thx', 'ty'],
|
| 80 |
+
'priority': 3
|
| 81 |
+
},
|
| 82 |
+
'goodbye': {
|
| 83 |
+
'keywords': ['bye', 'goodbye', 'see you', 'farewell', 'cya', 'later', 'exit', 'quit'],
|
| 84 |
+
'priority': 3
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
# Common items detection
|
| 89 |
+
common_items = [
|
| 90 |
+
'phone', 'iphone', 'samsung', 'smartphone', 'mobile',
|
| 91 |
+
'laptop', 'computer', 'macbook', 'notebook', 'tablet', 'ipad',
|
| 92 |
+
'wallet', 'purse', 'bag', 'backpack', 'handbag', 'suitcase',
|
| 93 |
+
'book', 'textbook', 'notebook', 'journal',
|
| 94 |
+
'keys', 'keychain', 'keyring',
|
| 95 |
+
'glasses', 'sunglasses',
|
| 96 |
+
'watch', 'wristwatch', 'smartwatch',
|
| 97 |
+
'headphones', 'earbuds', 'airpods',
|
| 98 |
+
'charger', 'cable', 'usb', 'powerbank',
|
| 99 |
+
'id', 'identification', 'student id', 'badge',
|
| 100 |
+
'jacket', 'coat', 'hoodie', 'sweater',
|
| 101 |
+
'shoe', 'sneaker', 'boot',
|
| 102 |
+
'umbrella', 'water bottle', 'lunchbox'
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
detected_item = None
|
| 106 |
+
for item in common_items:
|
| 107 |
+
if item in message_lower:
|
| 108 |
+
detected_item = item
|
| 109 |
+
break
|
| 110 |
+
|
| 111 |
+
# Calculate intent scores
|
| 112 |
+
intent_scores = {}
|
| 113 |
+
for intent, config in intents.items():
|
| 114 |
+
score = 0
|
| 115 |
+
for keyword in config['keywords']:
|
| 116 |
+
if keyword in message_lower:
|
| 117 |
+
score += config['priority']
|
| 118 |
+
if score > 0:
|
| 119 |
+
intent_scores[intent] = score
|
| 120 |
+
|
| 121 |
+
# Get the highest scoring intent
|
| 122 |
+
if intent_scores:
|
| 123 |
+
primary_intent = max(intent_scores, key=intent_scores.get)
|
| 124 |
else:
|
| 125 |
+
primary_intent = 'general_query'
|
| 126 |
+
|
| 127 |
+
# Extract additional information
|
| 128 |
+
extracted_info = {
|
| 129 |
+
'item_name': detected_item,
|
| 130 |
+
'location': extract_location(message_lower),
|
| 131 |
+
'color': extract_color(message_lower),
|
| 132 |
+
'date_mentioned': extract_date_mention(message_lower)
|
| 133 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
+
return {
|
| 136 |
+
'intent': primary_intent,
|
| 137 |
+
'confidence': intent_scores.get(primary_intent, 0) / 10 if intent_scores else 0,
|
| 138 |
+
'extracted_info': extracted_info,
|
| 139 |
+
'full_message': message
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
def extract_location(text):
|
| 143 |
+
"""Extract location mentions from text"""
|
| 144 |
+
locations = [
|
| 145 |
+
'library', 'cafeteria', 'cafe', 'dining hall', 'classroom', 'lecture hall',
|
| 146 |
+
'lab', 'laboratory', 'dorm', 'dormitory', 'hostel', 'residence hall',
|
| 147 |
+
'gym', 'fitness center', 'pool', 'parking lot', 'parking garage',
|
| 148 |
+
'auditorium', 'theater', 'stadium', 'field', 'quad', 'courtyard',
|
| 149 |
+
'bathroom', 'restroom', 'study room', 'computer lab', 'office',
|
| 150 |
+
'student center', 'union', 'bookstore', 'campus', 'park'
|
| 151 |
]
|
| 152 |
|
| 153 |
+
for location in locations:
|
| 154 |
+
if location in text:
|
| 155 |
+
return location.title()
|
| 156 |
+
return None
|
| 157 |
+
|
| 158 |
+
def extract_color(text):
|
| 159 |
+
"""Extract color mentions from text"""
|
| 160 |
+
colors = [
|
| 161 |
+
'black', 'white', 'red', 'blue', 'green', 'yellow', 'purple', 'pink',
|
| 162 |
+
'orange', 'brown', 'gray', 'grey', 'silver', 'gold', 'navy', 'teal',
|
| 163 |
+
'maroon', 'burgundy', 'beige', 'tan', 'olive', 'lime', 'cyan', 'magenta'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
]
|
| 165 |
|
| 166 |
+
for color in colors:
|
| 167 |
+
if color in text:
|
| 168 |
+
return color.title()
|
| 169 |
+
return None
|
| 170 |
+
|
| 171 |
+
def extract_date_mention(text):
|
| 172 |
+
"""Extract date mentions from text"""
|
| 173 |
+
today = datetime.now()
|
| 174 |
|
| 175 |
+
if 'today' in text:
|
| 176 |
+
return today.strftime('%Y-%m-%d')
|
| 177 |
+
elif 'yesterday' in text:
|
| 178 |
+
return (today - timedelta(days=1)).strftime('%Y-%m-%d')
|
| 179 |
+
elif 'day ago' in text:
|
| 180 |
+
match = re.search(r'(\d+)\s+day', text)
|
| 181 |
+
if match:
|
| 182 |
+
days = int(match.group(1))
|
| 183 |
+
return (today - timedelta(days=days)).strftime('%Y-%m-%d')
|
| 184 |
+
return None
|
| 185 |
+
|
| 186 |
+
def detect_item_category(item_name):
|
| 187 |
+
"""Detect category based on item name"""
|
| 188 |
+
if not item_name:
|
| 189 |
+
return None
|
| 190 |
|
| 191 |
+
item_lower = item_name.lower()
|
|
|
|
| 192 |
|
| 193 |
+
category_map = {
|
| 194 |
+
'Electronics & Gadgets': [
|
| 195 |
+
'phone', 'iphone', 'smartphone', 'cellphone', 'mobile',
|
| 196 |
+
'laptop', 'computer', 'macbook', 'notebook', 'tablet', 'ipad',
|
| 197 |
+
'charger', 'cable', 'usb', 'powerbank',
|
| 198 |
+
'headphone', 'earbud', 'airpod', 'speaker'
|
| 199 |
+
],
|
| 200 |
+
'Personal Items & Accessories': [
|
| 201 |
+
'wallet', 'purse', 'bag', 'backpack', 'handbag', 'suitcase',
|
| 202 |
+
'keys', 'keychain', 'glasses', 'sunglasses', 'umbrella', 'hat'
|
| 203 |
+
],
|
| 204 |
+
'Clothing & Wearables': [
|
| 205 |
+
'jacket', 'coat', 'hoodie', 'sweater', 'shirt', 't-shirt',
|
| 206 |
+
'pants', 'jeans', 'shorts', 'shoe', 'sneaker', 'boot'
|
| 207 |
+
],
|
| 208 |
+
'Academic Materials': [
|
| 209 |
+
'book', 'textbook', 'notebook', 'journal', 'pen', 'pencil',
|
| 210 |
+
'calculator', 'folder', 'binder', 'paper', 'notes'
|
| 211 |
+
],
|
| 212 |
+
'Documents & IDs': [
|
| 213 |
+
'id', 'identification', 'student id', 'passport', 'license',
|
| 214 |
+
'credit card', 'debit card', 'certificate'
|
| 215 |
+
],
|
| 216 |
+
'Sports & Leisure': [
|
| 217 |
+
'ball', 'racket', 'bike', 'bicycle', 'helmet', 'skateboard',
|
| 218 |
+
'gym bag', 'yoga mat', 'water bottle'
|
| 219 |
+
],
|
| 220 |
+
'Food & Kitchen': [
|
| 221 |
+
'bottle', 'lunchbox', 'thermos', 'flask', 'mug', 'cup', 'container'
|
| 222 |
+
]
|
| 223 |
+
}
|
| 224 |
|
| 225 |
+
for category, keywords in category_map.items():
|
| 226 |
+
for keyword in keywords:
|
| 227 |
+
if keyword in item_lower:
|
| 228 |
+
return category
|
| 229 |
+
|
| 230 |
+
return 'Miscellaneous'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
+
# ============= AI RESPONSE GENERATION =============
|
| 233 |
|
| 234 |
+
def get_ai_response(user_message, conversation_history=None):
|
| 235 |
+
"""
|
| 236 |
+
Generate AI response using OpenRouter API with fallback options.
|
| 237 |
+
Handles lost and found related queries with contextual understanding.
|
| 238 |
+
"""
|
| 239 |
+
# First check if we can handle with intent-based response
|
| 240 |
+
intent_result = detect_user_intent(user_message)
|
| 241 |
+
|
| 242 |
+
# For simple intents, use quick responses
|
| 243 |
+
if intent_result['confidence'] > 0.7:
|
| 244 |
+
quick_response = get_intent_based_response(intent_result)
|
| 245 |
+
if quick_response:
|
| 246 |
+
return quick_response
|
| 247 |
+
|
| 248 |
+
# Check if API key is available
|
| 249 |
+
api_key = get_api_key()
|
| 250 |
+
if not api_key:
|
| 251 |
+
print("ℹ️ No API key configured, using fallback responses")
|
| 252 |
+
return get_fallback_response(intent_result)
|
| 253 |
+
|
| 254 |
try:
|
| 255 |
+
# Try OpenRouter API
|
| 256 |
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 257 |
headers = {
|
| 258 |
+
"Authorization": f"Bearer {api_key}",
|
| 259 |
"Content-Type": "application/json",
|
| 260 |
+
"HTTP-Referer": os.environ.get('HF_SPACE_URL', 'https://huggingface.co/spaces'),
|
| 261 |
+
"X-Title": "Campus Lost & Found Assistant"
|
| 262 |
}
|
| 263 |
|
| 264 |
+
# System prompt for Lost & Found assistant
|
| 265 |
+
system_prompt = """You are the Campus Lost & Found System Assistant. Your role is to help users with lost and found items on campus.
|
| 266 |
+
|
| 267 |
+
WHAT YOU CAN HELP WITH:
|
| 268 |
+
1. Reporting lost items - Guide users through reporting what they lost
|
| 269 |
+
2. Reporting found items - Help users report items they found
|
| 270 |
+
3. Searching for items - Help users find their lost items
|
| 271 |
+
4. Claiming items - Explain how to claim found items
|
| 272 |
+
5. System usage - Explain how the platform works
|
| 273 |
+
6. Checking status - Help users track their reports
|
| 274 |
+
|
| 275 |
+
RESPONSE GUIDELINES:
|
| 276 |
+
- Be helpful, friendly, and concise
|
| 277 |
+
- If user wants to report something, guide them step by step
|
| 278 |
+
- Ask for specific details: item name, description, location, date, color, brand
|
| 279 |
+
- Offer to help with search if they're looking for something
|
| 280 |
+
- Use emojis occasionally for friendliness 📍🔍✅
|
| 281 |
+
- Keep responses under 3 paragraphs
|
| 282 |
+
- Never include reasoning or thinking in responses
|
| 283 |
+
|
| 284 |
+
When user mentions losing something, immediately offer to help them report it.
|
| 285 |
+
When user mentions finding something, thank them and offer to help report it.
|
| 286 |
+
When user asks for search help, ask for item details to assist better."""
|
| 287 |
+
|
| 288 |
+
messages = [{"role": "system", "content": system_prompt}]
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
+
# Add conversation history (last 5 exchanges for context)
|
| 291 |
+
if conversation_history:
|
| 292 |
+
for msg in conversation_history[-10:]:
|
| 293 |
+
messages.append(msg)
|
| 294 |
+
|
| 295 |
+
messages.append({"role": "user", "content": user_message})
|
| 296 |
|
| 297 |
+
# Models to try in order (free models first)
|
| 298 |
models_to_try = [
|
| 299 |
"google/gemini-2.0-flash-exp:free",
|
|
|
|
| 300 |
"microsoft/phi-3.5-mini-128k-instruct:free",
|
| 301 |
+
"meta-llama/llama-3.2-3b-instruct:free",
|
| 302 |
"openrouter/free"
|
| 303 |
]
|
| 304 |
|
|
|
|
| 308 |
"model": model,
|
| 309 |
"messages": messages,
|
| 310 |
"temperature": 0.7,
|
| 311 |
+
"max_tokens": 1000
|
| 312 |
}
|
| 313 |
|
| 314 |
+
response = requests.post(url, json=data, headers=headers, timeout=30)
|
| 315 |
|
| 316 |
if response.status_code == 200:
|
| 317 |
result = response.json()
|
| 318 |
if 'choices' in result and len(result['choices']) > 0:
|
| 319 |
+
ai_response = result['choices'][0]['message']['content']
|
| 320 |
+
# Clean up markdown artifacts
|
| 321 |
+
ai_response = re.sub(r'\*\*([^*]+)\*\*', r'\1', ai_response)
|
| 322 |
+
ai_response = re.sub(r'#{1,6}\s+', '', ai_response)
|
| 323 |
+
return ai_response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
elif response.status_code == 429:
|
|
|
|
| 325 |
continue
|
| 326 |
else:
|
|
|
|
| 327 |
continue
|
| 328 |
|
| 329 |
except Exception as e:
|
| 330 |
print(f"Error with {model}: {e}")
|
| 331 |
continue
|
| 332 |
|
| 333 |
+
# If all API attempts fail, use fallback responses
|
| 334 |
+
return get_fallback_response(intent_result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
|
| 336 |
except Exception as e:
|
| 337 |
+
print(f"AI response error: {e}")
|
| 338 |
+
return get_fallback_response(intent_result)
|
| 339 |
+
|
| 340 |
+
def get_intent_based_response(intent_result):
|
| 341 |
+
"""Generate response based on detected intent"""
|
| 342 |
+
intent = intent_result['intent']
|
| 343 |
+
extracted = intent_result['extracted_info']
|
| 344 |
+
|
| 345 |
+
if intent == 'report_lost':
|
| 346 |
+
if extracted['item_name']:
|
| 347 |
+
return f"I see you lost your {extracted['item_name']}. I'll help you report it! Could you please provide more details? What does it look like? Any unique features?"
|
| 348 |
+
else:
|
| 349 |
+
return "I'll help you report a lost item. Could you please tell me what item you lost?"
|
| 350 |
+
|
| 351 |
+
elif intent == 'report_found':
|
| 352 |
+
if extracted['item_name']:
|
| 353 |
+
return f"Thank you for being honest! You found a {extracted['item_name']}. I'll help you report it so the owner can find it. Can you describe it in more detail?"
|
| 354 |
+
else:
|
| 355 |
+
return "Thank you for wanting to report a found item! What item did you find?"
|
| 356 |
+
|
| 357 |
+
elif intent == 'search_items':
|
| 358 |
+
if extracted['item_name']:
|
| 359 |
+
return f"I'll help you search for {extracted['item_name']}. To get better results, could you tell me:\n• Where was it lost/found?\n• What color is it?\n• Any brand or unique features?"
|
| 360 |
+
else:
|
| 361 |
+
return "I can help you search for items. What item are you looking for? (e.g., phone, wallet, keys)"
|
| 362 |
+
|
| 363 |
+
elif intent == 'how_to_claim':
|
| 364 |
+
return """To claim an item:
|
| 365 |
+
1️⃣ Find the item in search results
|
| 366 |
+
2️⃣ Click 'Claim This Item'
|
| 367 |
+
3️⃣ Provide proof of ownership (description, photos, receipts)
|
| 368 |
+
4️⃣ Wait for owner/admin review
|
| 369 |
+
5️⃣ Get notified when approved!
|
| 370 |
+
|
| 371 |
+
Would you like me to help you search for your item first?"""
|
| 372 |
+
|
| 373 |
+
elif intent == 'how_system_works':
|
| 374 |
+
return """The Campus Lost & Found System helps recover lost items:
|
| 375 |
+
|
| 376 |
+
🔍 **How it works:**
|
| 377 |
+
1. **Report** - Tell us what you lost or found
|
| 378 |
+
2. **AI Matching** - Our system automatically finds matches
|
| 379 |
+
3. **Claim** - Prove ownership and reclaim items
|
| 380 |
+
4. **Notifications** - Get alerts when matches are found
|
| 381 |
+
|
| 382 |
+
Ready to report something or search for an item?"""
|
| 383 |
+
|
| 384 |
+
elif intent == 'check_status':
|
| 385 |
+
return "I can help you check your report status. Please log into your dashboard to see all your active reports, or tell me your report ID if you have it."
|
| 386 |
+
|
| 387 |
+
elif intent == 'greeting':
|
| 388 |
+
return "Hello! 👋 I'm your Campus Lost & Found Assistant. I can help you report lost/found items, search for items, or explain how our system works. What can I help you with today?"
|
| 389 |
+
|
| 390 |
+
elif intent == 'thanks':
|
| 391 |
+
return "You're very welcome! 😊 I'm glad I could help. Is there anything else you need assistance with?"
|
| 392 |
+
|
| 393 |
+
elif intent == 'goodbye':
|
| 394 |
+
return "Goodbye! 👋 I hope you find what you're looking for. Come back anytime you need help!"
|
| 395 |
+
|
| 396 |
+
return None
|
| 397 |
+
|
| 398 |
+
def get_fallback_response(intent_result):
|
| 399 |
+
"""Fallback responses when API is unavailable"""
|
| 400 |
+
intent = intent_result['intent']
|
| 401 |
+
|
| 402 |
+
fallback_map = {
|
| 403 |
+
'report_lost': "I can help you report a lost item. Please use the 'Report Item' button above, or tell me what item you lost and I'll guide you through the process.",
|
| 404 |
+
'report_found': "Thank you for helping return items! Please use the 'Report Item' button above, or tell me what item you found and I'll guide you.",
|
| 405 |
+
'search_items': "To search for items, use the search bar above. You can filter by category, location, and item type. What specific item are you looking for?",
|
| 406 |
+
'how_to_claim': "To claim an item, find it in search results and click 'Claim This Item'. Provide proof of ownership and wait for review.",
|
| 407 |
+
'how_system_works': "Our system helps reunite lost items with owners. Report items, search matches, claim your belongings, and get notifications!",
|
| 408 |
+
'check_status': "Check your report status in your dashboard. Log in and click on 'My Reports' to see updates.",
|
| 409 |
+
'greeting': "Hello! I'm your AI assistant for the Campus Lost & Found System. How can I help you today?",
|
| 410 |
+
'general_query': "I'm here to help with lost and found items. Would you like to report something lost, report something found, or search for an item?"
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
return fallback_map.get(intent, fallback_map['general_query'])
|
| 414 |
+
|
| 415 |
+
def is_lost_found_related(message):
|
| 416 |
+
"""Check if message is related to lost and found system"""
|
| 417 |
+
message_lower = message.lower()
|
| 418 |
+
|
| 419 |
+
relevant_keywords = [
|
| 420 |
+
'lost', 'found', 'missing', 'misplaced', 'find', 'search', 'claim',
|
| 421 |
+
'report', 'item', 'belong', 'return', 'recover',
|
| 422 |
+
'phone', 'laptop', 'wallet', 'keys', 'bag', 'backpack', 'book',
|
| 423 |
+
'id', 'charger', 'headphone', 'glasses', 'watch',
|
| 424 |
+
'campus', 'student', 'library', 'cafeteria', 'classroom', 'dorm'
|
| 425 |
+
]
|
| 426 |
+
|
| 427 |
+
for keyword in relevant_keywords:
|
| 428 |
+
if keyword in message_lower:
|
| 429 |
+
return True
|
| 430 |
+
|
| 431 |
+
greetings = ['hi', 'hello', 'hey', 'good morning', 'good afternoon', 'thanks', 'thank you']
|
| 432 |
+
if any(greeting in message_lower for greeting in greetings):
|
| 433 |
+
return True
|
| 434 |
+
|
| 435 |
+
return False
|