File size: 2,703 Bytes
8f874db 2d48616 8f874db 2d48616 8f874db 2d48616 8f874db 2d48616 8f874db 2d48616 8f874db 2d48616 8f874db 2d48616 8f874db | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | 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}</s>\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) |