Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import urllib.parse
|
| 3 |
+
import requests
|
| 4 |
+
from flask import Flask, Response, request
|
| 5 |
+
|
| 6 |
+
app = Flask(__name__)
|
| 7 |
+
|
| 8 |
+
# Read the Pollinations URL template from the secret "FLUX"
|
| 9 |
+
# e.g. "https://image.pollinations.ai/prompt/[prompt]?width=[w]&height=[h]&seed=[seed]&nologo=true&enhance=true"
|
| 10 |
+
URL_TEMPLATE = os.environ.get("FLUX")
|
| 11 |
+
if URL_TEMPLATE is None:
|
| 12 |
+
raise RuntimeError("Missing FLUX secret (Pollinations URL template)")
|
| 13 |
+
|
| 14 |
+
@app.route("/generate", methods=["GET"])
|
| 15 |
+
def generate_image():
|
| 16 |
+
"""
|
| 17 |
+
Query params:
|
| 18 |
+
- prompt (string, required)
|
| 19 |
+
- width (int, optional, default=512)
|
| 20 |
+
- height (int, optional, default=512)
|
| 21 |
+
- seed (int, optional, default=0)
|
| 22 |
+
"""
|
| 23 |
+
prompt = request.args.get("prompt", "").strip()
|
| 24 |
+
if not prompt:
|
| 25 |
+
return Response("Error: 'prompt' is required", status=400)
|
| 26 |
+
|
| 27 |
+
# Defaults
|
| 28 |
+
width = request.args.get("width", "512")
|
| 29 |
+
height = request.args.get("height", "512")
|
| 30 |
+
seed = request.args.get("seed", "0")
|
| 31 |
+
|
| 32 |
+
# URL‐encode the prompt
|
| 33 |
+
encoded_prompt = urllib.parse.quote(prompt, safe="")
|
| 34 |
+
|
| 35 |
+
# Build the actual Pollinations URL
|
| 36 |
+
url = URL_TEMPLATE.replace("[prompt]", encoded_prompt) \
|
| 37 |
+
.replace("[w]", width) \
|
| 38 |
+
.replace("[h]", height) \
|
| 39 |
+
.replace("[seed]", seed)
|
| 40 |
+
|
| 41 |
+
# Fetch the image bytes
|
| 42 |
+
resp = requests.get(url, stream=True)
|
| 43 |
+
if resp.status_code != 200:
|
| 44 |
+
return Response(f"Failed to fetch image (status {resp.status_code})", status=502)
|
| 45 |
+
|
| 46 |
+
# Forward the content‐type header (likely "image/png" or "image/jpeg")
|
| 47 |
+
content_type = resp.headers.get("Content-Type", "application/octet-stream")
|
| 48 |
+
return Response(resp.content, content_type=content_type)
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
# If you run `python app.py` locally, this will start Flask’s dev server.
|
| 52 |
+
app.run(host="0.0.0.0", port=7860)
|