ginipick's picture
Update app.py
6cd9d56 verified
raw
history blame contribute delete
No virus
12.5 kB
import gradio as gr
from gradio_client import Client
import os
import logging
import json
from datetime import datetime
import shutil
from moviepy.editor import VideoFileClip
# ๋กœ๊น… ์„ค์ •
logging.basicConfig(level=logging.INFO)
# API ํด๋ผ์ด์–ธํŠธ ์„ค์ •
api_client = Client("http://211.233.58.202:7960/")
# ๊ฐค๋Ÿฌ๋ฆฌ ์ €์žฅ ๋””๋ ‰ํ† ๋ฆฌ ์„ค์ •
GALLERY_DIR = "/home/user/app/gallery"
GALLERY_JSON = "/home/user/app/gallery.json"
# ๊ฐค๋Ÿฌ๋ฆฌ ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ
os.makedirs(GALLERY_DIR, exist_ok=True)
def respond(message, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
logging.info(f"Received message: {message}, seed: {seed}, randomize_seed: {randomize_seed}, "
f"width: {width}, height: {height}, guidance_scale: {guidance_scale}, "
f"num_inference_steps: {num_inference_steps}")
try:
# ์ด๋ฏธ์ง€ ์ƒ์„ฑ ์š”์ฒญ
result = api_client.predict(
prompt=message,
seed=seed,
randomize_seed=randomize_seed,
width=width,
height=height,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
api_name="/infer_t2i"
)
logging.info("API response received: %s", result)
# ๊ฒฐ๊ณผ ํ™•์ธ ๋ฐ ์ฒ˜๋ฆฌ
if isinstance(result, tuple) and len(result) >= 1:
image_path = result[0]
saved_image_path = save_to_gallery(image_path, message)
return saved_image_path
else:
raise ValueError("Unexpected API response format")
except Exception as e:
logging.error("Error during API request: %s", str(e))
return "Failed to generate image due to an error."
css = """
footer {
visibility: hidden;
}
"""
# ์ด๋ฏธ์ง€ ์ƒ์„ฑ์„ ์œ„ํ•œ ์˜ˆ์ œ ํ”„๋กฌํ”„ํŠธ
examples = [
["A photograph of the front view portrait of an Man in a full body dynamic pose on a red background in the style of high fashion moment, with rich colors, dramatic light, in a fantasy art style, with surrealism, elegant details, a golden ratio composition, and detailed texture", "q21.png"],
["the image show the fourth elements, each one in a part of the picture, first part is at top left and show a splashing multicolor water text with many water reflections, the text is made of water, the water word is 'WATER', the background is splashing water, the second part of the image is a top right and show a soil rounded text, the word made of soil is 'EARTH', the background is planet earth, the third part of the image is at bottom left and show a cloud multicolor rounded text, the word is 'AIR' made of colorfull cloud the background is a sunset, and the last part of the image in the bottom right show a red fire rounded text made of lava, the colorfull big word made of fire is 'FIRE', the background is the closeup ", "q22.png"],
["Dramatic news broadcast scene in a Teahupoสปo wave's where a cow surfing, mimicking pro surf rider poses. Yogis laugh and take pictures. The news banner reads: 'COW win Olympics!!'. An inset shows an anchor openfree.ai@","q23.png"],
["a beautiful cute joyful and playful 29 year old woman view from bottom, red haired, dressed in a cozy sherpa jacket over a turtleneck and skinny jeans, in the street of Paris at night eiffel tower in background, detailed masterpiece most beautiful artwork in the world Ultrarealistic, Sony A7, Nostalgic lighting","q24.png"],
["A man climbing a rock wall reaching for the next hold", "q25.png"],
["pov of an austronaut holding a small red rock that has a portal showing the Statue of Liberty, alien landscape of a red planet in the background, surreal","q26.png"],
["a smartphone product showcase, smartphone display showing immersive wallpaper and time, blurred turquoise background","q27.png"],
["A glamorous young woman with long, wavy blonde hair and smokey eye makeup, posing in a luxury hotel room. Sheโ€™s wearing a sparkly gold cocktail dress and holding up a white card with 'openfree.ai' written on it in elegant calligraphy. Soft, warm lighting creates a luxurious atmosphere. ", "q1.webp"],
["A fit male fitness influencer with short dark hair and stubble, standing shirtless in a modern gym. He has defined abs and arm muscles, and is holding a protein shake in one hand and a card that says 'openfree.ai' in the other. Bright, clean lighting highlights his physique.", "q2.webp"],
["A bohemian-style female travel blogger with sun-kissed skin and messy beach waves, sitting on a tropical beach at sunset. Sheโ€™s wearing a flowy white sundress and holding up a weathered postcard with 'openfree.ai' scrawled on it. Golden hour lighting bathes the scene in warm tones. ", "q3.webp"],
["A trendy male fashion influencer with perfectly styled hair and designer stubble, posing on a city street. Heโ€™s wearing a tailored suit and holding up a sleek black business card with 'openfree.ai' printed in minimalist white font. The background shows blurred city lights, creating a chic urban atmosphere.", "q4.webp"],
["A fresh-faced young female beauty guru with freckles and natural makeup, sitting at a vanity covered in cosmetics. Sheโ€™s wearing a pastel pink robe and holding up a makeup palette with 'openfree.ai' written on it in lipstick. Soft, flattering lighting enhances her radiant complexion. ", "q5.webp"],
["A stylish young woman with long, wavy ombre hair and winged eyeliner, posing in front of a neon-lit city skyline at night. Sheโ€™s wearing a sleek black leather jacket over a sparkly crop top and holding up a holographic business card that says 'openfree.ai' in futuristic font. The card reflects the colorful neon lights, creating a cyberpunk aesthetic.", "q6.webp"],
["Create a surreal advertisement poster for a fictional time travel agency. The background should depict a swirling vortex of clock faces and historical landmarks from different eras. In the foreground, place large, bold text that reads โ€œAI TOURS: YOUR PAST IS OUR FUTUREโ€ in a retro-futuristic font. The text should appear to be partially disintegrating into particles that are being sucked into the time vortex. Include smaller text at the bottom with fictional pricing and the slogan โ€œHistory is just a ticket away!โ€", "q7.webp"],
["Photo realistic scene inspired by LOTR: [A tiny red dragon sleeps curled up in a nest on a medieval wizard's table]. Shot with a macro lens (f/2.8, 50mm) and a Canon EOSR5, the soft focus captures [the cozy morning light filtering through a near by window]. The pastel colors and whimsical steam shapes enhance the serene atmosphere, evoking a DnD RPG setting. The image is rendered in 16K and 8K, highlighting [the intricate details and medieval charm].", "q8.webp"],
["์ฌ๊ธ€๋ผ์Šค๋ฅผ ์ฐฉ์šฉํ•œ ๊ท€์—ฌ์šด ๊ฐ•์•„์ง€๊ฐ€ 'Openfree.ai'๋ผ๊ณ  ์“ฐ์—ฌ์ง„ ํ‘œ์ง€ํŒ์„ ๋“ค๊ณ ์žˆ๋‹ค.", "q9.webp"],
["๋ฏธ๋ ˆ์ ์ธ ๋„์‹œ์˜ ํ•ด์ง€๋Š” ํ’๊ฒฝ", "q10.webp"],
["๋นจ๊ฐ„์ƒ‰ ๋ฐ•์Šค์— 'openfree.ai'๋ผ๊ณ  ๊ธ€์”จ๊ฐ€ ์“ฐ์—ฌ์žˆ๊ณ , ๊ทธ์œ„์— ๊ฐ•์•„์ง€์™€ ๊ณ ์–‘์ด๊ฐ€ ์•‰์•„์žˆ๋‹ค.", "q11.webp"],
["๋กœ๋ด‡์ด ๊ณต์‚ฌ์žฅ์—์„œ ์ž‘์—…์ค‘์ด๋‹ค. ๋ฐฐ๊ฒฝ์— 'Coming soon~'๋ผ๋Š” ๊ธ€์ž๊ฐ€ ์“ฐ์—ฌ์žˆ๋‹ค.", "q20.webp"],
["A serene landscape with mountains in the background and a clear lake in the foreground.", "q12.webp"],
["A street scene from Tokyo at night, vibrant and full of lights.", "q13.webp"],
["An astronaut riding a horse on Mars.", "q14.webp"],
["A surreal painting of a tree growing books.", "q15.webp"],
["A cottage in a snowy forest, lit by warm lights.", "q16.webp"],
["A still life of various fruits and a wine glass on a table.", "q17.webp"],
["A digital artwork of a neon-lit alley in a cyberpunk city.", "q18.webp"],
["A fantasy map of a fictional world, with detailed terrain and cities.", "q19.webp"]
]
def use_prompt(prompt):
return prompt
with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as demo:
with gr.Tab("Generate"):
with gr.Row():
input_text = gr.Textbox(label="Enter your prompt for image generation")
output_image = gr.Image(label="Generated Image")
with gr.Row():
seed = gr.Slider(minimum=0, maximum=1000000, step=1, label="Seed", value=123)
randomize_seed = gr.Checkbox(label="Randomize Seed", value=False)
with gr.Row():
width = gr.Slider(minimum=256, maximum=1024, step=64, label="Width", value=1024)
height = gr.Slider(minimum=256, maximum=1024, step=64, label="Height", value=576)
with gr.Row():
guidance_scale = gr.Slider(minimum=1, maximum=20, step=0.1, label="Guidance Scale", value=5)
num_inference_steps = gr.Slider(minimum=1, maximum=100, step=1, label="Number of Inference Steps", value=28)
with gr.Row():
for prompt, image_file in examples:
with gr.Column():
gr.Image(image_file, label=prompt[:50] + "...") # ํ”„๋กฌํ”„ํŠธ์˜ ์ฒ˜์Œ 50์ž๋งŒ ํ‘œ์‹œ
gr.Button("Use this prompt").click(
fn=use_prompt,
inputs=[],
outputs=input_text,
api_name=False
).then(
lambda x=prompt: x,
inputs=[],
outputs=input_text
)
with gr.Tab("Gallery"):
gallery = gr.Gallery(
label="Generated Images",
show_label=False,
elem_id="gallery",
columns=[5],
rows=[3],
object_fit="contain",
height="auto"
)
refresh_btn = gr.Button("Refresh Gallery")
def update_gallery():
return load_gallery()
refresh_btn.click(fn=update_gallery, inputs=None, outputs=gallery)
demo.load(fn=update_gallery, inputs=None, outputs=gallery)
input_text.submit(
fn=respond,
inputs=[input_text, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
outputs=output_image
).then(
fn=update_gallery,
inputs=None,
outputs=gallery
)
def load_gallery():
print(f"Loading gallery from: {GALLERY_JSON}") # ๋กœ๊ทธ ์ถ”๊ฐ€
if os.path.exists(GALLERY_JSON):
print(f"Gallery JSON permissions: {oct(os.stat(GALLERY_JSON).st_mode)[-3:]}") # ๋กœ๊ทธ ์ถ”๊ฐ€
try:
with open(GALLERY_JSON, "r") as f:
gallery = json.load(f)
return [(item["image"], item["prompt"]) for item in reversed(gallery)]
except Exception as e:
print(f"Error loading gallery: {str(e)}")
return []
def check_gallery_status():
print(f"Gallery directory exists: {os.path.exists(GALLERY_DIR)}")
print(f"Gallery JSON exists: {os.path.exists(GALLERY_JSON)}")
if os.path.exists(GALLERY_JSON):
try:
with open(GALLERY_JSON, "r") as f:
gallery = json.load(f)
print(f"Number of items in gallery: {len(gallery)}")
except Exception as e:
print(f"Error reading gallery JSON: {str(e)}")
def save_to_gallery(image_path, prompt):
try:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
new_image_path = os.path.join(GALLERY_DIR, f"{timestamp}.png")
print(f"Saving image to: {new_image_path}") # ๋กœ๊ทธ ์ถ”๊ฐ€
shutil.copy2(image_path, new_image_path)
print(f"File permissions: {oct(os.stat(new_image_path).st_mode)[-3:]}") # ๋กœ๊ทธ ์ถ”๊ฐ€
gallery_info = {
"image": new_image_path,
"prompt": prompt,
"timestamp": timestamp
}
if os.path.exists(GALLERY_JSON):
with open(GALLERY_JSON, "r") as f:
gallery = json.load(f)
else:
gallery = []
gallery.append(gallery_info)
with open(GALLERY_JSON, "w") as f:
json.dump(gallery, f, indent=2)
return new_image_path
except Exception as e:
print(f"Error saving to gallery: {str(e)}")
raise
# ๋ฉ”์ธ ๋ถ€๋ถ„์— ๋‹ค์Œ ์ฝ”๋“œ ์ถ”๊ฐ€
if __name__ == "__main__":
print("Environment variables:")
for key, value in os.environ.items():
print(f"{key}: {value}")
check_gallery_status()
demo.launch()