Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
import os
|
3 |
+
import gradio as gr
|
4 |
+
import requests
|
5 |
+
from PIL import Image
|
6 |
+
|
7 |
+
app = Flask(__name__)
|
8 |
+
|
9 |
+
# Load Gradio Model
|
10 |
+
model = gr.Interface.load("models/stabilityai/stable-diffusion-3.5-large")
|
11 |
+
|
12 |
+
# Chevereto Configuration
|
13 |
+
CHEVERETO_API_URL = os.environ.get("API_URL")
|
14 |
+
CHEVERETO_API_KEY = os.environ.get("API_KEY")
|
15 |
+
CHEVERETO_ALBUM_ID = os.environ.get("ALBUM_ID")
|
16 |
+
|
17 |
+
def upload_to_chevereto(img_path: str) -> str:
|
18 |
+
"""Uploads an image to Chevereto and returns the public image URL."""
|
19 |
+
with open(img_path, "rb") as image_file:
|
20 |
+
files = {"source": image_file}
|
21 |
+
data = {
|
22 |
+
"key": CHEVERETO_API_KEY,
|
23 |
+
"format": "json",
|
24 |
+
"album": CHEVERETO_ALBUM_ID
|
25 |
+
}
|
26 |
+
response = requests.post(CHEVERETO_API_URL, files=files, data=data)
|
27 |
+
|
28 |
+
if response.status_code == 200:
|
29 |
+
return response.json().get("image", {}).get("url")
|
30 |
+
else:
|
31 |
+
return f"Error uploading image: {response.text}"
|
32 |
+
|
33 |
+
def generate_image_and_upload(prompt: str) -> str:
|
34 |
+
"""Generates an image using AI and uploads it to Chevereto."""
|
35 |
+
img = model(prompt) # Generate the image
|
36 |
+
|
37 |
+
if isinstance(img, list):
|
38 |
+
img = img[0]
|
39 |
+
|
40 |
+
if isinstance(img, Image.Image):
|
41 |
+
img_path = "generated_image.png"
|
42 |
+
img.save(img_path, format="PNG") # Save image locally
|
43 |
+
|
44 |
+
return upload_to_chevereto(img_path) # Upload and return URL
|
45 |
+
else:
|
46 |
+
return "Error: Model did not return a valid image"
|
47 |
+
|
48 |
+
@app.route("/generate", methods=["POST"])
|
49 |
+
def generate():
|
50 |
+
"""API Endpoint: Generate an image from a text prompt and upload it."""
|
51 |
+
data = request.get_json()
|
52 |
+
prompt = data.get("prompt", "")
|
53 |
+
|
54 |
+
if not prompt:
|
55 |
+
return jsonify({"error": "Missing prompt"}), 400
|
56 |
+
|
57 |
+
image_url = generate_image_and_upload(prompt)
|
58 |
+
return jsonify({"image_url": image_url})
|
59 |
+
|
60 |
+
if __name__ == "__main__":
|
61 |
+
app.run(host="0.0.0.0", port=7860)
|