Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
import requests
|
3 |
+
import io
|
4 |
+
import random
|
5 |
+
import os
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
app = Flask(__name__)
|
9 |
+
|
10 |
+
API_URL = "https://api-inference.huggingface.co/models/openskyml/dalle-3-xl"
|
11 |
+
API_TOKEN = os.getenv("HF_READ_TOKEN") # it is free
|
12 |
+
headers = {"Authorization": f"Bearer {API_TOKEN}"}
|
13 |
+
|
14 |
+
|
15 |
+
def query(prompt, is_negative=False, steps=1, cfg_scale=6, seed=None):
|
16 |
+
payload = {
|
17 |
+
"inputs": prompt,
|
18 |
+
"is_negative": is_negative,
|
19 |
+
"steps": steps,
|
20 |
+
"cfg_scale": cfg_scale,
|
21 |
+
"seed": seed if seed is not None else random.randint(-1, 2147483647)
|
22 |
+
}
|
23 |
+
|
24 |
+
image_bytes = requests.post(API_URL, headers=headers, json=payload).content
|
25 |
+
image = Image.open(io.BytesIO(image_bytes))
|
26 |
+
return image
|
27 |
+
|
28 |
+
|
29 |
+
@app.route("/generate", methods=["POST"])
|
30 |
+
def generate():
|
31 |
+
try:
|
32 |
+
data = request.get_json()
|
33 |
+
prompt = data["prompt"]
|
34 |
+
negative_prompt = data.get("negative_prompt", "")
|
35 |
+
is_negative = True if negative_prompt else False
|
36 |
+
|
37 |
+
image = query(prompt, is_negative=is_negative)
|
38 |
+
|
39 |
+
# Convert PIL Image to bytes
|
40 |
+
img_byte_array = io.BytesIO()
|
41 |
+
image.save(img_byte_array, format='PNG')
|
42 |
+
img_byte_array = img_byte_array.getvalue()
|
43 |
+
|
44 |
+
response = {
|
45 |
+
"success": True,
|
46 |
+
"image": img_byte_array.decode('latin-1')
|
47 |
+
}
|
48 |
+
except Exception as e:
|
49 |
+
response = {
|
50 |
+
"success": False,
|
51 |
+
"error": str(e)
|
52 |
+
}
|
53 |
+
|
54 |
+
return jsonify(response)
|
55 |
+
|
56 |
+
|
57 |
+
if __name__ == "__main__":
|
58 |
+
app.run(debug=True)
|