Spaces:
Sleeping
Sleeping
from flask import Flask, request, jsonify, render_template | |
import os | |
import gradio as gr | |
import requests | |
from PIL import Image | |
app = Flask(__name__) | |
# Load Gradio Model | |
model = gr.Interface.load("models/stabilityai/stable-diffusion-3.5-large") | |
# Chevereto Configuration | |
CHEVERETO_API_URL = os.environ.get("API_URL") | |
CHEVERETO_API_KEY = os.environ.get("API_KEY") | |
CHEVERETO_ALBUM_ID = os.environ.get("ALBUM_ID") | |
def upload_to_chevereto(img_path: str) -> str: | |
"""Uploads an image to Chevereto and returns the public image URL.""" | |
with open(img_path, "rb") as image_file: | |
files = {"source": image_file} | |
data = { | |
"key": CHEVERETO_API_KEY, | |
"format": "json", | |
"album": CHEVERETO_ALBUM_ID | |
} | |
response = requests.post(CHEVERETO_API_URL, files=files, data=data) | |
if response.status_code == 200: | |
return response.json().get("image", {}).get("url") | |
else: | |
return f"Error uploading image: {response.text}" | |
def generate_image_and_upload(prompt: str) -> str: | |
"""Generates an image using AI and uploads it to Chevereto.""" | |
img = model(prompt) # Generate the image | |
if isinstance(img, list): | |
img = img[0] | |
if isinstance(img, Image.Image): | |
img_path = "generated_image.png" | |
img.save(img_path, format="PNG") # Save image locally | |
return upload_to_chevereto(img_path) # Upload and return URL | |
else: | |
return "Error: Model did not return a valid image" | |
def index(): | |
"""Renders the Star Trek-themed UI.""" | |
return render_template("index.html") | |
def generate(): | |
"""API Endpoint: Generate an image from a text prompt and upload it.""" | |
data = request.get_json() | |
prompt = data.get("prompt", "") | |
if not prompt: | |
return jsonify({"error": "Missing prompt"}), 400 | |
image_url = generate_image_and_upload(prompt) | |
return jsonify({"image_url": image_url}) | |
if __name__ == "__main__": | |
app.run(host="0.0.0.0", port=7860) | |