Update app.py
Browse files64 unmodified lines65666768697020 unmodified lines9192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261275 unmodified lines13313413513613713813914043 unmodified lines1841851861871881891901918 unmodified lines2002012022032042052061 unmodified line20820921021121221321421518 unmodified lines234235236237238239240241242243244245246247248249250251252253254255256257258259260396 unmodified lines65765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471564 unmodified lines}}# -------------------------------------------------# --------------- TRANSLATION FUNCTION ----------# -------------------------------------------------20 unmodified linesraise gr.Error("Translation failed. Please try again.")raise gr.Error("Translation failed. Please try again.")# -------------------------------------------------# ------------------- PIPELINE --------------------# -------------------------------------------------pipe = WanImageToVideoPipeline.from_pretrained(MODEL_ID,transformer=WanTransformer3DModel.from_pretrained('cbensimon/Wan2.2-I2V-A14B-bf16-Diffusers',subfolder='transformer',torch_dtype=torch.bfloat16,device_map='cuda',),transformer_2=WanTransformer3DModel.from_pretrained('cbensimon/Wan2.2-I2V-A14B-bf16-Diffusers',subfolder='transformer_2',torch_dtype=torch.bfloat16,device_map='cuda',),torch_dtype=torch.bfloat16,).to('cuda')pipe.load_lora_weights("Kijai/WanVideo_comfy",weight_name="Lightx2v/lightx2v_I2V_14B_480p_cfg_step_distill_rank128_bf16.safetensors",adapter_name="lightx2v")kwargs_lora = {"load_into_transformer_2": True}pipe.load_lora_weights("Kijai/WanVideo_comfy",weight_name="Lightx2v/lightx2v_I2V_14B_480p_cfg_step_distill_rank128_bf16.safetensors",adapter_name="lightx2v_2",**kwargs_lora)pipe.set_adapters(["lightx2v", "lightx2v_2"], adapter_weights=[1.0, 1.0])pipe.fuse_lora(adapter_names=["lightx2v"], lora_scale=3.0, components=["transformer"])5 unmodified linesquantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())quantize_(pipe.transformer_2, Float8DynamicActivationFloat8WeightConfig())aoti.aoti_blocks_load(pipe.transformer, 'zerogpu-aoti/Wan2', variant='fp8da')aoti.aoti_blocks_load(pipe.transformer_2, 'zerogpu-aoti/Wan2', variant='fp8da')# -------------------------------------------------# ----------------- HELPERS ----------------------43 unmodified lines)def get_duration(input_image, prompt, steps, negative_prompt, duration_seconds,guidance_scale, guidance_scale_2, seed, randomize_seed, progress):BASE_FRAMES_HEIGHT_WIDTH = 81 * 832 * 624BASE_STEP_DURATION = 15width, height = resize_image(input_image).size8 unmodified linesinput_image,prompt,steps=4,negative_prompt=UI_TEXT["en"]["negative_prompt"], # placeholder – overridden by UIduration_seconds=MAX_DURATION,guidance_scale=1,guidance_scale_2=1,1 unmodified linerandomize_seed=False,progress=gr.Progress(track_tqdm=True),):if input_image is None:raise gr.Error("Please upload an input image.")num_frames = get_num_frames(duration_seconds)current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)resized_image = resize_image(input_image)18 unmodified lines# -------------------------------------------------# ------------------- DEMO -----------------------# -------------------------------------------------def create_demo():# ---- Detect language from request path ----try:path = gr.Request().url.path.lower()except Exception:path = "/"if "spanish" in path:lang = "es"else: # includes '/spaceishere' and any other path -> Englishlang = "en"txt = UI_TEXT[lang]with gr.Blocks(css="", title=txt["title"]) as demo:# -----------------------------------------------------------------# KEEP THE ORIGINAL CSS+JS BLOCK EXACTLY AS‑IS (including the 500 page)# -----------------------------------------------------------------gr.HTML("""<style>@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;600;700&display=swap');@keyframes glow {396 unmodified lines}, 500);});</script>""")with gr.Row(elem_id="general_items"):# Title & subtitle (language‑specific)gr.Markdown(txt["title"])gr.Markdown(txt["subtitle"], elem_id="subtitle")with gr.Column(elem_id="input_column"):input_image = gr.Image(type="pil",label=txt["input_label"],sources=["upload"],show_download_button=False,show_share_button=False,interactive=True,elem_classes=["gradio-component", "image-container"])prompt = gr.Textbox(label=txt["prompt_label"],value=txt["prompt_default"],lines=3,placeholder=txt["prompt_placeholder"],elem_classes=["gradio-component"])generate_button = gr.Button(txt["generate_btn"],variant="primary",elem_classes=["gradio-component", "gr-button-primary"])output_video = gr.Video(label=txt["output_label"],autoplay=True,interactive=False,show_download_button=True,show_share_button=False,elem_classes=["gradio-component", "image-container"])# ---- Hidden states (steps, negative prompt, etc.) ----generate_button.click(fn=generate_video,inputs=[input_image,prompt,gr.State(value=4), # stepsgr.State(value=txt["negative_prompt"]), # negative promptgr.State(value=5.0), # duration_seconds (max)gr.State(value=1), # guidance_scalegr.State(value=1), # guidance_scale_2gr.State(value=42), # seedgr.State(value=True) # randomize_seed],outputs=[output_video, gr.State(value=42)])return demo64 unmodified lines6566676869707120 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281295 unmodified lines13513613713813914014114243 unmodified lines1861871881891901911921931941951961971981992002012022038 unmodified lines2122132142152162172181 unmodified line22022122222322422522622722822923023123223323423523623723818 unmodified lines257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298396 unmodified lines69569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477564 unmodified lines}}# -------------------------------------------------# --------------- TRANSLATION FUNCTION ----------# -------------------------------------------------20 unmodified linesraise gr.Error("Translation failed. Please try again.")raise gr.Error("Translation failed. Please try again.")# -------------------------------------------------# ------------------- PIPELINE --------------------# -------------------------------------------------pipe = WanImageToVideoPipeline.from_pretrained(MODEL_ID,transformer=WanTransformer3DModel.from_pretrained("cbensimon/Wan2.2-I2V-A14B-bf16-Diffusers",subfolder="transformer",torch_dtype=torch.bfloat16,device_map="cuda",),transformer_2=WanTransformer3DModel.from_pretrained("cbensimon/Wan2.2-I2V-A14B-bf16-Diffusers",subfolder="transformer_2",torch_dtype=torch.bfloat16,device_map="cuda",),torch_dtype=torch.bfloat16,).to("cuda")pipe.load_lora_weights("Kijai/WanVideo_comfy",weight_name="Lightx2v/lightx2v_I2V_14B_480p_cfg_step_distill_rank128_bf16.safetensors",adapter_name="lightx2v",)kwargs_lora = {"load_into_transformer_2": True}pipe.load_lora_weights("Kijai/WanVideo_comfy",weight_name="Lightx2v/lightx2v_I2V_14B_480p_cfg_step_distill_rank128_bf16.safetensors",adapter_name="lightx2v_2",**kwargs_lora,)pipe.set_adapters(["lightx2v", "lightx2v_2"], adapter_weights=[1.0, 1.0])pipe.fuse_lora(adapter_names=["lightx2v"], lora_scale=3.0, components=["transformer"])5 unmodified linesquantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())quantize_(pipe.transformer_2, Float8DynamicActivationFloat8WeightConfig())aoti.aoti_blocks_load(pipe.transformer, "zerogpu-aoti/Wan2", variant="fp8da")aoti.aoti_blocks_load(pipe.transformer_2, "zerogpu-aoti/Wan2", variant="fp8da")# -------------------------------------------------# ----------------- HELPERS ----------------------43 unmodified lines)def get_duration(input_image,prompt,steps,negative_prompt,duration_seconds,guidance_scale,guidance_scale_2,seed,randomize_seed,progress,):BASE_FRAMES_HEIGHT_WIDTH = 81 * 832 * 624BASE_STEP_DURATION = 15width, height = resize_image(input_image).size8 unmodified linesinput_image,prompt,steps=4,negative_prompt=None, # will be filled in based on URLduration_seconds=MAX_DURATION,guidance_scale=1,guidance_scale_2=1,1 unmodified linerandomize_seed=False,progress=gr.Progress(track_tqdm=True),):"""Run the pipeline and return a temporary mp4 file + the seed used."""if input_image is None:raise gr.Error("Please upload an input image.")# ---- pick the correct negative prompt according to the URL ----if negative_prompt is None:try:path = gr.Request().url.path.lower()except Exception:path = "/"lang = "es" if "spanish" in path else "en"negative_prompt = UI_TEXT[lang]["negative_prompt"]num_frames = get_num_frames(duration_seconds)current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)resized_image = resize_image(input_image)18 unmodified lines# -------------------------------------------------# --------------- LANGUAGE DETECTION ------------# -------------------------------------------------def detect_language():"""Called on page‑load; returns a list of Gradio updates for every UI component."""try:path = gr.Request().url.path.lower()except Exception:path = "/"lang = "es" if "spanish" in path else "en"txt = UI_TEXT[lang]# order must match the outputs list in demo.load()return [gr.update(value=txt["title"]), # title markdowngr.update(value=txt["subtitle"]), # subtitle markdowngr.update(label=txt["input_label"]), # input image labelgr.update(label=txt["prompt_label"],value=txt["prompt_default"],placeholder=txt["prompt_placeholder"],), # prompt textboxgr.update(value=txt["generate_btn"]), # generate button textgr.update(label=txt["output_label"]), # video label]# -------------------------------------------------# ------------------- DEMO -----------------------# -------------------------------------------------def create_demo():with gr.Blocks(css="", title="Fast Image to Video") as demo:# -----------------------------------------------------------------# KEEP YOUR ORIGINAL CSS/JS BLOCK (unchanged)# -----------------------------------------------------------------gr.HTML("""<style>@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;600;700&display=swap');@keyframes glow {396 unmodified lines}, 500);});</script>""")# -------------------------------------------------# UI components – they will be updated on page load# -------------------------------------------------# Title & subtitle (place‑holders; will be overwritten by demo.load())title_md = gr.Markdown("", elem_id="title_md")subtitle_md = gr.Markdown("", elem_id="subtitle_md")with gr.Row(elem_id="general_items"):with gr.Column(elem_id="input_column"):input_image = gr.Image(type="pil",label="Input Image", # placeholder – will be updatedsources=["upload"],show_download_button=False,show_share_button=False,interactive=True,elem_classes=["gradio-component", "image-container"],)prompt = gr.Textbox(label="Prompt",value="",lines=3,placeholder="",elem_classes=["gradio-component"],)generate_button = gr.Button("Generate Video",variant="primary",elem_classes=["gradio-component", "gr-button-primary"],)output_video = gr.Video(label="Generated Video",autoplay=True,interactive=False,show_download_button=True,show_share_button=False,elem_classes=["gradio-component", "image-container"],)# -------------------------------------------------# Update UI texts according to the URL (runs on every page load)# -------------------------------------------------demo.load(fn=detect_language,inputs=[],outputs=[title_md,subtitle_md,input_image,prompt,generate_button,output_video,],)# -------------------------------------------------# Generation click – note that the negative prompt is handled inside generate_video()# -------------------------------------------------generate_button.click(fn=generate_video,inputs=[input_image,prompt,gr.State(value=4), # stepsgr.State(value=None), # negative_prompt (ignored, computed inside)gr.State(value=5.0), # duration_seconds (max)gr.State(value=1), # guidance_scalegr.State(value=1), # guidance_scale_2gr.State(value=42), # seedgr.State(value=True), # randomize_seed],outputs=[output_video, gr.State(value=42)],)return demo
app.py+109-49