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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py — Re-encode Frames to Video (FFmpeg only)
|
| 2 |
+
|
| 3 |
+
import os, zipfile, tempfile, subprocess, base64
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import List, Optional, Tuple
|
| 6 |
+
import gradio as gr
|
| 7 |
+
|
| 8 |
+
def try_load_logo_b64() -> str:
|
| 9 |
+
try:
|
| 10 |
+
with open("bifrost_logo.png", "rb") as f:
|
| 11 |
+
import base64
|
| 12 |
+
return base64.b64encode(f.read()).decode("utf-8")
|
| 13 |
+
except Exception:
|
| 14 |
+
return ""
|
| 15 |
+
LOGO_B64 = try_load_logo_b64()
|
| 16 |
+
|
| 17 |
+
def render_logo_html(px: int = 96) -> str:
|
| 18 |
+
img = f'<img src="data:image/png;base64,{LOGO_B64}" style="height:{px}px;width:auto;" />' if LOGO_B64 else ""
|
| 19 |
+
return f"""
|
| 20 |
+
<div style="display:flex;align-items:center;gap:16px;">
|
| 21 |
+
{img}
|
| 22 |
+
<div>
|
| 23 |
+
<div style="font-size:1.6rem;font-weight:800;">Bifröst · Re-encode Video</div>
|
| 24 |
+
<div style="opacity:0.8;">Frames → Video, optional audio mux</div>
|
| 25 |
+
</div>
|
| 26 |
+
</div>
|
| 27 |
+
<hr>
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def _which(name: str) -> Optional[str]:
|
| 31 |
+
from shutil import which
|
| 32 |
+
return which(name)
|
| 33 |
+
|
| 34 |
+
FFMPEG = _which("ffmpeg")
|
| 35 |
+
FFPROBE = _which("ffprobe")
|
| 36 |
+
MISSING_MSG = "" if (FFMPEG and FFPROBE) else (
|
| 37 |
+
"⚠️ FFmpeg/FFprobe not found. Add a 'packages.txt' with:\n"
|
| 38 |
+
"ffmpeg\nlibsm6\nlibxext6\nand restart the Space."
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
def render_progress(pct: float, label: str = "") -> str:
|
| 42 |
+
pct = max(0.0, min(100.0, pct))
|
| 43 |
+
return f'''<div style="width:100%;border:1px solid #ddd;border-radius:8px;overflow:hidden;height:18px;">
|
| 44 |
+
<div style="height:100%;width:{pct:.1f}%;background:#3b82f6;"></div></div>
|
| 45 |
+
<div style="font-size:12px;opacity:.8;margin-top:4px;">{label} {pct:.1f}%</div>'''
|
| 46 |
+
|
| 47 |
+
def prepare_frames_from_upload(files: List[gr.File] | None, prefix: str = "enc") -> Tuple[Optional[str], Optional[str]]:
|
| 48 |
+
if not files:
|
| 49 |
+
return None, None
|
| 50 |
+
work = Path(tempfile.mkdtemp(prefix="enc_"))
|
| 51 |
+
frames_dir = work / "frames"; frames_dir.mkdir(parents=True, exist_ok=True)
|
| 52 |
+
detected_prefix = None
|
| 53 |
+
|
| 54 |
+
if len(files) == 1 and Path(files[0].name).suffix.lower() == ".zip":
|
| 55 |
+
with zipfile.ZipFile(files[0].name, "r") as zf:
|
| 56 |
+
zf.extractall(frames_dir)
|
| 57 |
+
imgs = sorted(frames_dir.glob("*.jpg")) + sorted(frames_dir.glob("*.png"))
|
| 58 |
+
if imgs:
|
| 59 |
+
detected_prefix = Path(imgs[0]).stem.split("_")[0]
|
| 60 |
+
return str(frames_dir), detected_prefix or prefix
|
| 61 |
+
|
| 62 |
+
counter = 1
|
| 63 |
+
for f in files:
|
| 64 |
+
src = Path(f.name)
|
| 65 |
+
if src.suffix.lower() not in [".jpg", ".jpeg", ".png"]:
|
| 66 |
+
continue
|
| 67 |
+
dst = frames_dir / f"{prefix}_{counter:05d}{src.suffix.lower()}"
|
| 68 |
+
src.replace(dst) if src.exists() else None
|
| 69 |
+
counter += 1
|
| 70 |
+
return str(frames_dir), prefix
|
| 71 |
+
|
| 72 |
+
def build_ffmpeg_encode(frames_dir: str, prefix: str, fps: float, fmt: str, include_audio: bool, orig_video: str | None) -> list[str]:
|
| 73 |
+
pattern_jpg = Path(frames_dir) / f"{prefix}_%05d.jpg"
|
| 74 |
+
pattern_png = Path(frames_dir) / f"{prefix}_%05d.png"
|
| 75 |
+
pattern = str(pattern_jpg if pattern_jpg.exists() else pattern_png)
|
| 76 |
+
if not Path(pattern.replace("%05d", "00001")).with_suffix(Path(pattern).suffix).exists():
|
| 77 |
+
# if first frame isn't 00001, we still let ffmpeg start_number 1; files must be named *_00001.*
|
| 78 |
+
pass
|
| 79 |
+
args = [FFMPEG, "-y", "-start_number", "1", "-framerate", f"{fps:.6f}", "-i", pattern]
|
| 80 |
+
if include_audio and orig_video:
|
| 81 |
+
args += ["-i", orig_video, "-map", "0:v:0", "-map", "1:a:0", "-shortest"]
|
| 82 |
+
if fmt == "h265":
|
| 83 |
+
vcodec = ["-c:v", "libx265"]
|
| 84 |
+
elif fmt == "vp9":
|
| 85 |
+
vcodec = ["-c:v", "libvpx-vp9"]
|
| 86 |
+
else:
|
| 87 |
+
vcodec = ["-c:v", "libx264"]
|
| 88 |
+
args += vcodec + ["-pix_fmt", "yuv420p", "-crf", "18", "output.mp4" if fmt in ("h264", "h265") else "output.webm"]
|
| 89 |
+
return args
|
| 90 |
+
|
| 91 |
+
def step3_encode(
|
| 92 |
+
uploaded_frames: List[gr.File] | None,
|
| 93 |
+
uploaded_audio_video: gr.File | None,
|
| 94 |
+
fps: float,
|
| 95 |
+
fmt: str,
|
| 96 |
+
include_audio: bool,
|
| 97 |
+
prog_html: str,
|
| 98 |
+
):
|
| 99 |
+
if not (FFMPEG and FFPROBE):
|
| 100 |
+
yield None, "FFmpeg/FFprobe missing. See note below.", prog_html
|
| 101 |
+
return
|
| 102 |
+
frames_dir, prefix = prepare_frames_from_upload(uploaded_frames, "enc")
|
| 103 |
+
if not frames_dir or not prefix:
|
| 104 |
+
yield None, "No frames provided. Upload a ZIP or images.", prog_html
|
| 105 |
+
return
|
| 106 |
+
|
| 107 |
+
orig_path = uploaded_audio_video.name if uploaded_audio_video else None
|
| 108 |
+
cmd = build_ffmpeg_encode(frames_dir, prefix, float(fps or 30.0), fmt, include_audio, orig_path)
|
| 109 |
+
|
| 110 |
+
# Add progress pipe and run in frames_dir for clean output pathing
|
| 111 |
+
cmd = [cmd[0], "-progress", "pipe:2"] + cmd[1:]
|
| 112 |
+
proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, text=True, bufsize=1, cwd=frames_dir)
|
| 113 |
+
|
| 114 |
+
# Approximate by counting files
|
| 115 |
+
total_frames = len(list(Path(frames_dir).glob(f"{prefix}_*.jpg"))) + len(list(Path(frames_dir).glob(f"{prefix}_*.png")))
|
| 116 |
+
current = 0
|
| 117 |
+
|
| 118 |
+
while True:
|
| 119 |
+
line = proc.stderr.readline()
|
| 120 |
+
if not line and proc.poll() is not None:
|
| 121 |
+
break
|
| 122 |
+
if "frame=" in line:
|
| 123 |
+
try:
|
| 124 |
+
current = int(line.strip().split("=")[-1])
|
| 125 |
+
except Exception:
|
| 126 |
+
pass
|
| 127 |
+
if total_frames > 0:
|
| 128 |
+
pct = min(100.0, (current / total_frames) * 100.0)
|
| 129 |
+
yield None, f"Encoding… {current}/{total_frames} frames", render_progress(pct, f"Encoding {pct:.0f}%")
|
| 130 |
+
else:
|
| 131 |
+
yield None, "Encoding…", render_progress(50.0, "Encoding…"))
|
| 132 |
+
|
| 133 |
+
ret = proc.wait()
|
| 134 |
+
out_file = Path(frames_dir) / ("output.mp4" if fmt in ("h264", "h265") else "output.webm")
|
| 135 |
+
if ret != 0 or not out_file.exists():
|
| 136 |
+
err = ""
|
| 137 |
+
try:
|
| 138 |
+
err = proc.stderr.read() if proc.stderr else ""
|
| 139 |
+
except Exception:
|
| 140 |
+
pass
|
| 141 |
+
yield None, f"Encoding failed.\n\n{err}", render_progress(0.0, "Failed"))
|
| 142 |
+
return
|
| 143 |
+
|
| 144 |
+
yield str(out_file), f"Video created: {out_file.name}", render_progress(100.0, "Encoding complete")
|
| 145 |
+
|
| 146 |
+
def build_ui():
|
| 147 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 148 |
+
gr.HTML(render_logo_html(88))
|
| 149 |
+
gr.Markdown("Re-encode a folder/ZIP of frames into a video. Optionally mux audio from a video/audio file.")
|
| 150 |
+
|
| 151 |
+
uploaded_frames = gr.Files(label="Upload frames (ZIP or images)", type="filepath")
|
| 152 |
+
uploaded_audio = gr.File(label="Optional: video/audio for audio track", file_types=[".mp4",".mov",".mkv",".webm",".mp3",".wav"], type="filepath")
|
| 153 |
+
|
| 154 |
+
with gr.Row():
|
| 155 |
+
fps = gr.Number(value=30.0, label="FPS")
|
| 156 |
+
fmt = gr.Dropdown(["h264", "h265", "vp9"], value="h264", label="Video format")
|
| 157 |
+
include_audio = gr.Checkbox(True, label="Include audio if available")
|
| 158 |
+
|
| 159 |
+
btn_encode = gr.Button("Create Video", variant="primary")
|
| 160 |
+
prog = gr.HTML(render_progress(0.0, "Idle"))
|
| 161 |
+
video_player = gr.Video(label="Output video")
|
| 162 |
+
details = gr.Markdown("")
|
| 163 |
+
|
| 164 |
+
btn_encode.click(
|
| 165 |
+
step3_encode,
|
| 166 |
+
inputs=[uploaded_frames, uploaded_audio, fps, fmt, include_audio, prog],
|
| 167 |
+
outputs=[video_player, details, prog],
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
if MISSING_MSG:
|
| 171 |
+
gr.Markdown(f"<span style='color:#b45309'>{MISSING_MSG}</span>")
|
| 172 |
+
|
| 173 |
+
return demo
|
| 174 |
+
|
| 175 |
+
if __name__ == "__main__":
|
| 176 |
+
build_ui().queue().launch()
|