Spaces:
Running on Zero
Running on Zero
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,414 +0,0 @@
|
|
| 1 |
-
# app.py — DRIVE → MP4 CONVERTER (Space inayojitegemea, faili moja)
|
| 2 |
-
# Inachukua viungo vya Google Drive (au kiungo chochote cha moja kwa moja cha video), inapakua,
|
| 3 |
-
# inabadilisha kuwa MP4 inayocheza kwenye kila kivinjari/simu (H.264 + AAC, faststart),
|
| 4 |
-
# na (hiari) inapakia kwenye HF Dataset ili upate kiungo cha moja kwa moja cha kuweka kwenye app.
|
| 5 |
-
import os, re, sys, time, json, html, shutil, hashlib, threading, subprocess, tempfile, glob
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
from urllib.parse import quote, unquote, urlparse, parse_qs
|
| 8 |
-
|
| 9 |
-
# ZeroGPU Spaces zinadai angalau function moja ya @spaces.GPU wakati wa kuanza.
|
| 10 |
-
# Converter hii inatumia CPU (ffmpeg) tu; function hii ni ya kimya na haifanyi chochote.
|
| 11 |
-
# Ukitumia "CPU basic" (inapendekezwa) kipande hiki hakina athari.
|
| 12 |
-
try:
|
| 13 |
-
import spaces
|
| 14 |
-
|
| 15 |
-
@spaces.GPU
|
| 16 |
-
def _gpu_placeholder():
|
| 17 |
-
return None
|
| 18 |
-
except Exception:
|
| 19 |
-
pass
|
| 20 |
-
|
| 21 |
-
WORK_DIR = os.path.join(tempfile.gettempdir(), "mp4_work")
|
| 22 |
-
OUT_DIR = os.path.join(tempfile.gettempdir(), "mp4_out")
|
| 23 |
-
os.makedirs(WORK_DIR, exist_ok=True)
|
| 24 |
-
os.makedirs(OUT_DIR, exist_ok=True)
|
| 25 |
-
VIDEO_EXTS = (".mp4", ".mkv", ".avi", ".mov", ".webm", ".flv", ".wmv", ".m4v", ".ts", ".3gp", ".mpg", ".mpeg")
|
| 26 |
-
|
| 27 |
-
_lock = threading.Lock()
|
| 28 |
-
_ffmpeg = {"ff": None}
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
class ToolError(Exception):
|
| 32 |
-
pass
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
def human_size(n):
|
| 36 |
-
for u in ["B", "KB", "MB", "GB"]:
|
| 37 |
-
if n < 1024:
|
| 38 |
-
return f"{n:.1f} {u}"
|
| 39 |
-
n /= 1024
|
| 40 |
-
return f"{n:.1f} TB"
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def fmt_time(sec):
|
| 44 |
-
sec = int(max(0, sec))
|
| 45 |
-
return f"{sec // 3600}:{sec % 3600 // 60:02d}:{sec % 60:02d}"
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def cleanup_old(max_age_h=6):
|
| 49 |
-
now = time.time()
|
| 50 |
-
for base in (WORK_DIR, OUT_DIR):
|
| 51 |
-
for p in glob.glob(os.path.join(base, "*")):
|
| 52 |
-
try:
|
| 53 |
-
if now - os.path.getmtime(p) > max_age_h * 3600:
|
| 54 |
-
shutil.rmtree(p, ignore_errors=True) if os.path.isdir(p) else os.remove(p)
|
| 55 |
-
except Exception:
|
| 56 |
-
pass
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
# ── Viungo ───────────────────────────────────────────────────
|
| 60 |
-
def extract_drive_id(link):
|
| 61 |
-
link = (link or "").strip()
|
| 62 |
-
m = re.search(r"drive\.google\.com/(?:file/d/|open\?id=|uc\?(?:[^#]*&)?id=)([A-Za-z0-9_-]{15,})", link)
|
| 63 |
-
if m:
|
| 64 |
-
return m.group(1)
|
| 65 |
-
m = re.search(r"[?&]id=([A-Za-z0-9_-]{15,})", link) if "google.com" in link else None
|
| 66 |
-
return m.group(1) if m else None
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
def clean_title(name):
|
| 70 |
-
base = os.path.splitext(name)[0]
|
| 71 |
-
base = re.sub(r"(?i)(https?://)?www\.[^\s]+", " ", base) # ondoa anwani za tovuti kwenye jina
|
| 72 |
-
base = re.sub(r"[^\w\s\-\.\(\)]", " ", base, flags=re.UNICODE) # ondoa emoji/alama
|
| 73 |
-
base = re.sub(r"\s+", " ", base).strip(" .-_")
|
| 74 |
-
return (base or "video")[:80]
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def slug_file(title):
|
| 78 |
-
s = re.sub(r"[^A-Za-z0-9]+", "-", title).strip("-").lower()
|
| 79 |
-
return s or "video"
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
def _filename_from_headers(r, fallback):
|
| 83 |
-
cd = r.headers.get("content-disposition", "") or ""
|
| 84 |
-
m = re.search(r"filename\*=UTF-8''([^;]+)", cd, re.I)
|
| 85 |
-
if m:
|
| 86 |
-
return unquote(m.group(1)).strip('"')
|
| 87 |
-
m = re.search(r'filename="?([^";]+)"?', cd, re.I)
|
| 88 |
-
if m:
|
| 89 |
-
try:
|
| 90 |
-
return m.group(1).encode("latin-1").decode("utf-8")
|
| 91 |
-
except Exception:
|
| 92 |
-
return m.group(1)
|
| 93 |
-
return fallback
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def parse_confirm_form(page):
|
| 97 |
-
"""Ukurasa wa onyo la Drive ('haiwezi kuskani virusi') una form yenye uuid/at/confirm."""
|
| 98 |
-
action = re.search(r'<form[^>]+action="([^"]+)"', page)
|
| 99 |
-
if not action:
|
| 100 |
-
return None, {}
|
| 101 |
-
fields = {}
|
| 102 |
-
for tag in re.findall(r"<input[^>]+>", page):
|
| 103 |
-
n = re.search(r'name="([^"]+)"', tag)
|
| 104 |
-
v = re.search(r'value="([^"]*)"', tag)
|
| 105 |
-
if n:
|
| 106 |
-
fields[html.unescape(n.group(1))] = html.unescape(v.group(1)) if v else ""
|
| 107 |
-
return html.unescape(action.group(1)), fields
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
def explain_drive_page(page):
|
| 111 |
-
low = page.lower()
|
| 112 |
-
if "quota" in low or "too many users" in low:
|
| 113 |
-
return ("Drive imezuia upakuaji (kikomo/quota). Tengeneza nakala ya faili kwenye Drive yako "
|
| 114 |
-
"(Right-click > Make a copy) kisha tumia kiungo cha nakala hiyo, au jaribu baadaye.")
|
| 115 |
-
if "sign in" in low or "accounts.google.com" in low or "request access" in low or "you need access" in low:
|
| 116 |
-
return "Faili si la umma. Fungua Share > General access > 'Anyone with the link' kisha jaribu tena."
|
| 117 |
-
if "not found" in low or "404" in low:
|
| 118 |
-
return "Faili halipatikani (limefutwa au kiungo si sahihi)."
|
| 119 |
-
return "Drive imerudisha ukurasa badala ya video. Hakikisha faili ni 'Anyone with the link'."
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
def download_gen(link, dest_dir):
|
| 123 |
-
"""Generator: yield ('p', ujumbe) kwa maendeleo, kisha ('file', path, jina_asili)."""
|
| 124 |
-
import requests
|
| 125 |
-
os.makedirs(dest_dir, exist_ok=True)
|
| 126 |
-
s = requests.Session()
|
| 127 |
-
s.headers["User-Agent"] = "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 Chrome/120 Mobile Safari/537.36"
|
| 128 |
-
fid = extract_drive_id(link)
|
| 129 |
-
if fid:
|
| 130 |
-
url, params = "https://drive.usercontent.google.com/download", {"id": fid, "export": "download", "confirm": "t"}
|
| 131 |
-
fallback = fid
|
| 132 |
-
elif re.match(r"^https?://", link.strip()):
|
| 133 |
-
url, params = link.strip(), None
|
| 134 |
-
fallback = os.path.basename(urlparse(link).path) or "video"
|
| 135 |
-
else:
|
| 136 |
-
raise ToolError("Kiungo si sahihi. Weka kiungo cha Google Drive au kiungo cha moja kwa moja cha video.")
|
| 137 |
-
try:
|
| 138 |
-
r = s.get(url, params=params, stream=True, timeout=(15, 60), allow_redirects=True)
|
| 139 |
-
if fid and "text/html" in r.headers.get("content-type", ""):
|
| 140 |
-
action, fields = parse_confirm_form(r.text)
|
| 141 |
-
if action and fields:
|
| 142 |
-
r = s.get(action, params=fields, stream=True, timeout=(15, 60))
|
| 143 |
-
if r.status_code >= 400:
|
| 144 |
-
raise ToolError(f"Seva imejibu HTTP {r.status_code}.")
|
| 145 |
-
if "text/html" in r.headers.get("content-type", ""):
|
| 146 |
-
raise ToolError(explain_drive_page(r.text[:20000]) if fid else "Kiungo kinarudisha ukurasa wa tovuti, si faili la video.")
|
| 147 |
-
except requests.RequestException as e:
|
| 148 |
-
raise ToolError(f"Mtandao: {e}")
|
| 149 |
-
name = _filename_from_headers(r, fallback)
|
| 150 |
-
safe = re.sub(r"[^\w\.\- ]", "_", name, flags=re.UNICODE)[:120] or "video"
|
| 151 |
-
if not safe.lower().endswith(VIDEO_EXTS):
|
| 152 |
-
safe += ".mp4"
|
| 153 |
-
path = os.path.join(dest_dir, safe)
|
| 154 |
-
total = int(r.headers.get("content-length") or 0)
|
| 155 |
-
got, t0, last = 0, time.time(), 0
|
| 156 |
-
with open(path, "wb") as f:
|
| 157 |
-
for chunk in r.iter_content(1024 * 1024):
|
| 158 |
-
if not chunk:
|
| 159 |
-
continue
|
| 160 |
-
f.write(chunk)
|
| 161 |
-
got += len(chunk)
|
| 162 |
-
if time.time() - last > 2:
|
| 163 |
-
last = time.time()
|
| 164 |
-
sp = got / max(0.1, time.time() - t0)
|
| 165 |
-
pct = f" ({got / total * 100:.1f}%)" if total else ""
|
| 166 |
-
yield ("p", f"⬇️ {human_size(got)}" + (f" / {human_size(total)}" if total else "") + f"{pct} · {human_size(sp)}/s")
|
| 167 |
-
if got < 10 * 1024:
|
| 168 |
-
raise ToolError("Faili lililopakuliwa ni dogo mno (si video). Angalia ruhusa za kiungo.")
|
| 169 |
-
yield ("file", path, name)
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
# ── ffmpeg ───────────────────────────────────────────────────
|
| 173 |
-
def ensure_ffmpeg():
|
| 174 |
-
if _ffmpeg["ff"]:
|
| 175 |
-
return _ffmpeg["ff"]
|
| 176 |
-
ff = shutil.which("ffmpeg")
|
| 177 |
-
if not ff:
|
| 178 |
-
subprocess.run("apt-get update -qq && apt-get install -y -qq ffmpeg", shell=True,
|
| 179 |
-
capture_output=True, timeout=900)
|
| 180 |
-
ff = shutil.which("ffmpeg")
|
| 181 |
-
if not ff:
|
| 182 |
-
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "imageio-ffmpeg"], capture_output=True, timeout=600)
|
| 183 |
-
try:
|
| 184 |
-
import imageio_ffmpeg
|
| 185 |
-
ff = imageio_ffmpeg.get_ffmpeg_exe()
|
| 186 |
-
except Exception:
|
| 187 |
-
ff = None
|
| 188 |
-
if not ff:
|
| 189 |
-
raise ToolError("ffmpeg haikuweza kusakinishwa kwenye Space.")
|
| 190 |
-
_ffmpeg["ff"] = ff
|
| 191 |
-
return ff
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
def probe(ff, path):
|
| 195 |
-
"""Soma codec/urefu kutoka output ya 'ffmpeg -i' (haihitaji ffprobe)."""
|
| 196 |
-
p = subprocess.run([ff, "-hide_banner", "-i", path], capture_output=True, text=True, timeout=120)
|
| 197 |
-
txt = p.stderr
|
| 198 |
-
info = {"v": None, "a": None, "dur": 0.0, "vline": "", "w": 0, "h": 0}
|
| 199 |
-
m = re.search(r"Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)", txt)
|
| 200 |
-
if m:
|
| 201 |
-
info["dur"] = int(m.group(1)) * 3600 + int(m.group(2)) * 60 + float(m.group(3))
|
| 202 |
-
m = re.search(r"Stream #[^\n]*Video: ([^\n]+)", txt)
|
| 203 |
-
if m:
|
| 204 |
-
info["vline"] = m.group(1)
|
| 205 |
-
info["v"] = m.group(1).split()[0].split("(")[0].strip(",")
|
| 206 |
-
d = re.search(r"(\d{3,5})x(\d{3,5})", m.group(1))
|
| 207 |
-
if d:
|
| 208 |
-
info["w"], info["h"] = int(d.group(1)), int(d.group(2))
|
| 209 |
-
m = re.search(r"Stream #[^\n]*Audio: (\w+)", txt)
|
| 210 |
-
if m:
|
| 211 |
-
info["a"] = m.group(1)
|
| 212 |
-
return info
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
def choose_plan(mode, info):
|
| 216 |
-
"""Returns (video_mode, audio_mode): 'copy' au 'enc'."""
|
| 217 |
-
if mode == "Remux tu (haraka, bila kupoteza ubora)":
|
| 218 |
-
return "copy", "copy"
|
| 219 |
-
if mode == "Re-encode kamili (H.264 + AAC)":
|
| 220 |
-
return "enc", "enc"
|
| 221 |
-
# Auto
|
| 222 |
-
vl = info.get("vline", "")
|
| 223 |
-
browser_ok_video = info.get("v") == "h264" and not re.search(r"High 10|High 4:2:2|High 4:4:4|10le|yuv422|yuv444", vl)
|
| 224 |
-
v = "copy" if browser_ok_video else "enc"
|
| 225 |
-
a = "copy" if info.get("a") in (None, "aac", "mp3") else "enc"
|
| 226 |
-
return v, a
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
def build_cmd(ff, src, dst, vmode, amode, height):
|
| 230 |
-
cmd = [ff, "-y", "-hide_banner", "-nostdin", "-i", src, "-map", "0:v:0", "-map", "0:a:0?", "-sn", "-dn"]
|
| 231 |
-
if vmode == "copy":
|
| 232 |
-
cmd += ["-c:v", "copy"]
|
| 233 |
-
else:
|
| 234 |
-
cmd += ["-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p"]
|
| 235 |
-
if height:
|
| 236 |
-
cmd += ["-vf", f"scale=-2:{height}:flags=lanczos"]
|
| 237 |
-
if amode == "copy":
|
| 238 |
-
cmd += ["-c:a", "copy"]
|
| 239 |
-
else:
|
| 240 |
-
cmd += ["-c:a", "aac", "-b:a", "128k", "-ac", "2"]
|
| 241 |
-
cmd += ["-movflags", "+faststart", "-progress", "pipe:1", "-nostats", dst]
|
| 242 |
-
return cmd
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
def convert_gen(ff, src, dst, mode, height):
|
| 246 |
-
info = probe(ff, src)
|
| 247 |
-
if not info["v"]:
|
| 248 |
-
raise ToolError("Hakuna video ndani ya faili hili (ffmpeg haikuona video stream).")
|
| 249 |
-
vmode, amode = choose_plan(mode, info)
|
| 250 |
-
if height and info["h"] and info["h"] <= height:
|
| 251 |
-
height = None # usikuze video ndogo
|
| 252 |
-
yield ("p", f"🎞️ Video: {info['v']} {info['w']}x{info['h']} · Audio: {info['a'] or 'hakuna'} · Urefu: {fmt_time(info['dur'])}")
|
| 253 |
-
yield ("p", f"🛠️ Mpango: video={'nakili' if vmode == 'copy' else 'encode H.264'} · audio={'nakili' if amode == 'copy' else 'encode AAC'}"
|
| 254 |
-
+ (f" · {height}p" if (height and vmode == 'enc') else ""))
|
| 255 |
-
cmd = build_cmd(ff, src, dst, vmode, amode, height if vmode == "enc" else None)
|
| 256 |
-
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
|
| 257 |
-
tail, last, t0 = [], 0, time.time()
|
| 258 |
-
for line in proc.stdout:
|
| 259 |
-
line = line.strip()
|
| 260 |
-
if line.startswith("out_time_ms="):
|
| 261 |
-
try:
|
| 262 |
-
cur = int(line.split("=")[1]) / 1e6
|
| 263 |
-
except Exception:
|
| 264 |
-
continue
|
| 265 |
-
if time.time() - last > 2:
|
| 266 |
-
last = time.time()
|
| 267 |
-
pct = f" ({min(99.9, cur / info['dur'] * 100):.1f}%)" if info["dur"] else ""
|
| 268 |
-
speed = cur / max(0.1, time.time() - t0)
|
| 269 |
-
yield ("p", f"⚙️ {fmt_time(cur)} / {fmt_time(info['dur'])}{pct} · kasi {speed:.1f}x")
|
| 270 |
-
elif "=" not in line and line:
|
| 271 |
-
tail.append(line)
|
| 272 |
-
tail = tail[-25:]
|
| 273 |
-
proc.wait()
|
| 274 |
-
if proc.returncode != 0 or not os.path.exists(dst) or os.path.getsize(dst) < 1024:
|
| 275 |
-
raise ToolError("ffmpeg imeshindwa:\n" + "\n".join(tail[-12:]))
|
| 276 |
-
yield ("file", dst)
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
# ── Upload kwenye HF Dataset (hiari) ─────────────────────────
|
| 280 |
-
def hf_upload(path, repo, token, name):
|
| 281 |
-
from huggingface_hub import HfApi
|
| 282 |
-
api = HfApi(token=token)
|
| 283 |
-
api.create_repo(repo, repo_type="dataset", exist_ok=True, private=False)
|
| 284 |
-
api.upload_file(path_or_fileobj=path, path_in_repo=f"videos/{name}", repo_id=repo, repo_type="dataset")
|
| 285 |
-
return f"https://huggingface.co/datasets/{repo}/resolve/main/videos/{quote(name)}"
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
# ── Pipeline kuu (generator kwa Gradio) ──────────────────────
|
| 289 |
-
def run_pipeline(links_text, mode, res_choice, do_upload, repo, token):
|
| 290 |
-
height = {"Asili": None, "720p": 720, "480p": 480}.get(res_choice)
|
| 291 |
-
links = [l.strip() for l in (links_text or "").splitlines() if l.strip()]
|
| 292 |
-
logs, outputs, urls = [], [], []
|
| 293 |
-
|
| 294 |
-
def render(extra=""):
|
| 295 |
-
return "\n".join(logs) + (("\n" + extra) if extra else "")
|
| 296 |
-
|
| 297 |
-
if not links:
|
| 298 |
-
yield "❌ Weka angalau kiungo kimoja (kimoja kwa kila mstari).", None, ""
|
| 299 |
-
return
|
| 300 |
-
if do_upload:
|
| 301 |
-
token = (token or "").strip() or os.environ.get("HF_TOKEN", "")
|
| 302 |
-
repo = (repo or "").strip()
|
| 303 |
-
if not token or not re.match(r"^[\w.-]+/[\w.-]+$", repo):
|
| 304 |
-
yield "❌ Kwa upload weka repo kama `username/jina-la-dataset` na HF token (au weka HF_TOKEN kwenye Space Secrets).", None, ""
|
| 305 |
-
return
|
| 306 |
-
if not _lock.acquire(blocking=False):
|
| 307 |
-
yield "⏳ Kazi nyingine inaendelea. Subiri imalize kisha ujaribu tena.", None, ""
|
| 308 |
-
return
|
| 309 |
-
try:
|
| 310 |
-
cleanup_old()
|
| 311 |
-
logs.append(f"🎬 DRIVE → MP4 · viungo: {len(links)} · mode: {mode} · ubora: {res_choice}")
|
| 312 |
-
logs.append("═" * 60)
|
| 313 |
-
yield render(), None, ""
|
| 314 |
-
try:
|
| 315 |
-
ff = ensure_ffmpeg()
|
| 316 |
-
except ToolError as e:
|
| 317 |
-
logs.append(f"❌ {e}")
|
| 318 |
-
yield render(), None, ""
|
| 319 |
-
return
|
| 320 |
-
for i, link in enumerate(links, 1):
|
| 321 |
-
logs.append(f"\n[{i}/{len(links)}] {link[:90]}")
|
| 322 |
-
job = os.path.join(WORK_DIR, hashlib.md5(f"{link}{time.time()}".encode()).hexdigest()[:8])
|
| 323 |
-
try:
|
| 324 |
-
src = orig = None
|
| 325 |
-
for ev in download_gen(link, job):
|
| 326 |
-
if ev[0] == "p":
|
| 327 |
-
yield render(ev[1]), outputs or None, "\n".join(urls)
|
| 328 |
-
else:
|
| 329 |
-
src, orig = ev[1], ev[2]
|
| 330 |
-
logs.append(f"✅ Imepakuliwa: {os.path.basename(src)} ({human_size(os.path.getsize(src))})")
|
| 331 |
-
title = clean_title(orig)
|
| 332 |
-
dst = os.path.join(OUT_DIR, f"{slug_file(title)}.mp4")
|
| 333 |
-
if os.path.exists(dst):
|
| 334 |
-
if dst in outputs: # jina limegongana ndani ya kundi hili moja
|
| 335 |
-
dst = os.path.join(OUT_DIR, f"{slug_file(title)}-{i}.mp4")
|
| 336 |
-
else: # faili la zamani la kikao kilichopita: liandike upya, jina libaki sahihi
|
| 337 |
-
os.remove(dst)
|
| 338 |
-
out = None
|
| 339 |
-
for ev in convert_gen(ff, src, dst, mode, height):
|
| 340 |
-
if ev[0] == "p":
|
| 341 |
-
yield render(ev[1]), outputs or None, "\n".join(urls)
|
| 342 |
-
else:
|
| 343 |
-
out = ev[1]
|
| 344 |
-
logs.append(f"✅ MP4 tayari: {os.path.basename(out)} ({human_size(os.path.getsize(out))})")
|
| 345 |
-
outputs.append(out)
|
| 346 |
-
if do_upload:
|
| 347 |
-
logs.append("☁️ Inapakia kwenye HF Dataset...")
|
| 348 |
-
yield render(), outputs, "\n".join(urls)
|
| 349 |
-
u = hf_upload(out, repo, token, os.path.basename(out))
|
| 350 |
-
urls.append(u)
|
| 351 |
-
logs.append(f"🔗 {u}")
|
| 352 |
-
except ToolError as e:
|
| 353 |
-
logs.append(f"❌ {e}")
|
| 354 |
-
except Exception as e:
|
| 355 |
-
logs.append(f"❌ Hitilafu: {e}")
|
| 356 |
-
finally:
|
| 357 |
-
shutil.rmtree(job, ignore_errors=True)
|
| 358 |
-
yield render(), outputs or None, "\n".join(urls)
|
| 359 |
-
logs.append("\n" + "═" * 60)
|
| 360 |
-
logs.append(f"🏁 Imekamilika: {len(outputs)}/{len(links)} zimefanikiwa.")
|
| 361 |
-
if outputs:
|
| 362 |
-
logs.append("Pakua MP4 kwenye kisanduku cha Download. Zinahifadhiwa kwa masaa 6 tu kwenye Space.")
|
| 363 |
-
yield render(), outputs or None, "\n".join(urls)
|
| 364 |
-
finally:
|
| 365 |
-
_lock.release()
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
# ── UI ───────────────────────────────────────────────────────
|
| 369 |
-
CSS = """
|
| 370 |
-
body, .gradio-container { background:#060810 !important; color:#c8ffd4 !important; }
|
| 371 |
-
.gradio-container { max-width: 1200px !important; margin: 0 auto !important; }
|
| 372 |
-
textarea, input[type="text"], input[type="password"] { background:#090d12 !important; color:#00ff88 !important; border:1px solid #1e4a3a !important; }
|
| 373 |
-
#log textarea { background:#040710 !important; color:#b8ffcc !important; font-family: monospace !important; font-size:0.85em !important; }
|
| 374 |
-
button.primary { background: linear-gradient(135deg,#00cc66,#0099ff) !important; color:#000 !important; border:none !important; font-weight:700 !important; }
|
| 375 |
-
footer { display:none !important; }
|
| 376 |
-
"""
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
def build_ui():
|
| 380 |
-
import gradio as gr
|
| 381 |
-
with gr.Blocks(title="DRIVE → MP4", css=CSS) as demo:
|
| 382 |
-
gr.Markdown(
|
| 383 |
-
"# 🎬 DRIVE → MP4\n"
|
| 384 |
-
"Weka viungo vya **Google Drive** (kimoja kwa kila mstari; faili lazima liwe *Anyone with the link*) "
|
| 385 |
-
"au viungo vya moja kwa moja vya video. Inapakua, inabadilisha kuwa **MP4 (H.264 + AAC)** inayocheza kila mahali, "
|
| 386 |
-
"na inaweza kuipakia kwenye HF Dataset ili upate **kiungo cha moja kwa moja**."
|
| 387 |
-
)
|
| 388 |
-
with gr.Row():
|
| 389 |
-
with gr.Column(scale=1, min_width=340):
|
| 390 |
-
m_links = gr.Textbox(label="Viungo (kimoja kwa kila mstari)", lines=5,
|
| 391 |
-
placeholder="https://drive.google.com/file/d/....../view")
|
| 392 |
-
m_mode = gr.Radio(choices=["Auto (inapendekezwa)", "Remux tu (haraka, bila kupoteza ubora)", "Re-encode kamili (H.264 + AAC)"],
|
| 393 |
-
value="Auto (inapendekezwa)", label="Njia ya kubadilisha")
|
| 394 |
-
m_res = gr.Radio(choices=["Asili", "720p", "480p"], value="Asili",
|
| 395 |
-
label="Ubora (unatumika kama re-encode inafanyika)")
|
| 396 |
-
m_up = gr.Checkbox(label="Pakia kwenye HF Dataset (pata kiungo cha moja kwa moja)", value=False)
|
| 397 |
-
m_repo = gr.Textbox(label="Dataset repo", placeholder="username/jaynes-videos", lines=1)
|
| 398 |
-
m_tok = gr.Textbox(label="HF Token (write) — au weka HF_TOKEN kwenye Space Secrets", type="password", lines=1)
|
| 399 |
-
m_btn = gr.Button("⚡ CHUKUA & BADILISHA KUWA MP4", variant="primary")
|
| 400 |
-
m_files = gr.File(label="📥 Download MP4", interactive=False, file_count="multiple")
|
| 401 |
-
with gr.Column(scale=2):
|
| 402 |
-
m_log = gr.Textbox(label="Log (live)", lines=18, max_lines=300, elem_id="log",
|
| 403 |
-
placeholder="Bandika viungo kisha bonyeza kitufe. Maendeleo yataonekana hapa papo hapo.")
|
| 404 |
-
m_urls = gr.Textbox(label="🔗 Viungo vya moja kwa moja (kama umepakia)", lines=4,
|
| 405 |
-
placeholder="Viungo vya MP4 vitaonekana hapa.")
|
| 406 |
-
m_btn.click(fn=run_pipeline, inputs=[m_links, m_mode, m_res, m_up, m_repo, m_tok],
|
| 407 |
-
outputs=[m_log, m_files, m_urls])
|
| 408 |
-
return demo
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
demo = build_ui()
|
| 412 |
-
|
| 413 |
-
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