Upload app.py
Browse files707 unmodified lines708709710711712713714715716717718719720721722723724725726727728109 unmodified lines83883984084184284384484584684784884985085185285315 unmodified lines86987087187287387487517 unmodified lines893894895896897898899900901902707 unmodified linesreturn image_pathdef _fit_keyframe(image_path, current_canvas):"""Snap the canvas to a keyframe's aspect ratio, then cover-crop the keyframe to that canvas."""from PIL import Image as _Imagewith _Image.open(image_path) as img:aspect = img.width / img.heightlabel = _snap_canvas(aspect, current_canvas)return _cover_crop(image_path, label), labeldef _fit_keyframe_ui(image_path, current_canvas):"""``image.upload`` handler — the reference Space's behaviour, ported.Doing this on upload (rather than only server-side inside ``generate``) is the whole point: theuser immediately sees the keyframe cropped to the ratio the video will be rendered at, and theCanvas dropdown moves to the snapped resolution instead of sitting on the 16:9 default."""path = _as_path(image_path)if not path:return gr.update(), gr.update()109 unmodified linesfrom diffusers.utils import encode_video# The UI already snapped + cropped on upload, so this is a no-op there; it still runs for API# callers (and for a canvas the user changed afterwards) so the output geometry always follows the# I2V image. The *first* frame owns the canvas — a last frame is only cover-cropped to match it.first, last = _as_path(image_path), _as_path(last_image_path)if first:first, canvas = _fit_keyframe(first, canvas)if last:last = _cover_crop(last, canvas)elif last:last, canvas = _fit_keyframe(last, canvas)num_frames = snap_frames(duration)15 unmodified linesrewrite_prompt=bool(enhance_prompt),)condition_seconds = time.time() - conditionedheight, width, num_frames = (int(metadata[key]) for key in ("height", "width", "num_frames"))# `None` whenever no rewrite happened — either none was asked for, or the conditioner declined one.enhanced = (plan or {}).get("refined_prompt") or ""17 unmodified linespath = os.path.join(OUTPUT_DIR, f"h3-flashgen-{int(time.time() * 1000)}.mp4")encode_video(frames, fps=FPS, output_path=path, audio=audio, audio_sample_rate=sampling_rate)# Reported, not assumed: `steps_taken` is the number of Euler updates the scheduler actually took.schedule = " → ".join(f"{s:g}" for s in sigmas_used)report = (f"{width}x{height} · {num_frames} frames ({num_frames / FPS:.3f}s) · "f"{steps_taken} steps (FlashGen σ {schedule}) · "f"conditioner {condition_seconds:.0f}s{' (prompt enhanced)' if enhanced else ''} · "f"denoise + decode {generate_seconds:.0f}s · seed {int(seed)}"707 unmodified lines708709710711712713714715716717718109 unmodified lines82882983083183283383483583683783883984015 unmodified lines85685785885986086186286386417 unmodified lines882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936707 unmodified linesreturn image_pathdef _fit_keyframe(image_path, current_canvas):"""Crop a keyframe to the selected canvas ratio without changing the selected resolution."""return _cover_crop(image_path, current_canvas), current_canvasdef _fit_keyframe_ui(image_path, current_canvas):"""Crop the uploaded keyframe to the selected canvas ratio; preserve the Canvas dropdown."""path = _as_path(image_path)if not path:return gr.update(), gr.update()109 unmodified linesfrom diffusers.utils import encode_video# The user's Canvas selection is authoritative. Crop keyframes to its aspect ratio,# but never replace the selected resolution with a preset chosen from the source image.first, last = _as_path(image_path), _as_path(last_image_path)if first:first = _cover_crop(first, canvas)if last:last = _cover_crop(last, canvas)num_frames = snap_frames(duration)15 unmodified linesrewrite_prompt=bool(enhance_prompt),)condition_seconds = time.time() - conditioned# Keep the requested Canvas dimensions even if the remote conditioner reports a fallback size.height, width = CANVASES[canvas]num_frames = int(metadata["num_frames"])# `None` whenever no rewrite happened — either none was asked for, or the conditioner declined one.enhanced = (plan or {}).get("refined_prompt") or ""17 unmodified linespath = os.path.join(OUTPUT_DIR, f"h3-flashgen-{int(time.time() * 1000)}.mp4")encode_video(frames, fps=FPS, output_path=path, audio=audio, audio_sample_rate=sampling_rate)# Verify the encoded MP4 dimensions. If the pipeline/encoder emitted another size, normalize# the final video to the selected Canvas while preserving its audio track.import jsonimport shutilimport subprocessffprobe = shutil.which("ffprobe")ffmpeg = shutil.which("ffmpeg")actual_width, actual_height = width, heightif ffprobe:probe = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0","-show_entries", "stream=width,height", "-of", "json", path],capture_output=True, text=True, check=True,)streams = json.loads(probe.stdout).get("streams", [])if streams:actual_width = int(streams[0]["width"])actual_height = int(streams[0]["height"])resized = Falseif (actual_width, actual_height) != (width, height):if not ffmpeg:raise gr.Error(f"Выбрано {width}x{height}, но модель создала {actual_width}x{actual_height}; ""FFmpeg недоступен для исправления размера.")corrected = path[:-4] + "-canvas.mp4"subprocess.run([ffmpeg, "-y", "-i", path,"-vf", f"scale={width}:{height}:force_original_aspect_ratio=increase:flags=lanczos,"f"crop={width}:{height}","-c:v", "libx264", "-preset", "veryfast", "-crf", "18","-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", corrected],capture_output=True, text=True, check=True,)os.replace(corrected, path)resized = Trueprint(f"[canvas] Model/encoder output {actual_width}x{actual_height}; "f"final MP4 normalized to selected Canvas {width}x{height}.",flush=True,)# Reported, not assumed: `steps_taken` is the number of Euler updates the scheduler actually took.schedule = " → ".join(f"{s:g}" for s in sigmas_used)report = (f"{width}x{height}{' (final size corrected with FFmpeg)' if resized else ''} · "f"{num_frames} frames ({num_frames / FPS:.3f}s) · "f"{steps_taken} steps (FlashGen σ {schedule}) · "f"conditioner {condition_seconds:.0f}s{' (prompt enhanced)' if enhanced else ''} · "f"denoise + decode {generate_seconds:.0f}s · seed {int(seed)}"
app.py+57-23