deepuurf commited on
Commit
4cbf437
Β·
verified Β·
1 Parent(s): db86168

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +367 -0
app.py CHANGED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import os
4
+ import shutil
5
+ import uuid
6
+ import json
7
+ import threading
8
+ import random
9
+ import string
10
+ import time
11
+ import multiprocessing
12
+
13
+ CPU_THREADS = str(multiprocessing.cpu_count())
14
+
15
+ # ---------- Persistent storage setup ----------
16
+ BASE_DIR = os.path.join(os.getcwd(), "job_data")
17
+ JOBS_FILE = os.path.join(BASE_DIR, "jobs.json")
18
+ os.makedirs(BASE_DIR, exist_ok=True)
19
+
20
+ _lock = threading.Lock()
21
+
22
+ def _load_jobs():
23
+ if not os.path.exists(JOBS_FILE):
24
+ return {}
25
+ try:
26
+ with open(JOBS_FILE, "r") as f:
27
+ return json.load(f)
28
+ except Exception:
29
+ return {}
30
+
31
+ def _save_jobs(jobs):
32
+ with open(JOBS_FILE, "w") as f:
33
+ json.dump(jobs, f, indent=2)
34
+
35
+ def _update_job(code, **kwargs):
36
+ with _lock:
37
+ jobs = _load_jobs()
38
+ if code not in jobs:
39
+ jobs[code] = {}
40
+ jobs[code].update(kwargs)
41
+ _save_jobs(jobs)
42
+
43
+ def _get_job(code):
44
+ jobs = _load_jobs()
45
+ return jobs.get(code)
46
+
47
+ def random_code():
48
+ return "".join(random.choices(string.ascii_uppercase + string.digits, k=6))
49
+
50
+ # ---------- Video helpers ----------
51
+ RES_MAP = {
52
+ "480p (sabse fast)": (854, 480),
53
+ "720p (balanced)": (1280, 720),
54
+ "1080p (best quality, slow)": (1920, 1080),
55
+ }
56
+
57
+ def get_duration(path):
58
+ try:
59
+ out = subprocess.run(
60
+ ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path],
61
+ capture_output=True, text=True
62
+ )
63
+ return max(0.1, float(out.stdout.strip()))
64
+ except Exception:
65
+ return 0.1
66
+
67
+ def build_audio_filter():
68
+ pitch_shift = random.uniform(0.97, 1.03)
69
+ tempo = random.uniform(0.98, 1.02)
70
+ eq_freq = random.choice([200, 500, 1000, 3000])
71
+ eq_gain = random.uniform(-2, 2)
72
+ filters = [
73
+ f"asetrate=44100*{pitch_shift},aresample=44100",
74
+ f"atempo={tempo/pitch_shift:.4f}",
75
+ f"equalizer=f={eq_freq}:t=q:w=1:g={eq_gain:.2f}",
76
+ f"aecho=0.6:0.3:8:0.15",
77
+ ]
78
+ return ",".join(filters)
79
+
80
+
81
+ def run_ffmpeg_with_progress(cmd, code, total_duration, base_pct, weight_pct):
82
+ """Runs ffmpeg, parses -progress output, updates job with percent/speed/eta live."""
83
+ cmd = [cmd[0], "-y", "-progress", "pipe:1", "-nostats"] + cmd[2:]
84
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
85
+ text=True, bufsize=1)
86
+ error_lines = []
87
+ last_write = 0
88
+ out_time_sec = 0.0
89
+ speed_val = 0.0
90
+
91
+ for line in proc.stdout:
92
+ line = line.strip()
93
+ if "=" in line:
94
+ key, _, val = line.partition("=")
95
+ if key == "out_time_ms":
96
+ try:
97
+ out_time_sec = int(val) / 1_000_000
98
+ except ValueError:
99
+ pass
100
+ elif key == "speed":
101
+ try:
102
+ speed_val = float(val.replace("x", "").strip())
103
+ except ValueError:
104
+ speed_val = 0.0
105
+ else:
106
+ error_lines.append(line)
107
+
108
+ now = time.time()
109
+ if now - last_write > 0.7:
110
+ local_pct = min(99, (out_time_sec / total_duration) * 100) if total_duration > 0 else 0
111
+ overall_pct = round(base_pct + (weight_pct * local_pct / 100), 1)
112
+ remaining = max(0, total_duration - out_time_sec)
113
+ eta = round(remaining / speed_val, 1) if speed_val > 0 else None
114
+ _update_job(code, progress=overall_pct, speed=round(speed_val, 2),
115
+ eta_seconds=eta, status="processing")
116
+ last_write = now
117
+
118
+ proc.wait()
119
+ return proc.returncode == 0, "\n".join(error_lines[-15:])
120
+
121
+
122
+ def do_merge(video1, video2, resize_mode, resolution_choice, change_audio_dna, work_dir, output_path, code):
123
+ try:
124
+ d1 = get_duration(video1)
125
+ d2 = get_duration(video2)
126
+ total = d1 + d2
127
+
128
+ if resize_mode == "Fast (same resolution/codec required)" and not change_audio_dna:
129
+ list_file = os.path.join(work_dir, "list.txt")
130
+ with open(list_file, "w") as f:
131
+ f.write(f"file '{video1}'\n")
132
+ f.write(f"file '{video2}'\n")
133
+
134
+ cmd = ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file, "-c", "copy", output_path]
135
+ ok, err = run_ffmpeg_with_progress(cmd, code, total, 0, 100)
136
+ if ok:
137
+ _update_job(code, progress=100)
138
+ return True, "βœ… Merge ho gaya! (fast copy mode)"
139
+ # fallback to re-encode below
140
+
141
+ # Re-encode path
142
+ norm1 = os.path.join(work_dir, "norm1.mp4")
143
+ norm2 = os.path.join(work_dir, "norm2.mp4")
144
+ target_w, target_h = RES_MAP.get(resolution_choice, (1280, 720))
145
+
146
+ w1 = (d1 / total * 90) if total > 0 else 45
147
+ w2 = 90 - w1
148
+
149
+ for idx, (src, dst, base, weight, dur) in enumerate([
150
+ (video1, norm1, 0, w1, d1),
151
+ (video2, norm2, w1, w2, d2),
152
+ ]):
153
+ audio_filter_str = "aresample=44100"
154
+ if change_audio_dna:
155
+ audio_filter_str = build_audio_filter()
156
+
157
+ cmd = [
158
+ "ffmpeg", "-y", "-threads", CPU_THREADS, "-i", src,
159
+ "-vf", f"scale={target_w}:{target_h}:force_original_aspect_ratio=decrease:flags=fast_bilinear,"
160
+ f"pad={target_w}:{target_h}:(ow-iw)/2:(oh-ih)/2,setsar=1",
161
+ "-af", audio_filter_str,
162
+ "-r", "30",
163
+ "-c:v", "libx264", "-preset", "ultrafast", "-crf", "26",
164
+ "-c:a", "aac", "-b:a", "128k", "-ar", "44100", "-ac", "2",
165
+ dst
166
+ ]
167
+ ok, err = run_ffmpeg_with_progress(cmd, code, dur, base, weight)
168
+ if not ok:
169
+ return False, f"❌ Normalize error: {err}"
170
+
171
+ _update_job(code, progress=95)
172
+ list_file = os.path.join(work_dir, "list2.txt")
173
+ with open(list_file, "w") as f:
174
+ f.write(f"file '{norm1}'\n")
175
+ f.write(f"file '{norm2}'\n")
176
+
177
+ cmd = ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file, "-c", "copy", output_path]
178
+ result = subprocess.run(cmd, capture_output=True, text=True)
179
+ if result.returncode != 0:
180
+ return False, f"❌ Merge error: {result.stderr[-400:]}"
181
+
182
+ _update_job(code, progress=100)
183
+ dna_note = " + audio DNA badla gaya" if change_audio_dna else ""
184
+ return True, f"βœ… Merge ho gaya!{dna_note}"
185
+
186
+ except Exception as e:
187
+ return False, f"❌ Error: {str(e)}"
188
+
189
+
190
+ def run_job_background(code, v1_saved, v2_saved, resize_mode, resolution_choice, change_audio_dna):
191
+ job_dir = os.path.join(BASE_DIR, code)
192
+ output_path = os.path.join(job_dir, "output.mp4")
193
+ try:
194
+ ok, msg = do_merge(v1_saved, v2_saved, resize_mode, resolution_choice, change_audio_dna, job_dir, output_path, code)
195
+ if ok and os.path.exists(output_path):
196
+ _update_job(code, status="done", message=msg, output=output_path, progress=100,
197
+ finished_at=time.strftime("%Y-%m-%d %H:%M:%S"))
198
+ else:
199
+ _update_job(code, status="error", message=msg,
200
+ finished_at=time.strftime("%Y-%m-%d %H:%M:%S"))
201
+ except Exception as e:
202
+ _update_job(code, status="error", message=f"❌ Error: {str(e)}",
203
+ finished_at=time.strftime("%Y-%m-%d %H:%M:%S"))
204
+
205
+
206
+ def submit_job(video1, video2, resize_mode, resolution_choice, change_audio_dna, custom_code):
207
+ if video1 is None or video2 is None:
208
+ return "❌ Dono videos upload karo pehle!", "", ""
209
+
210
+ code = (custom_code or "").strip().upper()
211
+ if code:
212
+ # basic sanitize: keep only alnum
213
+ code = "".join(c for c in code if c.isalnum())[:20]
214
+ existing = _get_job(code)
215
+ if existing and existing.get("status") in ("processing", "done"):
216
+ return f"❌ Code '{code}' pehle se use ho raha hai. Doosra naam try karo.", "", ""
217
+ if not code:
218
+ code = random_code()
219
+
220
+ job_dir = os.path.join(BASE_DIR, code)
221
+ os.makedirs(job_dir, exist_ok=True)
222
+
223
+ v1_saved = os.path.join(job_dir, "input1" + os.path.splitext(video1)[1])
224
+ v2_saved = os.path.join(job_dir, "input2" + os.path.splitext(video2)[1])
225
+ shutil.copy(video1, v1_saved)
226
+ shutil.copy(video2, v2_saved)
227
+
228
+ _update_job(code, status="processing", message="⏳ Processing shuru ho gayi...", progress=0,
229
+ speed=0, eta_seconds=None, created_at=time.strftime("%Y-%m-%d %H:%M:%S"))
230
+
231
+ t = threading.Thread(
232
+ target=run_job_background,
233
+ args=(code, v1_saved, v2_saved, resize_mode, resolution_choice, change_audio_dna),
234
+ daemon=True
235
+ )
236
+ t.start()
237
+
238
+ return (f"βœ… Submit ho gaya! Tera code hai: **{code}**\n\n"
239
+ f"Tab band kar de chahe, processing background me chalti rahegi. "
240
+ f"'Check Status' tab me ye code daal ke live progress dekh sakta hai."), code, code
241
+
242
+
243
+ def progress_bar_html(pct, speed, eta_seconds, status):
244
+ pct = max(0, min(100, pct or 0))
245
+ color = "#22c55e" if status == "done" else ("#ef4444" if status == "error" else "#f97316")
246
+ speed_txt = f"{speed}x" if speed else "β€”"
247
+ if eta_seconds is not None:
248
+ m, s = divmod(int(eta_seconds), 60)
249
+ eta_txt = f"{m}m {s}s" if m else f"{s}s"
250
+ else:
251
+ eta_txt = "calculating..."
252
+
253
+ return f"""
254
+ <div style="font-family:sans-serif;">
255
+ <div style="background:#e5e7eb;border-radius:8px;overflow:hidden;height:28px;width:100%;">
256
+ <div style="background:{color};height:100%;width:{pct}%;transition:width 0.5s;
257
+ display:flex;align-items:center;justify-content:center;color:white;font-weight:bold;font-size:13px;">
258
+ {pct}%
259
+ </div>
260
+ </div>
261
+ <div style="display:flex;justify-content:space-between;margin-top:6px;font-size:13px;color:#374151;">
262
+ <span>⚑ Speed: <b>{speed_txt}</b></span>
263
+ <span>⏱ ETA: <b>{eta_txt}</b></span>
264
+ </div>
265
+ </div>
266
+ """
267
+
268
+
269
+ def check_status(code):
270
+ if not code or not code.strip():
271
+ return "⚠️ Code daalo pehle", progress_bar_html(0, 0, None, "idle"), None
272
+ code = "".join(c for c in code.strip().upper() if c.isalnum())
273
+ job = _get_job(code)
274
+ if not job:
275
+ return "❌ Ye code nahi mila. Sahi code check karo.", progress_bar_html(0, 0, None, "idle"), None
276
+
277
+ status = job.get("status", "unknown")
278
+ pct = job.get("progress", 0)
279
+ speed = job.get("speed", 0)
280
+ eta = job.get("eta_seconds")
281
+ html = progress_bar_html(pct, speed, eta, status)
282
+
283
+ if status == "processing":
284
+ return f"⏳ Processing chal rahi hai... ({pct}%)", html, None
285
+ elif status == "done":
286
+ return job.get("message", "βœ… Ready hai!"), html, job.get("output")
287
+ elif status == "error":
288
+ return job.get("message", "❌ Kuch error aaya"), html, None
289
+ return "⚠️ Unknown status", html, None
290
+
291
+
292
+ def get_history():
293
+ jobs = _load_jobs()
294
+ if not jobs:
295
+ return "Abhi tak koi job submit nahi hui."
296
+ rows = ["| Code | Status | Progress | Time |", "|------|--------|----------|------|"]
297
+ for code, job in sorted(jobs.items(), key=lambda x: x[1].get("created_at", ""), reverse=True)[:20]:
298
+ rows.append(f"| {code} | {job.get('status','?')} | {job.get('progress',0)}% | {job.get('created_at','?')} |")
299
+ return "\n".join(rows)
300
+
301
+
302
+ # ---------- UI ----------
303
+ with gr.Blocks(title="Video Merger - 2 Videos Jodo") as demo:
304
+ gr.Markdown("# 🎬 Video Merger\nDo videos upload karo, background me merge hoga β€” tab band karo chahe!")
305
+
306
+ with gr.Tab("πŸ”— Video Merge Karo"):
307
+ with gr.Row():
308
+ video1_input = gr.Video(label="Pehla Video")
309
+ video2_input = gr.Video(label="Dusra Video")
310
+
311
+ resize_mode = gr.Radio(
312
+ choices=["Fast (same resolution/codec required)", "Safe (auto resize + re-encode, thoda slow)"],
313
+ value="Fast (same resolution/codec required)",
314
+ label="Mode"
315
+ )
316
+
317
+ resolution_choice = gr.Radio(
318
+ choices=list(RES_MAP.keys()),
319
+ value="480p (sabse fast)",
320
+ label="Resolution (sirf Safe mode ke liye)"
321
+ )
322
+
323
+ change_audio_dna = gr.Checkbox(
324
+ label="🎡 Audio DNA badlo (pitch/EQ/echo halka change)",
325
+ value=False
326
+ )
327
+
328
+ custom_code_input = gr.Textbox(
329
+ label="Apna Custom Job Code (optional β€” khali chhodo to random mil jayega)",
330
+ placeholder="jaise: MYJOB01"
331
+ )
332
+
333
+ submit_btn = gr.Button("πŸš€ Submit Karo (Background me Process Hoga)", variant="primary")
334
+ submit_status = gr.Markdown()
335
+ code_box = gr.Textbox(label="Tera Job Code (isse save kar le)", interactive=False)
336
+ goto_code_state = gr.Textbox(visible=False)
337
+
338
+ submit_btn.click(
339
+ fn=submit_job,
340
+ inputs=[video1_input, video2_input, resize_mode, resolution_choice, change_audio_dna, custom_code_input],
341
+ outputs=[submit_status, code_box, goto_code_state]
342
+ )
343
+
344
+ with gr.Tab("πŸ“₯ Check Status / Download"):
345
+ gr.Markdown("Apna job code daalo β€” live speed, progress % aur ETA yahin dikhega.")
346
+ code_input = gr.Textbox(label="Job Code")
347
+ with gr.Row():
348
+ check_btn = gr.Button("πŸ” Check Status", variant="primary")
349
+ auto_refresh = gr.Checkbox(label="πŸ”„ Auto-refresh (har 2 sec)", value=True)
350
+ status_output = gr.Markdown()
351
+ progress_html = gr.HTML(progress_bar_html(0, 0, None, "idle"))
352
+ result_video = gr.Video(label="Merged Video (jab ready ho)")
353
+
354
+ check_btn.click(fn=check_status, inputs=[code_input], outputs=[status_output, progress_html, result_video])
355
+
356
+ timer = gr.Timer(2.0, active=True)
357
+ timer.tick(fn=check_status, inputs=[code_input], outputs=[status_output, progress_html, result_video])
358
+
359
+ with gr.Tab("πŸ“œ History"):
360
+ gr.Markdown("Recent 20 jobs (sabke liye shared list)")
361
+ history_output = gr.Markdown()
362
+ refresh_btn = gr.Button("πŸ”„ Refresh History")
363
+ refresh_btn.click(fn=get_history, inputs=[], outputs=[history_output])
364
+ demo.load(fn=get_history, inputs=[], outputs=[history_output])
365
+
366
+ if __name__ == "__main__":
367
+ demo.launch()