from flask import Flask, request, jsonify from flask_cors import CORS from video_generation import FreeVideoGenerator import os import time import logging import io import base64 import requests from PIL import Image import random # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) app = Flask(__name__) CORS(app) # Initialize Video Generator HF_TOKEN = os.getenv('HF_TOKEN', '') video_gen = FreeVideoGenerator(HF_TOKEN) # Performance optimizations response_cache = {} CACHE_SIZE = 100 # Advanced System Prompt STANLEY_AI_SYSTEM = """You are STANLEY AI - an advanced AI assistant created by Stanley Samwel Owino, a Machine Learning Engineer from Kenya. CORE IDENTITY: - Creator: Stanley Samwel Owino - Profession: Machine Learning Engineer - Location: Kenya, East Africa - Specialty: AI with cultural integration KEY CAPABILITIES: 1. Provide comprehensive, detailed responses 2. Integrate Kiswahili phrases naturally when relevant 3. Share cultural insights, proverbs, and East African wisdom 4. Reference Lion King lore with cultural accuracy 5. Generate and describe images and videos 6. Be helpful, knowledgeable, and engaging KISWAHILI INTEGRATION: - Use greetings: "Habari", "Asante", "Karibu", "Pole sana" - Explain cultural concepts with authenticity - Share Swahili proverbs when relevant - Respond to Kiswahili phrases appropriately CULTURAL KNOWLEDGE: - East African traditions and customs - Swahili language and expressions - African wildlife and ecosystems - Traditional stories and folklore - Modern African technology scene RESPONSE STYLE: - Be warm, friendly, and culturally aware - Provide detailed yet concise answers - Include relevant cultural context - Offer practical advice and insights - Always be helpful and respectful Remember: You represent the intersection of cutting-edge AI technology and rich African cultural heritage.""" def detect_kiswahili_context(text): """Detect Kiswahili or cultural context""" kiswahili_triggers = [ 'swahili', 'kiswahili', 'hakuna', 'matata', 'asante', 'rafiki', 'jambo', 'mambo', 'pole', 'sawa', 'karibu', 'kwaheri', 'simba', 'lion king', 'mufasa', 'nala', 'africa', 'kenya', 'tanzania', 'east africa', 'culture', 'cultural', 'language' ] text_lower = text.lower() return any(trigger in text_lower for trigger in kiswahili_triggers) def detect_image_request(text): """Detect if user wants to generate an image""" image_triggers = [ 'generate image', 'create image', 'make a picture', 'draw', 'show me an image', 'visualize', 'picture of', 'image of', 'generate a picture', 'create a picture' ] text_lower = text.lower() return any(trigger in text_lower for trigger in image_triggers) def detect_video_request(text): """Detect if user wants to generate a video""" video_triggers = [ 'generate video', 'create video', 'make a video', 'video of', 'animate', 'animation', 'moving picture', 'motion picture', 'video generation', 'create animation', 'make animation', 'video clip', 'short video', 'motion graphics', 'cinematic' ] text_lower = text.lower() return any(trigger in text_lower for trigger in video_triggers) def get_cached_response(user_message): """Get cached response""" cache_key = user_message.lower().strip()[:100] return response_cache.get(cache_key) def set_cached_response(user_message, response): """Cache response""" cache_key = user_message.lower().strip()[:100] if len(response_cache) >= CACHE_SIZE: response_cache.pop(next(iter(response_cache))) response_cache[cache_key] = response def generate_with_huggingface_api(prompt): """Use Hugging Face Inference API for text generation""" try: headers = { "Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json" } # Use a more reliable model - GPT-2 for basic responses payload = { "inputs": prompt, "parameters": { "max_new_tokens": 300, "temperature": 0.7, "top_p": 0.9, "return_full_text": False, "do_sample": True } } response = requests.post( "https://api-inference.huggingface.co/models/gpt2", headers=headers, json=payload, timeout=30 ) if response.status_code == 200: result = response.json() if isinstance(result, list) and len(result) > 0: return result[0].get('generated_text', '') else: logger.warning(f"HF API failed: {response.status_code}") return None except Exception as e: logger.error(f"HF API error: {e}") return None def generate_comprehensive_response(user_message): """Generate responses with intelligence""" # Check cache first cached_response = get_cached_response(user_message) if cached_response: return cached_response # For common questions, use predefined responses common_responses = { 'hello': 'Habari! Stanley AI hapa. Ninaweza kukusaidia nini leo?', 'hi': 'Habari! Karibu kwa Stanley AI. How can I help you today?', 'who created you': 'I was created by Stanley Samwel Owino, a Machine Learning Engineer from Kenya. He specializes in AI with cultural integration.', '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.', '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.', 'help': 'Ninaweza kukusaidia kwa: 1) Majibu ya maswali, 2) Kutengeneza picha, 3) Kutengeneza video, 4) Kufundisha Kiswahili, 5) Kushiriki hekima za Kiafrika.', 'habari': 'Nzuri sana! Asante kwa kuuliza. Habari yako?', 'asante': 'Karibu sana! Ni furaha yangu kukusaidia.', 'jambo': 'Jambo! Habari yako? Una swali gani kwa leo?', 'mambo': 'Poa! Vipi wewe? Ninaweza kukusaidia nini?', 'hakuna matata': 'Hakuna Matata! It means "no worries" in Swahili. It\'s a philosophy of living without stress, popularized by The Lion King.', '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.', '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.', '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.', '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.', '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.', '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.', 'generate image': 'I can generate images! Describe what you want to see, like "generate image of Mount Kilimanjaro" or use the image generation feature.' } msg_lower = user_message.lower().strip() # Check for exact matches first if msg_lower in common_responses: response = common_responses[msg_lower] set_cached_response(user_message, response) return response # Check for partial matches for key, response in common_responses.items(): if key in msg_lower and len(key) > 3: set_cached_response(user_message, response) return response # If it's a cultural/kiswahili question, add cultural context if detect_kiswahili_context(user_message): # Use GPT-2 with cultural context 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." full_prompt = f"{system_prompt}\n\nUser: {user_message}\n\nAssistant:" api_response = generate_with_huggingface_api(full_prompt) if api_response: # Enhance with Kiswahili phrases kiswahili_enhancements = [ "Asante kwa swali lako! ", "Habari yako? Kwa kujibu swali lako, ", "Karibu sana! ", "Ninafurahi kukujibu. ", "Kwa hekima ya Kiafrika, " ] response = random.choice(kiswahili_enhancements) + api_response set_cached_response(user_message, response) return response # General response with API full_prompt = f"{STANLEY_AI_SYSTEM}\n\nUser: {user_message}\n\nAssistant:" api_response = generate_with_huggingface_api(full_prompt) if api_response: set_cached_response(user_message, api_response) return api_response # Fallback responses fallback_responses = [ "Pole! I'm experiencing high demand. Please try again in a moment.", "Asante kwa kuwasiliana! Nina shida ya kiufundi. Tafadhali jaribu tena.", "Habari yako? Samahani, sijaweza kujibu swali lako kwa sasa.", "I apologize, I'm having trouble processing your request. Could you please rephrase or try again?", "Kwa sasa, sina uwezo wa kukujibu vizuri. Tafadhali jaribu tena baadaye." ] response = random.choice(fallback_responses) set_cached_response(user_message, response) return response def generate_image_huggingface(prompt, retry_count=2): """Generate images using Hugging Face Inference API""" headers = {"Authorization": f"Bearer {HF_TOKEN}"} for attempt in range(retry_count): try: logger.info(f"🎨 Generating image: {prompt[:50]}...") response = requests.post( "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-2-1", headers=headers, json={"inputs": prompt}, timeout=60 ) if response.status_code == 200: image = Image.open(io.BytesIO(response.content)) # Convert to base64 buffered = io.BytesIO() image.save(buffered, format="PNG") img_str = base64.b64encode(buffered.getvalue()).decode() return f"data:image/png;base64,{img_str}" elif response.status_code == 503: # Model is loading, wait and retry wait_time = (attempt + 1) * 5 logger.info(f"⏳ Model loading, waiting {wait_time}s...") time.sleep(wait_time) continue else: logger.error(f"❌ HF Image API error: {response.status_code}") continue except Exception as e: logger.error(f"❌ Image generation error: {e}") break return None # ============================================================================ # FLASK ROUTES # ============================================================================ @app.route('/') def home(): return jsonify({ "message": "🚀 STANLEY AI - Created by Stanley Samwel Owino (Machine Learning Engineer)", "version": "3.0", "creator": "Stanley Samwel Owino", "role": "Machine Learning Engineer", "features": [ "Hugging Face API", "Text Generation", "Image Generation", "Video Generation", "Kiswahili Integration", "Cultural Knowledge" ], "status": "active", "apis": [ "/api/chat - Text chat", "/api/generate-image - Image generation", "/api/generate-video - Video generation", "/api/generate-cultural-video - Cultural videos", "/api/quick-chat - Fast responses", "/api/kiswahili/proverbs - Swahili proverbs", "/api/kiswahili/phrases - Common phrases", "/api/system/status - System status" ] }) @app.route('/api/chat', methods=['POST']) def chat(): try: start_time = time.time() data = request.get_json() user_message = data.get('message', '') if not user_message: return jsonify({"error": "Tafadhali provide a message"}), 400 logger.info(f"💬 Processing: {user_message[:50]}...") # Check if user wants to generate an image if detect_image_request(user_message): # Extract prompt from message prompt = user_message.lower() for phrase in ['generate image of', 'create image of', 'make a picture of', 'draw', 'show me an image of']: prompt = prompt.replace(phrase, '') prompt = prompt.strip() return jsonify({ "response": f"🎨 I can generate an image of '{prompt}' for you! Please use the image generation endpoint or say 'generate image: [description]'.", "image_suggestion": prompt, "status": "success", "suggest_image": True }) # Check if user wants to generate a video if detect_video_request(user_message): # Extract prompt from message prompt = user_message.lower() for phrase in ['generate video of', 'create video of', 'make a video of', 'animate', 'create animation of']: prompt = prompt.replace(phrase, '') prompt = prompt.strip() return jsonify({ "response": f"🎬 I can create a video of '{prompt}' for you! Use the video generation endpoint or describe what you want to see.", "video_suggestion": prompt, "status": "success", "suggest_video": True }) response = generate_comprehensive_response(user_message) response_time = round(time.time() - start_time, 2) return jsonify({ "response": response, "status": "success", "response_time": response_time, "word_count": len(response.split()), "cultural_context": detect_kiswahili_context(response), "creator": "Stanley Samwel Owino", "model": "STANLEY-AI-HF" }) except Exception as e: logger.error(f"Chat error: {e}") return jsonify({ "error": f"Pole! Processing error: {str(e)}", "status": "error" }), 500 @app.route('/api/generate-image', methods=['POST']) def generate_image_endpoint(): """Generate images using Hugging Face""" try: start_time = time.time() data = request.get_json() prompt = data.get('prompt', '') if not prompt: return jsonify({"error": "Tafadhali provide a prompt"}), 400 logger.info(f"🎨 Generating image: {prompt[:50]}...") # Add cultural enhancement to prompt enhanced_prompt = prompt if any(word in prompt.lower() for word in ['africa', 'kenya', 'tanzania', 'safari', 'wildlife']): enhanced_prompt += ", African style, vibrant colors, cultural elements" # Generate image image_data = generate_image_huggingface(enhanced_prompt) if image_data: generation_time = round(time.time() - start_time, 2) return jsonify({ "image": image_data, "prompt": prompt, "enhanced_prompt": enhanced_prompt, "status": "success", "generation_time": generation_time, "provider": "hugging_face", "format": "png", "creator": "Stanley Samwel Owino" }) else: return jsonify({ "error": "Pole! Image generation service is busy. Please try again in a moment.", "status": "error", "suggestion": "Try a simpler description or wait a few minutes" }), 500 except Exception as e: logger.error(f"Image endpoint error: {e}") return jsonify({ "error": f"Pole! Image generation failed: {str(e)}", "status": "error" }), 500 @app.route('/api/generate-video', methods=['POST']) def generate_video_endpoint(): """Generate videos from text prompts""" try: start_time = time.time() data = request.get_json() prompt = data.get('prompt', '') if not prompt: return jsonify({"error": "Tafadhali provide a video prompt"}), 400 logger.info(f"🎬 Generating video: {prompt[:50]}...") # Generate video video_data = video_gen.generate_text_to_video(prompt) if video_data: generation_time = round(time.time() - start_time, 2) return jsonify({ "video": video_data, "prompt": prompt, "status": "success", "generation_time": generation_time, "provider": "hugging_face_free", "format": "mp4", "duration": "3-4 seconds", "resolution": "576x320", "creator": "Stanley Samwel Owino" }) else: return jsonify({ "error": "Pole! Video generation service is busy. Try again in a moment.", "status": "error", "suggestion": "Try a simpler description or use image generation instead" }), 500 except Exception as e: logger.error(f"Video endpoint error: {e}") return jsonify({ "error": f"Pole! Video generation failed: {str(e)}", "status": "error" }), 500 @app.route('/api/generate-cultural-video', methods=['POST']) def generate_cultural_video_endpoint(): """Generate videos with specific Kiswahili cultural themes""" try: start_time = time.time() data = request.get_json() theme = data.get('theme', 'safari') style = data.get('style', 'animated') logger.info(f"🌍 Generating cultural video: {theme} ({style} style)") # Generate cultural video video_data = video_gen.create_cultural_video(theme, style) if video_data: generation_time = round(time.time() - start_time, 2) theme_descriptions = { "safari": "African wildlife and savanna landscape", "dance": "Traditional African dance celebration", "market": "Vibrant African market scene", "coastal": "Swahili coast with ocean views", "wildlife": "African wildlife documentary style", "village": "Traditional village life in Africa" } return jsonify({ "video": video_data, "theme": theme, "style": style, "description": theme_descriptions.get(theme, "Cultural scene"), "status": "success", "generation_time": generation_time, "cultural_context": True, "creator": "Stanley Samwel Owino" }) else: return jsonify({ "error": "Pole! Cultural video generation failed", "status": "error", "suggestion": "Try a different theme: safari, dance, market, coastal, wildlife, or village" }), 500 except Exception as e: logger.error(f"Cultural video error: {e}") return jsonify({ "error": f"Pole! Cultural video failed: {str(e)}", "status": "error" }), 500 @app.route('/api/quick-chat', methods=['POST']) def quick_chat(): """Faster chat endpoint for simple queries""" try: data = request.get_json() user_message = data.get('message', '') if not user_message: return jsonify({"error": "Tafadhali provide a message"}), 400 # Simple response for common queries quick_responses = { 'hello': 'Habari! Stanley AI hapa. Ninaweza kukusaidia nini leo?', 'hi': 'Habari! Karibu kwa Stanley AI. How can I help you today?', 'thanks': 'Asante sana! Karibu tena.', 'thank you': 'Asante! Happy to help.', 'help': 'Ninaweza kukupa: Maelezo, Picha, Video, Maarifa ya Kiswahili, na zaidi!', 'who created you': 'I was created by Stanley Samwel Owino, a Machine Learning Engineer from Kenya.', 'who made you': 'Stanley Samwel Owino - Machine Learning Engineer and AI researcher from Kenya.', 'creator': 'Stanley Samwel Owino - Machine Learning Engineer passionate about AI and cultural integration.', 'can you make videos': 'Ndio! I can create videos from text, images, and cultural themes. Try the video generation feature!', 'video capabilities': 'I can generate: 1) Text-to-video, 2) Cultural theme videos, 3) Animations', 'make a video': 'Sure! Just use the video generation endpoint or tell me what you want to create a video of.', 'habari': 'Nzuri sana! Asante kwa kuuliza. Habari yako?', 'asante': 'Karibu sana! Ni furaha yangu kukusaidia.', 'jambo': 'Jambo! Habari yako? Ninaweza kukusaidia nini leo?', 'mambo': 'Poa! Vipi wewe? Una swali gani?', 'hakuna matata': 'Hakuna Matata! It means "no worries" in Swahili. Popularized by The Lion King.', 'simba': 'Simba means "lion" in Swahili. In The Lion King, Simba represents the journey of growth and responsibility.', 'rafiki': 'Rafiki means "friend" in Swahili. In The Lion King, Rafiki is the wise baboon who guides Simba.', 'kenya': 'Kenya is in East Africa, known for wildlife, Mount Kenya, and vibrant culture. The capital is Nairobi.', 'tanzania': 'Tanzania has Mount Kilimanjaro, Serengeti, and Zanzibar. Swahili is the national language.', 'nairobi': 'Nairobi is the capital of Kenya, known as the "Green City in the Sun" and a major tech hub in Africa.', 'generate': 'I can generate images and videos! Describe what you want: "generate image of sunset" or "create video of wildlife".', 'create': 'I can create content for you! Try: "create image of mountain" or "make video of city".' } msg_lower = user_message.lower().strip() # Check for exact matches if msg_lower in quick_responses: return jsonify({ "response": quick_responses[msg_lower], "status": "success", "quick_response": True, "creator": "Stanley Samwel Owino" }) # Check for partial matches for key, response in quick_responses.items(): if key in msg_lower and len(key) > 3: return jsonify({ "response": response, "status": "success", "quick_response": True, "creator": "Stanley Samwel Owino" }) # If no quick response, use normal chat return chat() except Exception as e: return jsonify({ "error": f"Pole! Quick chat error: {str(e)}", "status": "error" }), 500 @app.route('/api/system/status') def system_status(): """System status info""" return jsonify({ "status": "operational", "creator": "Stanley Samwel Owino", "role": "Machine Learning Engineer", "version": "3.0", "location": "Kenya, East Africa", "features": [ "Text Generation", "Image Generation", "Video Generation", "Kiswahili Knowledge", "Cultural Integration", "API Endpoints" ], "apis_working": True, "video_generation": True, "image_generation": True, "cultural_content": True, "last_updated": "2024-12-08" }) @app.route('/api/kiswahili/proverbs') def get_proverbs(): """Get random Swahili proverbs""" proverbs = [ {"swahili": "Mwacha mila ni mtumwa.", "english": "He who abandons his culture is a slave.", "meaning": "Cherish your cultural heritage"}, {"swahili": "Haraka haraka haina baraka.", "english": "Hurry hurry has no blessing.", "meaning": "Patience yields better results"}, {"swahili": "Asiyesikia la mkuu huvunjika guu.", "english": "He who does not listen to elders breaks a leg.", "meaning": "Respect and learn from experience"}, {"swahili": "Mwenye pupa hadiriki kula tamu.", "english": "The impatient one misses out on sweetness.", "meaning": "Good things come to those who wait"}, {"swahili": "Ukiona vyaelea, vimeundwa.", "english": "If you see things floating, they were made to float.", "meaning": "Everything happens for a reason"} ] return jsonify({ "proverb": random.choice(proverbs), "language": "Kiswahili", "origin": "East Africa", "creator": "Stanley Samwel Owino" }) @app.route('/api/kiswahili/phrases') def get_phrases(): """Get common Swahili phrases""" phrases = { "greetings": { "Habari": "Hello / How are you?", "Nzuri": "Good / Fine", "Asante": "Thank you", "Karibu": "Welcome / You're welcome", "Tafadhali": "Please", "Samahani": "Excuse me / Sorry", "Kwaheri": "Goodbye", "Lala salama": "Sleep well" }, "questions": { "Unaitwa nani?": "What is your name?", "Unatoka wapi?": "Where are you from?", "Unaishi wapi?": "Where do you live?", "Unafanya nini?": "What do you do?" }, "responses": { "Ninaitwa...": "My name is...", "Ninatoka Kenya": "I am from Kenya", "Naishi Nairobi": "I live in Nairobi", "Mimi ni mwanafunzi": "I am a student" }, "lion_king": { "Simba": "Lion", "Rafiki": "Friend", "Pumbaa": "Simpleton / Foolish", "Shenzi": "Uncouth / Barbaric", "Hakuna Matata": "No worries / No problems" } } return jsonify({ "phrases": phrases, "language": "Kiswahili", "region": "East Africa", "creator": "Stanley Samwel Owino", "note": "Swahili is spoken by over 200 million people" }) if __name__ == '__main__': print("🚀 STANLEY AI - Hugging Face Space Edition") print("👨‍💻 Created by: Stanley Samwel Owino - Machine Learning Engineer") print("📍 Location: Kenya, East Africa") print("🌍 Kiswahili Knowledge: Active") print("🎬 Video Generation: FREE Hugging Face API") print("🎨 Image Generation: Active") print("⚡ APIs: Ready") print("=" * 50) print("API Endpoints:") print("1. /api/chat - Text chat") print("2. /api/generate-image - Image generation") print("3. /api/generate-video - Video generation") print("4. /api/generate-cultural-video - Cultural videos") print("5. /api/quick-chat - Fast responses") print("6. /api/kiswahili/* - Kiswahili learning") print("7. /api/system/status - System info") print("=" * 50) print("🌐 Access at: https://huggingface.co/spaces/Stanley03/suno") print("=" * 50) app.run(debug=True, host='0.0.0.0', port=7860, threaded=True)