Hydui commited on
Commit
fea03b0
·
verified ·
1 Parent(s): 487856d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +362 -127
app.py CHANGED
@@ -6,12 +6,22 @@ import shutil
6
  import tempfile
7
  import json
8
  import time
 
 
 
9
  from pathlib import Path
 
 
 
 
 
10
 
11
  class UltimateVideoEvader:
12
  def __init__(self):
13
  self.ffmpeg_path = self._find_ffmpeg()
14
  self.ffprobe_path = self.ffmpeg_path.replace("ffmpeg", "ffprobe")
 
 
15
 
16
  def _find_ffmpeg(self):
17
  for cmd in ["ffmpeg", "/usr/bin/ffmpeg"]:
@@ -25,7 +35,7 @@ class UltimateVideoEvader:
25
  self.ffprobe_path,
26
  "-v", "error",
27
  "-select_streams", "v:0",
28
- "-show_entries", "stream=width,height",
29
  "-of", "json",
30
  input_file
31
  ]
@@ -33,10 +43,13 @@ class UltimateVideoEvader:
33
  if result.returncode == 0:
34
  data = json.loads(result.stdout)
35
  if "streams" in data and data["streams"]:
36
- return (int(data["streams"][0]["width"]), int(data["streams"][0]["height"]))
 
 
 
37
  except:
38
  pass
39
- return (1920, 1080)
40
 
41
  def _random_float(self, a, b):
42
  return round(random.uniform(a, b), 4)
@@ -44,46 +57,26 @@ class UltimateVideoEvader:
44
  def build_brutal_command(self, input_file, output_file):
45
  cmd = [self.ffmpeg_path, "-i", input_file]
46
 
47
- # 1. मेटाडेटा हटाएँ
48
  cmd.extend(["-map_metadata", "-1"])
49
 
50
- # 2. रिज़ॉल्यूशन – 0.6x से 1.4x
51
  scale = self._random_float(0.6, 1.4)
52
- w, h = self._get_resolution(input_file)
53
  new_w = int(w * scale)
54
  new_h = int(h * scale)
55
  new_w = new_w if new_w % 2 == 0 else new_w + 1
56
  new_h = new_h if new_h % 2 == 0 else new_h + 1
57
 
58
- # 3. फ़्रेमरेट – 15 से 60 fps
59
  fps = self._random_float(15, 60)
60
-
61
- # 4. स्पीड – 0.8x से 1.3x
62
  speed = self._random_float(0.8, 1.3)
63
-
64
- # 5. ऑडियो टेम्पो – 0.8 से 1.3 (स्पीड के साथ)
65
  tempo = self._random_float(0.8, 1.3) * speed
66
  tempo = min(tempo, 2.0)
67
-
68
- # 6. ऑडियो पिच – ±1 सेमीटोन
69
  pitch = self._random_float(-1.0, 1.0)
70
-
71
- # 7. शोर – 1 से 12 dB
72
  noise_db = self._random_float(1, 12)
73
-
74
- # 8. ब्राइटनेस – ±10%
75
  bright = self._random_float(-0.1, 0.1)
76
-
77
- # 9. कंट्रास्ट – 0.85x से 1.15x
78
  contrast = self._random_float(0.85, 1.15)
79
-
80
- # 10. सैचुरेशन – 0.7x से 1.3x
81
  saturation = self._random_float(0.7, 1.3)
82
-
83
- # 11. ह्यू – 0 से 360°
84
  hue = self._random_float(0, 360)
85
 
86
- # 12. क्रॉप + पैड
87
  crop_percent = self._random_float(0.90, 0.98)
88
  crop_w = int(new_w * crop_percent)
89
  crop_h = int(new_h * crop_percent)
@@ -92,7 +85,6 @@ class UltimateVideoEvader:
92
  pad_left = (new_w - crop_w) // 2
93
  pad_top = (new_h - crop_h) // 2
94
 
95
- # ———— सभी वीडियो फ़िल्टर्स एक chain में ————
96
  video_filters = []
97
  video_filters.append(f"scale={new_w}:{new_h}")
98
  video_filters.append(f"setpts={1/speed}*PTS")
@@ -101,31 +93,21 @@ class UltimateVideoEvader:
101
  video_filters.append(f"hue=H={hue}")
102
  video_filters.append(f"crop={crop_w}:{crop_h}:{pad_left}:{pad_top},pad={new_w}:{new_h}:{pad_left}:{pad_top}")
103
 
104
- # —— मिरर (hflip / vflip) हटा दिया गया है ——
105
- # (पहले यहाँ hflip और vflip थे – अब हटा दिए गए)
106
-
107
- # रैंडम ऑफ़सेट
108
  offset = random.randint(0, 120)
109
  if offset > 0:
110
  video_filters.append(f"trim=start_frame={offset}")
111
 
112
- # रिवर्स
113
  if random.choice([True, False]):
114
  video_filters.append("reverse")
115
 
116
- # ब्लर
117
  if random.choice([True, False]):
118
  blur = self._random_float(0.5, 2.0)
119
  video_filters.append(f"gblur=sigma={blur}")
120
 
121
- # सभी फ़िल्टर्स को जोड़ें
122
  filter_chain = ",".join(video_filters)
123
  cmd.extend(["-vf", filter_chain])
124
-
125
- # ———— फ़्रेमरेट (बिना -vsync के) ————
126
  cmd.extend(["-r", str(round(fps, 2))])
127
 
128
- # ———— ऑडियो फ़िल्टर्स ————
129
  audio_filters = []
130
  if 0.5 <= tempo <= 2.0:
131
  audio_filters.append(f"atempo={tempo}")
@@ -134,139 +116,392 @@ class UltimateVideoEvader:
134
  if audio_filters:
135
  cmd.extend(["-af", ",".join(audio_filters)])
136
 
137
- # ———— कोडेक ————
138
  codec = random.choice(["libx264", "libx265", "libvpx-vp9"])
139
  cmd.extend(["-c:v", codec])
140
 
141
- # ———— प्रीसेट ————
142
  preset = random.choice(["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow"])
143
  cmd.extend(["-preset", preset])
144
 
145
- # ———— CRF (क्वालिटी) ————
146
  crf = random.randint(18, 28)
147
  cmd.extend(["-crf", str(crf)])
148
 
149
- # ———— ऑडियो कोडेक ————
150
  audio_codec = random.choice(["aac", "libmp3lame"])
151
  cmd.extend(["-c:a", audio_codec, "-b:a", "128k"])
152
 
153
- # ———— कंटेनर ————
154
  container = random.choice(["mp4", "mkv", "mov"])
155
  base = os.path.splitext(output_file)[0]
156
  output_file = f"{base}.{container}"
157
 
158
- # ———— आउटपुट ————
159
  cmd.extend(["-y", output_file])
160
-
161
  return cmd, output_file
162
 
163
- def process_video(self, input_path, progress=gr.Progress()):
164
- progress(0, desc="तैयारी...")
165
- output_dir = tempfile.mkdtemp()
166
- output_base = os.path.join(output_dir, "evaded_video")
167
 
168
- cmd, final_output = self.build_brutal_command(input_path, output_base)
169
- progress(0.2, desc="FFmpeg कमांड तैयार...")
170
 
171
- progress(0.3, desc="प्रोसेसिंग शुरू (2-5 मिनट लग सकते हैं)...")
172
  try:
173
- subprocess.run(cmd, check=True, capture_output=True, text=True)
174
- except subprocess.CalledProcessError as e:
175
- return f"❌ त्रुटि:\n{e.stderr}", None
176
-
177
- progress(0.9, desc="फ़ाइल तैयार...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
- if os.path.exists(final_output) and os.path.getsize(final_output) > 0:
180
- progress(1.0, desc="✅ पूरा!")
181
- info = f"""✅ वीडियो सफलतापूर्वक प्रोसेस हो गया!
182
-
183
- लागू किए गए ट्रांसफ़ॉर्मेशन:
184
- • मेटाडेटा हटाया गया
185
- • रिज़ॉल्यूशन बदला गया ({scale:.2f}x)
186
- • फ़्रेमरेट बदला गया ({round(fps, 2)} fps)
187
- • स्पीड बदली गई ({speed:.2f}x)
188
- ��� ऑडियो टेम्पो बदला गया
189
- • ऑडियो पिच शिफ्ट किया गया
190
- • शोर डाला गया
191
- • ब्राइटनेस/कंट्रास्ट/सैचुरेशन बदला गया
192
- • ह्यू शिफ्ट किया गया
193
- • क्रॉप + पैड किया गया
194
- • रैंडम ऑफ़सेट लगाया गया
195
- • रिवर्स किया गया
196
- • ब्लर लगाया गया
197
- • कोडेक बदला गया
198
- • कंटेनर बदला गया
199
- • CRF/प्रीसेट बदला गया
200
-
201
- 📁 आउटपुट: {os.path.basename(final_output)}
202
- 📦 आकार: {round(os.path.getsize(final_output) / (1024*1024), 2)} MB
203
- """
204
- return info, final_output
205
- else:
206
- return "❌ आउटपुट नहीं बना। कृपया दोबारा प्रयास करें।", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
 
208
 
209
- # ===== Gradio Interface =====
210
  def create_interface():
211
- with gr.Blocks(title="Video Fingerprint Evader", theme=gr.themes.Soft()) as demo:
 
 
212
  gr.Markdown("""
213
- # 🚀 Video Fingerprint Evader – Copyright Bypass Tool
214
-
215
- **कैसे काम करता है:**
216
- 1. वीडियो अपलोड करें
217
- 2. "Process" बटन दबाएँ
218
- 3. 15+ ट्रांसफ़ॉर्मेशन लागू होंगे
219
- 4. आउटपुट डाउनलोड करें
220
-
221
- > ⚠️ **यह केवल तकनीकी प्रयोग के लिए है – उपयोगकर्ता स्वयं उत्तरदायी होगा।**
222
  """)
223
 
224
- with gr.Row():
225
- with gr.Column(scale=1):
226
- input_video = gr.File(
227
- label="📤 वीडियो अपलोड करें",
228
- file_types=[".mp4", ".mkv", ".avi", ".mov", ".webm", ".flv"],
229
- type="filepath"
230
- )
231
- process_btn = gr.Button("🔥 Process Video (Brutal Mode)", variant="primary")
232
- clear_btn = gr.Button("🗑️ Clear All")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
 
234
- with gr.Column(scale=1):
235
- output_video = gr.Video(label="📥 प्रोसेस्ड वीडियो", interactive=False)
236
- status_text = gr.Textbox(label="📊 स्टेटस", lines=10, interactive=False)
237
-
238
- evader = UltimateVideoEvader()
239
-
240
- def process(file_path):
241
- if file_path is None:
242
- return "❌ कृपया पहले वीडियो अपलोड करें।", None
243
- if not os.path.exists(file_path):
244
- return "❌ फ़ाइल मौजूद नहीं है।", None
245
- return evader.process_video(file_path)
246
-
247
- def clear_all():
248
- return None, None, ""
 
 
 
 
 
 
 
 
 
 
249
 
250
  process_btn.click(
251
- process,
252
  inputs=[input_video],
253
- outputs=[status_text, output_video]
254
  )
255
 
256
- clear_btn.click(
257
- clear_all,
 
 
 
 
 
 
 
 
 
 
 
 
258
  inputs=[],
259
- outputs=[input_video, output_video, status_text]
 
 
 
 
 
 
260
  )
261
 
262
- with gr.Row():
263
- gr.Markdown("""
264
- ### 🔧 ट्रांसफ़ॉर्मेशन की पूरी सूची (मिरर हटा दिया गया):
265
- मेटाडेटा हटाना · रिज़ॉल्यूशन स्केल · फ़्रेमरेट बदलना · स्पीड बदलना · ऑडियो टेम्पो · ऑडियो पिच · शोर · ब्राइटनेस/कंट्रास्ट/सैचुरेशन · ह्यू शिफ्ट · क्रॉप+पैड · ऑफ़सेट · रिवर्स · ब्लर · कोडेक बदलना · कंटेनर बदलना · CRF/प्रीसेट
266
- """)
 
 
 
 
 
 
 
 
 
267
 
268
  return demo
269
 
 
270
  if __name__ == "__main__":
271
  demo = create_interface()
272
  demo.launch(debug=True)
 
6
  import tempfile
7
  import json
8
  import time
9
+ import threading
10
+ import uuid
11
+ import re
12
  from pathlib import Path
13
+ from datetime import datetime
14
+ from queue import Queue
15
+
16
+ # ========== Global Job Storage ==========
17
+ jobs = {} # job_id -> {status, input_file, output_file, timestamp, progress, error, log_queue}
18
 
19
  class UltimateVideoEvader:
20
  def __init__(self):
21
  self.ffmpeg_path = self._find_ffmpeg()
22
  self.ffprobe_path = self.ffmpeg_path.replace("ffmpeg", "ffprobe")
23
+ self.output_base_dir = tempfile.mkdtemp(prefix="vfe_jobs_")
24
+ print(f"[*] Job output directory: {self.output_base_dir}")
25
 
26
  def _find_ffmpeg(self):
27
  for cmd in ["ffmpeg", "/usr/bin/ffmpeg"]:
 
35
  self.ffprobe_path,
36
  "-v", "error",
37
  "-select_streams", "v:0",
38
+ "-show_entries", "stream=width,height,duration",
39
  "-of", "json",
40
  input_file
41
  ]
 
43
  if result.returncode == 0:
44
  data = json.loads(result.stdout)
45
  if "streams" in data and data["streams"]:
46
+ w = int(data["streams"][0]["width"])
47
+ h = int(data["streams"][0]["height"])
48
+ duration = float(data["streams"][0].get("duration", 0))
49
+ return (w, h, duration)
50
  except:
51
  pass
52
+ return (1920, 1080, 0)
53
 
54
  def _random_float(self, a, b):
55
  return round(random.uniform(a, b), 4)
 
57
  def build_brutal_command(self, input_file, output_file):
58
  cmd = [self.ffmpeg_path, "-i", input_file]
59
 
 
60
  cmd.extend(["-map_metadata", "-1"])
61
 
 
62
  scale = self._random_float(0.6, 1.4)
63
+ w, h, duration = self._get_resolution(input_file)
64
  new_w = int(w * scale)
65
  new_h = int(h * scale)
66
  new_w = new_w if new_w % 2 == 0 else new_w + 1
67
  new_h = new_h if new_h % 2 == 0 else new_h + 1
68
 
 
69
  fps = self._random_float(15, 60)
 
 
70
  speed = self._random_float(0.8, 1.3)
 
 
71
  tempo = self._random_float(0.8, 1.3) * speed
72
  tempo = min(tempo, 2.0)
 
 
73
  pitch = self._random_float(-1.0, 1.0)
 
 
74
  noise_db = self._random_float(1, 12)
 
 
75
  bright = self._random_float(-0.1, 0.1)
 
 
76
  contrast = self._random_float(0.85, 1.15)
 
 
77
  saturation = self._random_float(0.7, 1.3)
 
 
78
  hue = self._random_float(0, 360)
79
 
 
80
  crop_percent = self._random_float(0.90, 0.98)
81
  crop_w = int(new_w * crop_percent)
82
  crop_h = int(new_h * crop_percent)
 
85
  pad_left = (new_w - crop_w) // 2
86
  pad_top = (new_h - crop_h) // 2
87
 
 
88
  video_filters = []
89
  video_filters.append(f"scale={new_w}:{new_h}")
90
  video_filters.append(f"setpts={1/speed}*PTS")
 
93
  video_filters.append(f"hue=H={hue}")
94
  video_filters.append(f"crop={crop_w}:{crop_h}:{pad_left}:{pad_top},pad={new_w}:{new_h}:{pad_left}:{pad_top}")
95
 
 
 
 
 
96
  offset = random.randint(0, 120)
97
  if offset > 0:
98
  video_filters.append(f"trim=start_frame={offset}")
99
 
 
100
  if random.choice([True, False]):
101
  video_filters.append("reverse")
102
 
 
103
  if random.choice([True, False]):
104
  blur = self._random_float(0.5, 2.0)
105
  video_filters.append(f"gblur=sigma={blur}")
106
 
 
107
  filter_chain = ",".join(video_filters)
108
  cmd.extend(["-vf", filter_chain])
 
 
109
  cmd.extend(["-r", str(round(fps, 2))])
110
 
 
111
  audio_filters = []
112
  if 0.5 <= tempo <= 2.0:
113
  audio_filters.append(f"atempo={tempo}")
 
116
  if audio_filters:
117
  cmd.extend(["-af", ",".join(audio_filters)])
118
 
 
119
  codec = random.choice(["libx264", "libx265", "libvpx-vp9"])
120
  cmd.extend(["-c:v", codec])
121
 
 
122
  preset = random.choice(["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow"])
123
  cmd.extend(["-preset", preset])
124
 
 
125
  crf = random.randint(18, 28)
126
  cmd.extend(["-crf", str(crf)])
127
 
 
128
  audio_codec = random.choice(["aac", "libmp3lame"])
129
  cmd.extend(["-c:a", audio_codec, "-b:a", "128k"])
130
 
 
131
  container = random.choice(["mp4", "mkv", "mov"])
132
  base = os.path.splitext(output_file)[0]
133
  output_file = f"{base}.{container}"
134
 
 
135
  cmd.extend(["-y", output_file])
 
136
  return cmd, output_file
137
 
138
+ def process_video_background(self, job_id, input_path):
139
+ """Background thread function with live logs"""
140
+ log_queue = jobs[job_id]["log_queue"]
 
141
 
142
+ def log(msg):
143
+ log_queue.put(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}")
144
 
 
145
  try:
146
+ log("🚀 Job started")
147
+ jobs[job_id]["status"] = "processing"
148
+ jobs[job_id]["progress"] = 10
149
+
150
+ job_dir = os.path.join(self.output_base_dir, job_id)
151
+ os.makedirs(job_dir, exist_ok=True)
152
+ output_base = os.path.join(job_dir, "evaded_video")
153
+
154
+ log("📦 Building FFmpeg command...")
155
+ cmd, final_output = self.build_brutal_command(input_path, output_base)
156
+ jobs[job_id]["progress"] = 20
157
+
158
+ # Copy input
159
+ input_copy = os.path.join(job_dir, "input_" + os.path.basename(input_path))
160
+ shutil.copy2(input_path, input_copy)
161
+ log(f"📁 Input file: {os.path.basename(input_path)}")
162
+
163
+ # Get input duration
164
+ _, _, duration = self._get_resolution(input_path)
165
+ if duration > 0:
166
+ log(f"⏱️ Input duration: {duration:.2f} seconds")
167
+
168
+ jobs[job_id]["progress"] = 25
169
+ log("⚙️ Starting FFmpeg processing...")
170
+
171
+ # Run FFmpeg with live stderr capture
172
+ process = subprocess.Popen(
173
+ cmd,
174
+ stdout=subprocess.PIPE,
175
+ stderr=subprocess.PIPE,
176
+ text=True,
177
+ bufsize=1,
178
+ universal_newlines=True
179
+ )
180
+
181
+ # Parse FFmpeg progress
182
+ speed_pattern = re.compile(r'speed=\s*([\d.]+)x')
183
+ fps_pattern = re.compile(r'fps=\s*([\d.]+)')
184
+ time_pattern = re.compile(r'time=(\d{2}):(\d{2}):(\d{2})\.(\d{2})')
185
+ frame_pattern = re.compile(r'frame=\s*(\d+)')
186
+ bitrate_pattern = re.compile(r'bitrate=\s*([\d.]+)')
187
+
188
+ start_time = time.time()
189
+ last_log_time = 0
190
+ processed_frames = 0
191
+
192
+ # Read stderr line by line
193
+ while True:
194
+ line = process.stderr.readline()
195
+ if not line:
196
+ break
197
+
198
+ line = line.strip()
199
+
200
+ # Parse progress info
201
+ if 'frame=' in line or 'time=' in line:
202
+ # Extract frame number
203
+ frame_match = frame_pattern.search(line)
204
+ if frame_match:
205
+ processed_frames = int(frame_match.group(1))
206
+
207
+ # Extract time
208
+ time_match = time_pattern.search(line)
209
+ if time_match:
210
+ h, m, s, cs = time_match.groups()
211
+ current_time = int(h) * 3600 + int(m) * 60 + int(s) + int(cs) / 100
212
+
213
+ # Extract speed
214
+ speed_match = speed_pattern.search(line)
215
+ speed_val = speed_match.group(1) if speed_match else "?"
216
+
217
+ # Extract FPS
218
+ fps_match = fps_pattern.search(line)
219
+ fps_val = fps_match.group(1) if fps_match else "?"
220
+
221
+ # Calculate ETA
222
+ if duration > 0 and time_match and speed_match:
223
+ elapsed = time.time() - start_time
224
+ if float(speed_val) > 0:
225
+ eta = (duration - current_time) / float(speed_val)
226
+ eta_min = int(eta // 60)
227
+ eta_sec = int(eta % 60)
228
+ eta_str = f"{eta_min}m {eta_sec}s"
229
+ else:
230
+ eta_str = "calculating..."
231
+
232
+ percent = min(100, int((current_time / duration) * 100)) if duration > 0 else 0
233
+ jobs[job_id]["progress"] = min(25 + int(percent * 0.7), 95)
234
+
235
+ # Log every 3 seconds
236
+ if time.time() - last_log_time > 3:
237
+ log(f"⏳ Progress: {percent}% | Time: {current_time:.1f}s/{duration:.1f}s | Speed: {speed_val}x | FPS: {fps_val} | ETA: {eta_str}")
238
+ last_log_time = time.time()
239
+
240
+ # Wait for process to finish
241
+ process.wait()
242
+
243
+ if process.returncode != 0:
244
+ jobs[job_id]["status"] = "failed"
245
+ jobs[job_id]["error"] = "FFmpeg error"
246
+ jobs[job_id]["progress"] = 0
247
+ log("❌ FFmpeg failed with error")
248
+ return
249
+
250
+ # Check output
251
+ if os.path.exists(final_output) and os.path.getsize(final_output) > 0:
252
+ jobs[job_id]["status"] = "completed"
253
+ jobs[job_id]["output_file"] = final_output
254
+ jobs[job_id]["progress"] = 100
255
+ jobs[job_id]["timestamp"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
256
+ file_size = round(os.path.getsize(final_output) / (1024 * 1024), 2)
257
+ log(f"✅ Processing complete! Output size: {file_size} MB")
258
+ log(f"📥 Download ready: {os.path.basename(final_output)}")
259
+ else:
260
+ jobs[job_id]["status"] = "failed"
261
+ jobs[job_id]["error"] = "Output file not created"
262
+ jobs[job_id]["progress"] = 0
263
+ log("❌ Output file not created")
264
+
265
+ except Exception as e:
266
+ jobs[job_id]["status"] = "failed"
267
+ jobs[job_id]["error"] = str(e)
268
+ jobs[job_id]["progress"] = 0
269
+ log(f"❌ Error: {str(e)}")
270
+
271
+ log("🏁 Job finished")
272
+ log_queue.put("__END__")
273
+
274
+ def start_job(self, input_path):
275
+ """Start a new background job"""
276
+ if not input_path or not os.path.exists(input_path):
277
+ return "❌ कोई फ़ाइल नहीं", None
278
+
279
+ job_id = str(uuid.uuid4())[:8]
280
+ log_queue = Queue()
281
+ jobs[job_id] = {
282
+ "status": "queued",
283
+ "input_file": input_path,
284
+ "output_file": None,
285
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
286
+ "progress": 0,
287
+ "error": None,
288
+ "job_id": job_id,
289
+ "log_queue": log_queue
290
+ }
291
+
292
+ # Start background thread
293
+ thread = threading.Thread(
294
+ target=self.process_video_background,
295
+ args=(job_id, input_path)
296
+ )
297
+ thread.daemon = True
298
+ thread.start()
299
 
300
+ return f"✅ Job started! ID: {job_id}\nआप इस टैब को बंद कर सकते हैं – बाद में Job History से डाउनलोड करें।", job_id
301
+
302
+ def get_job_status(self, job_id):
303
+ """Get status of a specific job"""
304
+ if job_id not in jobs:
305
+ return "❌ Job not found", None, None
306
+ job = jobs[job_id]
307
+ status = job["status"]
308
+ progress = job["progress"]
309
+ error = job.get("error", "")
310
+
311
+ status_text = f"Status: {status}\nProgress: {progress}%"
312
+ if error:
313
+ status_text += f"\nError: {error}"
314
+
315
+ output_file = job.get("output_file")
316
+ return status_text, output_file, status
317
+
318
+ def get_live_logs(self, job_id):
319
+ """Get live logs from queue"""
320
+ if job_id not in jobs:
321
+ return "No job found"
322
+ queue = jobs[job_id].get("log_queue")
323
+ if not queue:
324
+ return "Log queue not initialized"
325
+
326
+ logs = []
327
+ while not queue.empty():
328
+ msg = queue.get()
329
+ if msg == "__END__":
330
+ break
331
+ logs.append(msg)
332
+ return "\n".join(logs) if logs else "Waiting for logs..."
333
+
334
+ def get_all_jobs(self):
335
+ """Get list of all jobs for history"""
336
+ job_list = []
337
+ for job_id, job in jobs.items():
338
+ job_list.append({
339
+ "job_id": job_id,
340
+ "status": job["status"],
341
+ "timestamp": job.get("timestamp", "Unknown"),
342
+ "output_file": job.get("output_file", ""),
343
+ "input_file": os.path.basename(job.get("input_file", "unknown")),
344
+ "progress": job.get("progress", 0),
345
+ "has_output": job.get("output_file") is not None and os.path.exists(job.get("output_file", ""))
346
+ })
347
+ job_list.sort(key=lambda x: x["timestamp"], reverse=True)
348
+ return job_list
349
 
350
 
351
+ # ========== Gradio Interface ==========
352
  def create_interface():
353
+ evader = UltimateVideoEvader()
354
+
355
+ with gr.Blocks(title="Video Fingerprint Evader", theme=gr.themes.Soft(), fill_height=True) as demo:
356
  gr.Markdown("""
357
+ # 🚀 Video Fingerprint Evader – Live Logs + Background Processing
358
+ **Live Logs में ETA, Speed, FPS और Progress की पूरी जानकारी देखें।**
 
 
 
 
 
 
 
359
  """)
360
 
361
+ with gr.Tab("📤 Upload & Process"):
362
+ with gr.Row():
363
+ with gr.Column(scale=1):
364
+ input_video = gr.File(
365
+ label="📤 वी��ियो अपलोड करें",
366
+ file_types=[".mp4", ".mkv", ".avi", ".mov", ".webm", ".flv"],
367
+ type="filepath"
368
+ )
369
+ process_btn = gr.Button("🔥 Process in Background", variant="primary")
370
+ job_status = gr.Textbox(label="📊 Job Status", lines=3, interactive=False)
371
+ current_job_id = gr.Textbox(label="🆔 Job ID", visible=False)
372
+ download_btn = gr.Button("📥 Download Completed Video", variant="secondary")
373
+ download_output = gr.File(label="📥 Download", visible=False)
374
+
375
+ with gr.Column(scale=2):
376
+ log_display = gr.Textbox(
377
+ label="📋 Live Logs",
378
+ lines=25,
379
+ interactive=False,
380
+ autoscroll=True
381
+ )
382
+ refresh_logs_btn = gr.Button("🔄 Refresh Logs", variant="secondary")
383
+ status_display = gr.Textbox(label="📊 Quick Status", lines=2, interactive=False)
384
+
385
+ with gr.Tab("📜 Job History"):
386
+ gr.Markdown("### सभी Jobs की History")
387
+ history_refresh_btn = gr.Button("🔄 Refresh History")
388
+ job_history = gr.Dataframe(
389
+ headers=["Job ID", "Input File", "Status", "Timestamp", "Progress", "Download"],
390
+ datatype=["str", "str", "str", "str", "number", "str"],
391
+ label="Job History",
392
+ interactive=False
393
+ )
394
+ history_download = gr.File(label="📥 Download", visible=False)
395
+
396
+ # ===== Processing Functions =====
397
+
398
+ def start_process(file_path):
399
+ if not file_path:
400
+ return "❌ कृपया पहले वीडियो अपलोड करें।", "", "No job", ""
401
+ status, job_id = evader.start_job(file_path)
402
+ return status, job_id, f"Job {job_id} running...", ""
403
+
404
+ def refresh_logs(job_id):
405
+ if not job_id or job_id not in jobs:
406
+ return "❌ No job running or invalid ID", "No job"
407
+ logs = evader.get_live_logs(job_id)
408
+ _, _, status = evader.get_job_status(job_id)
409
+ return logs, f"Status: {status} | Progress: {jobs.get(job_id, {}).get('progress', 0)}%"
410
+
411
+ def refresh_full_status(job_id):
412
+ if not job_id or job_id not in jobs:
413
+ return "❌ No job", "", False
414
+ status_text, output_file, status = evader.get_job_status(job_id)
415
+ download_visible = status == "completed" and output_file
416
+ return status_text, gr.update(visible=bool(download_visible))
417
+
418
+ def download_completed(job_id):
419
+ if not job_id or job_id not in jobs:
420
+ return None
421
+ job = jobs.get(job_id)
422
+ if job and job.get("status") == "completed" and job.get("output_file"):
423
+ return job["output_file"]
424
+ return None
425
+
426
+ def refresh_history():
427
+ job_list = evader.get_all_jobs()
428
+ if not job_list:
429
+ return gr.update(value=[], visible=True)
430
 
431
+ rows = []
432
+ for j in job_list:
433
+ download_link = "✅ Ready" if j["has_output"] else ("⏳ Processing" if j["status"] == "processing" else "❌ Failed")
434
+ rows.append([
435
+ j["job_id"],
436
+ j["input_file"],
437
+ j["status"],
438
+ j["timestamp"],
439
+ f"{j['progress']}%",
440
+ download_link
441
+ ])
442
+ return gr.update(value=rows, visible=True)
443
+
444
+ def download_from_history(evt: gr.SelectData, history_data):
445
+ if not history_data:
446
+ return None
447
+ row_idx = evt.index[0] if isinstance(evt.index, (list, tuple)) else evt.index
448
+ if row_idx < len(history_data):
449
+ job_id = history_data[row_idx][0]
450
+ job = jobs.get(job_id)
451
+ if job and job.get("status") == "completed" and job.get("output_file"):
452
+ return job["output_file"]
453
+ return None
454
+
455
+ # ===== Event Handlers =====
456
 
457
  process_btn.click(
458
+ start_process,
459
  inputs=[input_video],
460
+ outputs=[job_status, current_job_id, status_display, log_display]
461
  )
462
 
463
+ refresh_logs_btn.click(
464
+ refresh_logs,
465
+ inputs=[current_job_id],
466
+ outputs=[log_display, status_display]
467
+ )
468
+
469
+ download_btn.click(
470
+ download_completed,
471
+ inputs=[current_job_id],
472
+ outputs=[download_output]
473
+ )
474
+
475
+ history_refresh_btn.click(
476
+ refresh_history,
477
  inputs=[],
478
+ outputs=[job_history]
479
+ )
480
+
481
+ job_history.select(
482
+ download_from_history,
483
+ inputs=[job_history],
484
+ outputs=[history_download]
485
  )
486
 
487
+ # ===== Auto-refresh with timer =====
488
+ def auto_refresh():
489
+ import time
490
+ while True:
491
+ time.sleep(5)
492
+ yield
493
+
494
+ # Add a small timer to auto-refresh logs periodically
495
+ demo.load(
496
+ refresh_logs,
497
+ inputs=[current_job_id],
498
+ outputs=[log_display, status_display],
499
+ every=5
500
+ )
501
 
502
  return demo
503
 
504
+
505
  if __name__ == "__main__":
506
  demo = create_interface()
507
  demo.launch(debug=True)