Zrelv commited on
Commit ·
d144ea2
1
Parent(s): 8a3705e
Make identical to wan777: base Wan2.2-I2V-A14B + wan777 code/deps/gradio
Browse filesUser wants all 5 like wan777 (base Wan2.2). Copy wan777's exact stack (app.py,
release requirements, gradio 5.44.1) and unset REPO_ID so it uses the hardcoded
base model. README title/emoji preserved.
3 unmodified lines456789103 unmodified linescolorFrom: yellowcolorTo: pinksdk: gradiosdk_version: 6.0.1app_file: app.pypinned: falseshort_description: generate a video from an image with a text prompt3 unmodified lines45678910113 unmodified linescolorFrom: yellowcolorTo: pinksdk: gradiosdk_version: 5.44.1python_version: "3.10"app_file: app.pypinned: falseshort_description: generate a video from an image with a text prompt
10 unmodified lines1112131415161718192021105 unmodified lines12712812913013113213313413513639 unmodified lines1761771781791801811824 unmodified lines18718818919019119219319419519619734 unmodified lines2322332342352362372382392402412422432442 unmodified lines2472482492502512522539 unmodified lines26326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430523 unmodified lines32933033133233333433533633733833934034129 unmodified lines37137237337437537647 unmodified lines42442542642742842943043143243343443543643712 unmodified lines4504514524534544554568 unmodified lines4654664674684694704719 unmodified lines4814824834844854864871 unmodified line4894904914924934944954964974984997 unmodified lines50750850951051151251313 unmodified lines52752852953053153253353470 unmodified lines60560660760860961013 unmodified lines6246256266276286296306316329 unmodified lines64264364464564664764812 unmodified lines6616626636646656666676686696706716726736746756766773 unmodified lines68168268368468568668768868969069169269321 unmodified lines71571671771871972010 unmodified linesimport gcimport uuidfrom tqdm import tqdmimport cv2import numpy as npimport torchimport torch._dynamofrom huggingface_hub import list_modelsfrom torch.nn import functional as Ffrom PIL import Image105 unmodified lines"""Interpolation maintaining Numpy Float 0-1 format.Args:frames_np: Numpy Array (Time, Height, Width, Channels) - Float32 [0.0, 1.0]multiplier: int (2, 4, 8)Returns:List of Numpy Arrays (Height, Width, Channels) - Float32 [0.0, 1.0]"""# Handle input shape39 unmodified linesdef make_inference(I0, I1, n):if rife_model.version >= 3.9:res = []for i in range(n):res.append(rife_model.inference(I0, I1, (i+1) * 1. / (n+1), scale))return res4 unmodified linesfirst_half = make_inference(I0, middle, n=n//2)second_half = make_inference(middle, I1, n=n//2)if n % 2:return [*first_half, middle, *second_half]else:return [*first_half, *second_half]output_frames = []# Process Frames# Load first frame into GPU34 unmodified lines# WANORG_NAME = "TestOrganizationPleaseIgnore"# MODEL_ID = "Wan-AI/Wan2.2-I2V-A14B-Diffusers"MODEL_ID = os.getenv("REPO_ID") or "TestOrganizationPleaseIgnore/WAMU_v3_WAN2.2_I2V_LIGHTNING"CACHE_DIR = os.path.expanduser("~/.cache/huggingface/")LORA_MODELS = [] # WAMU is a pre-merged lightning model — no extra LoRA neededMAX_DIM = 832MIN_DIM = 480SQUARE_DIM = 6402 unmodified linesFIXED_FPS = 16MIN_FRAMES_MODEL = 8MAX_FRAMES_MODEL = 1280MIN_DURATION = round(MIN_FRAMES_MODEL / FIXED_FPS, 1)MAX_DURATION = round(MAX_FRAMES_MODEL / FIXED_FPS, 1)9 unmodified lines}pipe = WanImageToVideoPipeline.from_pretrained(MODEL_ID,torch_dtype=torch.bfloat16,).to('cuda')original_scheduler = copy.deepcopy(pipe.scheduler)for i, lora in enumerate(LORA_MODELS):name_high_tr = lora["high_tr"].split(".")[0].split("/")[-1] + "Hh"name_low_tr = lora["low_tr"].split(".")[0].split("/")[-1] + "Ll"try:pipe.load_lora_weights(lora["repo_id"],weight_name=lora["high_tr"],adapter_name=name_high_tr)kwargs_lora = {"load_into_transformer_2": True}pipe.load_lora_weights(lora["repo_id"],weight_name=lora["low_tr"],adapter_name=name_low_tr,**kwargs_lora)pipe.set_adapters([name_high_tr, name_low_tr], adapter_weights=[1.0, 1.0])pipe.fuse_lora(adapter_names=[name_high_tr], lora_scale=lora["high_scale"], components=["transformer"])pipe.fuse_lora(adapter_names=[name_low_tr], lora_scale=lora["low_scale"], components=["transformer_2"])pipe.unload_lora_weights()print(f"Applied: {lora['high_tr']}, hs={lora['high_scale']}/ls={lora['low_scale']}, {i+1}/{len(LORA_MODELS)}")except Exception as e:print("Error:", str(e))print("Failed LoRA:", name_high_tr)pipe.unload_lora_weights()# if os.path.exists(CACHE_DIR):# shutil.rmtree(CACHE_DIR)# print("Deleted Hugging Face cache.")23 unmodified linesdefault_negative_prompt = "色调艳丽, 过曝, 静态, 细节模糊不清, 字幕, 风格, 作品, 画作, 画面, 静止, 整体发灰, 最差质量, 低质量, JPEG压缩残留, 丑陋的, 残缺的, 多余的手指, 画得不好的手部, 画得不好的脸部, 畸形的, 毁容的, 形态畸形的肢体, 手指融合, 静止不动的画面, 杂乱的背景, 三条腿, 背景人很多, 倒着走"def model_title():repo_name = MODEL_ID.split('/')[-1].replace("_", " ")url = f"https://huggingface.co/{MODEL_ID}"return f"## This space is currently running [{repo_name}]({url}) 🐢"def resize_image(image: Image.Image) -> Image.Image:width, height = image.sizeif width == height:return image.resize((SQUARE_DIM, SQUARE_DIM), Image.LANCZOS)29 unmodified linesdef resize_and_crop_to_match(target_image, reference_image):ref_width, ref_height = reference_image.sizetarget_width, target_height = target_image.sizescale = max(ref_width / target_width, ref_height / target_height)47 unmodified linestotal_time = 15 + gen_timeif safe_mode:total_time = total_time * 1.30# Cap reserved GPU duration so the reported reservation (×2 for xlarge) stays# under free-tier ZeroGPU's ~300s per-call limit — the padded worst-case was# tripping "requested GPU duration larger than the maximum allowed". 140 →# ~280s reported, still covers real p90 (~107s) and the 150s caller timeout.total_time = min(total_time, 145)return total_time@spaces.GPU(duration=get_inference_duration, size='xlarge')12 unmodified linesframe_multiplier,quality,duration_seconds,safe_mode=False,progress=gr.Progress(track_tqdm=True),):scheduler_class = SCHEDULER_MAP.get(scheduler_name)8 unmodified linesclear_vram()task_name = str(uuid.uuid4())[:8]print(f"Generating {num_frames} frames, task: {task_name}, {duration_seconds}, {resized_image.size}")start = time.time()result = pipe(image=resized_image,9 unmodified linesgenerator=torch.Generator(device="cuda").manual_seed(current_seed),output_type="np")print("gen time passed:", time.time() - start)raw_frames_np = result.frames[0] # Returns (T, H, W, C) float32pipe.scheduler = original_scheduler1 unmodified lineframe_factor = frame_multiplier // FIXED_FPSif frame_factor > 1:start = time.time()print(f"Processing frames (RIFE Multiplier: {frame_factor}x)...")rife_model.device()rife_model.flownet = rife_model.flownet.half()final_frames = interpolate_bits(raw_frames_np, multiplier=int(frame_factor))print("Interpolation time passed:", time.time() - start)else:final_frames = list(raw_frames_np)7 unmodified linespbar.update(2)export_to_video(final_frames, video_path, fps=final_fps, quality=quality)pbar.update(1)print(f"Export time passed, {final_fps} FPS:", time.time() - start)return video_path, task_name13 unmodified linesscheduler="UniPCMultistep",flow_shift=6.0,frame_multiplier=16,safe_mode=False,video_component=True,progress=gr.Progress(track_tqdm=True),):"""70 unmodified linessafe_mode,progress,)print(f"GPU complete: {task_n}")return (video_path if video_component else None), video_path, current_seed13 unmodified lines"""with gr.Blocks(delete_cache=(3600, 10800)) as demo:gr.Markdown(model_title())gr.Markdown("Run Wan 2.2 in just 4-8 steps, fp8 quantization & AoT compilation - compatible with 🧨 diffusers and ZeroGPU")with gr.Row():with gr.Column():9 unmodified linessafe_mode_checkbox = gr.Checkbox(label="🛠️ Safe Mode",value=True,info="Requests 30% extra processing time to try to prevent unfinished tasks when the server is busy.")with gr.Accordion("Advanced Settings", open=False):last_image_component = gr.Image(type="pil", label="Last Image (Optional)", sources=["upload", "clipboard"])12 unmodified lines)flow_shift_slider = gr.Slider(minimum=0.5, maximum=15.0, step=0.1, value=3.0, label="Flow Shift")play_result_video = gr.Checkbox(label="Display result", value=True, interactive=True)gr.Markdown(f"[ZeroGPU help, tips and troubleshooting](https://huggingface.co/datasets/{ORG_NAME}/help/blob/main/gpu_help.md)")gr.Markdown( # TestOrganizationPleaseIgnore/wamu-tools"To use a different model, **duplicate this Space** first, then change the `REPO_ID` environment variable. ""[See compatible models here](https://huggingface.co/models?other=diffusers:WanImageToVideoPipeline&sort=trending&search=WAN2.2_I2V_LIGHTNING).")generate_button = gr.Button("Generate Video", variant="primary")with gr.Column():# ASSIGNED elem_id="generated-video" so JS can find itvideo_output = gr.Video(label="Generated Video", autoplay=True, sources=["upload"], buttons=["download", "share"], interactive=True, elem_id="generated-video")# --- Frame Grabbing UI ---with gr.Row():3 unmodified linesfile_output = gr.File(label="Download Video")ui_inputs = [input_image_component, last_image_component, prompt_input, steps_slider,negative_prompt_input, duration_seconds_input,guidance_scale_input, guidance_scale_2_input, seed_input, randomize_seed_checkbox,quality_slider, scheduler_dropdown, flow_shift_slider, frame_multi,safe_mode_checkbox,play_result_video]generate_button.click(21 unmodified linesif __name__ == "__main__":demo.queue().launch(mcp_server=True,css=CSS,show_error=True,)10 unmodified lines11121314151617181920105 unmodified lines12612712812913013113213313413539 unmodified lines1751761771781791801814 unmodified lines18618718818919019119219319419519634 unmodified lines2312322332342352362372382392 unmodified lines2422432442452462472489 unmodified lines25825926026126226326426526626726823 unmodified lines29229329429529629729829930030129 unmodified lines33133233333433533633747 unmodified lines38538638738838939039139239339439539639739839940040112 unmodified lines4144154164174184194208 unmodified lines4294304314324334344359 unmodified lines4454464474484494501 unmodified line4524534544554564574584594607 unmodified lines46846947047147247313 unmodified lines48748848949049149249349470 unmodified lines56556656756856957057113 unmodified lines5855865875885895905915925939 unmodified lines60360460560660760860912 unmodified lines6226236246256266276286296306316326333 unmodified lines63763863964064164264364464564664764821 unmodified lines67067167267367467510 unmodified linesimport gcimport uuidfrom tqdm import tqdmimport cv2import numpy as npimport torchfrom torch.nn import functional as Ffrom PIL import Image105 unmodified lines"""Interpolation maintaining Numpy Float 0-1 format.Args:frames_np: Numpy Array (Time, Height, Width, Channels) - Float32[0.0, 1.0]multiplier: int (2, 4, 8)Returns:List of Numpy Arrays (Height, Width, Channels) - Float32[0.0, 1.0]"""# Handle input shape39 unmodified linesdef make_inference(I0, I1, n):if rife_model.version >= 3.9:res =[]for i in range(n):res.append(rife_model.inference(I0, I1, (i+1) * 1. / (n+1), scale))return res4 unmodified linesfirst_half = make_inference(I0, middle, n=n//2)second_half = make_inference(middle, I1, n=n//2)if n % 2:return[*first_half, middle, *second_half]else:return[*first_half, *second_half]output_frames =[]# Process Frames# Load first frame into GPU34 unmodified lines# WANMODEL_ID = "Wan-AI/Wan2.2-I2V-A14B-Diffusers"CACHE_DIR = os.path.expanduser("~/.cache/huggingface/")MAX_DIM = 832MIN_DIM = 480SQUARE_DIM = 6402 unmodified linesFIXED_FPS = 16MIN_FRAMES_MODEL = 8MAX_FRAMES_MODEL = 160MIN_DURATION = round(MIN_FRAMES_MODEL / FIXED_FPS, 1)MAX_DURATION = round(MAX_FRAMES_MODEL / FIXED_FPS, 1)9 unmodified lines}pipe = WanImageToVideoPipeline.from_pretrained("TestOrganizationPleaseIgnore/WAMU_v3_WAN2.2_I2V_LIGHTNING",torch_dtype=torch.bfloat16,).to('cuda')original_scheduler = copy.deepcopy(pipe.scheduler)# if os.path.exists(CACHE_DIR):# shutil.rmtree(CACHE_DIR)# print("Deleted Hugging Face cache.")23 unmodified linesdefault_negative_prompt = "色调艳丽, 过曝, 静态, 细节模糊不清, 字幕, 风格, 作品, 画作, 画面, 静止, 整体发灰, 最差质量, 低质量, JPEG压缩残留, 丑陋的, 残缺的, 多余的手指, 画得不好的手部, 画得不好的脸部, 畸形的, 毁容的, 形态畸形的肢体, 手指融合, 静止不动的画面, 杂乱的背景, 三条腿, 背景人很多, 倒着走"def resize_image(image: Image.Image) -> Image.Image:"""Resizes an image to fit within the model's constraints, preserving aspect ratio as much as possible."""width, height = image.sizeif width == height:return image.resize((SQUARE_DIM, SQUARE_DIM), Image.LANCZOS)29 unmodified linesdef resize_and_crop_to_match(target_image, reference_image):"""Resizes and center-crops the target image to match the reference image's dimensions."""ref_width, ref_height = reference_image.sizetarget_width, target_height = target_image.sizescale = max(ref_width / target_width, ref_height / target_height)47 unmodified linestotal_time = 15 + gen_timeif safe_mode:total_time = total_time * 1.3# Cap the reserved GPU duration so the reported reservation (×2 for xlarge)# stays under free-tier ZeroGPU's ~300s per-call limit. The padded worst-case# estimate ran 3-10x the real p90 (~107s) and tripped "The requested GPU# duration (…) is larger than the maximum allowed". 145 → ~290s reported,# still covers p90 and matches the caller's 150s hard timeout. Revert to 140# if the cap turns out stricter than 300s.total_time = min(total_time, 145)return total_time@spaces.GPU(duration=get_inference_duration, size='xlarge')12 unmodified linesframe_multiplier,quality,duration_seconds,safe_mode,progress=gr.Progress(track_tqdm=True),):scheduler_class = SCHEDULER_MAP.get(scheduler_name)8 unmodified linesclear_vram()task_name = str(uuid.uuid4())[:8]print(f"Task: {task_name}, {duration_seconds}, {resized_image.size}, FM={frame_multiplier}")start = time.time()result = pipe(image=resized_image,9 unmodified linesgenerator=torch.Generator(device="cuda").manual_seed(current_seed),output_type="np")raw_frames_np = result.frames[0] # Returns (T, H, W, C) float32pipe.scheduler = original_scheduler1 unmodified lineframe_factor = frame_multiplier // FIXED_FPSif frame_factor > 1:start = time.time()rife_model.device()rife_model.flownet = rife_model.flownet.half()final_frames = interpolate_bits(raw_frames_np, multiplier=int(frame_factor))else:final_frames = list(raw_frames_np)7 unmodified linespbar.update(2)export_to_video(final_frames, video_path, fps=final_fps, quality=quality)pbar.update(1)return video_path, task_name13 unmodified linesscheduler="UniPCMultistep",flow_shift=6.0,frame_multiplier=16,video_component=True,safe_mode=False,progress=gr.Progress(track_tqdm=True),):"""70 unmodified linessafe_mode,progress,)print(f"GPU complete: {task_n}")return (video_path if video_component else None), video_path, current_seed13 unmodified lines"""with gr.Blocks(theme=gr.themes.Soft(), css=CSS, delete_cache=(3600, 3700)) as demo:gr.Markdown("## Wan 2.2 I2V (14B) — Fast ⚡")gr.Markdown("Run Wan 2.2 in just 4-8 steps, fp8 quantization & AoT compilation - compatible with 🧨 diffusers and ZeroGPU.")with gr.Row():with gr.Column():9 unmodified linessafe_mode_checkbox = gr.Checkbox(label="🛠️ Safe Mode",value=True,info="Safe Mode: Requests 30% extra processing time to try to prevent unfinished tasks when the server is busy.")with gr.Accordion("Advanced Settings", open=False):last_image_component = gr.Image(type="pil", label="Last Image (Optional)", sources=["upload", "clipboard"])12 unmodified lines)flow_shift_slider = gr.Slider(minimum=0.5, maximum=15.0, step=0.1, value=3.0, label="Flow Shift")play_result_video = gr.Checkbox(label="Display result", value=True, interactive=True)generate_button = gr.Button("Generate Video", variant="primary")with gr.Column():# ASSIGNED elem_id="generated-video" so JS can find itvideo_output = gr.Video(label="Generated Video", autoplay=True, sources=["upload"], show_download_button=True, show_share_button=True, interactive=False, elem_id="generated-video")# --- Frame Grabbing UI ---with gr.Row():3 unmodified linesfile_output = gr.File(label="Download Video")ui_inputs =[input_image_component, last_image_component, prompt_input, steps_slider,negative_prompt_input, duration_seconds_input,guidance_scale_input, guidance_scale_2_input, seed_input, randomize_seed_checkbox,quality_slider, scheduler_dropdown, flow_shift_slider, frame_multi,play_result_video, safe_mode_checkbox]generate_button.click(21 unmodified linesif __name__ == "__main__":demo.queue().launch(mcp_server=True,ssr_mode=False,show_error=True,)
README.md+2-1
app.py+35-80