add two gradio text inputs for width_low, height_low
import os
import uuid
import gradio as gr
import torch
import PIL
from PIL import Image
from pyramid_dit import PyramidDiTForVideoGeneration
from diffusers.utils import export_to_video
from huggingface_hub import snapshot_download
import threading
Global model cache
model_cache = {}
Lock to ensure thread-safe access to the model cache
model_cache_lock = threading.Lock()
Configuration
model_name = "pyramid_flux" # or pyramid_mmdit
model_repo = "rain1011/pyramid-flow-sd3" if model_name == "pyramid_mmdit" else "rain1011/pyramid-flow-miniflux"
model_dtype = "bf16" # Support bf16 and fp32
variants = {
'high': 'diffusion_transformer_768p', # For high-resolution version
'low': 'diffusion_transformer_384p' # For low-resolution version
}
required_file = 'config.json' # Ensure config.json is present
width_high = 1280
height_high = 768
width_low = 640
height_low = 384
cpu_offloading = True # enable cpu_offloading by default
Get the current working directory and create a folder to store the model
current_directory = os.getcwd()
model_path = os.path.join(current_directory, "pyramid_flow_model") # Directory to store the model
Download the model if not already present
def download_model_from_hf(model_repo, model_dir, variants, required_file):
need_download = False
if not os.path.exists(model_dir):
print(f"[INFO] Model directory '{model_dir}' does not exist. Initiating download...")
need_download = True
else:
# Check if all required files exist for each variant
for variant_key, variant_dir in variants.items():
variant_path = os.path.join(model_dir, variant_dir)
file_path = os.path.join(variant_path, required_file)
if not os.path.exists(file_path):
print(f"[WARNING] Required file '{required_file}' missing in '{variant_path}'.")
need_download = True
break
if need_download:
print(f"[INFO] Downloading model from '{model_repo}' to '{model_dir}'...")
try:
snapshot_download(
repo_id=model_repo,
local_dir=model_dir,
local_dir_use_symlinks=False,
repo_type='model'
)
print("[INFO] Model download complete.")
except Exception as e:
print(f"[ERROR] Failed to download the model: {e}")
raise
else:
print(f"[INFO] All required model files are present in '{model_dir}'. Skipping download.")
Function to initialize the model based on user options
def initialize_model(variant):
print(f"[INFO] Initializing model with variant='{variant}', using bf16 precision...")
# Determine the correct variant directory
variant_dir = variants['high'] if variant == '768p' else variants['low']
base_path = model_path # Pass the base model path
print(f"[DEBUG] Model base path: {base_path}")
# Verify that config.json exists in the variant directory
config_path = os.path.join(model_path, variant_dir, 'config.json')
if not os.path.exists(config_path):
print(f"[ERROR] config.json not found in '{os.path.join(model_path, variant_dir)}'.")
raise FileNotFoundError(f"config.json not found in '{os.path.join(model_path, variant_dir)}'.")
if model_dtype == "bf16":
torch_dtype_selected = torch.bfloat16
else:
torch_dtype_selected = torch.float32
# Initialize the model
try:
# TODO: remove this check code after miniflux 768 version is released
if model_name == "pyramid_flux":
if variant_dir == "diffusion_transformer_768p":
raise NotImplementedError("The pyramid_flux does not support high resolution now, we will release it after finishing training. \
You can modify the model_name to pyramid_mmdit to support 768p version generation")
model = PyramidDiTForVideoGeneration(
base_path, # Pass the base model path
model_name=model_name, # set to pyramid_flux or pyramid_mmdit
model_dtype=model_dtype, # Use bf16
model_variant=variant_dir, # Pass the variant directory name
cpu_offloading=cpu_offloading, # Pass the CPU offloading flag
)
# Always enable tiling for the VAE
model.vae.enable_tiling()
# Remove manual device placement when using CPU offloading
# The components will be moved to the appropriate devices automatically
if torch.cuda.is_available():
torch.cuda.set_device(0)
# Manual device replacement when not using CPU offloading
if not cpu_offloading:
model.vae.to("cuda")
model.dit.to("cuda")
model.text_encoder.to("cuda")
else:
print("[WARNING] CUDA is not available. Proceeding without GPU.")
print("[INFO] Model initialized successfully.")
return model, torch_dtype_selected
except Exception as e:
print(f"[ERROR] Error initializing model: {e}")
raise
Assistant
User
fix the error 'TypeError: float() argument must be a string or a number, not 'Textbox''
width_low = float(gr.Textbox(label="Model Width", placeholder="Enter a video width.", lines=1))
height_low = float(gr.Textbox(label="Model Height", placeholder="Enter a video height.", lines=1))
Assistant
The error you're encountering is due to trying to convert a Gradio Textbox component directly to a float, which is not the correct way to handle user input in Gradio. Instead, you should define the Textbox without attempting to convert it immediately. The conversion should take place within the callback function where the textbox inputs are used.
User
fix the python code format indentions in the code below
# Define low resolution width and height as Gradio Textbox inputs
width_low_input = gr.Textbox(value=str(width_low), label="Low Resolution Width", placeholder="Enter width for low resolution")
height_low_input = gr.Textbox(value=str(height_low), label="Low Resolution Height", placeholder="Enter height for low resolution")
# Function to update low resolution dimensions, converting text input to float
def update_low_resolution_dimensions(width, height):
global width_low, height_low
try:
width_low = float(width)
height_low = float(height)
except ValueError:
print("[ERROR] Invalid input for width or height. Please enter a valid number.")
Assistant
Certainly! To fix the indentation and ensure proper formatting, the code should be aligned to follow Python's indentation rules. Here's the corrected code:
# Define low resolution width and height as Gradio Textbox inputs
width_low_input = gr.Textbox(value=str(width_low), label="Low Resolution Width", placeholder="Enter width for low resolution")
height_low_input = gr.Textbox(value=str(height_low), label="Low Resolution Height", placeholder="Enter height for low resolution")
# Function to update low resolution dimensions, converting text input to float
def update_low_resolution_dimensions(width, height):
global width_low, height_low
try:
width_low = float(width)
height_low = float(height)
except ValueError:
print("[ERROR] Invalid input for width or height. Please enter a valid number.")
Key changes:
Ensure that the function update_low_resolution_dimensions has correct indentation for its body.
Align the try, except, and the global statement within the function block.
This should address any issues with indentation in your Python script.
User
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
# Check if the model is already in the cache
if key not in model_cache:
with model_cache_lock:
# Double-checked locking to prevent race conditions
if key not in model_cache:
model, dtype = initialize_model(variant)
model_cache[key] = (model, dtype)
return model_cache[key]
try:
image = resize_crop_image(image, width, height)
print("[INFO] Image resized and cropped successfully.")
except Exception as e:
print(f"[ERROR] Error processing image: {e}")
return f"Error processing image: {e}"
def progress_callback(i, m):
progress(i/m)
# Initialize model based on user options using cached function
try:
model, torch_dtype_selected = initialize_model_cached(variant)
except Exception as e:
print(f"[ERROR] Model initialization failed: {e}")
return f"Model initialization failed: {e}"
try:
print("[INFO] Starting image-to-video generation...")
with torch.no_grad(), torch.autocast('cuda', dtype=torch_dtype_selected):
frames = model.generate_i2v(
prompt=prompt,
input_image=image,
num_inference_steps=[10, 10, 10],
temp=temp,
video_guidance_scale=video_guidance_scale,
output_type="pil",
cpu_offloading=cpu_offloading,
save_memory=True,
callback=progress_callback,
)
print("[INFO] Image-to-video generation completed.")
except Exception as e:
print(f"[ERROR] Error during image-to-video generation: {e}")
return f"Error during video generation: {e}"
video_path = f"{str(uuid.uuid4())}_image_to_video_sample.mp4"
try:
export_to_video(frames, video_path, fps=24)
print(f"[INFO] Video exported to {video_path}.")
except Exception as e:
print(f"[ERROR] Error exporting video: {e}")
return f"Error exporting video: {e}"
return video_path
Gradio interface
with gr.Blocks() as demo:
gr.Markdown(
"""
Pyramid Flow Video Generation Demo
Pyramid Flow is a training-efficient Autoregressive Video Generation model based on Flow Matching. It is trained only on open-source datasets within 20.7k A100 GPU hours.
# Shared settings
with gr.Row():
resolution_dropdown = gr.Dropdown(
choices=["768p", "384p"],
value="384p",
label="Model Resolution"
)
with gr.Tab("Text-to-Video"):
with gr.Row():
with gr.Column():
text_prompt = gr.Textbox(label="Prompt (Less than 128 words)", placeholder="Enter a text prompt for the video", lines=2)
temp_slider = gr.Slider(1, 16, value=16, step=1, label="Duration")
guidance_scale_slider = gr.Slider(1.0, 15.0, value=9.0, step=0.1, label="Guidance Scale")
video_guidance_scale_slider = gr.Slider(1.0, 10.0, value=5.0, step=0.1, label="Video Guidance Scale")
txt_generate = gr.Button("Generate Video")
with gr.Column():
txt_output = gr.Video(label="Generated Video")
gr.Examples(
examples=[
["A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors", 16, 7.0, 5.0, "384p"],
["Beautiful, snowy Tokyo city is bustling. The camera moves through the bustling city street, following several people enjoying the beautiful snowy weather and shopping at nearby stalls. Gorgeous sakura petals are flying through the wind along with snowflakes", 16, 7.0, 5.0, "384p"],
# ["Extreme close-up of chicken and green pepper kebabs grilling on a barbeque with flames. Shallow focus and light smoke. vivid colours", 31, 9.0, 5.0, "768p"],
],
inputs=[text_prompt, temp_slider, guidance_scale_slider, video_guidance_scale_slider, resolution_dropdown],
outputs=[txt_output],
fn=generate_text_to_video,
cache_examples='lazy',
)
with gr.Tab("Image-to-Video"):
with gr.Row():
with gr.Column():
image_input = gr.Image(type="pil", label="Input Image")
image_prompt = gr.Textbox(label="Prompt (Less than 128 words)", placeholder="Enter a text prompt for the video", lines=2)
image_temp_slider = gr.Slider(2, 16, value=16, step=1, label="Duration")
image_video_guidance_scale_slider = gr.Slider(1.0, 7.0, value=4.0, step=0.1, label="Video Guidance Scale")
img_generate = gr.Button("Generate Video")
with gr.Column():
img_output = gr.Video(label="Generated Video")
gr.Examples(
examples=[
['assets/the_great_wall.jpg', 'FPV flying over the Great Wall', 16, 4.0, "384p"]
],
inputs=[image_input, image_prompt, image_temp_slider, image_video_guidance_scale_slider, resolution_dropdown],
outputs=[img_output],
fn=generate_image_to_video,
cache_examples='lazy',
)
# Update generate functions to include resolution options
txt_generate.click(
generate_text_to_video,
inputs=[text_prompt, temp_slider, guidance_scale_slider, video_guidance_scale_slider, resolution_dropdown],
outputs=txt_output
)
img_generate.click(
generate_image_to_video,
inputs=[image_input, image_prompt, image_temp_slider, image_video_guidance_scale_slider, resolution_dropdown],
outputs=img_output
)
Launch Gradio app
demo.launch(share=False)
To add two Gradio text inputs for width_low and height_low, you'll need to modify the Gradio UI section of your current code. These inputs should likely be added alongside the existing resolution-related components. Here's how you can do it:
Add the text inputs to the shared settings section for width_low and height_low.
Update the functions to receive these inputs and change the width or height used for the 'low' resolution variant.
Here's how your code should be modified to include these inputs:
# Gradio interface
with gr.Blocks() as demo:
gr.Markdown(
"""
# Pyramid Flow Video Generation Demo
Pyramid Flow is a training-efficient **Autoregressive Video Generation** model based on **Flow Matching**. It is trained only on open-source datasets within 20.7k A100 GPU hours.
[[Paper]](https://arxiv.org/abs/2410.05954) [[Project Page]](https://pyramid-flow.github.io) [[Code]](https://github.com/jy0205/Pyramid-Flow) [[Model]](https://huggingface.co/rain1011/pyramid-flow-sd3)
"""
)
# Shared settings
with gr.Row():
resolution_dropdown = gr.Dropdown(
choices=["768p", "384p"],
value="384p",
label="Model Resolution"
)
width_low_input = gr.Textbox(value=str(width_low), label="Low Resolution Width", placeholder="Enter width for low resolution")
height_low_input = gr.Textbox(value=str(height_low), label="Low Resolution Height", placeholder="Enter height for low resolution")
with gr.Tab("Text-to-Video"):
with gr.Row():
with gr.Column():
text_prompt = gr.Textbox(label="Prompt (Less than 128 words)", placeholder="Enter a text prompt for the video", lines=2)
temp_slider = gr.Slider(1, 16, value=16, step=1, label="Duration")
guidance_scale_slider = gr.Slider(1.0, 15.0, value=9.0, step=0.1, label="Guidance Scale")
video_guidance_scale_slider = gr.Slider(1.0, 10.0, value=5.0, step=0.1, label="Video Guidance Scale")
txt_generate = gr.Button("Generate Video")
with gr.Column():
txt_output = gr.Video(label="Generated Video")
gr.Examples(
examples=[
["A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors", 16, 7.0, 5.0, "384p"],
["Beautiful, snowy Tokyo city is bustling. The camera moves through the bustling city street, following several people enjoying the beautiful snowy weather and shopping at nearby stalls. Gorgeous sakura petals are flying through the wind along with snowflakes", 16, 7.0, 5.0, "384p"],
# ["Extreme close-up of chicken and green pepper kebabs grilling on a barbeque with flames. Shallow focus and light smoke. vivid colours", 31, 9.0, 5.0, "768p"],
],
inputs=[text_prompt, temp_slider, guidance_scale_slider, video_guidance_scale_slider, resolution_dropdown],
outputs=[txt_output],
fn=generate_text_to_video,
cache_examples='lazy',
)
with gr.Tab("Image-to-Video"):
with gr.Row():
with gr.Column():
image_input = gr.Image(type="pil", label="Input Image")
image_prompt = gr.Textbox(label="Prompt (Less than 128 words)", placeholder="Enter a text prompt for the video", lines=2)
image_temp_slider = gr.Slider(2, 16, value=16, step=1, label="Duration")
image_video_guidance_scale_slider = gr.Slider(1.0, 7.0, value=4.0, step=0.1, label="Video Guidance Scale")
img_generate = gr.Button("Generate Video")
with gr.Column():
img_output = gr.Video(label="Generated Video")
gr.Examples(
examples=[
['assets/the_great_wall.jpg', 'FPV flying over the Great Wall', 16, 4.0, "384p"]
],
inputs=[image_input, image_prompt, image_temp_slider, image_video_guidance_scale_slider, resolution_dropdown],
outputs=[img_output],
fn=generate_image_to_video,
cache_examples='lazy',
)
def update_low_resolution_dimensions(width, height):
global width_low, height_low
width_low = int(width)
height_low = int(height)
# Update generate functions to include resolution options and low-resolution dimensions
txt_generate.click(
generate_text_to_video,
inputs=[text_prompt, temp_slider, guidance_scale_slider, video_guidance_scale_slider, resolution_dropdown],
outputs=txt_output
)
img_generate.click(
generate_image_to_video,
inputs=[image_input, image_prompt, image_temp_slider, image_video_guidance_scale_slider, resolution_dropdown],
outputs=img_output
)
# Listen to changes in the low resolution inputs
width_low_input.change(update_low_resolution_dimensions, inputs=[width_low_input, height_low_input])
# Launch Gradio app
demo.launch(share=False)
Key changes:
Added width_low_input and height_low_input textboxes in the shared settings section.
Created a function update_low_resolution_dimensions and added a .change() method to listen to changes in these textboxes and update the global width_low and height_low variables accordingly.
Passed width_low_input and height_low_input to the inputs of their respective buttons and resolution dropdowns.
These changes will allow users to input custom low-resolution dimensions when using the Gradio interface.
Here's how you can update your code to fix this issue:
Define Textbox components without attempting to convert them to floats.
Convert these inputs to floats when reading the values inside the relevant function.
Here's the modified code:
# Define low resolution width and height as Gradio Textbox inputs
width_low_input = gr.Textbox(value=str(width_low), label="Low Resolution Width", placeholder="Enter width for low resolution")
height_low_input = gr.Textbox(value=str(height_low), label="Low Resolution Height", placeholder="Enter height for low resolution")
# Function to update low resolution dimensions, converting text input to float
def update_low_resolution_dimensions(width, height):
global width_low, height_low
try:
width_low = float(width)
height_low = float(height)
except ValueError:
print("[ERROR] Invalid input for width or height. Please enter a valid number.")
# Register the change event handler for Textbox inputs
width_low_input.change(update_low_resolution_dimensions, inputs=[width_low_input, height_low_input])
height_low_input.change(update_low_resolution_dimensions, inputs=[width_low_input, height_low_input])
In the code above:
Textboxes width_low_input and height_low_input are defined to take user input.
A function update_low_resolution_dimensions() is created to update the global width_low and height_low variables. It converts the string input from the textboxes to a float and catches potential ValueError exceptions if the input is not a valid number.
The .change() method listens for changes in both width_low_input and height_low_input, ensuring that the conversion happens when the user makes an input.
This approach avoids the error and properly handles user input within Gradio.
fill in the missing code for width low and height low
"""
)
# Shared settings
with gr.Row():
resolution_dropdown = gr.Dropdown(
choices=["768p", "384p"],
value="384p",
label="Model Resolution"
)
width_low = float(gr.Textbox(label="Model Width", placeholder="Enter a video width.", lines=1))
height_low = float(gr.Textbox(label="Model Height", placeholder="Enter a video height.", lines=1))
with gr.Tab("Text-to-Video"):
with gr.Row():
with gr.Column():
text_prompt = gr.Textbox(label="Prompt (Less than 128 words)", placeholder="Enter a text prompt for the video", lines=2)
temp_slider = gr.Slider(1, 16, value=16, step=1, label="Duration")
guidance_scale_slider = gr.Slider(1.0, 15.0, value=9.0, step=0.1, label="Guidance Scale")
video_guidance_scale_slider = gr.Slider(1.0, 10.0, value=5.0, step=0.1, label="Video Guidance Scale")
txt_generate = gr.Button("Generate Video")
with gr.Column():
txt_output = gr.Video(label="Generated Video")
gr.Examples(
examples=[
["A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors", 16, 7.0, 5.0, "384p"],
["Beautiful, snowy Tokyo city is bustling. The camera moves through the bustling city street, following several people enjoying the beautiful snowy weather and shopping at nearby stalls. Gorgeous sakura petals are flying through the wind along with snowflakes", 16, 7.0, 5.0, "384p"],
# ["Extreme close-up of chicken and green pepper kebabs grilling on a barbeque with flames. Shallow focus and light smoke. vivid colours", 31, 9.0, 5.0, "768p"],
],
inputs=[text_prompt, temp_slider, guidance_scale_slider, video_guidance_scale_slider, resolution_dropdown],
outputs=[txt_output],
fn=generate_text_to_video,
cache_examples='lazy',
)
with gr.Tab("Image-to-Video"):
with gr.Row():
with gr.Column():
image_input = gr.Image(type="pil", label="Input Image")
image_prompt = gr.Textbox(label="Prompt (Less than 128 words)", placeholder="Enter a text prompt for the video", lines=2)
image_temp_slider = gr.Slider(2, 16, value=16, step=1, label="Duration")
image_video_guidance_scale_slider = gr.Slider(1.0, 7.0, value=4.0, step=0.1, label="Video Guidance Scale")
img_generate = gr.Button("Generate Video")
with gr.Column():
img_output = gr.Video(label="Generated Video")
gr.Examples(
examples=[
['assets/the_great_wall.jpg', 'FPV flying over the Great Wall', 16, 4.0, "384p"]
],
inputs=[image_input, image_prompt, image_temp_slider, image_video_guidance_scale_slider, resolution_dropdown],
outputs=[img_output],
fn=generate_image_to_video,
cache_examples='lazy',
)
# Update generate functions to include resolution options
txt_generate.click(
generate_text_to_video,
inputs=[text_prompt, temp_slider, guidance_scale_slider, video_guidance_scale_slider, resolution_dropdown],
outputs=txt_output
)
img_generate.click(
generate_image_to_video,
inputs=[image_input, image_prompt, image_temp_slider, image_video_guidance_scale_slider, resolution_dropdown],
outputs=img_output
)
Launch Gradio app
demo.launch(share=False)
To fix the issue related to the width_low and height_low inputs, you need to ensure that they are managed as interactive elements correctly integrated within the Gradio interface. Since you want to capture floating-point numbers from text inputs, I will guide you through setting up Textbox elements and ensuring their values are properly processed within the application logic.
Here’s how you can refine the code:
Use Textbox components to capture user inputs for width and height without converting them immediately.
Convert the inputs to floats when they’re needed in the processing function.
# Define low resolution width and height as Gradio Textbox inputs
width_low_input = gr.Textbox(value="640", label="Low Resolution Width", placeholder="Enter width for low resolution")
height_low_input = gr.Textbox(value="384", label="Low Resolution Height", placeholder="Enter height for low resolution")
# Function to update low resolution dimensions, converting text input to float
def update_low_resolution_dimensions(width, height):
global width_low, height_low
try:
width_low = float(width)
height_low = float(height)
except ValueError:
print("[ERROR] Invalid input for width or height. Please enter a valid number.")
# Gradio interface
with gr.Blocks() as demo:
gr.Markdown(
"""
# Pyramid Flow Video Generation Demo
Pyramid Flow is a training-efficient **Autoregressive Video Generation** model based on **Flow Matching**. It is trained only on open-source datasets within 20.7k A100 GPU hours.
[[Paper]](https://arxiv.org/abs/2410.05954) [[Project Page]](https://pyramid-flow.github.io) [[Code]](https://github.com/jy0205/Pyramid-Flow) [[Model]](https://huggingface.co/rain1011/pyramid-flow-sd3)
"""
)
# Shared settings
with gr.Row():
resolution_dropdown = gr.Dropdown(
choices=["768p", "384p"],
value="384p",
label="Model Resolution"
)
width_low_input = gr.Textbox(value="640", label="Low Resolution Width", placeholder="Enter width for low resolution")
height_low_input = gr.Textbox(value="384", label="Low Resolution Height", placeholder="Enter height for low resolution")
with gr.Tab("Text-to-Video"):
with gr.Row():
with gr.Column():
text_prompt = gr.Textbox(label="Prompt (Less than 128 words)", placeholder="Enter a text prompt for the video", lines=2)
temp_slider = gr.Slider(1, 16, value=16, step=1, label="Duration")
guidance_scale_slider = gr.Slider(1.0, 15.0, value=9.0, step=0.1, label="Guidance Scale")
video_guidance_scale_slider = gr.Slider(1.0, 10.0, value=5.0, step=0.1, label="Video Guidance Scale")
txt_generate = gr.Button("Generate Video")
with gr.Column():
txt_output = gr.Video(label="Generated Video")
gr.Examples(
examples=[
["A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors", 16, 7.0, 5.0, "384p"],
["Beautiful, snowy Tokyo city is bustling. The camera moves through the bustling city street, following several people enjoying the beautiful snowy weather and shopping at nearby stalls. Gorgeous sakura petals are flying through the wind along with snowflakes", 16, 7.0, 5.0, "384p"],
],
inputs=[text_prompt, temp_slider, guidance_scale_slider, video_guidance_scale_slider, resolution_dropdown],
outputs=[txt_output],
fn=generate_text_to_video,
cache_examples='lazy',
)
with gr.Tab("Image-to-Video"):
with gr.Row():
with gr.Column():
image_input = gr.Image(type="pil", label="Input Image")
image_prompt = gr.Textbox(label="Prompt (Less than 128 words)", placeholder="Enter a text prompt for the video", lines=2)
image_temp_slider = gr.Slider(2, 16, value=16, step=1, label="Duration")
image_video_guidance_scale_slider = gr.Slider(1.0, 7.0, value=4.0, step=0.1, label="Video Guidance Scale")
img_generate = gr.Button("Generate Video")
with gr.Column():
img_output = gr.Video(label="Generated Video")
gr.Examples(
examples=[
['assets/the_great_wall.jpg', 'FPV flying over the Great Wall', 16, 4.0, "384p"]
],
inputs=[image_input, image_prompt, image_temp_slider, image_video_guidance_scale_slider, resolution_dropdown],
outputs=[img_output],
fn=generate_image_to_video,
cache_examples='lazy',
)
# Update generate functions to include resolution options
txt_generate.click(
generate_text_to_video,
inputs=[text_prompt, temp_slider, guidance_scale_slider, video_guidance_scale_slider, resolution_dropdown, width_low_input, height_low_input],
outputs=txt_output
)
img_generate.click(
generate_image_to_video,
inputs=[image_input, image_prompt, image_temp_slider, image_video_guidance_scale_slider, resolution_dropdown, width_low_input, height_low_input],
outputs=img_output
)
# Launch Gradio app
demo.launch(share=False)
Key Elements:
The Textbox inputs are set as strings, and their values are then converted in the update_low_resolution_dimensions function.
The width and height of the low-resolution variant can be dynamically adjusted based on the user's textual input.
These inputs are added to the inputs list of the generate_text_to_video and generate_image_to_video functions to ensure they are used when generating outputs.
Ensure that the logic handling these dimensions inside your existing generate_text_to_video and generate_image_to_video functions is modified to use width_low and height_low correctly.