Download ai_server.py from Jakecybr/dnd2: direct link, hf CLI and curl.
- Browser
- Download file 2.7 kB
-
https://huggingface.co/spaces/Jakecybr/dnd2/resolve/main/ai_server.py
- Command line
-
hf download hf://spaces/Jakecybr/dnd2/ai_server.py
-
curl -L -o ai_server.py https://huggingface.co/spaces/Jakecybr/dnd2/resolve/main/ai_server.py
2.7 kB
| 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}") | |
| 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 | |
| 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) |