Upload app.py
Browse files707 unmodified lines708709710711712713714715716717711712713714720721722723724725715716717718109 unmodified lines82882983084184284383183283383484684784884985083583683783883984015 unmodified lines85685785887285986086186286386417 unmodified lines882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931899932933934935936707 unmodified lines return image_path
def _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 _Image
with _Image.open(image_path) as img: aspect = img.width / img.height label = _snap_canvas(aspect, current_canvas) return _cover_crop(image_path, label), label """Crop a keyframe to the selected canvas ratio without changing the selected resolution.""" return _cover_crop(image_path, current_canvas), current_canvas
def _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: the user immediately sees the keyframe cropped to the ratio the video will be rendered at, and the Canvas dropdown moves to the snapped resolution instead of sitting on the 16:9 default. """ """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 lines
from 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. # 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, canvas = _fit_keyframe(first, canvas) if last: last = _cover_crop(last, canvas) elif last: last, canvas = _fit_keyframe(last, canvas) first = _cover_crop(first, canvas) if last: last = _cover_crop(last, canvas)
num_frames = snap_frames(duration)
15 unmodified lines rewrite_prompt=bool(enhance_prompt), ) condition_seconds = time.time() - conditioned height, width, num_frames = (int(metadata[key]) for key in ("height", "width", "num_frames")) # 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 lines path = 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 json import shutil import subprocess
ffprobe = shutil.which("ffprobe") ffmpeg = shutil.which("ffmpeg") actual_width, actual_height = width, height if 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 = False if (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 = True print( 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} · {num_frames} frames ({num_frames / FPS:.3f}s) · " 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