from flask import Flask, request, jsonify from flask_cors import CORS import torch from diffusers import StableDiffusionPipeline from transformers import AutoTokenizer, AutoModelForCausalLM import base64 from io import BytesIO import os app = Flask(__name__) CORS(app) # SETUP: Define where models live (Persistent Storage) # The docs recommend this path to avoid re-downloading cache_dir = "/data/.huggingface" device = "cuda" if torch.cuda.is_available() else "cpu" print(f"🚀 AI SERVER STARTING ON: {device}") print(f"💾 MODEL CACHE: {cache_dir}") # 1. Load Image Model (Stable Diffusion 1.5) try: print("Loading Image Model (this may take time first run)...") image_pipe = StableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16, cache_dir=cache_dir ).to(device) print("✅ Image Model Loaded") except Exception as e: print(f"❌ Image Model Failed: {e}") # 2. Load Chat Model (TinyLlama) try: print("Loading Chat Model...") chat_tokenizer = AutoTokenizer.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0", cache_dir=cache_dir) chat_model = AutoModelForCausalLM.from_pretrained( "TinyLlama/TinyLlama-1.1B-Chat-v1.0", torch_dtype=torch.float16, cache_dir=cache_dir ).to(device) print("✅ Chat Model Loaded") except Exception as e: print(f"❌ Chat Model Failed: {e}") @app.route('/generate-image', methods=['POST']) def generate_image(): try: data = request.json prompt = data.get('prompt', '') # Run on GPU image = image_pipe(prompt, num_inference_steps=25).images[0] buffered = BytesIO() image.save(buffered, format="PNG") img_str = base64.b64encode(buffered.getvalue()).decode() return jsonify({"url": f"data:image/png;base64,{img_str}"}) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route('/chat', methods=['POST']) def chat(): try: data = request.json message = data.get('message', '') formatted_prompt = f"<|user|>\n{message}\n<|assistant|>\n" inputs = chat_tokenizer(formatted_prompt, return_tensors="pt").to(device) outputs = chat_model.generate(**inputs, max_new_tokens=150, do_sample=True, temperature=0.7) response = chat_tokenizer.decode(outputs[0], skip_special_tokens=True) if "<|assistant|>" in response: response = response.split("<|assistant|>")[-1].strip() return jsonify({"reply": response}) except Exception as e: return jsonify({"error": str(e)}), 500 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)