CharVid / demo.py
Rishi Desai
more work on async
b8037c7
import gradio as gr
import os
import tempfile
import base64
import asyncio
from main import process_async
# Create a single event loop for the entire application
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
async def process_image_and_generate_video_async(image, prompt):
# Create a temporary directory for intermediate files
with tempfile.TemporaryDirectory() as temp_dir:
# Save the uploaded image to a temporary file
temp_image_path = os.path.join(temp_dir, "input_image.png")
image.save(temp_image_path)
# Encode the image as base64 and create a data URL
with open(temp_image_path, "rb") as f:
encoded_image = base64.b64encode(f.read()).decode("utf-8")
data_url = f"data:image/png;base64,{encoded_image}"
# Process the image and generate video
result, generated_image_path, video_path = await process_async(data_url, prompt, temp_dir)
if result and video_path:
return video_path
else:
return None
def process_image_and_generate_video(image, prompt):
# Use the existing event loop instead of creating a new one
return loop.run_until_complete(process_image_and_generate_video_async(image, prompt))
# Create the Gradio interface
with gr.Blocks(title="Character Video Generation") as demo:
gr.Markdown("# Character Video Generation")
gr.Markdown("""
* Upload a high-quality image of a person (PNG, JPG, or JPEG only)
* Enter a prompt to generate a video
""")
with gr.Row():
with gr.Column():
input_image = gr.Image(
type="pil",
label="Upload Reference Image (PNG, JPG, or JPEG only)",
height=512,
width=512
)
prompt = gr.Textbox(label="Enter your prompt")
generate_btn = gr.Button("Generate")
with gr.Column():
output_video = gr.Video(label="Generated Video")
generate_btn.click(
fn=process_image_and_generate_video,
inputs=[input_image, prompt],
outputs=[output_video]
)
if __name__ == "__main__":
try:
demo.launch(share=True)
finally:
# Clean up the event loop when the application exits
loop.close()