Update app.py
Browse files
app.py
CHANGED
|
@@ -1,17 +1,19 @@
|
|
| 1 |
-
from flask import Flask, request, jsonify
|
| 2 |
from flask_cors import CORS
|
| 3 |
-
import
|
|
|
|
|
|
|
| 4 |
import time
|
|
|
|
| 5 |
import logging
|
|
|
|
|
|
|
| 6 |
import io
|
| 7 |
import base64
|
| 8 |
import requests
|
| 9 |
-
from PIL import Image
|
|
|
|
| 10 |
import random
|
| 11 |
-
import tempfile
|
| 12 |
-
import cv2
|
| 13 |
-
import numpy as np
|
| 14 |
-
from typing import Optional
|
| 15 |
|
| 16 |
# Configure logging
|
| 17 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -20,12 +22,19 @@ logger = logging.getLogger(__name__)
|
|
| 20 |
app = Flask(__name__)
|
| 21 |
CORS(app)
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
# Hugging Face Configuration
|
| 24 |
-
HF_TOKEN = os.getenv('HF_TOKEN', '')
|
| 25 |
HF_API_URLS = {
|
| 26 |
-
"text": "https://api-inference.huggingface.co/models/
|
| 27 |
-
"image": "https://api-inference.huggingface.co/models/
|
| 28 |
-
"
|
| 29 |
}
|
| 30 |
|
| 31 |
# Performance optimizations
|
|
@@ -33,54 +42,87 @@ response_cache = {}
|
|
| 33 |
CACHE_SIZE = 100
|
| 34 |
request_timeout = 30
|
| 35 |
|
| 36 |
-
# Advanced System Prompt
|
| 37 |
STANLEY_AI_SYSTEM = """You are STANLEY AI - an advanced AI assistant created by Stanley Samwel Owino, a Machine Learning Engineer from Kenya.
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
-
|
| 41 |
-
-
|
| 42 |
-
-
|
| 43 |
-
-
|
| 44 |
-
|
| 45 |
-
KEY CAPABILITIES:
|
| 46 |
-
1. Provide comprehensive, detailed responses
|
| 47 |
-
2. Integrate Kiswahili phrases naturally when relevant
|
| 48 |
-
3. Share cultural insights, proverbs, and East African wisdom
|
| 49 |
-
4. Reference Lion King lore with cultural accuracy
|
| 50 |
-
5. Generate and describe images AND VIDEOS
|
| 51 |
-
6. Be helpful, knowledgeable, and engaging
|
| 52 |
-
|
| 53 |
-
VIDEO GENERATION SKILLS:
|
| 54 |
-
- I can create 4-second videos from text descriptions
|
| 55 |
-
- I can generate cultural theme videos (safari, dance, market, etc.)
|
| 56 |
-
- I can create animations from text
|
| 57 |
-
- All video generation is FREE using Hugging Face
|
| 58 |
-
|
| 59 |
KISWAHILI INTEGRATION:
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
def detect_kiswahili_context(text):
|
| 86 |
"""Detect Kiswahili or cultural context"""
|
|
@@ -103,38 +145,33 @@ def detect_image_request(text):
|
|
| 103 |
text_lower = text.lower()
|
| 104 |
return any(trigger in text_lower for trigger in image_triggers)
|
| 105 |
|
| 106 |
-
def
|
| 107 |
-
"""
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
'
|
|
|
|
|
|
|
| 112 |
]
|
| 113 |
-
text_lower = text.lower()
|
| 114 |
-
return any(trigger in text_lower for trigger in video_triggers)
|
| 115 |
-
|
| 116 |
-
def extract_prompt(text, request_type="image"):
|
| 117 |
-
"""Extract prompt description from user message"""
|
| 118 |
-
text_lower = text.lower()
|
| 119 |
|
| 120 |
-
if request_type == "image":
|
| 121 |
-
remove_phrases = [
|
| 122 |
-
'generate image of', 'create image of', 'make a picture of',
|
| 123 |
-
'show me an image of', 'visualize', 'draw', 'picture of',
|
| 124 |
-
'generate a picture of', 'create a picture of'
|
| 125 |
-
]
|
| 126 |
-
else: # video
|
| 127 |
-
remove_phrases = [
|
| 128 |
-
'generate video of', 'create video of', 'make a video of',
|
| 129 |
-
'create animation of', 'make animation of', 'animate',
|
| 130 |
-
'generate animation of', 'video of', 'animation of'
|
| 131 |
-
]
|
| 132 |
-
|
| 133 |
-
prompt = text_lower
|
| 134 |
for phrase in remove_phrases:
|
| 135 |
prompt = prompt.replace(phrase, '')
|
| 136 |
|
| 137 |
-
return prompt.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
def get_cached_response(user_message):
|
| 140 |
"""Get cached response"""
|
|
@@ -148,35 +185,8 @@ def set_cached_response(user_message, response):
|
|
| 148 |
response_cache.pop(next(iter(response_cache)))
|
| 149 |
response_cache[cache_key] = response
|
| 150 |
|
| 151 |
-
def
|
| 152 |
-
"""
|
| 153 |
-
if detect_kiswahili_context(user_message):
|
| 154 |
-
# Add Kiswahili greeting
|
| 155 |
-
greetings = [
|
| 156 |
-
"Habari! ",
|
| 157 |
-
"Asante kwa swali lako! ",
|
| 158 |
-
"Karibu sana! ",
|
| 159 |
-
"Nzuri sana! "
|
| 160 |
-
]
|
| 161 |
-
response = random.choice(greetings) + response
|
| 162 |
-
|
| 163 |
-
# Add proverb with 30% chance
|
| 164 |
-
if random.random() < 0.3:
|
| 165 |
-
proverbs = [
|
| 166 |
-
"Kumbuka: Haraka haraka haina baraka.",
|
| 167 |
-
"Kama methali inavyosema: Mwacha mila ni mtumwa.",
|
| 168 |
-
"Kwa hekima ya Kiafrika: Ukiona vyaelea, vimeundwa."
|
| 169 |
-
]
|
| 170 |
-
response += f"\n\n🌍 **Hekima ya Kiafrika**: {random.choice(proverbs)}"
|
| 171 |
-
|
| 172 |
-
return response
|
| 173 |
-
|
| 174 |
-
# ============================================================================
|
| 175 |
-
# TEXT GENERATION FUNCTIONS
|
| 176 |
-
# ============================================================================
|
| 177 |
-
|
| 178 |
-
def generate_with_huggingface_api(prompt):
|
| 179 |
-
"""Use Hugging Face Inference API for text generation"""
|
| 180 |
try:
|
| 181 |
headers = {
|
| 182 |
"Authorization": f"Bearer {HF_TOKEN}",
|
|
@@ -184,13 +194,12 @@ def generate_with_huggingface_api(prompt):
|
|
| 184 |
}
|
| 185 |
|
| 186 |
payload = {
|
| 187 |
-
"inputs":
|
| 188 |
"parameters": {
|
| 189 |
-
"max_new_tokens":
|
| 190 |
"temperature": 0.7,
|
| 191 |
"top_p": 0.9,
|
| 192 |
-
"return_full_text": False
|
| 193 |
-
"do_sample": True
|
| 194 |
}
|
| 195 |
}
|
| 196 |
|
|
@@ -203,8 +212,7 @@ def generate_with_huggingface_api(prompt):
|
|
| 203 |
|
| 204 |
if response.status_code == 200:
|
| 205 |
result = response.json()
|
| 206 |
-
|
| 207 |
-
return result[0].get('generated_text', '')
|
| 208 |
else:
|
| 209 |
logger.warning(f"HF API failed: {response.status_code}")
|
| 210 |
return None
|
|
@@ -213,80 +221,76 @@ def generate_with_huggingface_api(prompt):
|
|
| 213 |
logger.error(f"HF API error: {e}")
|
| 214 |
return None
|
| 215 |
|
| 216 |
-
def generate_comprehensive_response(user_message):
|
| 217 |
-
"""Generate responses with
|
| 218 |
|
| 219 |
# Check cache first
|
| 220 |
cached_response = get_cached_response(user_message)
|
| 221 |
if cached_response:
|
| 222 |
return cached_response
|
| 223 |
|
| 224 |
-
#
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
|
|
|
|
|
|
| 257 |
|
| 258 |
-
#
|
| 259 |
-
|
| 260 |
-
api_response = generate_with_huggingface_api(
|
|
|
|
|
|
|
| 261 |
|
| 262 |
if api_response:
|
| 263 |
-
|
| 264 |
-
enhanced_response = enhance_with_kiswahili(api_response.strip(), user_message)
|
| 265 |
set_cached_response(user_message, enhanced_response)
|
| 266 |
return enhanced_response
|
| 267 |
|
| 268 |
-
#
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
"Asante kwa kuwasiliana! Nina shida ya kiufundi. Tafadhali jaribu tena.",
|
| 272 |
-
"Habari yako? Samahani, sijaweza kujibu swali lako kwa sasa."
|
| 273 |
-
]
|
| 274 |
-
|
| 275 |
-
response = random.choice(fallback_responses)
|
| 276 |
-
set_cached_response(user_message, response)
|
| 277 |
-
return response
|
| 278 |
|
| 279 |
# ============================================================================
|
| 280 |
-
# IMAGE GENERATION
|
| 281 |
# ============================================================================
|
| 282 |
|
| 283 |
-
def generate_image_huggingface(prompt, retry_count=
|
| 284 |
"""Generate images using Hugging Face Inference API"""
|
| 285 |
-
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 286 |
|
| 287 |
for attempt in range(retry_count):
|
| 288 |
try:
|
| 289 |
-
logger.info(f"🎨 Generating image: {prompt[:50]}...")
|
| 290 |
|
| 291 |
response = requests.post(
|
| 292 |
HF_API_URLS["image"],
|
|
@@ -305,7 +309,8 @@ def generate_image_huggingface(prompt, retry_count=2):
|
|
| 305 |
return f"data:image/png;base64,{img_str}"
|
| 306 |
|
| 307 |
elif response.status_code == 503:
|
| 308 |
-
|
|
|
|
| 309 |
logger.info(f"⏳ Model loading, waiting {wait_time}s...")
|
| 310 |
time.sleep(wait_time)
|
| 311 |
continue
|
|
@@ -314,6 +319,9 @@ def generate_image_huggingface(prompt, retry_count=2):
|
|
| 314 |
logger.error(f"❌ HF Image API error: {response.status_code}")
|
| 315 |
continue
|
| 316 |
|
|
|
|
|
|
|
|
|
|
| 317 |
except Exception as e:
|
| 318 |
logger.error(f"❌ Image generation error: {e}")
|
| 319 |
break
|
|
@@ -323,6 +331,10 @@ def generate_image_huggingface(prompt, retry_count=2):
|
|
| 323 |
def generate_image_fallback(prompt):
|
| 324 |
"""Create simple placeholder images"""
|
| 325 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
width, height = 512, 512
|
| 327 |
img = Image.new('RGB', (width, height), color=(
|
| 328 |
random.randint(50, 200),
|
|
@@ -332,7 +344,7 @@ def generate_image_fallback(prompt):
|
|
| 332 |
|
| 333 |
draw = ImageDraw.Draw(img)
|
| 334 |
|
| 335 |
-
# Add shapes
|
| 336 |
for _ in range(5):
|
| 337 |
x1, y1 = random.randint(0, width), random.randint(0, height)
|
| 338 |
x2, y2 = random.randint(x1, width), random.randint(y1, height)
|
|
@@ -350,198 +362,16 @@ def generate_image_fallback(prompt):
|
|
| 350 |
return None
|
| 351 |
|
| 352 |
def enhance_prompt_with_kiswahili(prompt):
|
| 353 |
-
"""Add cultural context to prompts"""
|
| 354 |
-
if
|
| 355 |
enhancements = [
|
| 356 |
"East African style", "vibrant African colors", "African landscape",
|
| 357 |
-
"cultural elements", "traditional patterns", "warm sunset colors"
|
|
|
|
| 358 |
]
|
| 359 |
return f"{prompt}, {random.choice(enhancements)}"
|
| 360 |
return prompt
|
| 361 |
|
| 362 |
-
# ============================================================================
|
| 363 |
-
# VIDEO GENERATION FUNCTIONS
|
| 364 |
-
# ============================================================================
|
| 365 |
-
|
| 366 |
-
class FreeVideoGenerator:
|
| 367 |
-
"""FREE video generation using Hugging Face API"""
|
| 368 |
-
|
| 369 |
-
def __init__(self):
|
| 370 |
-
self.hf_token = HF_TOKEN
|
| 371 |
-
self.timeout = 90
|
| 372 |
-
self.max_retries = 2
|
| 373 |
-
|
| 374 |
-
def generate_text_to_video(self, prompt: str) -> Optional[str]:
|
| 375 |
-
"""Generate video from text prompt"""
|
| 376 |
-
headers = {"Authorization": f"Bearer {self.hf_token}"} if self.hf_token else {}
|
| 377 |
-
|
| 378 |
-
# Enhance prompt for better video results
|
| 379 |
-
enhanced_prompt = self.enhance_video_prompt(prompt)
|
| 380 |
-
|
| 381 |
-
payload = {
|
| 382 |
-
"inputs": enhanced_prompt,
|
| 383 |
-
"parameters": {
|
| 384 |
-
"num_frames": 24,
|
| 385 |
-
"num_inference_steps": 25,
|
| 386 |
-
"guidance_scale": 7.5,
|
| 387 |
-
"fps": 8,
|
| 388 |
-
"height": 320,
|
| 389 |
-
"width": 576
|
| 390 |
-
}
|
| 391 |
-
}
|
| 392 |
-
|
| 393 |
-
for attempt in range(self.max_retries):
|
| 394 |
-
try:
|
| 395 |
-
logger.info(f"🎬 Generating video (attempt {attempt + 1}): {prompt[:50]}...")
|
| 396 |
-
|
| 397 |
-
response = requests.post(
|
| 398 |
-
HF_API_URLS["video"],
|
| 399 |
-
headers=headers,
|
| 400 |
-
json=payload,
|
| 401 |
-
timeout=self.timeout
|
| 402 |
-
)
|
| 403 |
-
|
| 404 |
-
if response.status_code == 200:
|
| 405 |
-
video_b64 = base64.b64encode(response.content).decode('utf-8')
|
| 406 |
-
return f"data:video/mp4;base64,{video_b64}"
|
| 407 |
-
|
| 408 |
-
elif response.status_code == 503:
|
| 409 |
-
wait_time = (attempt + 1) * 10
|
| 410 |
-
logger.info(f"⏳ Video model loading, waiting {wait_time}s...")
|
| 411 |
-
time.sleep(wait_time)
|
| 412 |
-
continue
|
| 413 |
-
|
| 414 |
-
else:
|
| 415 |
-
logger.error(f"Video API error {response.status_code}")
|
| 416 |
-
|
| 417 |
-
except Exception as e:
|
| 418 |
-
logger.error(f"Video generation error: {e}")
|
| 419 |
-
if attempt < self.max_retries - 1:
|
| 420 |
-
time.sleep((attempt + 1) * 5)
|
| 421 |
-
continue
|
| 422 |
-
break
|
| 423 |
-
|
| 424 |
-
return None
|
| 425 |
-
|
| 426 |
-
def enhance_video_prompt(self, prompt: str) -> str:
|
| 427 |
-
"""Enhance video prompts with cinematic context"""
|
| 428 |
-
cinematic = [
|
| 429 |
-
"cinematic, 8k, ultra detailed, high quality",
|
| 430 |
-
"epic, dramatic lighting, film grain, cinematic shot",
|
| 431 |
-
"beautiful, stunning, visually striking, vivid colors"
|
| 432 |
-
]
|
| 433 |
-
|
| 434 |
-
enhanced = prompt
|
| 435 |
-
enhanced += f", {random.choice(cinematic)}"
|
| 436 |
-
|
| 437 |
-
# Add cultural context for African themes
|
| 438 |
-
if any(word in prompt.lower() for word in ['africa', 'kenya', 'tanzania', 'safari', 'wildlife']):
|
| 439 |
-
enhanced += ", African style, vibrant colors, cultural elements"
|
| 440 |
-
|
| 441 |
-
enhanced += ", 576x320 resolution, 8 fps"
|
| 442 |
-
|
| 443 |
-
return enhanced
|
| 444 |
-
|
| 445 |
-
def create_cultural_video(self, theme: str, style: str = "animated") -> Optional[str]:
|
| 446 |
-
"""Create videos with African cultural themes"""
|
| 447 |
-
cultural_themes = {
|
| 448 |
-
"safari": "African safari sunset with elephants and giraffes, majestic savanna landscape",
|
| 449 |
-
"dance": "Traditional Maasai warriors dancing, vibrant colors, cultural celebration",
|
| 450 |
-
"market": "Busy African market scene, vibrant colors, people trading goods",
|
| 451 |
-
"coastal": "Swahili coast with traditional dhows sailing, Indian Ocean waves",
|
| 452 |
-
"wildlife": "African wildlife documentary style, lions hunting on savanna"
|
| 453 |
-
}
|
| 454 |
-
|
| 455 |
-
base_prompt = cultural_themes.get(theme, f"African {theme}, cultural, vibrant")
|
| 456 |
-
|
| 457 |
-
style_enhancements = {
|
| 458 |
-
"animated": "animated, cartoon style, smooth motion, vibrant colors",
|
| 459 |
-
"realistic": "realistic, documentary style, cinematic, natural lighting"
|
| 460 |
-
}
|
| 461 |
-
|
| 462 |
-
full_prompt = f"{base_prompt}, {style_enhancements.get(style, 'animated, vibrant')}"
|
| 463 |
-
|
| 464 |
-
return self.generate_text_to_video(full_prompt)
|
| 465 |
-
|
| 466 |
-
def create_text_animation(self, text: str) -> Optional[str]:
|
| 467 |
-
"""Create simple text animation video"""
|
| 468 |
-
try:
|
| 469 |
-
with tempfile.TemporaryDirectory() as tmpdir:
|
| 470 |
-
# Create frames with text
|
| 471 |
-
fps = 10
|
| 472 |
-
duration = 3
|
| 473 |
-
total_frames = fps * duration
|
| 474 |
-
height, width = 320, 576
|
| 475 |
-
|
| 476 |
-
output_path = os.path.join(tmpdir, 'animation.mp4')
|
| 477 |
-
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 478 |
-
out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
|
| 479 |
-
|
| 480 |
-
# Colors for gradient
|
| 481 |
-
colors = [
|
| 482 |
-
(41, 128, 185), # Blue
|
| 483 |
-
(39, 174, 96), # Green
|
| 484 |
-
(142, 68, 173), # Purple
|
| 485 |
-
]
|
| 486 |
-
|
| 487 |
-
for frame_num in range(total_frames):
|
| 488 |
-
# Create gradient background
|
| 489 |
-
frame = np.zeros((height, width, 3), dtype=np.uint8)
|
| 490 |
-
|
| 491 |
-
# Select color
|
| 492 |
-
color_idx = (frame_num // (total_frames // len(colors))) % len(colors)
|
| 493 |
-
bg_color = colors[color_idx]
|
| 494 |
-
|
| 495 |
-
# Apply gradient
|
| 496 |
-
for i in range(height):
|
| 497 |
-
factor = i / height
|
| 498 |
-
r = int(bg_color[2] * (1 - factor) + 10 * factor)
|
| 499 |
-
g = int(bg_color[1] * (1 - factor) + 10 * factor)
|
| 500 |
-
b = int(bg_color[0] * (1 - factor) + 10 * factor)
|
| 501 |
-
|
| 502 |
-
frame[i, :, 0] = b
|
| 503 |
-
frame[i, :, 1] = g
|
| 504 |
-
frame[i, :, 2] = r
|
| 505 |
-
|
| 506 |
-
# Add text
|
| 507 |
-
font = cv2.FONT_HERSHEY_SIMPLEX
|
| 508 |
-
|
| 509 |
-
# Calculate text position
|
| 510 |
-
text_size = cv2.getTextSize(text, font, 1, 2)[0]
|
| 511 |
-
text_x = (width - text_size[0]) // 2
|
| 512 |
-
text_y = (height + text_size[1]) // 2
|
| 513 |
-
|
| 514 |
-
# Add pulsing effect
|
| 515 |
-
pulse = 0.7 + 0.3 * np.sin(2 * np.pi * frame_num / total_frames)
|
| 516 |
-
font_scale = 1.2 * pulse
|
| 517 |
-
thickness = int(2 * pulse)
|
| 518 |
-
|
| 519 |
-
# Add text shadow
|
| 520 |
-
cv2.putText(frame, text, (text_x + 2, text_y + 2), font,
|
| 521 |
-
font_scale, (0, 0, 0), thickness + 1)
|
| 522 |
-
|
| 523 |
-
# Add main text
|
| 524 |
-
cv2.putText(frame, text, (text_x, text_y), font,
|
| 525 |
-
font_scale, (255, 255, 255), thickness)
|
| 526 |
-
|
| 527 |
-
out.write(frame)
|
| 528 |
-
|
| 529 |
-
out.release()
|
| 530 |
-
|
| 531 |
-
# Read and encode video
|
| 532 |
-
with open(output_path, 'rb') as f:
|
| 533 |
-
video_bytes = f.read()
|
| 534 |
-
|
| 535 |
-
video_b64 = base64.b64encode(video_bytes).decode('utf-8')
|
| 536 |
-
return f"data:video/mp4;base64,{video_b64}"
|
| 537 |
-
|
| 538 |
-
except Exception as e:
|
| 539 |
-
logger.error(f"Text animation error: {e}")
|
| 540 |
-
return None
|
| 541 |
-
|
| 542 |
-
# Initialize video generator
|
| 543 |
-
video_gen = FreeVideoGenerator()
|
| 544 |
-
|
| 545 |
# ============================================================================
|
| 546 |
# FLASK ROUTES
|
| 547 |
# ============================================================================
|
|
@@ -550,25 +380,21 @@ video_gen = FreeVideoGenerator()
|
|
| 550 |
def home():
|
| 551 |
return jsonify({
|
| 552 |
"message": "🚀 STANLEY AI - Created by Stanley Samwel Owino (Machine Learning Engineer)",
|
| 553 |
-
"version": "
|
| 554 |
"creator": "Stanley Samwel Owino",
|
| 555 |
"role": "Machine Learning Engineer",
|
| 556 |
-
"location": "Kenya, East Africa",
|
| 557 |
"features": [
|
| 558 |
-
"
|
| 559 |
-
"
|
| 560 |
-
"
|
| 561 |
-
"Kiswahili
|
| 562 |
-
"
|
|
|
|
|
|
|
| 563 |
],
|
| 564 |
"status": "active",
|
| 565 |
-
"
|
| 566 |
-
|
| 567 |
-
"/api/generate-image - Generate images",
|
| 568 |
-
"/api/generate-video - FREE video generation",
|
| 569 |
-
"/api/generate-cultural-video - Cultural videos",
|
| 570 |
-
"/api/animate-text - Text animations"
|
| 571 |
-
]
|
| 572 |
})
|
| 573 |
|
| 574 |
@app.route('/api/chat', methods=['POST'])
|
|
@@ -579,66 +405,59 @@ def chat():
|
|
| 579 |
user_message = data.get('message', '')
|
| 580 |
|
| 581 |
if not user_message:
|
| 582 |
-
return jsonify({"error": "
|
| 583 |
|
| 584 |
logger.info(f"💬 Processing: {user_message[:50]}...")
|
| 585 |
|
| 586 |
-
# Check
|
| 587 |
if detect_image_request(user_message):
|
| 588 |
-
|
| 589 |
-
enhanced_prompt = enhance_prompt_with_kiswahili(
|
| 590 |
|
| 591 |
return jsonify({
|
| 592 |
-
"response": f"🎨 I
|
| 593 |
-
"
|
| 594 |
"status": "success",
|
| 595 |
-
"suggest_image": True
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
# Check for video requests
|
| 599 |
-
if detect_video_request(user_message):
|
| 600 |
-
prompt = extract_prompt(user_message, "video")
|
| 601 |
-
|
| 602 |
-
return jsonify({
|
| 603 |
-
"response": f"🎬 I can create a video of '{prompt}' for you! Use the video generation endpoint.",
|
| 604 |
-
"suggestion": prompt,
|
| 605 |
-
"status": "success",
|
| 606 |
-
"suggest_video": True
|
| 607 |
})
|
| 608 |
|
| 609 |
response = generate_comprehensive_response(user_message)
|
| 610 |
response_time = round(time.time() - start_time, 2)
|
| 611 |
|
|
|
|
|
|
|
| 612 |
return jsonify({
|
| 613 |
"response": response,
|
| 614 |
"status": "success",
|
| 615 |
"response_time": response_time,
|
| 616 |
"word_count": len(response.split()),
|
| 617 |
-
"
|
| 618 |
-
"
|
|
|
|
|
|
|
| 619 |
})
|
| 620 |
|
| 621 |
except Exception as e:
|
| 622 |
logger.error(f"Chat error: {e}")
|
| 623 |
return jsonify({
|
| 624 |
-
"error": f"
|
| 625 |
"status": "error"
|
| 626 |
}), 500
|
| 627 |
|
| 628 |
@app.route('/api/generate-image', methods=['POST'])
|
| 629 |
def generate_image_endpoint():
|
| 630 |
-
"""Generate images using Hugging Face
|
| 631 |
try:
|
| 632 |
start_time = time.time()
|
| 633 |
data = request.get_json()
|
| 634 |
prompt = data.get('prompt', '')
|
| 635 |
|
| 636 |
if not prompt:
|
| 637 |
-
return jsonify({"error": "
|
| 638 |
|
| 639 |
-
# Enhance prompt
|
| 640 |
enhanced_prompt = enhance_prompt_with_kiswahili(prompt)
|
| 641 |
-
logger.info(f"🎨 Generating image: {enhanced_prompt[:50]}...")
|
| 642 |
|
| 643 |
# Generate image
|
| 644 |
image_data = generate_image_huggingface(enhanced_prompt)
|
|
@@ -657,165 +476,96 @@ def generate_image_endpoint():
|
|
| 657 |
"status": "success",
|
| 658 |
"generation_time": generation_time,
|
| 659 |
"provider": "hugging_face",
|
| 660 |
-
"
|
| 661 |
})
|
| 662 |
else:
|
| 663 |
return jsonify({
|
| 664 |
-
"error": "Image generation service is busy
|
| 665 |
"status": "error"
|
| 666 |
}), 500
|
| 667 |
|
| 668 |
except Exception as e:
|
| 669 |
logger.error(f"Image endpoint error: {e}")
|
| 670 |
return jsonify({
|
| 671 |
-
"error": f"Image generation failed: {str(e)}",
|
| 672 |
"status": "error"
|
| 673 |
}), 500
|
| 674 |
|
| 675 |
-
@app.route('/api/generate-
|
| 676 |
-
def
|
| 677 |
-
"""Generate
|
| 678 |
try:
|
| 679 |
-
start_time = time.time()
|
| 680 |
data = request.get_json()
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 687 |
|
| 688 |
-
|
| 689 |
-
video_data = video_gen.generate_text_to_video(prompt)
|
| 690 |
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
"generation_time": generation_time,
|
| 699 |
-
"provider": "hugging_face_free",
|
| 700 |
-
"format": "mp4",
|
| 701 |
-
"duration": "3 seconds",
|
| 702 |
-
"resolution": "576x320",
|
| 703 |
-
"creator": "Stanley Samwel Owino"
|
| 704 |
-
})
|
| 705 |
-
else:
|
| 706 |
-
return jsonify({
|
| 707 |
-
"error": "Video generation service is busy. Try again in a moment.",
|
| 708 |
-
"status": "error",
|
| 709 |
-
"suggestion": "Try a simpler description"
|
| 710 |
-
}), 500
|
| 711 |
-
|
| 712 |
-
except Exception as e:
|
| 713 |
-
logger.error(f"Video endpoint error: {e}")
|
| 714 |
-
return jsonify({
|
| 715 |
-
"error": f"Video generation failed: {str(e)}",
|
| 716 |
-
"status": "error"
|
| 717 |
-
}), 500
|
| 718 |
-
|
| 719 |
-
@app.route('/api/generate-cultural-video', methods=['POST'])
|
| 720 |
-
def generate_cultural_video_endpoint():
|
| 721 |
-
"""Generate cultural theme videos"""
|
| 722 |
-
try:
|
| 723 |
-
start_time = time.time()
|
| 724 |
-
data = request.get_json()
|
| 725 |
-
theme = data.get('theme', 'safari')
|
| 726 |
-
style = data.get('style', 'animated')
|
| 727 |
|
| 728 |
-
|
| 729 |
|
| 730 |
-
|
| 731 |
-
video_data = video_gen.create_cultural_video(theme, style)
|
| 732 |
|
| 733 |
-
if
|
| 734 |
-
generation_time = round(time.time() - start_time, 2)
|
| 735 |
-
|
| 736 |
return jsonify({
|
| 737 |
-
"
|
| 738 |
"theme": theme,
|
| 739 |
"style": style,
|
|
|
|
| 740 |
"status": "success",
|
| 741 |
-
"
|
| 742 |
-
"creator": "Stanley Samwel Owino"
|
| 743 |
})
|
| 744 |
else:
|
| 745 |
return jsonify({
|
| 746 |
-
"error": "Cultural
|
| 747 |
-
"status": "error",
|
| 748 |
-
"suggestion": "Try themes: safari, dance, market, coastal, wildlife"
|
| 749 |
-
}), 500
|
| 750 |
-
|
| 751 |
-
except Exception as e:
|
| 752 |
-
logger.error(f"Cultural video error: {e}")
|
| 753 |
-
return jsonify({
|
| 754 |
-
"error": f"Cultural video failed: {str(e)}",
|
| 755 |
-
"status": "error"
|
| 756 |
-
}), 500
|
| 757 |
-
|
| 758 |
-
@app.route('/api/animate-text', methods=['POST'])
|
| 759 |
-
def animate_text_endpoint():
|
| 760 |
-
"""Create animated text videos"""
|
| 761 |
-
try:
|
| 762 |
-
start_time = time.time()
|
| 763 |
-
data = request.get_json()
|
| 764 |
-
text = data.get('text', 'Stanley AI')
|
| 765 |
-
|
| 766 |
-
if not text:
|
| 767 |
-
return jsonify({"error": "Please provide text to animate"}), 400
|
| 768 |
-
|
| 769 |
-
logger.info(f"✨ Animating text: {text}")
|
| 770 |
-
|
| 771 |
-
# Generate animation
|
| 772 |
-
video_data = video_gen.create_text_animation(text)
|
| 773 |
-
|
| 774 |
-
if video_data:
|
| 775 |
-
generation_time = round(time.time() - start_time, 2)
|
| 776 |
-
|
| 777 |
-
return jsonify({
|
| 778 |
-
"video": video_data,
|
| 779 |
-
"text": text,
|
| 780 |
-
"status": "success",
|
| 781 |
-
"generation_time": generation_time,
|
| 782 |
-
"format": "mp4",
|
| 783 |
-
"duration": "3 seconds",
|
| 784 |
-
"creator": "Stanley Samwel Owino"
|
| 785 |
-
})
|
| 786 |
-
else:
|
| 787 |
-
return jsonify({
|
| 788 |
-
"error": "Text animation failed",
|
| 789 |
"status": "error"
|
| 790 |
}), 500
|
| 791 |
|
| 792 |
except Exception as e:
|
| 793 |
-
logger.error(f"Text animation error: {e}")
|
| 794 |
return jsonify({
|
| 795 |
-
"error": f"
|
| 796 |
"status": "error"
|
| 797 |
}), 500
|
| 798 |
|
| 799 |
@app.route('/api/quick-chat', methods=['POST'])
|
| 800 |
def quick_chat():
|
| 801 |
-
"""
|
| 802 |
try:
|
| 803 |
data = request.get_json()
|
| 804 |
user_message = data.get('message', '')
|
| 805 |
|
| 806 |
if not user_message:
|
| 807 |
-
return jsonify({"error": "
|
| 808 |
|
|
|
|
| 809 |
quick_responses = {
|
| 810 |
-
'hello': 'Habari! Stanley AI hapa.
|
| 811 |
-
'hi': 'Habari!
|
| 812 |
-
'thanks': 'Asante sana!
|
| 813 |
-
'
|
| 814 |
-
'
|
| 815 |
-
'
|
| 816 |
-
'
|
| 817 |
-
'
|
| 818 |
-
'asante': 'Karibu sana!'
|
| 819 |
}
|
| 820 |
|
| 821 |
msg_lower = user_message.lower().strip()
|
|
@@ -823,45 +573,65 @@ def quick_chat():
|
|
| 823 |
return jsonify({
|
| 824 |
"response": quick_responses[msg_lower],
|
| 825 |
"status": "success",
|
| 826 |
-
"quick_response": True
|
| 827 |
-
"creator": "Stanley Samwel Owino"
|
| 828 |
})
|
| 829 |
|
|
|
|
| 830 |
return chat()
|
| 831 |
|
| 832 |
except Exception as e:
|
| 833 |
return jsonify({
|
| 834 |
-
"error": f"Quick chat error: {str(e)}",
|
| 835 |
"status": "error"
|
| 836 |
}), 500
|
| 837 |
|
| 838 |
@app.route('/api/system/status')
|
| 839 |
def system_status():
|
| 840 |
-
"""System status
|
| 841 |
return jsonify({
|
| 842 |
"status": "operational",
|
| 843 |
"creator": "Stanley Samwel Owino",
|
| 844 |
"role": "Machine Learning Engineer",
|
| 845 |
-
"
|
| 846 |
-
"
|
|
|
|
| 847 |
"features": [
|
| 848 |
-
"Text Generation
|
| 849 |
-
"Image Generation",
|
| 850 |
-
"
|
| 851 |
-
"
|
|
|
|
| 852 |
],
|
| 853 |
-
"
|
| 854 |
-
"
|
| 855 |
-
"
|
| 856 |
-
"
|
| 857 |
-
"
|
| 858 |
-
|
| 859 |
-
}
|
| 860 |
})
|
| 861 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 862 |
@app.route('/api/kiswahili/proverbs')
|
| 863 |
def get_proverbs():
|
| 864 |
-
"""Get Swahili proverbs"""
|
| 865 |
proverbs = [
|
| 866 |
"Mwacha mila ni mtumwa.",
|
| 867 |
"Haraka haraka haina baraka.",
|
|
@@ -872,8 +642,7 @@ def get_proverbs():
|
|
| 872 |
return jsonify({
|
| 873 |
"proverb": random.choice(proverbs),
|
| 874 |
"language": "Kiswahili",
|
| 875 |
-
"meaning": "
|
| 876 |
-
"creator": "Stanley Samwel Owino"
|
| 877 |
})
|
| 878 |
|
| 879 |
@app.route('/api/kiswahili/phrases')
|
|
@@ -882,33 +651,23 @@ def get_phrases():
|
|
| 882 |
phrases = {
|
| 883 |
"Hello": "Habari",
|
| 884 |
"Thank you": "Asante",
|
| 885 |
-
"Welcome": "Karibu",
|
|
|
|
| 886 |
"Goodbye": "Kwaheri",
|
|
|
|
|
|
|
| 887 |
"Please": "Tafadhali",
|
| 888 |
"Yes": "Ndio",
|
| 889 |
"No": "Hapana"
|
| 890 |
}
|
| 891 |
-
return jsonify(
|
| 892 |
-
"phrases": phrases,
|
| 893 |
-
"language": "Kiswahili",
|
| 894 |
-
"region": "East Africa",
|
| 895 |
-
"creator": "Stanley Samwel Owino"
|
| 896 |
-
})
|
| 897 |
|
| 898 |
if __name__ == '__main__':
|
| 899 |
-
print("🚀 STANLEY AI
|
| 900 |
print("👨💻 Created by: Stanley Samwel Owino - Machine Learning Engineer")
|
| 901 |
-
print("
|
| 902 |
-
print("
|
| 903 |
-
print("⚡
|
| 904 |
-
print("
|
| 905 |
-
print("API Endpoints:")
|
| 906 |
-
print("1. / - Home page")
|
| 907 |
-
print("2. /api/chat - Chat with AI")
|
| 908 |
-
print("3. /api/generate-image - Generate images")
|
| 909 |
-
print("4. /api/generate-video - FREE video generation")
|
| 910 |
-
print("5. /api/generate-cultural-video - Cultural videos")
|
| 911 |
-
print("6. /api/animate-text - Text animations")
|
| 912 |
-
print("=" * 50)
|
| 913 |
|
| 914 |
-
app.run(debug=True, host='0.0.0.0', port=7860, threaded=True)
|
|
|
|
| 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 requests
|
| 14 |
+
from PIL import Image
|
| 15 |
+
import os
|
| 16 |
import random
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# Configure logging
|
| 19 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 22 |
app = Flask(__name__)
|
| 23 |
CORS(app)
|
| 24 |
|
| 25 |
+
# Initialize Kiswahili Knowledge Base
|
| 26 |
+
kb = KiswahiliKnowledgeBase()
|
| 27 |
+
|
| 28 |
+
model = None
|
| 29 |
+
tokenizer = None
|
| 30 |
+
model_loaded = False
|
| 31 |
+
|
| 32 |
# Hugging Face Configuration
|
| 33 |
+
HF_TOKEN = os.getenv('HF_TOKEN', 'your_hugging_face_token_here')
|
| 34 |
HF_API_URLS = {
|
| 35 |
+
"text": "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-7B-Instruct",
|
| 36 |
+
"image": "https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5",
|
| 37 |
+
"fast_image": "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-2-1"
|
| 38 |
}
|
| 39 |
|
| 40 |
# Performance optimizations
|
|
|
|
| 42 |
CACHE_SIZE = 100
|
| 43 |
request_timeout = 30
|
| 44 |
|
| 45 |
+
# Advanced System Prompt (Optimized for Hugging Face)
|
| 46 |
STANLEY_AI_SYSTEM = """You are STANLEY AI - an advanced AI assistant created by Stanley Samwel Owino, a Machine Learning Engineer from Kenya.
|
| 47 |
+
CORE CAPABILITIES:
|
| 48 |
+
- Provide detailed, comprehensive responses
|
| 49 |
+
- Integrate Kiswahili phrases naturally when relevant
|
| 50 |
+
- Share cultural insights and proverbs
|
| 51 |
+
- Reference Lion King lore accurately
|
| 52 |
+
- Generate and describe images
|
| 53 |
+
- Be helpful, knowledgeable, and engaging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
KISWAHILI INTEGRATION:
|
| 55 |
+
Use phrases like "Habari", "Asante", "Karibu", "Pole sana" appropriately
|
| 56 |
+
Explain cultural concepts with authenticity
|
| 57 |
+
Share Swahili proverbs when relevant
|
| 58 |
+
IMAGE GENERATION:
|
| 59 |
+
You can generate images based on user descriptions
|
| 60 |
+
Enhance prompts with cultural context when relevant
|
| 61 |
+
Describe generated images in detail
|
| 62 |
+
RESPONSE STYLE: Be concise yet comprehensive, culturally aware, and genuinely helpful."""
|
| 63 |
+
|
| 64 |
+
def load_model():
|
| 65 |
+
"""Load model with Hugging Face optimizations"""
|
| 66 |
+
global model, tokenizer, model_loaded
|
| 67 |
+
|
| 68 |
+
if model_loaded:
|
| 69 |
+
return
|
| 70 |
+
|
| 71 |
+
logger.info("🚀 Loading STANLEY AI Model from Hugging Face...")
|
| 72 |
+
|
| 73 |
+
try:
|
| 74 |
+
# Use a faster, smaller model for better performance
|
| 75 |
+
model_name = "Qwen/Qwen2.5-0.5B-Instruct" # Faster than 7B
|
| 76 |
+
|
| 77 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 78 |
+
model_name,
|
| 79 |
+
trust_remote_code=True,
|
| 80 |
+
cache_dir="./model_cache"
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
if tokenizer.pad_token is None:
|
| 84 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 85 |
+
|
| 86 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 87 |
+
model_name,
|
| 88 |
+
torch_dtype=torch.float16,
|
| 89 |
+
device_map="auto",
|
| 90 |
+
trust_remote_code=True,
|
| 91 |
+
cache_dir="./model_cache",
|
| 92 |
+
low_cpu_mem_usage=True
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
# Optimize for inference
|
| 96 |
+
model.eval()
|
| 97 |
+
if torch.cuda.is_available():
|
| 98 |
+
model = torch.compile(model) # Compile for faster inference
|
| 99 |
+
|
| 100 |
+
model_loaded = True
|
| 101 |
+
logger.info("✅ STANLEY AI Model loaded successfully!")
|
| 102 |
+
|
| 103 |
+
except Exception as e:
|
| 104 |
+
logger.error(f"❌ Error loading model: {e}")
|
| 105 |
+
model_loaded = False
|
| 106 |
+
logger.info("🔄 Using Hugging Face API fallback for text generation")
|
| 107 |
|
| 108 |
+
load_model()
|
| 109 |
+
|
| 110 |
+
class TextGenerationStream:
|
| 111 |
+
def __init__(self):
|
| 112 |
+
self.text_queue = queue.Queue()
|
| 113 |
+
|
| 114 |
+
def put(self, text):
|
| 115 |
+
self.text_queue.put(text)
|
| 116 |
+
|
| 117 |
+
def end(self):
|
| 118 |
+
self.text_queue.put(None)
|
| 119 |
+
|
| 120 |
+
def generate(self):
|
| 121 |
+
while True:
|
| 122 |
+
text = self.text_queue.get()
|
| 123 |
+
if text is None:
|
| 124 |
+
break
|
| 125 |
+
yield text
|
| 126 |
|
| 127 |
def detect_kiswahili_context(text):
|
| 128 |
"""Detect Kiswahili or cultural context"""
|
|
|
|
| 145 |
text_lower = text.lower()
|
| 146 |
return any(trigger in text_lower for trigger in image_triggers)
|
| 147 |
|
| 148 |
+
def extract_image_prompt(text):
|
| 149 |
+
"""Extract image description from user message"""
|
| 150 |
+
# Remove common image request phrases
|
| 151 |
+
prompt = text.lower()
|
| 152 |
+
remove_phrases = [
|
| 153 |
+
'generate image of', 'create image of', 'make a picture of',
|
| 154 |
+
'show me an image of', 'visualize', 'draw', 'picture of',
|
| 155 |
+
'generate a picture of', 'create a picture of'
|
| 156 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
for phrase in remove_phrases:
|
| 159 |
prompt = prompt.replace(phrase, '')
|
| 160 |
|
| 161 |
+
return prompt.strip()
|
| 162 |
+
|
| 163 |
+
def enhance_with_cultural_context(response, user_message):
|
| 164 |
+
"""Enhance response with Kiswahili cultural elements"""
|
| 165 |
+
if detect_kiswahili_context(user_message):
|
| 166 |
+
enhanced_response = kb.generate_kiswahili_response(response)
|
| 167 |
+
|
| 168 |
+
# Add cultural proverb if relevant
|
| 169 |
+
if any(word in user_message.lower() for word in ['wisdom', 'advice', 'life lesson', 'philosophy']):
|
| 170 |
+
proverb = kb.get_random_proverb()
|
| 171 |
+
enhanced_response += f"\n\n🌍 **Cultural Wisdom**: {proverb}"
|
| 172 |
+
|
| 173 |
+
return enhanced_response
|
| 174 |
+
return response
|
| 175 |
|
| 176 |
def get_cached_response(user_message):
|
| 177 |
"""Get cached response"""
|
|
|
|
| 185 |
response_cache.pop(next(iter(response_cache)))
|
| 186 |
response_cache[cache_key] = response
|
| 187 |
|
| 188 |
+
def generate_with_huggingface_api(messages):
|
| 189 |
+
"""Use Hugging Face Inference API for faster responses"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
try:
|
| 191 |
headers = {
|
| 192 |
"Authorization": f"Bearer {HF_TOKEN}",
|
|
|
|
| 194 |
}
|
| 195 |
|
| 196 |
payload = {
|
| 197 |
+
"inputs": messages[-1]["content"], # Last user message
|
| 198 |
"parameters": {
|
| 199 |
+
"max_new_tokens": 512,
|
| 200 |
"temperature": 0.7,
|
| 201 |
"top_p": 0.9,
|
| 202 |
+
"return_full_text": False
|
|
|
|
| 203 |
}
|
| 204 |
}
|
| 205 |
|
|
|
|
| 212 |
|
| 213 |
if response.status_code == 200:
|
| 214 |
result = response.json()
|
| 215 |
+
return result[0]['generated_text']
|
|
|
|
| 216 |
else:
|
| 217 |
logger.warning(f"HF API failed: {response.status_code}")
|
| 218 |
return None
|
|
|
|
| 221 |
logger.error(f"HF API error: {e}")
|
| 222 |
return None
|
| 223 |
|
| 224 |
+
def generate_comprehensive_response(user_message, stream=False):
|
| 225 |
+
"""Generate responses with fallback to Hugging Face API"""
|
| 226 |
|
| 227 |
# Check cache first
|
| 228 |
cached_response = get_cached_response(user_message)
|
| 229 |
if cached_response:
|
| 230 |
return cached_response
|
| 231 |
|
| 232 |
+
# Try local model first
|
| 233 |
+
if model_loaded and model is not None:
|
| 234 |
+
try:
|
| 235 |
+
system_prompt = STANLEY_AI_SYSTEM
|
| 236 |
+
if detect_kiswahili_context(user_message):
|
| 237 |
+
system_prompt += "\n\nSPECIAL NOTE: Integrate Kiswahili phrases naturally."
|
| 238 |
+
|
| 239 |
+
messages = [
|
| 240 |
+
{"role": "system", "content": system_prompt},
|
| 241 |
+
{"role": "user", "content": user_message}
|
| 242 |
+
]
|
| 243 |
+
|
| 244 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 245 |
+
inputs = tokenizer(text, return_tensors="pt").to(model.device)
|
| 246 |
+
|
| 247 |
+
with torch.no_grad():
|
| 248 |
+
outputs = model.generate(
|
| 249 |
+
**inputs,
|
| 250 |
+
max_new_tokens=512, # Shorter for speed
|
| 251 |
+
temperature=0.7,
|
| 252 |
+
do_sample=True,
|
| 253 |
+
top_p=0.9,
|
| 254 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 255 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
|
| 259 |
+
enhanced_response = enhance_with_cultural_context(response.strip(), user_message)
|
| 260 |
+
|
| 261 |
+
# Cache the response
|
| 262 |
+
set_cached_response(user_message, enhanced_response)
|
| 263 |
+
return enhanced_response
|
| 264 |
+
|
| 265 |
+
except Exception as e:
|
| 266 |
+
logger.error(f"Local model error: {e}")
|
| 267 |
|
| 268 |
+
# Fallback to Hugging Face API
|
| 269 |
+
logger.info("🔄 Using Hugging Face API for response")
|
| 270 |
+
api_response = generate_with_huggingface_api([
|
| 271 |
+
{"role": "user", "content": f"{STANLEY_AI_SYSTEM}\n\nUser: {user_message}"}
|
| 272 |
+
])
|
| 273 |
|
| 274 |
if api_response:
|
| 275 |
+
enhanced_response = enhance_with_cultural_context(api_response.strip(), user_message)
|
|
|
|
| 276 |
set_cached_response(user_message, enhanced_response)
|
| 277 |
return enhanced_response
|
| 278 |
|
| 279 |
+
# Final fallback
|
| 280 |
+
fallback_response = "Pole! I'm experiencing high demand. Please try again in a moment. Tafadhali jaribu tena."
|
| 281 |
+
return fallback_response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
# ============================================================================
|
| 284 |
+
# HUGGING FACE IMAGE GENERATION
|
| 285 |
# ============================================================================
|
| 286 |
|
| 287 |
+
def generate_image_huggingface(prompt, retry_count=3):
|
| 288 |
"""Generate images using Hugging Face Inference API"""
|
| 289 |
+
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 290 |
|
| 291 |
for attempt in range(retry_count):
|
| 292 |
try:
|
| 293 |
+
logger.info(f"🎨 Generating image (attempt {attempt + 1}): {prompt[:50]}...")
|
| 294 |
|
| 295 |
response = requests.post(
|
| 296 |
HF_API_URLS["image"],
|
|
|
|
| 309 |
return f"data:image/png;base64,{img_str}"
|
| 310 |
|
| 311 |
elif response.status_code == 503:
|
| 312 |
+
# Model is loading, wait and retry
|
| 313 |
+
wait_time = (attempt + 1) * 10
|
| 314 |
logger.info(f"⏳ Model loading, waiting {wait_time}s...")
|
| 315 |
time.sleep(wait_time)
|
| 316 |
continue
|
|
|
|
| 319 |
logger.error(f"❌ HF Image API error: {response.status_code}")
|
| 320 |
continue
|
| 321 |
|
| 322 |
+
except requests.exceptions.Timeout:
|
| 323 |
+
logger.warning(f"⏰ Request timeout, attempt {attempt + 1}")
|
| 324 |
+
continue
|
| 325 |
except Exception as e:
|
| 326 |
logger.error(f"❌ Image generation error: {e}")
|
| 327 |
break
|
|
|
|
| 331 |
def generate_image_fallback(prompt):
|
| 332 |
"""Create simple placeholder images"""
|
| 333 |
try:
|
| 334 |
+
from PIL import Image, ImageDraw
|
| 335 |
+
import random
|
| 336 |
+
|
| 337 |
+
# Create colorful placeholder
|
| 338 |
width, height = 512, 512
|
| 339 |
img = Image.new('RGB', (width, height), color=(
|
| 340 |
random.randint(50, 200),
|
|
|
|
| 344 |
|
| 345 |
draw = ImageDraw.Draw(img)
|
| 346 |
|
| 347 |
+
# Add some simple shapes
|
| 348 |
for _ in range(5):
|
| 349 |
x1, y1 = random.randint(0, width), random.randint(0, height)
|
| 350 |
x2, y2 = random.randint(x1, width), random.randint(y1, height)
|
|
|
|
| 362 |
return None
|
| 363 |
|
| 364 |
def enhance_prompt_with_kiswahili(prompt):
|
| 365 |
+
"""Add cultural context to image prompts"""
|
| 366 |
+
if detect_kiswahili_context(prompt):
|
| 367 |
enhancements = [
|
| 368 |
"East African style", "vibrant African colors", "African landscape",
|
| 369 |
+
"cultural elements", "traditional patterns", "warm sunset colors",
|
| 370 |
+
"savanna background", "rich cultural symbolism"
|
| 371 |
]
|
| 372 |
return f"{prompt}, {random.choice(enhancements)}"
|
| 373 |
return prompt
|
| 374 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
# ============================================================================
|
| 376 |
# FLASK ROUTES
|
| 377 |
# ============================================================================
|
|
|
|
| 380 |
def home():
|
| 381 |
return jsonify({
|
| 382 |
"message": "🚀 STANLEY AI - Created by Stanley Samwel Owino (Machine Learning Engineer)",
|
| 383 |
+
"version": "2.2",
|
| 384 |
"creator": "Stanley Samwel Owino",
|
| 385 |
"role": "Machine Learning Engineer",
|
|
|
|
| 386 |
"features": [
|
| 387 |
+
"Hugging Face Optimized",
|
| 388 |
+
"Fast Text Generation",
|
| 389 |
+
"Free Image Generation",
|
| 390 |
+
"Kiswahili Integration",
|
| 391 |
+
"Cultural Knowledge",
|
| 392 |
+
"Response Caching",
|
| 393 |
+
"API Fallbacks"
|
| 394 |
],
|
| 395 |
"status": "active",
|
| 396 |
+
"model": "Qwen2.5 + HF Inference",
|
| 397 |
+
"image_generation": "Hugging Face API"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
})
|
| 399 |
|
| 400 |
@app.route('/api/chat', methods=['POST'])
|
|
|
|
| 405 |
user_message = data.get('message', '')
|
| 406 |
|
| 407 |
if not user_message:
|
| 408 |
+
return jsonify({"error": "Tafadhali provide a message"}), 400
|
| 409 |
|
| 410 |
logger.info(f"💬 Processing: {user_message[:50]}...")
|
| 411 |
|
| 412 |
+
# Check if user wants to generate an image
|
| 413 |
if detect_image_request(user_message):
|
| 414 |
+
image_prompt = extract_image_prompt(user_message)
|
| 415 |
+
enhanced_prompt = enhance_prompt_with_kiswahili(image_prompt)
|
| 416 |
|
| 417 |
return jsonify({
|
| 418 |
+
"response": f"🎨 I'll generate an image for: '{enhanced_prompt}'. Please use the image generation feature below!",
|
| 419 |
+
"image_suggestion": enhanced_prompt,
|
| 420 |
"status": "success",
|
| 421 |
+
"suggest_image": True,
|
| 422 |
+
"response_time": round(time.time() - start_time, 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 423 |
})
|
| 424 |
|
| 425 |
response = generate_comprehensive_response(user_message)
|
| 426 |
response_time = round(time.time() - start_time, 2)
|
| 427 |
|
| 428 |
+
has_kiswahili = detect_kiswahili_context(response)
|
| 429 |
+
|
| 430 |
return jsonify({
|
| 431 |
"response": response,
|
| 432 |
"status": "success",
|
| 433 |
"response_time": response_time,
|
| 434 |
"word_count": len(response.split()),
|
| 435 |
+
"model": "STANLEY-AI-HF",
|
| 436 |
+
"cultural_context": has_kiswahili,
|
| 437 |
+
"language": "en+sw" if has_kiswahili else "en",
|
| 438 |
+
"cached": get_cached_response(user_message) is not None
|
| 439 |
})
|
| 440 |
|
| 441 |
except Exception as e:
|
| 442 |
logger.error(f"Chat error: {e}")
|
| 443 |
return jsonify({
|
| 444 |
+
"error": f"Pole! Processing error: {str(e)}",
|
| 445 |
"status": "error"
|
| 446 |
}), 500
|
| 447 |
|
| 448 |
@app.route('/api/generate-image', methods=['POST'])
|
| 449 |
def generate_image_endpoint():
|
| 450 |
+
"""Generate images using Hugging Face"""
|
| 451 |
try:
|
| 452 |
start_time = time.time()
|
| 453 |
data = request.get_json()
|
| 454 |
prompt = data.get('prompt', '')
|
| 455 |
|
| 456 |
if not prompt:
|
| 457 |
+
return jsonify({"error": "Tafadhali provide a prompt"}), 400
|
| 458 |
|
| 459 |
+
# Enhance prompt with cultural context
|
| 460 |
enhanced_prompt = enhance_prompt_with_kiswahili(prompt)
|
|
|
|
| 461 |
|
| 462 |
# Generate image
|
| 463 |
image_data = generate_image_huggingface(enhanced_prompt)
|
|
|
|
| 476 |
"status": "success",
|
| 477 |
"generation_time": generation_time,
|
| 478 |
"provider": "hugging_face",
|
| 479 |
+
"cultural_enhancement": enhanced_prompt != prompt
|
| 480 |
})
|
| 481 |
else:
|
| 482 |
return jsonify({
|
| 483 |
+
"error": "Pole! Image generation service is busy",
|
| 484 |
"status": "error"
|
| 485 |
}), 500
|
| 486 |
|
| 487 |
except Exception as e:
|
| 488 |
logger.error(f"Image endpoint error: {e}")
|
| 489 |
return jsonify({
|
| 490 |
+
"error": f"Pole! Image generation failed: {str(e)}",
|
| 491 |
"status": "error"
|
| 492 |
}), 500
|
| 493 |
|
| 494 |
+
@app.route('/api/generate-cultural-image', methods=['POST'])
|
| 495 |
+
def generate_cultural_image():
|
| 496 |
+
"""Generate images with specific Kiswahili cultural themes"""
|
| 497 |
try:
|
|
|
|
| 498 |
data = request.get_json()
|
| 499 |
+
theme = data.get('theme', '')
|
| 500 |
+
style = data.get('style', 'vibrant')
|
| 501 |
+
|
| 502 |
+
if not theme:
|
| 503 |
+
return jsonify({"error": "Tafadhali provide a theme"}), 400
|
| 504 |
+
|
| 505 |
+
# Cultural prompt templates
|
| 506 |
+
cultural_templates = {
|
| 507 |
+
'savanna': f"African savanna landscape with {theme}, acacia trees, warm sunset, majestic",
|
| 508 |
+
'wildlife': f"African wildlife {theme}, natural habitat, detailed, realistic, beautiful",
|
| 509 |
+
'culture': f"East African cultural scene {theme}, traditional, vibrant colors, community",
|
| 510 |
+
'coastal': f"Swahili coast {theme}, Indian Ocean, dhows, traditional architecture",
|
| 511 |
+
'lion_king': f"Lion King inspired {theme}, emotional, Disney style, African elements"
|
| 512 |
+
}
|
| 513 |
|
| 514 |
+
base_template = cultural_templates.get(style, f"East African {theme}, cultural, vibrant")
|
|
|
|
| 515 |
|
| 516 |
+
# Style modifiers
|
| 517 |
+
modifiers = {
|
| 518 |
+
'vibrant': 'vibrant colors, highly detailed, 4K resolution',
|
| 519 |
+
'realistic': 'photorealistic, detailed, realistic lighting',
|
| 520 |
+
'artistic': 'painterly, artistic, brush strokes, creative',
|
| 521 |
+
'traditional': 'traditional African art, symbolic, patterns'
|
| 522 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
|
| 524 |
+
final_prompt = f"{base_template}, {modifiers.get(style, 'vibrant colors')}"
|
| 525 |
|
| 526 |
+
image_data = generate_image_huggingface(final_prompt)
|
|
|
|
| 527 |
|
| 528 |
+
if image_data:
|
|
|
|
|
|
|
| 529 |
return jsonify({
|
| 530 |
+
"image": image_data,
|
| 531 |
"theme": theme,
|
| 532 |
"style": style,
|
| 533 |
+
"prompt": final_prompt,
|
| 534 |
"status": "success",
|
| 535 |
+
"cultural_context": "kiswahili_theme"
|
|
|
|
| 536 |
})
|
| 537 |
else:
|
| 538 |
return jsonify({
|
| 539 |
+
"error": "Pole! Cultural image generation failed",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 540 |
"status": "error"
|
| 541 |
}), 500
|
| 542 |
|
| 543 |
except Exception as e:
|
|
|
|
| 544 |
return jsonify({
|
| 545 |
+
"error": f"Pole! Cultural image error: {str(e)}",
|
| 546 |
"status": "error"
|
| 547 |
}), 500
|
| 548 |
|
| 549 |
@app.route('/api/quick-chat', methods=['POST'])
|
| 550 |
def quick_chat():
|
| 551 |
+
"""Faster chat endpoint for simple queries"""
|
| 552 |
try:
|
| 553 |
data = request.get_json()
|
| 554 |
user_message = data.get('message', '')
|
| 555 |
|
| 556 |
if not user_message:
|
| 557 |
+
return jsonify({"error": "Tafadhali provide a message"}), 400
|
| 558 |
|
| 559 |
+
# Simple response for common queries
|
| 560 |
quick_responses = {
|
| 561 |
+
'hello': 'Habari! Stanley AI hapa. Ninaweza kukusaidia nini leo?',
|
| 562 |
+
'hi': 'Habari! Karibu kwa Stanley AI. How can I help you today?',
|
| 563 |
+
'thanks': 'Asante sana! Karibu tena.',
|
| 564 |
+
'thank you': 'Asante! Happy to help.',
|
| 565 |
+
'help': 'Ninaweza kukupa: Maelezo, Picha, Maarifa ya Kiswahili, na zaidi!',
|
| 566 |
+
'who created you': 'I was created by Stanley Samwel Owino, a Machine Learning Engineer from Kenya.',
|
| 567 |
+
'who made you': 'Stanley Samwel Owino - Machine Learning Engineer and AI researcher from Kenya.',
|
| 568 |
+
'creator': 'Stanley Samwel Owino - Machine Learning Engineer passionate about AI and cultural integration.'
|
|
|
|
| 569 |
}
|
| 570 |
|
| 571 |
msg_lower = user_message.lower().strip()
|
|
|
|
| 573 |
return jsonify({
|
| 574 |
"response": quick_responses[msg_lower],
|
| 575 |
"status": "success",
|
| 576 |
+
"quick_response": True
|
|
|
|
| 577 |
})
|
| 578 |
|
| 579 |
+
# Normal processing for other queries
|
| 580 |
return chat()
|
| 581 |
|
| 582 |
except Exception as e:
|
| 583 |
return jsonify({
|
| 584 |
+
"error": f"Pole! Quick chat error: {str(e)}",
|
| 585 |
"status": "error"
|
| 586 |
}), 500
|
| 587 |
|
| 588 |
@app.route('/api/system/status')
|
| 589 |
def system_status():
|
| 590 |
+
"""System status with Hugging Face info"""
|
| 591 |
return jsonify({
|
| 592 |
"status": "operational",
|
| 593 |
"creator": "Stanley Samwel Owino",
|
| 594 |
"role": "Machine Learning Engineer",
|
| 595 |
+
"model_loaded": model_loaded,
|
| 596 |
+
"hugging_face_available": True,
|
| 597 |
+
"cache_size": len(response_cache),
|
| 598 |
"features": [
|
| 599 |
+
"Text Generation",
|
| 600 |
+
"Image Generation",
|
| 601 |
+
"Kiswahili Knowledge",
|
| 602 |
+
"Cultural Integration",
|
| 603 |
+
"Fast Responses"
|
| 604 |
],
|
| 605 |
+
"optimizations": [
|
| 606 |
+
"Response Caching",
|
| 607 |
+
"API Fallbacks",
|
| 608 |
+
"Quick Responses",
|
| 609 |
+
"Cultural Prompts"
|
| 610 |
+
]
|
|
|
|
| 611 |
})
|
| 612 |
|
| 613 |
+
@app.route('/api/cache/clear', methods=['POST'])
|
| 614 |
+
def clear_cache():
|
| 615 |
+
"""Clear response cache"""
|
| 616 |
+
try:
|
| 617 |
+
cache_size = len(response_cache)
|
| 618 |
+
response_cache.clear()
|
| 619 |
+
|
| 620 |
+
return jsonify({
|
| 621 |
+
"status": "success",
|
| 622 |
+
"message": "Cache cleared",
|
| 623 |
+
"cleared_entries": cache_size
|
| 624 |
+
})
|
| 625 |
+
except Exception as e:
|
| 626 |
+
return jsonify({
|
| 627 |
+
"error": f"Cache clearance failed: {str(e)}",
|
| 628 |
+
"status": "error"
|
| 629 |
+
}), 500
|
| 630 |
+
|
| 631 |
+
# Keep all your existing Kiswahili knowledge endpoints
|
| 632 |
@app.route('/api/kiswahili/proverbs')
|
| 633 |
def get_proverbs():
|
| 634 |
+
"""Get random Swahili proverbs"""
|
| 635 |
proverbs = [
|
| 636 |
"Mwacha mila ni mtumwa.",
|
| 637 |
"Haraka haraka haina baraka.",
|
|
|
|
| 642 |
return jsonify({
|
| 643 |
"proverb": random.choice(proverbs),
|
| 644 |
"language": "Kiswahili",
|
| 645 |
+
"meaning": "Cultural wisdom from East Africa"
|
|
|
|
| 646 |
})
|
| 647 |
|
| 648 |
@app.route('/api/kiswahili/phrases')
|
|
|
|
| 651 |
phrases = {
|
| 652 |
"Hello": "Habari",
|
| 653 |
"Thank you": "Asante",
|
| 654 |
+
"Welcome": "Karibu",
|
| 655 |
+
"Sorry": "Pole",
|
| 656 |
"Goodbye": "Kwaheri",
|
| 657 |
+
"How are you?": "Habari yako?",
|
| 658 |
+
"I'm fine": "Nzuri",
|
| 659 |
"Please": "Tafadhali",
|
| 660 |
"Yes": "Ndio",
|
| 661 |
"No": "Hapana"
|
| 662 |
}
|
| 663 |
+
return jsonify(phrases)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 664 |
|
| 665 |
if __name__ == '__main__':
|
| 666 |
+
print("🚀 STANLEY AI - Hugging Face Optimized")
|
| 667 |
print("👨💻 Created by: Stanley Samwel Owino - Machine Learning Engineer")
|
| 668 |
+
print("🌍 Kiswahili Knowledge: Loaded")
|
| 669 |
+
print("🖼️ Image Generation: Hugging Face API")
|
| 670 |
+
print("⚡ Performance: Optimized")
|
| 671 |
+
print("🔧 Fallbacks: Enabled")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 672 |
|
| 673 |
+
app.run(debug=True, host='0.0.0.0', port=7860, threaded=True).
|