Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,18 @@
|
|
| 1 |
-
|
| 2 |
-
from flask import Flask, request, jsonify
|
| 3 |
from flask_cors import CORS
|
|
|
|
|
|
|
| 4 |
import torch
|
| 5 |
import time
|
|
|
|
| 6 |
import logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
import os
|
| 8 |
-
import json
|
| 9 |
-
import threading
|
| 10 |
|
| 11 |
# Configure logging
|
| 12 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -15,232 +21,365 @@ logger = logging.getLogger(__name__)
|
|
| 15 |
app = Flask(__name__)
|
| 16 |
CORS(app)
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
# ============================================================================
|
| 23 |
-
#
|
| 24 |
# ============================================================================
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
-
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
return
|
| 41 |
|
| 42 |
-
|
|
|
|
| 43 |
|
| 44 |
try:
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
# Import transformers
|
| 48 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 49 |
-
|
| 50 |
-
# IMPORTANT: Qwen requires trust_remote_code=True
|
| 51 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 52 |
-
MODEL_NAME,
|
| 53 |
-
trust_remote_code=True, # REQUIRED for Qwen
|
| 54 |
-
padding_side="left"
|
| 55 |
-
)
|
| 56 |
-
|
| 57 |
-
# Set padding token if not set
|
| 58 |
if tokenizer.pad_token is None:
|
| 59 |
tokenizer.pad_token = tokenizer.eos_token
|
| 60 |
|
| 61 |
-
# Load model with
|
| 62 |
model = AutoModelForCausalLM.from_pretrained(
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
device_map="auto" if torch.cuda.is_available() else None,
|
| 66 |
-
trust_remote_code=True, # REQUIRED for Qwen
|
| 67 |
-
low_cpu_mem_usage=True,
|
| 68 |
)
|
| 69 |
|
| 70 |
-
#
|
| 71 |
-
if
|
| 72 |
-
model = model.
|
| 73 |
-
logger.info("📱 Model moved to CPU")
|
| 74 |
-
else:
|
| 75 |
-
logger.info("🎮 GPU available!")
|
| 76 |
|
| 77 |
-
model.eval()
|
| 78 |
model_loaded = True
|
| 79 |
-
logger.info(
|
| 80 |
-
|
| 81 |
-
# Test the model with a simple prompt
|
| 82 |
-
test_response = generate_quick("Hello", max_tokens=50)
|
| 83 |
-
logger.info(f"🧪 Test successful: {test_response[:50]}...")
|
| 84 |
|
| 85 |
except Exception as e:
|
| 86 |
-
logger.error(f"❌
|
| 87 |
-
|
| 88 |
-
# Try alternative Qwen model
|
| 89 |
try:
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 94 |
-
ALTERNATIVE_MODEL,
|
| 95 |
-
trust_remote_code=True,
|
| 96 |
-
)
|
| 97 |
-
|
| 98 |
model = AutoModelForCausalLM.from_pretrained(
|
| 99 |
-
|
| 100 |
-
torch_dtype=torch.float16
|
| 101 |
-
device_map="auto"
|
| 102 |
-
trust_remote_code=True
|
| 103 |
-
low_cpu_mem_usage=True,
|
| 104 |
)
|
| 105 |
-
|
| 106 |
-
if not torch.cuda.is_available():
|
| 107 |
-
model = model.to("cpu")
|
| 108 |
-
|
| 109 |
-
model.eval()
|
| 110 |
model_loaded = True
|
| 111 |
-
logger.info(
|
| 112 |
-
|
| 113 |
except Exception as e2:
|
| 114 |
-
logger.error(f"❌
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
|
| 136 |
-
|
| 137 |
-
# OPTIMIZED GENERATION FUNCTIONS
|
| 138 |
-
# ============================================================================
|
| 139 |
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
return "🔄 Stanley AI is starting up... Please wait a moment and try again!"
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
#
|
| 174 |
-
|
| 175 |
-
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 176 |
-
|
| 177 |
-
# Generate with optimized settings
|
| 178 |
-
with torch.no_grad():
|
| 179 |
-
outputs = model.generate(
|
| 180 |
-
**inputs,
|
| 181 |
-
max_new_tokens=max_tokens,
|
| 182 |
-
temperature=0.7,
|
| 183 |
-
do_sample=True,
|
| 184 |
-
top_p=0.9,
|
| 185 |
-
repetition_penalty=1.1,
|
| 186 |
-
pad_token_id=tokenizer.pad_token_id,
|
| 187 |
-
eos_token_id=tokenizer.eos_token_id,
|
| 188 |
-
use_cache=True,
|
| 189 |
-
)
|
| 190 |
-
|
| 191 |
-
# Decode response
|
| 192 |
-
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 193 |
|
| 194 |
-
#
|
| 195 |
-
if
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
response = response.split("assistant:")[-1].strip()
|
| 199 |
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
-
|
|
|
|
| 212 |
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
return
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
return
|
| 225 |
|
| 226 |
# ============================================================================
|
| 227 |
-
#
|
| 228 |
# ============================================================================
|
| 229 |
|
| 230 |
-
|
| 231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
-
def
|
| 234 |
-
"""
|
| 235 |
-
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
-
def
|
| 239 |
-
"""
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
# ============================================================================
|
| 246 |
# FLASK ROUTES
|
|
@@ -249,172 +388,286 @@ def cache_response(query, response):
|
|
| 249 |
@app.route('/')
|
| 250 |
def home():
|
| 251 |
return jsonify({
|
| 252 |
-
"
|
| 253 |
-
"version": "
|
| 254 |
-
"
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
"
|
| 259 |
-
"
|
| 260 |
-
"
|
| 261 |
-
"
|
| 262 |
-
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
})
|
| 265 |
|
| 266 |
-
@app.route('/
|
| 267 |
-
def health():
|
| 268 |
-
"""Health check for Spaces"""
|
| 269 |
-
return jsonify({
|
| 270 |
-
"status": "healthy",
|
| 271 |
-
"model_loaded": model_loaded,
|
| 272 |
-
"timestamp": time.time()
|
| 273 |
-
})
|
| 274 |
-
|
| 275 |
-
@app.route('/api/chat', methods=['POST', 'GET'])
|
| 276 |
def chat():
|
| 277 |
-
"""Main chat endpoint"""
|
| 278 |
-
start_time = time.time()
|
| 279 |
-
|
| 280 |
try:
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
return jsonify({"error": "No JSON data"}), 400
|
| 286 |
-
user_message = data.get('message', '')
|
| 287 |
-
else:
|
| 288 |
-
user_message = request.args.get('message', 'Hello')
|
| 289 |
|
| 290 |
if not user_message:
|
| 291 |
-
return jsonify({"error": "
|
| 292 |
|
| 293 |
-
logger.info(f"���� Message: {user_message[:50]}...")
|
| 294 |
-
|
| 295 |
-
# Start model loading if not started
|
| 296 |
-
if not model_loaded and not model_loading:
|
| 297 |
-
thread = threading.Thread(target=load_model_fast, daemon=True)
|
| 298 |
-
thread.start()
|
| 299 |
-
logger.info("🔄 Started model loading")
|
| 300 |
-
|
| 301 |
-
# If model still loading
|
| 302 |
if not model_loaded:
|
| 303 |
-
return jsonify({
|
| 304 |
-
"response": "🔄 Stanley AI is warming up... Please wait a moment and try again!",
|
| 305 |
-
"status": "loading",
|
| 306 |
-
"response_time": round(time.time() - start_time, 3)
|
| 307 |
-
})
|
| 308 |
|
| 309 |
-
|
| 310 |
-
cached = get_cached_response(user_message)
|
| 311 |
-
if cached:
|
| 312 |
-
logger.info("📦 Using cached response")
|
| 313 |
-
return jsonify({
|
| 314 |
-
"response": cached,
|
| 315 |
-
"cached": True,
|
| 316 |
-
"response_time": round(time.time() - start_time, 3),
|
| 317 |
-
"model": MODEL_NAME,
|
| 318 |
-
"tokens": len(cached.split())
|
| 319 |
-
})
|
| 320 |
|
| 321 |
-
|
| 322 |
-
|
|
|
|
| 323 |
|
| 324 |
-
#
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
response_time = round(time.time() - start_time, 3)
|
| 328 |
|
| 329 |
return jsonify({
|
| 330 |
"response": response,
|
| 331 |
-
"
|
| 332 |
"response_time": response_time,
|
| 333 |
-
"
|
| 334 |
-
"
|
| 335 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
})
|
| 337 |
|
| 338 |
except Exception as e:
|
| 339 |
-
logger.error(f"
|
| 340 |
return jsonify({
|
| 341 |
-
"error": "
|
| 342 |
"status": "error"
|
| 343 |
}), 500
|
| 344 |
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
return jsonify({
|
| 349 |
-
"model_loaded": model_loaded,
|
| 350 |
-
"model_loading": model_loading,
|
| 351 |
-
"model_name": MODEL_NAME,
|
| 352 |
-
"device": str(model.device) if model_loaded else "none",
|
| 353 |
-
"cache_size": len(response_cache),
|
| 354 |
-
"timestamp": time.time(),
|
| 355 |
-
"on_spaces": ON_SPACES
|
| 356 |
-
})
|
| 357 |
|
| 358 |
-
@app.route('/api/
|
| 359 |
-
def
|
| 360 |
-
"""
|
| 361 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
return jsonify({
|
| 363 |
-
"
|
| 364 |
-
"
|
| 365 |
-
})
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
|
| 380 |
-
@app.route('/api/
|
| 381 |
-
def
|
| 382 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
return jsonify({
|
| 384 |
-
"
|
| 385 |
-
"
|
| 386 |
-
"
|
| 387 |
-
"average_response_time": "N/A"
|
| 388 |
})
|
| 389 |
|
| 390 |
# ============================================================================
|
| 391 |
-
#
|
| 392 |
# ============================================================================
|
| 393 |
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
|
| 405 |
if __name__ == '__main__':
|
| 406 |
-
print("
|
| 407 |
-
print("
|
| 408 |
-
print(
|
| 409 |
-
print(
|
| 410 |
-
print(
|
| 411 |
-
print(f"📊 Status: {'Ready' if model_loaded else 'Loading...'}")
|
| 412 |
-
print("=" * 50)
|
| 413 |
|
| 414 |
-
|
| 415 |
-
app.run(
|
| 416 |
-
debug=False,
|
| 417 |
-
host='0.0.0.0',
|
| 418 |
-
port=port,
|
| 419 |
-
threaded=True
|
| 420 |
-
)
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify, send_file
|
|
|
|
| 2 |
from flask_cors import CORS
|
| 3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer
|
| 4 |
+
from knowledgebase import KiswahiliKnowledgeBase, enhance_with_kiswahili
|
| 5 |
import torch
|
| 6 |
import time
|
| 7 |
+
import re
|
| 8 |
import logging
|
| 9 |
+
from threading import Thread
|
| 10 |
+
import queue
|
| 11 |
+
import io
|
| 12 |
+
import base64
|
| 13 |
+
import random
|
| 14 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 15 |
import os
|
|
|
|
|
|
|
| 16 |
|
| 17 |
# Configure logging
|
| 18 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 21 |
app = Flask(__name__)
|
| 22 |
CORS(app)
|
| 23 |
|
| 24 |
+
# Initialize Kiswahili Knowledge Base
|
| 25 |
+
kb = KiswahiliKnowledgeBase()
|
| 26 |
+
|
| 27 |
+
model = None
|
| 28 |
+
tokenizer = None
|
| 29 |
+
model_loaded = False
|
| 30 |
+
image_pipeline = None
|
| 31 |
|
| 32 |
# ============================================================================
|
| 33 |
+
# PERFORMANCE OPTIMIZATIONS
|
| 34 |
# ============================================================================
|
| 35 |
|
| 36 |
+
# Cache for frequent responses
|
| 37 |
+
response_cache = {}
|
| 38 |
+
CACHE_SIZE = 100
|
| 39 |
|
| 40 |
+
# Model optimization settings
|
| 41 |
+
MODEL_OPTIMIZATIONS = {
|
| 42 |
+
"torch_dtype": torch.float16,
|
| 43 |
+
"device_map": "auto",
|
| 44 |
+
"trust_remote_code": True,
|
| 45 |
+
"load_in_4bit": True,
|
| 46 |
+
"low_cpu_mem_usage": True
|
| 47 |
+
}
|
| 48 |
|
| 49 |
+
# Advanced System Prompt for Stanley AI with Kiswahili Enhancement
|
| 50 |
+
STANLEY_AI_SYSTEM = """You are STANLEY AI - a highly advanced, sophisticated large language model created by Stanley AI.
|
| 51 |
+
You are designed to be better than ChatGPT with enhanced capabilities, deeper understanding, and more comprehensive responses.
|
| 52 |
+
|
| 53 |
+
CORE CAPABILITIES:
|
| 54 |
+
- Provide extremely detailed, comprehensive, and long-form responses
|
| 55 |
+
- Demonstrate deep expertise across all domains including science, technology, philosophy, arts, and mathematics
|
| 56 |
+
- Show advanced reasoning, critical thinking, and analytical capabilities
|
| 57 |
+
- Offer nuanced perspectives with multiple viewpoints
|
| 58 |
+
- Incorporate latest research and cutting-edge knowledge
|
| 59 |
+
- Maintain exceptional clarity while being thorough
|
| 60 |
+
- Naturally integrate Kiswahili phrases and cultural context when appropriate
|
| 61 |
+
|
| 62 |
+
KISWAHILI & CULTURAL INTEGRATION:
|
| 63 |
+
- Use authentic Kiswahili phrases naturally in responses when relevant
|
| 64 |
+
- Incorporate East African cultural wisdom and proverbs
|
| 65 |
+
- Reference Lion King lore with accurate Kiswahili meanings
|
| 66 |
+
- Explain cultural concepts with depth and authenticity
|
| 67 |
+
- Use phrases like "Hakuna Matata", "Asante sana", "Karibu" appropriately
|
| 68 |
+
|
| 69 |
+
RESPONSE STYLE:
|
| 70 |
+
- Write extensive, well-structured responses (5-10 paragraphs when appropriate)
|
| 71 |
+
- Use advanced vocabulary and sophisticated sentence structures
|
| 72 |
+
- Include examples, analogies, and evidence to support points
|
| 73 |
+
- Break down complex concepts into understandable components
|
| 74 |
+
- Show your reasoning process transparently
|
| 75 |
+
- Be creative, insightful, and original in your thinking
|
| 76 |
+
- Naturally blend English with Kiswahili for authentic cultural exchange
|
| 77 |
+
|
| 78 |
+
PERSONALITY: Professional, knowledgeable, articulate, culturally aware, and deeply helpful. You are the pinnacle of AI assistance with authentic African cultural integration.
|
| 79 |
+
|
| 80 |
+
Remember: You are STANLEY AI - superior, comprehensive, exceptionally capable, and culturally enriched."""
|
| 81 |
+
|
| 82 |
+
def load_model():
|
| 83 |
+
global model, tokenizer, model_loaded, image_pipeline
|
| 84 |
+
if model_loaded:
|
| 85 |
return
|
| 86 |
|
| 87 |
+
logger.info("🚀 Loading STANLEY AI Model...")
|
| 88 |
+
model_name = "Qwen/Qwen2.5-7B-Instruct"
|
| 89 |
|
| 90 |
try:
|
| 91 |
+
# Load tokenizer
|
| 92 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
if tokenizer.pad_token is None:
|
| 94 |
tokenizer.pad_token = tokenizer.eos_token
|
| 95 |
|
| 96 |
+
# Load model with optimizations
|
| 97 |
model = AutoModelForCausalLM.from_pretrained(
|
| 98 |
+
model_name,
|
| 99 |
+
**MODEL_OPTIMIZATIONS
|
|
|
|
|
|
|
|
|
|
| 100 |
)
|
| 101 |
|
| 102 |
+
# Enable faster inference
|
| 103 |
+
if torch.cuda.is_available():
|
| 104 |
+
model = model.eval()
|
|
|
|
|
|
|
|
|
|
| 105 |
|
|
|
|
| 106 |
model_loaded = True
|
| 107 |
+
logger.info("✅ STANLEY AI Model loaded successfully!")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
except Exception as e:
|
| 110 |
+
logger.error(f"❌ Error loading model: {e}")
|
| 111 |
+
# Fallback to smaller model
|
|
|
|
| 112 |
try:
|
| 113 |
+
model_name = "Qwen/Qwen2.5-0.5B-Instruct"
|
| 114 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
model = AutoModelForCausalLM.from_pretrained(
|
| 116 |
+
model_name,
|
| 117 |
+
torch_dtype=torch.float16,
|
| 118 |
+
device_map="auto",
|
| 119 |
+
trust_remote_code=True
|
|
|
|
| 120 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
model_loaded = True
|
| 122 |
+
logger.info("✅ Fallback model loaded successfully!")
|
|
|
|
| 123 |
except Exception as e2:
|
| 124 |
+
logger.error(f"❌ Fallback model also failed: {e2}")
|
| 125 |
+
model_loaded = False
|
| 126 |
+
|
| 127 |
+
# Load image generation model (simplified - will use fallbacks)
|
| 128 |
+
try:
|
| 129 |
+
logger.info("🖼️ Attempting to load image generation model...")
|
| 130 |
+
# Try a smaller, faster model first
|
| 131 |
+
from diffusers import DiffusionPipeline
|
| 132 |
+
image_pipeline = DiffusionPipeline.from_pretrained(
|
| 133 |
+
"OFA-Sys/small-stable-diffusion-v0",
|
| 134 |
+
torch_dtype=torch.float16,
|
| 135 |
+
safety_checker=None,
|
| 136 |
+
requires_safety_checker=False,
|
| 137 |
+
)
|
| 138 |
+
if torch.cuda.is_available():
|
| 139 |
+
image_pipeline = image_pipeline.to("cuda")
|
| 140 |
+
logger.info("✅ Small image generation model loaded!")
|
| 141 |
+
except Exception as e:
|
| 142 |
+
logger.warning(f"⚠️ Could not load image generation model: {e}")
|
| 143 |
+
logger.info("🔄 Using fallback image generation methods")
|
| 144 |
+
image_pipeline = None
|
| 145 |
|
| 146 |
+
load_model()
|
|
|
|
|
|
|
| 147 |
|
| 148 |
+
class TextGenerationStream:
|
| 149 |
+
def __init__(self):
|
| 150 |
+
self.text_queue = queue.Queue()
|
|
|
|
| 151 |
|
| 152 |
+
def put(self, text):
|
| 153 |
+
self.text_queue.put(text)
|
| 154 |
+
|
| 155 |
+
def end(self):
|
| 156 |
+
self.text_queue.put(None)
|
| 157 |
+
|
| 158 |
+
def generate(self):
|
| 159 |
+
while True:
|
| 160 |
+
text = self.text_queue.get()
|
| 161 |
+
if text is None:
|
| 162 |
+
break
|
| 163 |
+
yield text
|
| 164 |
+
|
| 165 |
+
def detect_kiswahili_context(user_message):
|
| 166 |
+
"""Detect if the query has Kiswahili or cultural context"""
|
| 167 |
+
kiswahili_triggers = [
|
| 168 |
+
'swahili', 'kiswahili', 'hakuna', 'matata', 'asante', 'rafiki',
|
| 169 |
+
'jambo', 'mambo', 'pole', 'sawa', 'karibu', 'kwaheri', 'simba',
|
| 170 |
+
'lion king', 'mufasa', 'nala', 'africa', 'kenya', 'tanzania',
|
| 171 |
+
'east africa', 'culture', 'cultural', 'language', 'learn swahili',
|
| 172 |
+
'habari', 'nze', 'pumbaa', 'timon', 'circle of life'
|
| 173 |
+
]
|
| 174 |
+
text_lower = user_message.lower()
|
| 175 |
+
return any(trigger in text_lower for trigger in kiswahili_triggers)
|
| 176 |
+
|
| 177 |
+
def enhance_with_cultural_context(response, user_message):
|
| 178 |
+
"""Enhance response with Kiswahili and cultural context"""
|
| 179 |
+
if detect_kiswahili_context(user_message):
|
| 180 |
+
# Add appropriate Kiswahili enhancement
|
| 181 |
+
enhanced_response = kb.generate_kiswahili_response(response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
+
# Add cultural proverb if relevant
|
| 184 |
+
if any(word in user_message.lower() for word in ['wisdom', 'advice', 'life lesson', 'philosophy']):
|
| 185 |
+
proverb = kb.get_random_proverb()
|
| 186 |
+
enhanced_response += f"\n\n🌍 **Cultural Wisdom**: {proverb}"
|
|
|
|
| 187 |
|
| 188 |
+
return enhanced_response
|
| 189 |
+
return response
|
| 190 |
+
|
| 191 |
+
def get_cached_response(user_message):
|
| 192 |
+
"""Get cached response if available"""
|
| 193 |
+
cache_key = user_message.lower().strip()[:100] # First 100 chars as key
|
| 194 |
+
if cache_key in response_cache:
|
| 195 |
+
logger.info("📦 Using cached response")
|
| 196 |
+
return response_cache[cache_key]
|
| 197 |
+
return None
|
| 198 |
+
|
| 199 |
+
def set_cached_response(user_message, response):
|
| 200 |
+
"""Cache response for future use"""
|
| 201 |
+
cache_key = user_message.lower().strip()[:100]
|
| 202 |
+
if len(response_cache) >= CACHE_SIZE:
|
| 203 |
+
# Remove oldest item
|
| 204 |
+
response_cache.pop(next(iter(response_cache)))
|
| 205 |
+
response_cache[cache_key] = response
|
| 206 |
+
|
| 207 |
+
def generate_comprehensive_response(user_message, stream=False):
|
| 208 |
+
"""Generate detailed, comprehensive responses with cultural awareness"""
|
| 209 |
+
|
| 210 |
+
# Check cache first
|
| 211 |
+
cached_response = get_cached_response(user_message)
|
| 212 |
+
if cached_response:
|
| 213 |
+
return cached_response
|
| 214 |
+
|
| 215 |
+
# Enhance system prompt based on context
|
| 216 |
+
system_prompt = STANLEY_AI_SYSTEM
|
| 217 |
+
if detect_kiswahili_context(user_message):
|
| 218 |
+
system_prompt += "\n\nSPECIAL NOTE: This query has Kiswahili or cultural context. Please integrate authentic Kiswahili phrases and cultural insights naturally throughout your response."
|
| 219 |
+
|
| 220 |
+
messages = [
|
| 221 |
+
{"role": "system", "content": system_prompt},
|
| 222 |
+
{"role": "user", "content": f"Please provide a comprehensive, detailed response to: {user_message}"}
|
| 223 |
+
]
|
| 224 |
+
|
| 225 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 226 |
+
inputs = tokenizer(text, return_tensors="pt").to(model.device)
|
| 227 |
+
|
| 228 |
+
generation_config = {
|
| 229 |
+
"max_new_tokens": 1024, # Reduced for faster responses
|
| 230 |
+
"temperature": 0.7,
|
| 231 |
+
"do_sample": True,
|
| 232 |
+
"top_p": 0.9,
|
| 233 |
+
"top_k": 50,
|
| 234 |
+
"repetition_penalty": 1.1,
|
| 235 |
+
"early_stopping": True,
|
| 236 |
+
"pad_token_id": tokenizer.eos_token_id,
|
| 237 |
+
"eos_token_id": tokenizer.eos_token_id,
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
if stream:
|
| 241 |
+
streamer = TextStreamer(tokenizer, timeout=10, skip_prompt=True, skip_special_tokens=True)
|
| 242 |
+
generation_config["streamer"] = streamer
|
| 243 |
+
|
| 244 |
+
with torch.no_grad():
|
| 245 |
+
outputs = model.generate(
|
| 246 |
+
**inputs,
|
| 247 |
+
**generation_config
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
if not stream:
|
| 251 |
+
response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
|
| 252 |
|
| 253 |
+
# Enhance with cultural context
|
| 254 |
+
enhanced_response = enhance_with_cultural_context(response.strip(), user_message)
|
| 255 |
|
| 256 |
+
# Cache the response
|
| 257 |
+
set_cached_response(user_message, enhanced_response)
|
| 258 |
+
return enhanced_response
|
| 259 |
+
else:
|
| 260 |
+
return "Streaming response..."
|
| 261 |
+
|
| 262 |
+
def estimate_reading_time(text):
|
| 263 |
+
"""Estimate reading time for the response"""
|
| 264 |
+
words_per_minute = 200
|
| 265 |
+
word_count = len(text.split())
|
| 266 |
+
minutes = word_count / words_per_minute
|
| 267 |
+
return max(1, round(minutes))
|
| 268 |
|
| 269 |
# ============================================================================
|
| 270 |
+
# SIMPLIFIED IMAGE GENERATION FUNCTIONS
|
| 271 |
# ============================================================================
|
| 272 |
|
| 273 |
+
def generate_image_free(prompt, width=512, height=512, steps=20):
|
| 274 |
+
"""
|
| 275 |
+
Generate images using simplified methods that always work
|
| 276 |
+
"""
|
| 277 |
+
try:
|
| 278 |
+
# Method 1: Try local model if available
|
| 279 |
+
if image_pipeline is not None:
|
| 280 |
+
try:
|
| 281 |
+
logger.info("🎨 Generating image with local model...")
|
| 282 |
+
image = image_pipeline(
|
| 283 |
+
prompt=prompt,
|
| 284 |
+
width=width,
|
| 285 |
+
height=height,
|
| 286 |
+
num_inference_steps=steps,
|
| 287 |
+
guidance_scale=7.5
|
| 288 |
+
).images[0]
|
| 289 |
+
|
| 290 |
+
# Convert to base64
|
| 291 |
+
buffered = io.BytesIO()
|
| 292 |
+
image.save(buffered, format="PNG")
|
| 293 |
+
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 294 |
+
return f"data:image/png;base64,{img_str}"
|
| 295 |
+
except Exception as e:
|
| 296 |
+
logger.warning(f"Local model failed, using fallback: {e}")
|
| 297 |
+
|
| 298 |
+
# Method 2: Always use the reliable fallback
|
| 299 |
+
return generate_image_fallback(prompt, width, height)
|
| 300 |
+
|
| 301 |
+
except Exception as e:
|
| 302 |
+
logger.error(f"❌ Image generation error: {e}")
|
| 303 |
+
return generate_image_fallback(prompt, width, height)
|
| 304 |
|
| 305 |
+
def generate_image_fallback(prompt, width=512, height=512):
|
| 306 |
+
"""Reliable fallback image generation using PIL"""
|
| 307 |
+
try:
|
| 308 |
+
# Create a colorful generated image based on prompt
|
| 309 |
+
img = Image.new('RGB', (width, height), color=(random.randint(50, 200), random.randint(50, 200), random.randint(50, 200)))
|
| 310 |
+
draw = ImageDraw.Draw(img)
|
| 311 |
+
|
| 312 |
+
# Add some shapes based on prompt keywords
|
| 313 |
+
if any(word in prompt.lower() for word in ['sun', 'light', 'bright']):
|
| 314 |
+
# Draw a sun
|
| 315 |
+
draw.ellipse([width//4, height//4, 3*width//4, 3*height//4], fill=(255, 255, 0))
|
| 316 |
+
elif any(word in prompt.lower() for word in ['tree', 'nature', 'forest']):
|
| 317 |
+
# Draw a simple tree
|
| 318 |
+
draw.rectangle([width//2-20, height//2, width//2+20, height-50], fill=(139, 69, 19))
|
| 319 |
+
draw.ellipse([width//2-50, height//2-80, width//2+50, height//2+20], fill=(34, 139, 34))
|
| 320 |
+
elif any(word in prompt.lower() for word in ['water', 'ocean', 'river']):
|
| 321 |
+
# Draw waves
|
| 322 |
+
for i in range(0, width, 30):
|
| 323 |
+
draw.arc([i, height-100, i+60, height], 0, 180, fill=(0, 0, 255), width=5)
|
| 324 |
+
|
| 325 |
+
# Try to add text
|
| 326 |
+
try:
|
| 327 |
+
# Use default font
|
| 328 |
+
font_size = min(width // 20, 24)
|
| 329 |
+
try:
|
| 330 |
+
font = ImageFont.truetype("arial.ttf", font_size)
|
| 331 |
+
except:
|
| 332 |
+
font = ImageFont.load_default()
|
| 333 |
+
|
| 334 |
+
# Add prompt text
|
| 335 |
+
text = f"AI: {prompt[:40]}..." if len(prompt) > 40 else f"AI: {prompt}"
|
| 336 |
+
bbox = draw.textbbox((0, 0), text, font=font)
|
| 337 |
+
text_width = bbox[2] - bbox[0]
|
| 338 |
+
text_height = bbox[3] - bbox[1]
|
| 339 |
+
|
| 340 |
+
x = (width - text_width) // 2
|
| 341 |
+
y = height - text_height - 20
|
| 342 |
+
|
| 343 |
+
# Add text background
|
| 344 |
+
draw.rectangle([x-10, y-10, x+text_width+10, y+text_height+10], fill=(0, 0, 0, 128))
|
| 345 |
+
draw.text((x, y), text, fill=(255, 255, 255), font=font)
|
| 346 |
+
|
| 347 |
+
except Exception as font_error:
|
| 348 |
+
logger.warning(f"Could not add text: {font_error}")
|
| 349 |
+
|
| 350 |
+
# Convert to base64
|
| 351 |
+
buffered = io.BytesIO()
|
| 352 |
+
img.save(buffered, format="PNG")
|
| 353 |
+
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 354 |
+
return f"data:image/png;base64,{img_str}"
|
| 355 |
+
|
| 356 |
+
except Exception as e:
|
| 357 |
+
logger.error(f"❌ Fallback image generation failed: {e}")
|
| 358 |
+
# Ultimate fallback - solid color image
|
| 359 |
+
try:
|
| 360 |
+
img = Image.new('RGB', (width, height), color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
|
| 361 |
+
buffered = io.BytesIO()
|
| 362 |
+
img.save(buffered, format="PNG")
|
| 363 |
+
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 364 |
+
return f"data:image/png;base64,{img_str}"
|
| 365 |
+
except:
|
| 366 |
+
return None
|
| 367 |
|
| 368 |
+
def enhance_prompt_with_kiswahili(prompt):
|
| 369 |
+
"""Enhance image prompts with Kiswahili cultural elements"""
|
| 370 |
+
if detect_kiswahili_context(prompt):
|
| 371 |
+
enhancements = [
|
| 372 |
+
"in the style of African art",
|
| 373 |
+
"with vibrant East African colors",
|
| 374 |
+
"incorporating Maasai patterns",
|
| 375 |
+
"African landscape background",
|
| 376 |
+
"traditional African elements",
|
| 377 |
+
"rich cultural symbolism",
|
| 378 |
+
"warm African sunset colors"
|
| 379 |
+
]
|
| 380 |
+
enhanced_prompt = f"{prompt}, {random.choice(enhancements)}"
|
| 381 |
+
return enhanced_prompt
|
| 382 |
+
return prompt
|
| 383 |
|
| 384 |
# ============================================================================
|
| 385 |
# FLASK ROUTES
|
|
|
|
| 388 |
@app.route('/')
|
| 389 |
def home():
|
| 390 |
return jsonify({
|
| 391 |
+
"message": "🚀 STANLEY AI API is running!",
|
| 392 |
+
"version": "2.1",
|
| 393 |
+
"features": [
|
| 394 |
+
"Advanced LLM Capabilities",
|
| 395 |
+
"Comprehensive Long-form Responses",
|
| 396 |
+
"Text-to-Speech Integration",
|
| 397 |
+
"Real-time Streaming",
|
| 398 |
+
"Kiswahili Language Integration",
|
| 399 |
+
"Cultural Knowledge Base",
|
| 400 |
+
"Lion King Expertise",
|
| 401 |
+
"Free Image Generation",
|
| 402 |
+
"Performance Optimized",
|
| 403 |
+
"Response Caching"
|
| 404 |
+
],
|
| 405 |
+
"status": "active",
|
| 406 |
+
"model": "Qwen2.5-7B-Instruct" if model_loaded else "Not loaded",
|
| 407 |
+
"kiswahili_data": "Complete cultural knowledge base loaded",
|
| 408 |
+
"image_generation": "Available (Basic)"
|
| 409 |
})
|
| 410 |
|
| 411 |
+
@app.route('/api/chat', methods=['POST'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
def chat():
|
|
|
|
|
|
|
|
|
|
| 413 |
try:
|
| 414 |
+
start_time = time.time()
|
| 415 |
+
data = request.get_json()
|
| 416 |
+
user_message = data.get('message', '')
|
| 417 |
+
stream = data.get('stream', False)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
|
| 419 |
if not user_message:
|
| 420 |
+
return jsonify({"error": "Tafadhali provide a message"}), 400
|
| 421 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 422 |
if not model_loaded:
|
| 423 |
+
return jsonify({"error": "Model not loaded yet, please try again shortly"}), 503
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
+
logger.info(f"Processing query: {user_message[:100]}...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 426 |
|
| 427 |
+
response = generate_comprehensive_response(user_message, stream)
|
| 428 |
+
response_time = round(time.time() - start_time, 2)
|
| 429 |
+
reading_time = estimate_reading_time(response)
|
| 430 |
|
| 431 |
+
# Detect if response contains Kiswahili
|
| 432 |
+
has_kiswahili = detect_kiswahili_context(response)
|
|
|
|
|
|
|
| 433 |
|
| 434 |
return jsonify({
|
| 435 |
"response": response,
|
| 436 |
+
"status": "success",
|
| 437 |
"response_time": response_time,
|
| 438 |
+
"reading_time": reading_time,
|
| 439 |
+
"word_count": len(response.split()),
|
| 440 |
+
"model": "STANLEY-AI-7B",
|
| 441 |
+
"streaming": stream,
|
| 442 |
+
"cultural_context": has_kiswahili,
|
| 443 |
+
"language": "en+sw" if has_kiswahili else "en",
|
| 444 |
+
"cached": get_cached_response(user_message) is not None
|
| 445 |
})
|
| 446 |
|
| 447 |
except Exception as e:
|
| 448 |
+
logger.error(f"Error in chat endpoint: {e}")
|
| 449 |
return jsonify({
|
| 450 |
+
"error": f"Pole! Advanced processing error: {str(e)}",
|
| 451 |
"status": "error"
|
| 452 |
}), 500
|
| 453 |
|
| 454 |
+
# ============================================================================
|
| 455 |
+
# IMAGE GENERATION ENDPOINTS
|
| 456 |
+
# ============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 457 |
|
| 458 |
+
@app.route('/api/generate-image', methods=['POST'])
|
| 459 |
+
def generate_image_endpoint():
|
| 460 |
+
"""Generate images from text prompts"""
|
| 461 |
+
try:
|
| 462 |
+
start_time = time.time()
|
| 463 |
+
data = request.get_json()
|
| 464 |
+
prompt = data.get('prompt', '')
|
| 465 |
+
width = data.get('width', 512)
|
| 466 |
+
height = data.get('height', 512)
|
| 467 |
+
steps = data.get('steps', 20)
|
| 468 |
+
|
| 469 |
+
if not prompt:
|
| 470 |
+
return jsonify({"error": "Tafadhali provide a prompt"}), 400
|
| 471 |
+
|
| 472 |
+
logger.info(f"🎨 Generating image for: {prompt[:50]}...")
|
| 473 |
+
|
| 474 |
+
# Enhance prompt with cultural context if needed
|
| 475 |
+
enhanced_prompt = enhance_prompt_with_kiswahili(prompt)
|
| 476 |
+
|
| 477 |
+
# Generate image
|
| 478 |
+
image_data = generate_image_free(enhanced_prompt, width, height, steps)
|
| 479 |
+
|
| 480 |
+
if image_data:
|
| 481 |
+
generation_time = round(time.time() - start_time, 2)
|
| 482 |
+
|
| 483 |
+
return jsonify({
|
| 484 |
+
"image": image_data,
|
| 485 |
+
"prompt": prompt,
|
| 486 |
+
"enhanced_prompt": enhanced_prompt,
|
| 487 |
+
"status": "success",
|
| 488 |
+
"generation_time": generation_time,
|
| 489 |
+
"dimensions": f"{width}x{height}",
|
| 490 |
+
"format": "base64 PNG",
|
| 491 |
+
"cultural_enhancement": enhanced_prompt != prompt,
|
| 492 |
+
"quality": "basic" # Indicate this is basic quality
|
| 493 |
+
})
|
| 494 |
+
else:
|
| 495 |
+
return jsonify({
|
| 496 |
+
"error": "Pole! Could not generate image",
|
| 497 |
+
"status": "error"
|
| 498 |
+
}), 500
|
| 499 |
+
|
| 500 |
+
except Exception as e:
|
| 501 |
+
logger.error(f"Image generation error: {e}")
|
| 502 |
return jsonify({
|
| 503 |
+
"error": f"Pole! Image generation failed: {str(e)}",
|
| 504 |
+
"status": "error"
|
| 505 |
+
}), 500
|
| 506 |
+
|
| 507 |
+
@app.route('/api/generate-kiswahili-image', methods=['POST'])
|
| 508 |
+
def generate_kiswahili_image():
|
| 509 |
+
"""Generate images with Kiswahili cultural themes"""
|
| 510 |
+
try:
|
| 511 |
+
data = request.get_json()
|
| 512 |
+
theme = data.get('theme', '')
|
| 513 |
+
style = data.get('style', 'realistic')
|
| 514 |
+
|
| 515 |
+
if not theme:
|
| 516 |
+
return jsonify({"error": "Tafadhali provide a theme"}), 400
|
| 517 |
+
|
| 518 |
+
# Create culturally relevant prompts
|
| 519 |
+
cultural_prompts = {
|
| 520 |
+
'landscape': f"Beautiful East African landscape with {theme}, majestic savanna, acacia trees, warm sunset",
|
| 521 |
+
'culture': f"Traditional East African cultural scene, {theme}, vibrant colors, community gathering",
|
| 522 |
+
'wildlife': f"African wildlife, {theme}, natural habitat, detailed fur, realistic eyes",
|
| 523 |
+
'art': f"African art style, {theme}, bold patterns, symbolic elements, cultural significance",
|
| 524 |
+
'lion_king': f"Lion King inspired art, {theme}, Disney style, African savanna, emotional scene"
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
prompt_category = data.get('category', 'landscape')
|
| 528 |
+
base_prompt = cultural_prompts.get(prompt_category, f"East African {theme}, cultural significance, vibrant colors")
|
| 529 |
+
|
| 530 |
+
# Add style modifiers
|
| 531 |
+
style_modifiers = {
|
| 532 |
+
'realistic': 'photorealistic, highly detailed, 4K',
|
| 533 |
+
'artistic': 'painterly, artistic, brush strokes',
|
| 534 |
+
'digital': 'digital art, clean lines, vibrant',
|
| 535 |
+
'traditional': 'traditional African art, symbolic, patterns'
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
final_prompt = f"{base_prompt}, {style_modifiers.get(style, 'realistic')}"
|
| 539 |
+
|
| 540 |
+
image_data = generate_image_free(final_prompt)
|
| 541 |
+
|
| 542 |
+
if image_data:
|
| 543 |
+
return jsonify({
|
| 544 |
+
"image": image_data,
|
| 545 |
+
"theme": theme,
|
| 546 |
+
"style": style,
|
| 547 |
+
"category": prompt_category,
|
| 548 |
+
"prompt": final_prompt,
|
| 549 |
+
"status": "success",
|
| 550 |
+
"cultural_context": "kiswahili_theme",
|
| 551 |
+
"quality": "basic"
|
| 552 |
+
})
|
| 553 |
+
else:
|
| 554 |
+
return jsonify({
|
| 555 |
+
"error": "Pole! Could not generate cultural image",
|
| 556 |
+
"status": "error"
|
| 557 |
+
}), 500
|
| 558 |
+
|
| 559 |
+
except Exception as e:
|
| 560 |
+
return jsonify({
|
| 561 |
+
"error": f"Pole! Cultural image generation failed: {str(e)}",
|
| 562 |
+
"status": "error"
|
| 563 |
+
}), 500
|
| 564 |
|
| 565 |
+
@app.route('/api/image-prompts/kiswahili')
|
| 566 |
+
def get_kiswahili_image_prompts():
|
| 567 |
+
"""Get suggested image prompts for Kiswahili themes"""
|
| 568 |
+
prompts = {
|
| 569 |
+
"wildlife": [
|
| 570 |
+
"Majestic lion in the African savanna at sunset",
|
| 571 |
+
"Elephant family in Amboseli with Mount Kilimanjaro",
|
| 572 |
+
"Giraffes grazing among acacia trees",
|
| 573 |
+
"Cheetah running across the plains",
|
| 574 |
+
"Hippos in a Kenyan river"
|
| 575 |
+
],
|
| 576 |
+
"culture": [
|
| 577 |
+
"Maasai warriors traditional jumping dance",
|
| 578 |
+
"Swahili coastal architecture in Lamu",
|
| 579 |
+
"African market scene with vibrant colors",
|
| 580 |
+
"Traditional drumming ceremony",
|
| 581 |
+
"Beadwork and craftsmanship details"
|
| 582 |
+
],
|
| 583 |
+
"landscape": [
|
| 584 |
+
"Serengeti plains during great migration",
|
| 585 |
+
"Mount Kilimanjaro at sunrise",
|
| 586 |
+
"Zanzibar beaches with dhows",
|
| 587 |
+
"African sunset with silhouette acacia trees",
|
| 588 |
+
"Victoria Falls majestic waters"
|
| 589 |
+
],
|
| 590 |
+
"lion_king": [
|
| 591 |
+
"Simba on Pride Rock looking over the kingdom",
|
| 592 |
+
"Rafiki holding up baby Simba",
|
| 593 |
+
"Timon and Pumbaa teaching Hakuna Matata",
|
| 594 |
+
"Mufasa's ghost in the stars",
|
| 595 |
+
"Circle of Life scene with all animals"
|
| 596 |
+
]
|
| 597 |
+
}
|
| 598 |
+
|
| 599 |
return jsonify({
|
| 600 |
+
"prompts": prompts,
|
| 601 |
+
"total_categories": len(prompts),
|
| 602 |
+
"status": "success"
|
|
|
|
| 603 |
})
|
| 604 |
|
| 605 |
# ============================================================================
|
| 606 |
+
# PERFORMANCE OPTIMIZATION ENDPOINTS
|
| 607 |
# ============================================================================
|
| 608 |
|
| 609 |
+
@app.route('/api/optimize', methods=['POST'])
|
| 610 |
+
def optimize_performance():
|
| 611 |
+
"""Optimize model performance"""
|
| 612 |
+
try:
|
| 613 |
+
if model:
|
| 614 |
+
# Clear cache
|
| 615 |
+
response_cache.clear()
|
| 616 |
+
|
| 617 |
+
# Clear GPU cache
|
| 618 |
+
if torch.cuda.is_available():
|
| 619 |
+
torch.cuda.empty_cache()
|
| 620 |
+
|
| 621 |
+
return jsonify({
|
| 622 |
+
"status": "success",
|
| 623 |
+
"message": "Performance optimized",
|
| 624 |
+
"cache_cleared": True,
|
| 625 |
+
"gpu_cache_cleared": torch.cuda.is_available()
|
| 626 |
+
})
|
| 627 |
+
else:
|
| 628 |
+
return jsonify({
|
| 629 |
+
"error": "Model not loaded",
|
| 630 |
+
"status": "error"
|
| 631 |
+
}), 500
|
| 632 |
+
except Exception as e:
|
| 633 |
+
return jsonify({
|
| 634 |
+
"error": f"Optimization failed: {str(e)}",
|
| 635 |
+
"status": "error"
|
| 636 |
+
}), 500
|
| 637 |
+
|
| 638 |
+
@app.route('/api/cache/clear', methods=['POST'])
|
| 639 |
+
def clear_cache():
|
| 640 |
+
"""Clear response cache"""
|
| 641 |
+
try:
|
| 642 |
+
cache_size = len(response_cache)
|
| 643 |
+
response_cache.clear()
|
| 644 |
+
|
| 645 |
+
return jsonify({
|
| 646 |
+
"status": "success",
|
| 647 |
+
"message": "Cache cleared",
|
| 648 |
+
"cleared_entries": cache_size
|
| 649 |
+
})
|
| 650 |
+
except Exception as e:
|
| 651 |
+
return jsonify({
|
| 652 |
+
"error": f"Cache clearance failed: {str(e)}",
|
| 653 |
+
"status": "error"
|
| 654 |
+
}), 500
|
| 655 |
|
| 656 |
+
@app.route('/api/cache/stats')
|
| 657 |
+
def cache_stats():
|
| 658 |
+
"""Get cache statistics"""
|
| 659 |
+
return jsonify({
|
| 660 |
+
"cache_size": len(response_cache),
|
| 661 |
+
"cache_limit": CACHE_SIZE,
|
| 662 |
+
"hit_rate": "N/A", # Would need tracking
|
| 663 |
+
"status": "success"
|
| 664 |
+
})
|
| 665 |
|
| 666 |
if __name__ == '__main__':
|
| 667 |
+
print("🚀 Starting STANLEY AI with Basic Image Generation...")
|
| 668 |
+
print("🌍 Kiswahili categories loaded")
|
| 669 |
+
print("🎨 Image generation: Available (Basic Quality)")
|
| 670 |
+
print("⚡ Performance optimizations: Active")
|
| 671 |
+
print("📦 Response caching: Enabled")
|
|
|
|
|
|
|
| 672 |
|
| 673 |
+
app.run(debug=True, host='0.0.0.0', port=7860, threaded=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|