creative / app.py
artintel235's picture
Update app.py
9c51543 verified
raw
history blame
2.87 kB
import gradio as gr
import requests
from io import BytesIO
from PIL import Image
import os
# HARDCODED_URL = "" # Replace with your desired URL
GLIF_API_TOKEN = os.getenv("GLIF_API_TOKEN1")
GLIF_API_URL = "https://simple-api.glif.app"
glif_token_id = 1
glif_tokens_tried = 0
no_of_accounts = 3
import gradio as gr
from PIL import Image
from io import BytesIO
import requests
import os
def get_image_from_url(url):
"""
Fetches and returns an image from a given URL.
"""
try:
response = requests.get(url, stream=True)
response.raise_for_status()
image = Image.open(BytesIO(response.content))
return image
except requests.exceptions.RequestException as e:
return f"Error fetching image: {e}"
except Exception as e:
return f"Error processing image: {e}"
def generate_image(prompt, aspect_ratio, realism):
global glif_token_id
global GLIF_API_TOKEN
global glif_tokens_tried
global no_of_accounts
payload = {
"id": "cm3ugmzv2002gnckiosrwk6xi", # Replace with appropriate ID if necessary
"inputs": [prompt, aspect_ratio, str(realism).lower()],
}
headers = {"Authorization": f"Bearer {GLIF_API_TOKEN}"}
try:
response_data = requests.post(GLIF_API_URL, json=payload, headers=headers).json()
if "error" in response_data:
if 'error 429' in response_data['error']:
if glif_tokens_tried < no_of_accounts:
glif_token_id = (glif_token_id + 1) % no_of_accounts
glif_tokens_tried += 1
GLIF_API_TOKEN = os.getenv(f"GLIF_API_TOKEN{glif_token_id}")
response_data = generate_image(prompt, aspect_ratio, realism)
glif_tokens_tried = 0
return response_data
return "No credits available"
return response_data
elif "output" in response_data:
url = response_data['output']
return get_image_from_url(url) # Return the image directly
else:
return "Error: Unexpected response from server"
except Exception as e:
return f"Error: {e}"
# Define the Gradio interface
interface = gr.Interface(
fn=generate_image,
inputs=[
gr.Textbox(label="Prompt", placeholder="Describe the image you want to generate"),
gr.Radio(
choices=["1:1", "3:4", "4:3", "9:16", "16:9", "9:21", "21:9"],
label="Aspect Ratio",
value="16:9" # Default value
),
gr.Checkbox(label="Realism", value=True), # Checkbox for realism (True/False)
],
outputs=gr.Image(type="pil"), # Output image
title="Image Generator",
description="Provide a prompt, select an aspect ratio, and set realism to generate an image.",
)
# Launch the interface
interface.launch()