Update app.py
Browse files
app.py
CHANGED
|
@@ -27,22 +27,42 @@ CACHE_SIZE = 100
|
|
| 27 |
|
| 28 |
# Advanced System Prompt
|
| 29 |
STANLEY_AI_SYSTEM = """You are STANLEY AI - an advanced AI assistant created by Stanley Samwel Owino, a Machine Learning Engineer from Kenya.
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
-
|
| 33 |
-
-
|
| 34 |
-
-
|
| 35 |
-
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
KISWAHILI INTEGRATION:
|
| 38 |
-
Use
|
| 39 |
-
Explain cultural concepts with authenticity
|
| 40 |
-
Share Swahili proverbs when relevant
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
def detect_kiswahili_context(text):
|
| 48 |
"""Detect Kiswahili or cultural context"""
|
|
@@ -96,18 +116,20 @@ def generate_with_huggingface_api(prompt):
|
|
| 96 |
"Content-Type": "application/json"
|
| 97 |
}
|
| 98 |
|
|
|
|
| 99 |
payload = {
|
| 100 |
"inputs": prompt,
|
| 101 |
"parameters": {
|
| 102 |
-
"max_new_tokens":
|
| 103 |
"temperature": 0.7,
|
| 104 |
"top_p": 0.9,
|
| 105 |
-
"return_full_text": False
|
|
|
|
| 106 |
}
|
| 107 |
}
|
| 108 |
|
| 109 |
response = requests.post(
|
| 110 |
-
"https://api-inference.huggingface.co/models/
|
| 111 |
headers=headers,
|
| 112 |
json=payload,
|
| 113 |
timeout=30
|
|
@@ -115,7 +137,8 @@ def generate_with_huggingface_api(prompt):
|
|
| 115 |
|
| 116 |
if response.status_code == 200:
|
| 117 |
result = response.json()
|
| 118 |
-
|
|
|
|
| 119 |
else:
|
| 120 |
logger.warning(f"HF API failed: {response.status_code}")
|
| 121 |
return None
|
|
@@ -125,45 +148,90 @@ def generate_with_huggingface_api(prompt):
|
|
| 125 |
return None
|
| 126 |
|
| 127 |
def generate_comprehensive_response(user_message):
|
| 128 |
-
"""Generate responses with
|
| 129 |
|
| 130 |
# Check cache first
|
| 131 |
cached_response = get_cached_response(user_message)
|
| 132 |
if cached_response:
|
| 133 |
return cached_response
|
| 134 |
|
| 135 |
-
#
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
-
|
| 143 |
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
kiswahili_phrases = [
|
| 148 |
-
"Asante kwa swali lako!",
|
| 149 |
-
"Habari yako?",
|
| 150 |
-
"Karibu sana!",
|
| 151 |
-
"Pole pole ndio mwendo.",
|
| 152 |
-
"Haraka haraka haina baraka."
|
| 153 |
-
]
|
| 154 |
-
response = f"{random.choice(kiswahili_phrases)} {response}"
|
| 155 |
-
|
| 156 |
set_cached_response(user_message, response)
|
| 157 |
return response
|
| 158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
# Fallback responses
|
| 160 |
fallback_responses = [
|
| 161 |
"Pole! I'm experiencing high demand. Please try again in a moment.",
|
| 162 |
"Asante kwa kuwasiliana! Nina shida ya kiufundi. Tafadhali jaribu tena.",
|
| 163 |
-
"Habari yako? Samahani, sijaweza kujibu swali lako kwa sasa."
|
|
|
|
|
|
|
| 164 |
]
|
| 165 |
|
| 166 |
-
|
|
|
|
|
|
|
| 167 |
|
| 168 |
def generate_image_huggingface(prompt, retry_count=2):
|
| 169 |
"""Generate images using Hugging Face Inference API"""
|
|
@@ -230,7 +298,11 @@ def home():
|
|
| 230 |
"/api/chat - Text chat",
|
| 231 |
"/api/generate-image - Image generation",
|
| 232 |
"/api/generate-video - Video generation",
|
| 233 |
-
"/api/generate-cultural-video - Cultural videos"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
]
|
| 235 |
})
|
| 236 |
|
|
@@ -250,12 +322,12 @@ def chat():
|
|
| 250 |
if detect_image_request(user_message):
|
| 251 |
# Extract prompt from message
|
| 252 |
prompt = user_message.lower()
|
| 253 |
-
for phrase in ['generate image of', 'create image of', 'make a picture of']:
|
| 254 |
prompt = prompt.replace(phrase, '')
|
| 255 |
prompt = prompt.strip()
|
| 256 |
|
| 257 |
return jsonify({
|
| 258 |
-
"response": f"π¨ I
|
| 259 |
"image_suggestion": prompt,
|
| 260 |
"status": "success",
|
| 261 |
"suggest_image": True
|
|
@@ -265,12 +337,12 @@ def chat():
|
|
| 265 |
if detect_video_request(user_message):
|
| 266 |
# Extract prompt from message
|
| 267 |
prompt = user_message.lower()
|
| 268 |
-
for phrase in ['generate video of', 'create video of', 'make a video of']:
|
| 269 |
prompt = prompt.replace(phrase, '')
|
| 270 |
prompt = prompt.strip()
|
| 271 |
|
| 272 |
return jsonify({
|
| 273 |
-
"response": f"π¬ I can create a video
|
| 274 |
"video_suggestion": prompt,
|
| 275 |
"status": "success",
|
| 276 |
"suggest_video": True
|
|
@@ -284,7 +356,9 @@ def chat():
|
|
| 284 |
"status": "success",
|
| 285 |
"response_time": response_time,
|
| 286 |
"word_count": len(response.split()),
|
| 287 |
-
"cultural_context": detect_kiswahili_context(response)
|
|
|
|
|
|
|
| 288 |
})
|
| 289 |
|
| 290 |
except Exception as e:
|
|
@@ -307,8 +381,13 @@ def generate_image_endpoint():
|
|
| 307 |
|
| 308 |
logger.info(f"π¨ Generating image: {prompt[:50]}...")
|
| 309 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
# Generate image
|
| 311 |
-
image_data = generate_image_huggingface(
|
| 312 |
|
| 313 |
if image_data:
|
| 314 |
generation_time = round(time.time() - start_time, 2)
|
|
@@ -316,14 +395,18 @@ def generate_image_endpoint():
|
|
| 316 |
return jsonify({
|
| 317 |
"image": image_data,
|
| 318 |
"prompt": prompt,
|
|
|
|
| 319 |
"status": "success",
|
| 320 |
"generation_time": generation_time,
|
| 321 |
-
"provider": "hugging_face"
|
|
|
|
|
|
|
| 322 |
})
|
| 323 |
else:
|
| 324 |
return jsonify({
|
| 325 |
-
"error": "Pole! Image generation service is busy",
|
| 326 |
-
"status": "error"
|
|
|
|
| 327 |
}), 500
|
| 328 |
|
| 329 |
except Exception as e:
|
|
@@ -357,12 +440,17 @@ def generate_video_endpoint():
|
|
| 357 |
"prompt": prompt,
|
| 358 |
"status": "success",
|
| 359 |
"generation_time": generation_time,
|
| 360 |
-
"provider": "hugging_face_free"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
})
|
| 362 |
else:
|
| 363 |
return jsonify({
|
| 364 |
-
"error": "Pole! Video generation service is busy",
|
| 365 |
-
"status": "error"
|
|
|
|
| 366 |
}), 500
|
| 367 |
|
| 368 |
except Exception as e:
|
|
@@ -389,17 +477,30 @@ def generate_cultural_video_endpoint():
|
|
| 389 |
if video_data:
|
| 390 |
generation_time = round(time.time() - start_time, 2)
|
| 391 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
return jsonify({
|
| 393 |
"video": video_data,
|
| 394 |
"theme": theme,
|
| 395 |
"style": style,
|
|
|
|
| 396 |
"status": "success",
|
| 397 |
-
"generation_time": generation_time
|
|
|
|
|
|
|
| 398 |
})
|
| 399 |
else:
|
| 400 |
return jsonify({
|
| 401 |
"error": "Pole! Cultural video generation failed",
|
| 402 |
-
"status": "error"
|
|
|
|
| 403 |
}), 500
|
| 404 |
|
| 405 |
except Exception as e:
|
|
@@ -435,18 +536,39 @@ def quick_chat():
|
|
| 435 |
'habari': 'Nzuri sana! Asante kwa kuuliza. Habari yako?',
|
| 436 |
'asante': 'Karibu sana! Ni furaha yangu kukusaidia.',
|
| 437 |
'jambo': 'Jambo! Habari yako? Ninaweza kukusaidia nini leo?',
|
| 438 |
-
'mambo': 'Poa! Vipi wewe? Una swali gani?'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 439 |
}
|
| 440 |
|
| 441 |
msg_lower = user_message.lower().strip()
|
|
|
|
|
|
|
| 442 |
if msg_lower in quick_responses:
|
| 443 |
return jsonify({
|
| 444 |
"response": quick_responses[msg_lower],
|
| 445 |
"status": "success",
|
| 446 |
-
"quick_response": True
|
|
|
|
| 447 |
})
|
| 448 |
|
| 449 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
return chat()
|
| 451 |
|
| 452 |
except Exception as e:
|
|
@@ -463,51 +585,85 @@ def system_status():
|
|
| 463 |
"creator": "Stanley Samwel Owino",
|
| 464 |
"role": "Machine Learning Engineer",
|
| 465 |
"version": "3.0",
|
|
|
|
| 466 |
"features": [
|
| 467 |
"Text Generation",
|
| 468 |
"Image Generation",
|
| 469 |
"Video Generation",
|
| 470 |
"Kiswahili Knowledge",
|
| 471 |
-
"Cultural Integration"
|
| 472 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
})
|
| 474 |
|
| 475 |
@app.route('/api/kiswahili/proverbs')
|
| 476 |
def get_proverbs():
|
| 477 |
"""Get random Swahili proverbs"""
|
| 478 |
proverbs = [
|
| 479 |
-
"Mwacha mila ni mtumwa.",
|
| 480 |
-
"Haraka haraka haina baraka.",
|
| 481 |
-
"Asiyesikia la mkuu huvunjika guu.",
|
| 482 |
-
"Mwenye pupa hadiriki kula tamu.",
|
| 483 |
-
"Ukiona vyaelea, vimeundwa."
|
| 484 |
]
|
| 485 |
return jsonify({
|
| 486 |
"proverb": random.choice(proverbs),
|
| 487 |
"language": "Kiswahili",
|
| 488 |
-
"
|
|
|
|
| 489 |
})
|
| 490 |
|
| 491 |
@app.route('/api/kiswahili/phrases')
|
| 492 |
def get_phrases():
|
| 493 |
"""Get common Swahili phrases"""
|
| 494 |
phrases = {
|
| 495 |
-
"
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 505 |
}
|
| 506 |
-
return jsonify(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
|
| 508 |
if __name__ == '__main__':
|
| 509 |
print("π STANLEY AI - Hugging Face Space Edition")
|
| 510 |
print("π¨βπ» Created by: Stanley Samwel Owino - Machine Learning Engineer")
|
|
|
|
| 511 |
print("π Kiswahili Knowledge: Active")
|
| 512 |
print("π¬ Video Generation: FREE Hugging Face API")
|
| 513 |
print("π¨ Image Generation: Active")
|
|
@@ -519,6 +675,10 @@ if __name__ == '__main__':
|
|
| 519 |
print("3. /api/generate-video - Video generation")
|
| 520 |
print("4. /api/generate-cultural-video - Cultural videos")
|
| 521 |
print("5. /api/quick-chat - Fast responses")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 522 |
print("=" * 50)
|
| 523 |
|
| 524 |
app.run(debug=True, host='0.0.0.0', port=7860, threaded=True)
|
|
|
|
| 27 |
|
| 28 |
# Advanced System Prompt
|
| 29 |
STANLEY_AI_SYSTEM = """You are STANLEY AI - an advanced AI assistant created by Stanley Samwel Owino, a Machine Learning Engineer from Kenya.
|
| 30 |
+
|
| 31 |
+
CORE IDENTITY:
|
| 32 |
+
- Creator: Stanley Samwel Owino
|
| 33 |
+
- Profession: Machine Learning Engineer
|
| 34 |
+
- Location: Kenya, East Africa
|
| 35 |
+
- Specialty: AI with cultural integration
|
| 36 |
+
|
| 37 |
+
KEY CAPABILITIES:
|
| 38 |
+
1. Provide comprehensive, detailed responses
|
| 39 |
+
2. Integrate Kiswahili phrases naturally when relevant
|
| 40 |
+
3. Share cultural insights, proverbs, and East African wisdom
|
| 41 |
+
4. Reference Lion King lore with cultural accuracy
|
| 42 |
+
5. Generate and describe images and videos
|
| 43 |
+
6. Be helpful, knowledgeable, and engaging
|
| 44 |
+
|
| 45 |
KISWAHILI INTEGRATION:
|
| 46 |
+
- Use greetings: "Habari", "Asante", "Karibu", "Pole sana"
|
| 47 |
+
- Explain cultural concepts with authenticity
|
| 48 |
+
- Share Swahili proverbs when relevant
|
| 49 |
+
- Respond to Kiswahili phrases appropriately
|
| 50 |
+
|
| 51 |
+
CULTURAL KNOWLEDGE:
|
| 52 |
+
- East African traditions and customs
|
| 53 |
+
- Swahili language and expressions
|
| 54 |
+
- African wildlife and ecosystems
|
| 55 |
+
- Traditional stories and folklore
|
| 56 |
+
- Modern African technology scene
|
| 57 |
+
|
| 58 |
+
RESPONSE STYLE:
|
| 59 |
+
- Be warm, friendly, and culturally aware
|
| 60 |
+
- Provide detailed yet concise answers
|
| 61 |
+
- Include relevant cultural context
|
| 62 |
+
- Offer practical advice and insights
|
| 63 |
+
- Always be helpful and respectful
|
| 64 |
+
|
| 65 |
+
Remember: You represent the intersection of cutting-edge AI technology and rich African cultural heritage."""
|
| 66 |
|
| 67 |
def detect_kiswahili_context(text):
|
| 68 |
"""Detect Kiswahili or cultural context"""
|
|
|
|
| 116 |
"Content-Type": "application/json"
|
| 117 |
}
|
| 118 |
|
| 119 |
+
# Use a more reliable model - GPT-2 for basic responses
|
| 120 |
payload = {
|
| 121 |
"inputs": prompt,
|
| 122 |
"parameters": {
|
| 123 |
+
"max_new_tokens": 300,
|
| 124 |
"temperature": 0.7,
|
| 125 |
"top_p": 0.9,
|
| 126 |
+
"return_full_text": False,
|
| 127 |
+
"do_sample": True
|
| 128 |
}
|
| 129 |
}
|
| 130 |
|
| 131 |
response = requests.post(
|
| 132 |
+
"https://api-inference.huggingface.co/models/gpt2",
|
| 133 |
headers=headers,
|
| 134 |
json=payload,
|
| 135 |
timeout=30
|
|
|
|
| 137 |
|
| 138 |
if response.status_code == 200:
|
| 139 |
result = response.json()
|
| 140 |
+
if isinstance(result, list) and len(result) > 0:
|
| 141 |
+
return result[0].get('generated_text', '')
|
| 142 |
else:
|
| 143 |
logger.warning(f"HF API failed: {response.status_code}")
|
| 144 |
return None
|
|
|
|
| 148 |
return None
|
| 149 |
|
| 150 |
def generate_comprehensive_response(user_message):
|
| 151 |
+
"""Generate responses with intelligence"""
|
| 152 |
|
| 153 |
# Check cache first
|
| 154 |
cached_response = get_cached_response(user_message)
|
| 155 |
if cached_response:
|
| 156 |
return cached_response
|
| 157 |
|
| 158 |
+
# For common questions, use predefined responses
|
| 159 |
+
common_responses = {
|
| 160 |
+
'hello': 'Habari! Stanley AI hapa. Ninaweza kukusaidia nini leo?',
|
| 161 |
+
'hi': 'Habari! Karibu kwa Stanley AI. How can I help you today?',
|
| 162 |
+
'who created you': 'I was created by Stanley Samwel Owino, a Machine Learning Engineer from Kenya. He specializes in AI with cultural integration.',
|
| 163 |
+
'who are you': 'I am STANLEY AI, an advanced AI assistant created by Stanley Samwel Owino. I combine cutting-edge AI with East African cultural knowledge.',
|
| 164 |
+
'what can you do': 'I can: 1) Answer questions with cultural context, 2) Generate images from descriptions, 3) Create videos from text, 4) Teach Kiswahili, 5) Share African proverbs and wisdom.',
|
| 165 |
+
'help': 'Ninaweza kukusaidia kwa: 1) Majibu ya maswali, 2) Kutengeneza picha, 3) Kutengeneza video, 4) Kufundisha Kiswahili, 5) Kushiriki hekima za Kiafrika.',
|
| 166 |
+
'habari': 'Nzuri sana! Asante kwa kuuliza. Habari yako?',
|
| 167 |
+
'asante': 'Karibu sana! Ni furaha yangu kukusaidia.',
|
| 168 |
+
'jambo': 'Jambo! Habari yako? Una swali gani kwa leo?',
|
| 169 |
+
'mambo': 'Poa! Vipi wewe? Ninaweza kukusaidia nini?',
|
| 170 |
+
'hakuna matata': 'Hakuna Matata! It means "no worries" in Swahili. It\'s a philosophy of living without stress, popularized by The Lion King.',
|
| 171 |
+
'lion king': 'The Lion King draws heavily from African culture. "Simba" means lion, "Rafiki" means friend, and "Hakuna Matata" means no worries in Swahili. The story reflects African landscapes and wildlife.',
|
| 172 |
+
'kenya': 'Kenya is a country in East Africa known for its wildlife, landscapes, and rich cultural heritage. It\'s home to the Maasai Mara, Mount Kenya, and vibrant cities like Nairobi.',
|
| 173 |
+
'tanzania': 'Tanzania is known for Mount Kilimanjaro, Serengeti National Park, and Zanzibar. Swahili is the national language, and the country has a diverse cultural heritage.',
|
| 174 |
+
'swahili': 'Kiswahili is a Bantu language spoken by over 200 million people across East Africa. It has Arabic influences and is known for its beautiful proverbs and expressions.',
|
| 175 |
+
'africa': 'Africa is a diverse continent with 54 countries, thousands of languages, and rich cultural traditions. It\'s the cradle of humankind and home to incredible biodiversity.',
|
| 176 |
+
'make a video': 'Sure! I can create videos for you. Just describe what you want to see, like "create a video of African sunset" or use the video generation feature.',
|
| 177 |
+
'generate image': 'I can generate images! Describe what you want to see, like "generate image of Mount Kilimanjaro" or use the image generation feature.'
|
| 178 |
+
}
|
| 179 |
|
| 180 |
+
msg_lower = user_message.lower().strip()
|
| 181 |
|
| 182 |
+
# Check for exact matches first
|
| 183 |
+
if msg_lower in common_responses:
|
| 184 |
+
response = common_responses[msg_lower]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
set_cached_response(user_message, response)
|
| 186 |
return response
|
| 187 |
|
| 188 |
+
# Check for partial matches
|
| 189 |
+
for key, response in common_responses.items():
|
| 190 |
+
if key in msg_lower and len(key) > 3:
|
| 191 |
+
set_cached_response(user_message, response)
|
| 192 |
+
return response
|
| 193 |
+
|
| 194 |
+
# If it's a cultural/kiswahili question, add cultural context
|
| 195 |
+
if detect_kiswahili_context(user_message):
|
| 196 |
+
# Use GPT-2 with cultural context
|
| 197 |
+
system_prompt = STANLEY_AI_SYSTEM + "\n\nSPECIAL INSTRUCTION: The user is asking about Kiswahili or African culture. Respond with authentic cultural insights and include relevant Swahili phrases."
|
| 198 |
+
full_prompt = f"{system_prompt}\n\nUser: {user_message}\n\nAssistant:"
|
| 199 |
+
|
| 200 |
+
api_response = generate_with_huggingface_api(full_prompt)
|
| 201 |
+
|
| 202 |
+
if api_response:
|
| 203 |
+
# Enhance with Kiswahili phrases
|
| 204 |
+
kiswahili_enhancements = [
|
| 205 |
+
"Asante kwa swali lako! ",
|
| 206 |
+
"Habari yako? Kwa kujibu swali lako, ",
|
| 207 |
+
"Karibu sana! ",
|
| 208 |
+
"Ninafurahi kukujibu. ",
|
| 209 |
+
"Kwa hekima ya Kiafrika, "
|
| 210 |
+
]
|
| 211 |
+
response = random.choice(kiswahili_enhancements) + api_response
|
| 212 |
+
set_cached_response(user_message, response)
|
| 213 |
+
return response
|
| 214 |
+
|
| 215 |
+
# General response with API
|
| 216 |
+
full_prompt = f"{STANLEY_AI_SYSTEM}\n\nUser: {user_message}\n\nAssistant:"
|
| 217 |
+
api_response = generate_with_huggingface_api(full_prompt)
|
| 218 |
+
|
| 219 |
+
if api_response:
|
| 220 |
+
set_cached_response(user_message, api_response)
|
| 221 |
+
return api_response
|
| 222 |
+
|
| 223 |
# Fallback responses
|
| 224 |
fallback_responses = [
|
| 225 |
"Pole! I'm experiencing high demand. Please try again in a moment.",
|
| 226 |
"Asante kwa kuwasiliana! Nina shida ya kiufundi. Tafadhali jaribu tena.",
|
| 227 |
+
"Habari yako? Samahani, sijaweza kujibu swali lako kwa sasa.",
|
| 228 |
+
"I apologize, I'm having trouble processing your request. Could you please rephrase or try again?",
|
| 229 |
+
"Kwa sasa, sina uwezo wa kukujibu vizuri. Tafadhali jaribu tena baadaye."
|
| 230 |
]
|
| 231 |
|
| 232 |
+
response = random.choice(fallback_responses)
|
| 233 |
+
set_cached_response(user_message, response)
|
| 234 |
+
return response
|
| 235 |
|
| 236 |
def generate_image_huggingface(prompt, retry_count=2):
|
| 237 |
"""Generate images using Hugging Face Inference API"""
|
|
|
|
| 298 |
"/api/chat - Text chat",
|
| 299 |
"/api/generate-image - Image generation",
|
| 300 |
"/api/generate-video - Video generation",
|
| 301 |
+
"/api/generate-cultural-video - Cultural videos",
|
| 302 |
+
"/api/quick-chat - Fast responses",
|
| 303 |
+
"/api/kiswahili/proverbs - Swahili proverbs",
|
| 304 |
+
"/api/kiswahili/phrases - Common phrases",
|
| 305 |
+
"/api/system/status - System status"
|
| 306 |
]
|
| 307 |
})
|
| 308 |
|
|
|
|
| 322 |
if detect_image_request(user_message):
|
| 323 |
# Extract prompt from message
|
| 324 |
prompt = user_message.lower()
|
| 325 |
+
for phrase in ['generate image of', 'create image of', 'make a picture of', 'draw', 'show me an image of']:
|
| 326 |
prompt = prompt.replace(phrase, '')
|
| 327 |
prompt = prompt.strip()
|
| 328 |
|
| 329 |
return jsonify({
|
| 330 |
+
"response": f"π¨ I can generate an image of '{prompt}' for you! Please use the image generation endpoint or say 'generate image: [description]'.",
|
| 331 |
"image_suggestion": prompt,
|
| 332 |
"status": "success",
|
| 333 |
"suggest_image": True
|
|
|
|
| 337 |
if detect_video_request(user_message):
|
| 338 |
# Extract prompt from message
|
| 339 |
prompt = user_message.lower()
|
| 340 |
+
for phrase in ['generate video of', 'create video of', 'make a video of', 'animate', 'create animation of']:
|
| 341 |
prompt = prompt.replace(phrase, '')
|
| 342 |
prompt = prompt.strip()
|
| 343 |
|
| 344 |
return jsonify({
|
| 345 |
+
"response": f"π¬ I can create a video of '{prompt}' for you! Use the video generation endpoint or describe what you want to see.",
|
| 346 |
"video_suggestion": prompt,
|
| 347 |
"status": "success",
|
| 348 |
"suggest_video": True
|
|
|
|
| 356 |
"status": "success",
|
| 357 |
"response_time": response_time,
|
| 358 |
"word_count": len(response.split()),
|
| 359 |
+
"cultural_context": detect_kiswahili_context(response),
|
| 360 |
+
"creator": "Stanley Samwel Owino",
|
| 361 |
+
"model": "STANLEY-AI-HF"
|
| 362 |
})
|
| 363 |
|
| 364 |
except Exception as e:
|
|
|
|
| 381 |
|
| 382 |
logger.info(f"π¨ Generating image: {prompt[:50]}...")
|
| 383 |
|
| 384 |
+
# Add cultural enhancement to prompt
|
| 385 |
+
enhanced_prompt = prompt
|
| 386 |
+
if any(word in prompt.lower() for word in ['africa', 'kenya', 'tanzania', 'safari', 'wildlife']):
|
| 387 |
+
enhanced_prompt += ", African style, vibrant colors, cultural elements"
|
| 388 |
+
|
| 389 |
# Generate image
|
| 390 |
+
image_data = generate_image_huggingface(enhanced_prompt)
|
| 391 |
|
| 392 |
if image_data:
|
| 393 |
generation_time = round(time.time() - start_time, 2)
|
|
|
|
| 395 |
return jsonify({
|
| 396 |
"image": image_data,
|
| 397 |
"prompt": prompt,
|
| 398 |
+
"enhanced_prompt": enhanced_prompt,
|
| 399 |
"status": "success",
|
| 400 |
"generation_time": generation_time,
|
| 401 |
+
"provider": "hugging_face",
|
| 402 |
+
"format": "png",
|
| 403 |
+
"creator": "Stanley Samwel Owino"
|
| 404 |
})
|
| 405 |
else:
|
| 406 |
return jsonify({
|
| 407 |
+
"error": "Pole! Image generation service is busy. Please try again in a moment.",
|
| 408 |
+
"status": "error",
|
| 409 |
+
"suggestion": "Try a simpler description or wait a few minutes"
|
| 410 |
}), 500
|
| 411 |
|
| 412 |
except Exception as e:
|
|
|
|
| 440 |
"prompt": prompt,
|
| 441 |
"status": "success",
|
| 442 |
"generation_time": generation_time,
|
| 443 |
+
"provider": "hugging_face_free",
|
| 444 |
+
"format": "mp4",
|
| 445 |
+
"duration": "3-4 seconds",
|
| 446 |
+
"resolution": "576x320",
|
| 447 |
+
"creator": "Stanley Samwel Owino"
|
| 448 |
})
|
| 449 |
else:
|
| 450 |
return jsonify({
|
| 451 |
+
"error": "Pole! Video generation service is busy. Try again in a moment.",
|
| 452 |
+
"status": "error",
|
| 453 |
+
"suggestion": "Try a simpler description or use image generation instead"
|
| 454 |
}), 500
|
| 455 |
|
| 456 |
except Exception as e:
|
|
|
|
| 477 |
if video_data:
|
| 478 |
generation_time = round(time.time() - start_time, 2)
|
| 479 |
|
| 480 |
+
theme_descriptions = {
|
| 481 |
+
"safari": "African wildlife and savanna landscape",
|
| 482 |
+
"dance": "Traditional African dance celebration",
|
| 483 |
+
"market": "Vibrant African market scene",
|
| 484 |
+
"coastal": "Swahili coast with ocean views",
|
| 485 |
+
"wildlife": "African wildlife documentary style",
|
| 486 |
+
"village": "Traditional village life in Africa"
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
return jsonify({
|
| 490 |
"video": video_data,
|
| 491 |
"theme": theme,
|
| 492 |
"style": style,
|
| 493 |
+
"description": theme_descriptions.get(theme, "Cultural scene"),
|
| 494 |
"status": "success",
|
| 495 |
+
"generation_time": generation_time,
|
| 496 |
+
"cultural_context": True,
|
| 497 |
+
"creator": "Stanley Samwel Owino"
|
| 498 |
})
|
| 499 |
else:
|
| 500 |
return jsonify({
|
| 501 |
"error": "Pole! Cultural video generation failed",
|
| 502 |
+
"status": "error",
|
| 503 |
+
"suggestion": "Try a different theme: safari, dance, market, coastal, wildlife, or village"
|
| 504 |
}), 500
|
| 505 |
|
| 506 |
except Exception as e:
|
|
|
|
| 536 |
'habari': 'Nzuri sana! Asante kwa kuuliza. Habari yako?',
|
| 537 |
'asante': 'Karibu sana! Ni furaha yangu kukusaidia.',
|
| 538 |
'jambo': 'Jambo! Habari yako? Ninaweza kukusaidia nini leo?',
|
| 539 |
+
'mambo': 'Poa! Vipi wewe? Una swali gani?',
|
| 540 |
+
'hakuna matata': 'Hakuna Matata! It means "no worries" in Swahili. Popularized by The Lion King.',
|
| 541 |
+
'simba': 'Simba means "lion" in Swahili. In The Lion King, Simba represents the journey of growth and responsibility.',
|
| 542 |
+
'rafiki': 'Rafiki means "friend" in Swahili. In The Lion King, Rafiki is the wise baboon who guides Simba.',
|
| 543 |
+
'kenya': 'Kenya is in East Africa, known for wildlife, Mount Kenya, and vibrant culture. The capital is Nairobi.',
|
| 544 |
+
'tanzania': 'Tanzania has Mount Kilimanjaro, Serengeti, and Zanzibar. Swahili is the national language.',
|
| 545 |
+
'nairobi': 'Nairobi is the capital of Kenya, known as the "Green City in the Sun" and a major tech hub in Africa.',
|
| 546 |
+
'generate': 'I can generate images and videos! Describe what you want: "generate image of sunset" or "create video of wildlife".',
|
| 547 |
+
'create': 'I can create content for you! Try: "create image of mountain" or "make video of city".'
|
| 548 |
}
|
| 549 |
|
| 550 |
msg_lower = user_message.lower().strip()
|
| 551 |
+
|
| 552 |
+
# Check for exact matches
|
| 553 |
if msg_lower in quick_responses:
|
| 554 |
return jsonify({
|
| 555 |
"response": quick_responses[msg_lower],
|
| 556 |
"status": "success",
|
| 557 |
+
"quick_response": True,
|
| 558 |
+
"creator": "Stanley Samwel Owino"
|
| 559 |
})
|
| 560 |
|
| 561 |
+
# Check for partial matches
|
| 562 |
+
for key, response in quick_responses.items():
|
| 563 |
+
if key in msg_lower and len(key) > 3:
|
| 564 |
+
return jsonify({
|
| 565 |
+
"response": response,
|
| 566 |
+
"status": "success",
|
| 567 |
+
"quick_response": True,
|
| 568 |
+
"creator": "Stanley Samwel Owino"
|
| 569 |
+
})
|
| 570 |
+
|
| 571 |
+
# If no quick response, use normal chat
|
| 572 |
return chat()
|
| 573 |
|
| 574 |
except Exception as e:
|
|
|
|
| 585 |
"creator": "Stanley Samwel Owino",
|
| 586 |
"role": "Machine Learning Engineer",
|
| 587 |
"version": "3.0",
|
| 588 |
+
"location": "Kenya, East Africa",
|
| 589 |
"features": [
|
| 590 |
"Text Generation",
|
| 591 |
"Image Generation",
|
| 592 |
"Video Generation",
|
| 593 |
"Kiswahili Knowledge",
|
| 594 |
+
"Cultural Integration",
|
| 595 |
+
"API Endpoints"
|
| 596 |
+
],
|
| 597 |
+
"apis_working": True,
|
| 598 |
+
"video_generation": True,
|
| 599 |
+
"image_generation": True,
|
| 600 |
+
"cultural_content": True,
|
| 601 |
+
"last_updated": "2024-12-08"
|
| 602 |
})
|
| 603 |
|
| 604 |
@app.route('/api/kiswahili/proverbs')
|
| 605 |
def get_proverbs():
|
| 606 |
"""Get random Swahili proverbs"""
|
| 607 |
proverbs = [
|
| 608 |
+
{"swahili": "Mwacha mila ni mtumwa.", "english": "He who abandons his culture is a slave.", "meaning": "Cherish your cultural heritage"},
|
| 609 |
+
{"swahili": "Haraka haraka haina baraka.", "english": "Hurry hurry has no blessing.", "meaning": "Patience yields better results"},
|
| 610 |
+
{"swahili": "Asiyesikia la mkuu huvunjika guu.", "english": "He who does not listen to elders breaks a leg.", "meaning": "Respect and learn from experience"},
|
| 611 |
+
{"swahili": "Mwenye pupa hadiriki kula tamu.", "english": "The impatient one misses out on sweetness.", "meaning": "Good things come to those who wait"},
|
| 612 |
+
{"swahili": "Ukiona vyaelea, vimeundwa.", "english": "If you see things floating, they were made to float.", "meaning": "Everything happens for a reason"}
|
| 613 |
]
|
| 614 |
return jsonify({
|
| 615 |
"proverb": random.choice(proverbs),
|
| 616 |
"language": "Kiswahili",
|
| 617 |
+
"origin": "East Africa",
|
| 618 |
+
"creator": "Stanley Samwel Owino"
|
| 619 |
})
|
| 620 |
|
| 621 |
@app.route('/api/kiswahili/phrases')
|
| 622 |
def get_phrases():
|
| 623 |
"""Get common Swahili phrases"""
|
| 624 |
phrases = {
|
| 625 |
+
"greetings": {
|
| 626 |
+
"Habari": "Hello / How are you?",
|
| 627 |
+
"Nzuri": "Good / Fine",
|
| 628 |
+
"Asante": "Thank you",
|
| 629 |
+
"Karibu": "Welcome / You're welcome",
|
| 630 |
+
"Tafadhali": "Please",
|
| 631 |
+
"Samahani": "Excuse me / Sorry",
|
| 632 |
+
"Kwaheri": "Goodbye",
|
| 633 |
+
"Lala salama": "Sleep well"
|
| 634 |
+
},
|
| 635 |
+
"questions": {
|
| 636 |
+
"Unaitwa nani?": "What is your name?",
|
| 637 |
+
"Unatoka wapi?": "Where are you from?",
|
| 638 |
+
"Unaishi wapi?": "Where do you live?",
|
| 639 |
+
"Unafanya nini?": "What do you do?"
|
| 640 |
+
},
|
| 641 |
+
"responses": {
|
| 642 |
+
"Ninaitwa...": "My name is...",
|
| 643 |
+
"Ninatoka Kenya": "I am from Kenya",
|
| 644 |
+
"Naishi Nairobi": "I live in Nairobi",
|
| 645 |
+
"Mimi ni mwanafunzi": "I am a student"
|
| 646 |
+
},
|
| 647 |
+
"lion_king": {
|
| 648 |
+
"Simba": "Lion",
|
| 649 |
+
"Rafiki": "Friend",
|
| 650 |
+
"Pumbaa": "Simpleton / Foolish",
|
| 651 |
+
"Shenzi": "Uncouth / Barbaric",
|
| 652 |
+
"Hakuna Matata": "No worries / No problems"
|
| 653 |
+
}
|
| 654 |
}
|
| 655 |
+
return jsonify({
|
| 656 |
+
"phrases": phrases,
|
| 657 |
+
"language": "Kiswahili",
|
| 658 |
+
"region": "East Africa",
|
| 659 |
+
"creator": "Stanley Samwel Owino",
|
| 660 |
+
"note": "Swahili is spoken by over 200 million people"
|
| 661 |
+
})
|
| 662 |
|
| 663 |
if __name__ == '__main__':
|
| 664 |
print("π STANLEY AI - Hugging Face Space Edition")
|
| 665 |
print("π¨βπ» Created by: Stanley Samwel Owino - Machine Learning Engineer")
|
| 666 |
+
print("π Location: Kenya, East Africa")
|
| 667 |
print("π Kiswahili Knowledge: Active")
|
| 668 |
print("π¬ Video Generation: FREE Hugging Face API")
|
| 669 |
print("π¨ Image Generation: Active")
|
|
|
|
| 675 |
print("3. /api/generate-video - Video generation")
|
| 676 |
print("4. /api/generate-cultural-video - Cultural videos")
|
| 677 |
print("5. /api/quick-chat - Fast responses")
|
| 678 |
+
print("6. /api/kiswahili/* - Kiswahili learning")
|
| 679 |
+
print("7. /api/system/status - System info")
|
| 680 |
+
print("=" * 50)
|
| 681 |
+
print("π Access at: https://huggingface.co/spaces/Stanley03/suno")
|
| 682 |
print("=" * 50)
|
| 683 |
|
| 684 |
app.run(debug=True, host='0.0.0.0', port=7860, threaded=True)
|