Spaces:
Runtime error
Runtime error
import gradio as gr | |
from gradio_client import Client | |
import os | |
import logging | |
import json | |
from datetime import datetime | |
import tempfile | |
import numpy as np | |
from PIL import Image | |
import shutil | |
import httpx | |
import time | |
import base64 | |
from gradio_client import Client, handle_file | |
import cv2 | |
from moviepy.editor import VideoFileClip | |
# ๋ก๊น ์ค์ | |
logging.basicConfig(level=logging.INFO) | |
# ํ์์์ ์ค์ ์ 30์ด๋ก ๋๋ฆผ | |
httpx_client = httpx.Client(timeout=30.0) | |
max_retries = 3 | |
retry_delay = 5 # 5์ด ๋๊ธฐ | |
for attempt in range(max_retries): | |
try: | |
api_client = Client("http://211.233.58.202:7960/") | |
api_client.httpx_client = httpx_client # httpx ํด๋ผ์ด์ธํธ ์ค์ | |
break # ์ฑ๊ณตํ๋ฉด ๋ฃจํ ์ข ๋ฃ | |
except httpx.ReadTimeout: | |
if attempt < max_retries - 1: # ๋ง์ง๋ง ์๋๊ฐ ์๋๋ฉด | |
print(f"Connection timed out. Retrying in {retry_delay} seconds...") | |
time.sleep(retry_delay) | |
else: | |
print("Failed to connect after multiple attempts.") | |
raise # ๋ชจ๋ ์๋ ์คํจ ์ ์์ธ ๋ฐ์ | |
# ๊ฐค๋ฌ๋ฆฌ ์ ์ฅ ๋๋ ํ ๋ฆฌ ์ค์ | |
GALLERY_DIR = "gallery" | |
GALLERY_JSON = "gallery.json" | |
# ๊ฐค๋ฌ๋ฆฌ ๋๋ ํ ๋ฆฌ ์์ฑ | |
os.makedirs(GALLERY_DIR, exist_ok=True) | |
def save_to_gallery(video_path, prompt): | |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
new_video_name = f"{timestamp}.mp4" | |
new_video_path = os.path.join(GALLERY_DIR, new_video_name) | |
# ๋น๋์ค ํ์ผ ๋ณต์ฌ | |
shutil.copy2(video_path, new_video_path) | |
# ๊ฐค๋ฌ๋ฆฌ ์ ๋ณด ์ ์ฅ | |
gallery_info = { | |
"video": f"/file={new_video_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_video_path | |
def load_gallery(): | |
if os.path.exists(GALLERY_JSON): | |
with open(GALLERY_JSON, "r") as f: | |
gallery = json.load(f) | |
return [(item["video"], item["prompt"]) for item in reversed(gallery)] | |
return [] | |
def respond(image, prompt, steps, cfg_scale, eta, fs, seed, video_length): | |
logging.info(f"Received prompt: {prompt}, steps: {steps}, cfg_scale: {cfg_scale}, " | |
f"eta: {eta}, fs: {fs}, seed: {seed}, video_length: {video_length}") | |
try: | |
# ์ด๋ฏธ์ง ํ์ผ ์ฒ๋ฆฌ | |
if image is not None: | |
image_file = handle_file(image) | |
else: | |
image_file = None | |
# ๋น๋์ค ์์ฑ ์์ฒญ | |
result = api_client.predict( | |
image=image_file, | |
prompt=prompt, | |
steps=steps, | |
cfg_scale=cfg_scale, | |
eta=eta, | |
fs=fs, | |
seed=seed, | |
video_length=video_length, | |
api_name="/infer" | |
) | |
logging.info("API response received: %s", result) | |
if isinstance(result, dict) and 'video' in result: | |
saved_video_path = save_to_gallery(result['video'], prompt) | |
return saved_video_path | |
else: | |
raise ValueError("์์์น ๋ชปํ API ์๋ต ํ์") | |
except Exception as e: | |
logging.error("API ์์ฒญ ์ค ์ค๋ฅ ๋ฐ์: %s", str(e)) | |
return "์ค๋ฅ๋ก ์ธํด ๋น๋์ค ์์ฑ์ ์คํจํ์ต๋๋ค." | |
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"], | |
["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_and_image(prompt, image): | |
return prompt, image | |
def show_video(evt: gr.SelectData): | |
return evt.value[0] if isinstance(evt.value, tuple) and len(evt.value) > 0 else None | |
with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as demo: | |
with gr.Tab("Generate"): | |
with gr.Row(): | |
input_image = gr.Image(label="Upload an image", type="filepath") | |
input_text = gr.Textbox(label="Enter your prompt for video generation") | |
output_video = gr.Video(label="Generated Video") | |
with gr.Row(): | |
steps = gr.Slider(minimum=1, maximum=100, step=1, label="Steps", value=30) | |
cfg_scale = gr.Slider(minimum=1, maximum=15, step=0.1, label="CFG Scale", value=3.5) | |
eta = gr.Slider(minimum=0, maximum=1, step=0.1, label="ETA", value=1) | |
fs = gr.Slider(minimum=1, maximum=30, step=1, label="FPS", value=8) | |
seed = gr.Slider(minimum=0, maximum=1000000, step=1, label="Seed", value=123) | |
video_length = gr.Slider(minimum=1, maximum=10, step=1, label="Video Length (seconds)", value=2) | |
with gr.Row(): | |
for prompt, image_file in examples: | |
with gr.Column(): | |
gr.Image(image_file, label=prompt[:50] + "...") | |
gr.Button("Use this example").click( | |
fn=use_prompt_and_image, | |
inputs=[], | |
outputs=[input_text, input_image], | |
api_name=False | |
).then( | |
lambda p=prompt, i=image_file: (p, i), | |
inputs=[], | |
outputs=[input_text, input_image] | |
) | |
with gr.Tab("Gallery"): | |
gallery_html = gr.HTML() | |
selected_video = gr.Video(label="Selected Video") | |
refresh_btn = gr.Button("Refresh Gallery") | |
def update_gallery(): | |
gallery_items = load_gallery() | |
html = "<div style='display: flex; flex-wrap: wrap;'>" | |
for video_path, prompt in gallery_items: | |
html += f""" | |
<div style='margin: 10px; text-align: center;'> | |
<video width='200' height='200' controls> | |
<source src='{video_path}' type='video/mp4'> | |
</video> | |
<p>{prompt[:50]}...</p> | |
</div> | |
""" | |
html += "</div>" | |
return html | |
refresh_btn.click(fn=update_gallery, inputs=None, outputs=gallery_html) | |
demo.load(fn=update_gallery, inputs=None, outputs=gallery_html) | |
input_text.submit( | |
fn=respond, | |
inputs=[input_image, input_text, steps, cfg_scale, eta, fs, seed, video_length], | |
outputs=output_video | |
).then( | |
fn=update_gallery, | |
inputs=None, | |
outputs=gallery_html # ์ฌ๊ธฐ๋ฅผ gallery_html๋ก ๋ณ๊ฒฝ | |
) | |
if __name__ == "__main__": | |
demo.launch() |