skylinkd commited on
Commit
2035308
Β·
verified Β·
1 Parent(s): 1c9d980

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +449 -175
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  import sys
3
  import re
@@ -258,7 +259,7 @@ def load_whisper_model(model_name="base"):
258
  with model_load_lock:
259
  if whisper_model is None or whisper_model_name != model_name:
260
  print(f"Loading Whisper model '{model_name}'... (This may download files on first run)")
261
- whisper_model = whisper.load_model(model_name, device="cpu")
262
  whisper_model_name = model_name
263
  print("Whisper model loaded.")
264
  return whisper_model
@@ -281,6 +282,25 @@ get_detector("Canny") # Pre-load Canny detector
281
 
282
 
283
  # --- Utility Functions ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
  def parse_color(color_str):
285
  """
286
  Parses a color string from Gradio's ColorPicker.
@@ -331,6 +351,7 @@ def manipulate_image(image, operation):
331
  return image
332
 
333
  def manipulate_video(video_path, operation):
 
334
  if not video_path:
335
  raise gr.Error("Please upload a video first.")
336
 
@@ -481,7 +502,13 @@ def batch_image_processor(files, processing_function, job_name, **kwargs):
481
 
482
  output_path = os.path.join(job_temp_dir, output_filename)
483
 
484
- processing_function(input_path=file_obj.name, output_path=output_path, **kwargs)
 
 
 
 
 
 
485
  output_paths.append(output_path)
486
 
487
  except Exception as e:
@@ -508,7 +535,9 @@ def process_batch_images_with_detector(files, detector_name):
508
  return output_paths, zip_path
509
 
510
  def process_video_with_detector(video_path, detector_name):
 
511
  if not video_path: raise gr.Error("Please upload a video first.")
 
512
  detector = get_detector(detector_name)
513
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
514
  job_temp_dir = os.path.join(TEMP_DIR, f"job_{timestamp}")
@@ -534,33 +563,65 @@ def process_video_with_detector(video_path, detector_name):
534
  return output_video_path
535
 
536
  def extract_first_last_frame(video_path):
537
- if not video_path: raise gr.Error("Please upload a video first.")
 
 
538
  cap = cv2.VideoCapture(video_path)
539
- if not cap.isOpened(): raise gr.Error("Failed to open video file.")
 
 
540
  frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
541
- if frame_count < 1:
542
  cap.release()
543
  raise gr.Error("Video has no frames.")
544
-
545
- if frame_count < 2:
546
- success, frame_img = cap.read()
547
- cap.release()
548
- if not success: raise gr.Error("Could not read the only frame.")
549
- frame_rgb = cv2.cvtColor(frame_img, cv2.COLOR_BGR2RGB)
550
- return [frame_rgb, frame_rgb.copy()]
551
 
 
 
552
  success, first_frame_img = cap.read()
553
- if not success: raise gr.Error("Could not read the first frame.")
554
-
555
- cap.set(cv2.CAP_PROP_POS_FRAMES, frame_count - 1)
556
- success, last_frame_img = cap.read()
557
- if not success: raise gr.Error("Could not read the last frame.")
 
 
 
558
 
 
 
 
 
 
 
 
 
 
 
 
559
  cap.release()
560
- return [cv2.cvtColor(first_frame_img, cv2.COLOR_BGR2RGB), cv2.cvtColor(last_frame_img, cv2.COLOR_BGR2RGB)]
 
 
 
 
 
 
 
 
 
 
561
 
 
 
 
 
 
 
 
562
  def video_to_frames_extractor(video_path, skip_rate, rotation, do_resize, out_w, out_h, out_format, jpg_quality):
 
563
  if not video_path: raise gr.Error("Please upload a video first.")
 
564
  if do_resize and (out_w <= 0 or out_h <= 0): raise gr.Error("If resizing, width and height must be positive.")
565
  cap = cv2.VideoCapture(video_path)
566
  if not cap.isOpened(): raise gr.Error("Failed to open video file.")
@@ -616,6 +677,9 @@ def create_video_from_frames(files, fps, rotation, do_resize, out_w, out_h):
616
 
617
  def image_to_looping_video(image_array, duration, audio_path=None):
618
  if image_array is None: raise gr.Error("Please upload an image first.")
 
 
 
619
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
620
  temp_image_path = os.path.join(TEMP_DIR, f"temp_image_{timestamp}.png")
621
  output_video_path = os.path.join(TEMP_DIR, f"looping_video_{timestamp}.mp4")
@@ -639,6 +703,8 @@ def image_to_looping_video(image_array, duration, audio_path=None):
639
  def create_zoom_videos(files, duration, zoom_ratio, zoom_direction, combine_videos, audio_path=None):
640
  if not files:
641
  raise gr.Error("Please upload at least one image.")
 
 
642
 
643
  fps = 30
644
  total_frames = int(duration * fps)
@@ -696,7 +762,9 @@ def create_zoom_videos(files, duration, zoom_ratio, zoom_direction, combine_vide
696
 
697
 
698
  def change_video_speed(video_path, speed_multiplier):
 
699
  if not video_path: raise gr.Error("Please upload a video first.")
 
700
  if speed_multiplier <= 0: raise gr.Error("Speed multiplier must be positive.")
701
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
702
  output_video_path = os.path.join(TEMP_DIR, f"speed_change_{timestamp}.mp4")
@@ -728,6 +796,7 @@ def process_slowmo_enhance_video(video_path, output_path, slowdown_factor, metho
728
  """
729
  Processes a single video for slow-motion and enhancement.
730
  """
 
731
  if not video_path:
732
  raise gr.Error("Missing video path for processing.")
733
 
@@ -824,7 +893,13 @@ def batch_slowmo_enhance_videos(videos, slowdown_factor_str, method, progress=gr
824
  base, _ = os.path.splitext(os.path.basename(video_file.name))
825
  output_path = os.path.join(job_temp_dir, f"{base}_slowmo_{slowdown_factor}x.mp4")
826
 
827
- process_slowmo_enhance_video(video_file.name, output_path, slowdown_factor, method, progress)
 
 
 
 
 
 
828
  output_paths.append(output_path)
829
 
830
  if not output_paths:
@@ -837,8 +912,10 @@ def batch_slowmo_enhance_videos(videos, slowdown_factor_str, method, progress=gr
837
  return output_paths, zip_path
838
 
839
  def change_audio_speed(audio_path, speed_multiplier):
 
840
  if not audio_path:
841
  raise gr.Error("Please upload an audio file.")
 
842
  if speed_multiplier <= 0:
843
  raise gr.Error("Speed multiplier must be a positive number.")
844
 
@@ -862,7 +939,9 @@ def change_audio_speed(audio_path, speed_multiplier):
862
  return output_audio_path
863
 
864
  def reverse_video(video_path, audio_option):
 
865
  if not video_path: raise gr.Error("Please upload a video first.")
 
866
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
867
  output_video_path = os.path.join(TEMP_DIR, f"reversed_video_{timestamp}.mp4")
868
  filters = ["reverse"]
@@ -875,8 +954,11 @@ def reverse_video(video_path, audio_option):
875
  return output_video_path
876
 
877
  def add_audio_to_video(video_path, audio_path):
 
 
878
  if not video_path: raise gr.Error("Please upload a video.")
879
  if not audio_path: raise gr.Error("Please upload an audio file.")
 
880
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
881
  output_video_path = os.path.join(TEMP_DIR, f"video_with_audio_{timestamp}.mp4")
882
  cmd = ["ffmpeg", "-i", video_path, "-i", audio_path, "-c:v", "copy", "-c:a", "aac", "-shortest", "-y", output_video_path]
@@ -884,7 +966,9 @@ def add_audio_to_video(video_path, audio_path):
884
  return output_video_path
885
 
886
  def extract_audio(video_path, audio_format="mp3"):
 
887
  if not video_path: raise gr.Error("Please upload a video first.")
 
888
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
889
  output_audio_path = os.path.join(TEMP_DIR, f"extracted_audio_{timestamp}.{audio_format}")
890
  cmd = ["ffmpeg", "-i", video_path, "-vn"] # -vn strips video
@@ -896,7 +980,9 @@ def extract_audio(video_path, audio_format="mp3"):
896
  return output_audio_path
897
 
898
  def create_gif_from_video(video_path, start_time, end_time):
 
899
  if not video_path: raise gr.Error("Please upload a video first.")
 
900
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
901
  output_gif_path, palette_path = os.path.join(TEMP_DIR, f"video_to_gif_{timestamp}.gif"), os.path.join(TEMP_DIR, f"palette_{timestamp}.png")
902
  duration_filter = []
@@ -913,6 +999,7 @@ def create_gif_from_video(video_path, start_time, end_time):
913
 
914
  def get_frame_at_time(video_path, time_in_seconds=0):
915
  if not video_path: return None
 
916
  try:
917
  command = ['ffmpeg', '-ss', str(time_in_seconds), '-i', video_path, '-vframes', '1', '-f', 'image2pipe', '-c:v', 'png', '-']
918
  pipe = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
@@ -925,7 +1012,9 @@ def get_frame_at_time(video_path, time_in_seconds=0):
925
  return None
926
 
927
  def crop_video(video_path, x, y, w, h, do_resize, out_w, out_h):
 
928
  if not video_path: raise gr.Error("Please upload a video first.")
 
929
  w, h, x, y = int(w), int(h), int(x), int(y)
930
  w -= w % 2; h -= h % 2
931
  if w <= 0 or h <= 0: raise gr.Error("Crop dimensions must be positive.")
@@ -942,7 +1031,9 @@ def crop_video(video_path, x, y, w, h, do_resize, out_w, out_h):
942
  return output_video_path
943
 
944
  def trim_video(video_path, start_time, end_time):
 
945
  if not video_path: raise gr.Error("Please upload a video first.")
 
946
  if start_time < 0: start_time = 0
947
  if end_time <= start_time: end_time = 0
948
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
@@ -954,7 +1045,9 @@ def trim_video(video_path, start_time, end_time):
954
  return output_video_path
955
 
956
  def apply_video_watermark(video_path, text, position, opacity, size_scale, color):
 
957
  if not video_path: raise gr.Error("Please upload a video first.")
 
958
  if not text: raise gr.Error("Watermark text cannot be empty.")
959
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
960
  output_video_path = os.path.join(TEMP_DIR, f"watermarked_video_{timestamp}.mp4")
@@ -988,7 +1081,9 @@ def apply_video_watermark(video_path, text, position, opacity, size_scale, color
988
  return output_video_path
989
 
990
  def remove_video_background(video_path):
 
991
  if not video_path: raise gr.Error("Please upload a video first.")
 
992
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
993
  job_temp_dir = os.path.join(TEMP_DIR, f"bg_rem_job_{timestamp}"); input_frames_dir, output_frames_dir = os.path.join(job_temp_dir, "input_frames"), os.path.join(job_temp_dir, "output_frames")
994
  os.makedirs(input_frames_dir, exist_ok=True); os.makedirs(output_frames_dir, exist_ok=True)
@@ -1044,13 +1139,17 @@ def generate_ass_from_whisper(result):
1044
 
1045
  return "\n".join(ass_content)
1046
 
1047
- def transcribe_media(media_path, model_name):
1048
- if media_path is None: raise gr.Error("Please upload a video or audio file first.")
 
 
 
 
1049
  model = load_whisper_model(model_name)
1050
  if model is None: raise gr.Error("Whisper model is not available.")
1051
 
1052
- audio_path = media_path.name
1053
- base_name = os.path.splitext(os.path.basename(media_path.name))[0]
1054
 
1055
  if audio_path.lower().endswith(('.mp4', '.mov', '.mkv', '.avi', '.webm')):
1056
  audio_path_temp = os.path.join(TEMP_DIR, f"{base_name}.mp3")
@@ -1086,10 +1185,17 @@ def transcribe_media(media_path, model_name):
1086
 
1087
  def transcribe_and_prep_burn(media_file, model_name):
1088
  if not media_file: raise gr.Error("Please upload a file first.")
1089
- is_video = media_file.name.lower().endswith(('.mp4', '.mov', '.mkv', '.avi', '.webm'))
 
 
 
 
1090
  text, files = transcribe_media(media_file, model_name)
1091
- if is_video: return text, files, media_file.name, gr.update(visible=True)
1092
- else: return text, files, None, gr.update(visible=False)
 
 
 
1093
 
1094
  def reformat_srt_for_word_wrap(original_srt_path, words_per_line):
1095
  if not original_srt_path or not os.path.exists(original_srt_path):
@@ -1123,6 +1229,9 @@ def reformat_srt_for_word_wrap(original_srt_path, words_per_line):
1123
  return reformatted_path
1124
 
1125
  def burn_block_subtitles(video_path, srt_file_obj, font_size_scale, font_color, words_per_line):
 
 
 
1126
  original_srt_path = srt_file_obj[0].name
1127
  reformatted_srt_path = None
1128
  try:
@@ -1148,6 +1257,9 @@ def burn_block_subtitles(video_path, srt_file_obj, font_size_scale, font_color,
1148
  os.remove(reformatted_srt_path)
1149
 
1150
  def burn_karaoke_subtitles(video_path, subtitle_files, font_size_scale, base_color, highlight_color):
 
 
 
1151
  ass_file_path = subtitle_files[2].name
1152
  temp_ass_path = None
1153
  try:
@@ -1242,11 +1354,6 @@ def batch_resize_convert_images(files, output_format, quality, enable_resize, ma
1242
  job_name = "resized_converted"
1243
  job_temp_dir = os.path.join(TEMP_DIR, f"{job_name}_{timestamp}"); os.makedirs(job_temp_dir, exist_ok=True)
1244
  output_paths = []
1245
-
1246
- # Enable resizing if dimensions are provided, even if checkbox is somehow out of sync
1247
- if max_w > 0 and max_h > 0:
1248
- enable_resize = True
1249
-
1250
  processing_kwargs = {
1251
  'output_format': output_format, 'quality': quality, 'enable_resize': enable_resize,
1252
  'max_w': max_w, 'max_h': max_h, 'resize_mode': resize_mode
@@ -1256,7 +1363,11 @@ def batch_resize_convert_images(files, output_format, quality, enable_resize, ma
1256
  base, _ = os.path.splitext(os.path.basename(file_obj.name))
1257
  output_filename = f"{base}.{output_format.lower()}"
1258
  output_path = os.path.join(job_temp_dir, output_filename)
1259
- resize_convert_single_image(file_obj.name, output_path, **processing_kwargs)
 
 
 
 
1260
  output_paths.append(output_path)
1261
  except Exception as e: print(f"Skipping file {file_obj.name} due to error: {e}"); continue
1262
  if not output_paths: shutil.rmtree(job_temp_dir); raise gr.Error("No images could be processed.")
@@ -1284,53 +1395,34 @@ def apply_watermark_batch(files, watermark_text, position, opacity):
1284
  return output_paths, zip_path
1285
 
1286
  def convert_compress_video(video_path, out_format, v_codec, crf_value, scale_option, a_codec, a_bitrate):
1287
- if not video_path:
1288
- raise gr.Error("Please upload a video to convert.")
1289
-
1290
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1291
  output_filename = f"converted_{timestamp}.{out_format.lower()}"
1292
  output_path = os.path.join(TEMP_DIR, output_filename)
1293
-
1294
  cmd = ["ffmpeg", "-i", video_path]
1295
  vf_filters = []
1296
-
1297
- # Optional user downscale
1298
  if scale_option != "Original":
1299
  w, h = get_video_dimensions(video_path)
1300
  if w > 0 and h > 0:
1301
  target_h = int(scale_option.replace('p', ''))
1302
- target_w = round(w * target_h / h / 2) * 2 # keep even
1303
  vf_filters.append(f"scale={target_w}:{target_h}")
1304
-
1305
- # ALWAYS ensure even dimensions & square pixels
1306
- # Use pad so we don't shrink/warp odd inputs (e.g., 839 -> 840).
1307
- vf_filters.append("pad=ceil(iw/2)*2:ceil(ih/2)*2")
1308
- vf_filters.append("setsar=1")
1309
-
1310
- cmd.extend(["-vf", ",".join(vf_filters)])
1311
-
1312
  cmd.extend(["-c:v", v_codec])
1313
- if v_codec in ["libx264", "libx265"]:
1314
- cmd.extend(["-crf", str(crf_value)])
1315
-
1316
  cmd.extend(["-pix_fmt", "yuv420p"])
1317
-
1318
- if a_codec == "copy":
1319
- cmd.extend(["-c:a", "copy"])
1320
- else:
1321
- cmd.extend(["-c:a", a_codec, "-b:a", f"{a_bitrate}k"])
1322
-
1323
- # web-friendly mp4
1324
- if out_format.lower() in ["mp4", "mov"]:
1325
- cmd.extend(["-movflags", "+faststart"])
1326
-
1327
  cmd.extend(["-y", output_path])
1328
- run_ffmpeg_command(cmd, "Converting and Compressing Video.")
1329
  return output_path
1330
-
1331
 
1332
  def apply_video_fade(video_path, fade_in_duration, fade_out_duration):
 
1333
  if not video_path: raise gr.Error("Please upload a video.")
 
1334
  video_duration = get_media_duration(video_path)
1335
  if fade_in_duration + fade_out_duration > video_duration: raise gr.Error("The sum of fade durations cannot be greater than the video duration.")
1336
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
@@ -1389,6 +1481,7 @@ def preview_color_grading_ffmpeg(image_np, brightness, contrast, saturation, sha
1389
 
1390
  def apply_color_grading(video_path, brightness, contrast, saturation, sharpness):
1391
  """Applies color grading to a full video using FFMPEG."""
 
1392
  if not video_path:
1393
  raise gr.Error("Please upload a video first.")
1394
 
@@ -1417,7 +1510,9 @@ def apply_color_grading(video_path, brightness, contrast, saturation, sharpness)
1417
  # --- END ACCURATE Color Grading Functions ---
1418
 
1419
  def trim_and_fade_audio(audio_path, start_time, end_time, fade_in_duration, fade_out_duration):
 
1420
  if not audio_path: raise gr.Error("Please upload an audio file.")
 
1421
  audio_duration = get_media_duration(audio_path)
1422
  if start_time < 0: start_time = 0
1423
  if end_time <= 0 or end_time > audio_duration: end_time = audio_duration
@@ -1450,6 +1545,7 @@ def create_gradual_ramp_video(video_path, progress=gr.Progress(track_tqdm=True))
1450
  2. For videos >= 2.0s: The original advanced segmentation logic is used to create a
1451
  more detailed and noticeable ramp effect.
1452
  """
 
1453
  if not video_path:
1454
  raise gr.Error("Please upload a video to process.")
1455
 
@@ -1624,7 +1720,9 @@ def load_preset(presets, name):
1624
 
1625
  # --- Join/Beat-Sync/Etc Video Feature Functions ---
1626
  def ping_pong_video(video_path, audio_option):
 
1627
  if not video_path: raise gr.Error("Please upload a video.")
 
1628
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1629
  job_temp_dir = os.path.join(TEMP_DIR, f"pingpong_{timestamp}"); os.makedirs(job_temp_dir, exist_ok=True)
1630
  reversed_video_path = os.path.join(job_temp_dir, "reversed_temp.mp4")
@@ -1653,6 +1751,7 @@ def stabilize_video(video_path, shakiness, smoothing):
1653
  Pass 1: Detects motion vectors.
1654
  Pass 2: Uses the motion vectors to smooth the video.
1655
  """
 
1656
  if not video_path:
1657
  raise gr.Error("Please upload a video to stabilize.")
1658
 
@@ -1689,6 +1788,7 @@ def stabilize_video(video_path, shakiness, smoothing):
1689
  # ### --- NEW FEATURE: AUTO JUMP-CUT & WAVEFORM PREVIEW --- ###
1690
  def generate_waveform_preview(video_path):
1691
  """Generates a PNG image of the audio waveform."""
 
1692
  if not video_path or not has_audio_stream(video_path):
1693
  return None # Return None if no video or no audio
1694
 
@@ -1715,6 +1815,7 @@ def auto_jump_cut(video_path, silence_threshold, min_silence_duration, resolutio
1715
  """
1716
  Automatically removes silent parts from a video.
1717
  """
 
1718
  if not video_path:
1719
  raise gr.Error("Please upload a video to process.")
1720
  if not has_audio_stream(video_path):
@@ -2065,6 +2166,8 @@ def create_animatic(timeline_data, audio_path, out_w, out_h, keep_original_audio
2065
  if not timeline_data:
2066
  raise gr.Error("Timeline is empty. Please add assets to the timeline.")
2067
 
 
 
2068
  out_w, out_h = int(out_w), int(out_h)
2069
  if out_w <= 0 or out_h <= 0:
2070
  raise gr.Error("Output width and height must be positive numbers.")
@@ -2177,6 +2280,7 @@ def create_animatic(timeline_data, audio_path, out_w, out_h, keep_original_audio
2177
  return final_output_path
2178
 
2179
  def detect_bpm(audio_path):
 
2180
  if not audio_path:
2181
  return "Please upload an audio track first."
2182
  try:
@@ -2214,6 +2318,8 @@ def update_new_bpm_display(original_bpm_text, speed_multiplier):
2214
 
2215
  def create_rhythmic_animatic(timeline_data, audio_path, measure_choice, out_w, out_h):
2216
  if not timeline_data: raise gr.Error("Timeline is empty.")
 
 
2217
  if not audio_path: raise gr.Error("An audio track is required for rhythmic editing.")
2218
 
2219
  try:
@@ -2251,10 +2357,101 @@ def create_rhythmic_animatic(timeline_data, audio_path, measure_choice, out_w, o
2251
 
2252
  return create_animatic(rhythmic_timeline, audio_path, out_w, out_h, keep_original_audio=False)
2253
 
2254
- # --- NEW CREATIVE FUNCTIONS ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2256
  def _create_auto_trailer_impl(video_path, trailer_duration, clip_duration, analysis_method, transition_style, music_path, out_w, out_h, progress: Progress):
2257
  """Internal implementation of the auto-trailer creator."""
 
 
2258
  if not video_path: raise gr.Error("Please upload a source video.")
2259
 
2260
  source_duration = get_media_duration(video_path)
@@ -2386,6 +2583,7 @@ def auto_trailer_wrapper(video_path, trailer_duration, clip_duration, analysis_m
2386
 
2387
 
2388
  def generate_waveform_video(video_path, style, size, position, color):
 
2389
  if not video_path: raise gr.Error("Please upload a video first.")
2390
 
2391
  if not has_audio_stream(video_path):
@@ -2419,8 +2617,11 @@ def generate_waveform_video(video_path, style, size, position, color):
2419
  return output_video_path
2420
 
2421
  def create_pip_video(main_video, overlay_media, position, scale):
 
2422
  if not main_video: raise gr.Error("Please upload a main video.")
2423
- if not overlay_media: raise gr.Error("Please upload an overlay video or image.")
 
 
2424
 
2425
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
2426
  output_video_path = os.path.join(TEMP_DIR, f"pip_video_{timestamp}.mp4")
@@ -2440,7 +2641,7 @@ def create_pip_video(main_video, overlay_media, position, scale):
2440
  }
2441
  overlay_filter = f"[0:v][scaled_overlay]overlay={pos_map[position]}"
2442
 
2443
- cmd = ["ffmpeg", "-i", main_video, "-i", overlay_media.name]
2444
 
2445
  cmd.extend([
2446
  "-filter_complex", f"{scale_filter};{overlay_filter}",
@@ -2580,17 +2781,23 @@ def merge_videos(videos):
2580
  job_temp_dir = os.path.join(TEMP_DIR, f"merge_{timestamp}")
2581
  os.makedirs(job_temp_dir, exist_ok=True)
2582
 
2583
- first_video_path = videos[0].name
 
 
 
 
 
 
2584
  w, h = get_video_dimensions(first_video_path)
2585
  fps = get_video_fps(first_video_path)
2586
  w -= w % 2
2587
  h -= h % 2
2588
 
2589
  processed_clips = []
2590
- for i, video_file in enumerate(videos):
2591
  clip_path = os.path.join(job_temp_dir, f"clip_{i}.mp4")
2592
  cmd = [
2593
- "ffmpeg", "-i", video_file.name,
2594
  "-vf", f"scale={w}:{h},setsar=1", "-r", str(fps),
2595
  "-c:v", "libx264", "-pix_fmt", "yuv420p",
2596
  "-c:a", "aac", "-ar", "44100",
@@ -2659,7 +2866,7 @@ def create_collage(files, layout, width, height, bg_color_hex):
2659
  raise gr.Error("Please upload images to create a collage.")
2660
 
2661
  bg_color = parse_color(bg_color_hex)
2662
- images = [Image.open(file.name).convert("RGBA") for file in files]
2663
  n = len(images)
2664
 
2665
  if layout == "Grid":
@@ -2721,12 +2928,20 @@ def compile_video_grid(videos, layout, width, height, bg_color, audio_choice, mu
2721
 
2722
  cmd = ["ffmpeg", "-y"]
2723
  input_count = 0
2724
- for video_file in videos:
2725
- cmd.extend(["-i", video_file.name])
 
 
 
 
 
 
 
2726
  input_count += 1
2727
 
2728
- if music_path:
2729
- cmd.extend(["-i", music_path])
 
2730
 
2731
  filter_complex_parts = []
2732
 
@@ -2769,7 +2984,7 @@ def compile_video_grid(videos, layout, width, height, bg_color, audio_choice, mu
2769
  cmd.extend(["-map", "[vout]"])
2770
 
2771
  # Audio mapping logic
2772
- if music_path:
2773
  cmd.extend(["-map", f"{input_count}:a?"]) # Map the external audio track
2774
  cmd.extend(["-c:a", "aac", "-shortest"])
2775
  elif audio_choice != "None":
@@ -2791,6 +3006,8 @@ def compile_video_grid(videos, layout, width, height, bg_color, audio_choice, mu
2791
  def _create_automated_slideshow_impl(images, audio_path, kb_effect_style, transition_style, rhythm_choice, out_w, out_h, progress: Progress):
2792
  """Internal implementation of the slideshow creator with progress tracking."""
2793
  if not images: raise gr.Error("Please upload at least one image.")
 
 
2794
  if not audio_path: raise gr.Error("Please upload an audio track for rhythmic editing.")
2795
 
2796
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
@@ -2840,7 +3057,10 @@ def _create_automated_slideshow_impl(images, audio_path, kb_effect_style, transi
2840
 
2841
  output_clip_path = os.path.join(job_temp_dir, f"kb_clip_{i:04d}.mp4")
2842
 
2843
- with Image.open(looped_image_paths[i]) as img:
 
 
 
2844
  iw, ih = img.size
2845
 
2846
  zoom_levels = {"Subtle": (1.1, 1.15), "Standard": (1.1, 1.25), "Dynamic": (1.2, 1.5)}
@@ -2867,7 +3087,7 @@ def _create_automated_slideshow_impl(images, audio_path, kb_effect_style, transi
2867
 
2868
  zoompan_filter = f"zoompan=z='{z_expr}':x='{x_expr}':y='{y_expr}':d={total_frames}:s={output_res_str}:fps={fps}"
2869
 
2870
- cmd = ["ffmpeg", "-y", "-loop", "1", "-i", looped_image_paths[i], "-vf", zoompan_filter, "-t", str(clip_duration), "-c:v", "libx264", "-pix_fmt", "yuv420p", output_clip_path]
2871
  run_ffmpeg_command(cmd)
2872
  kb_clips.append({"path": output_clip_path, "duration": clip_duration})
2873
  current_step += 1
@@ -2913,6 +3133,8 @@ def slideshow_wrapper(images, audio_path, kb_effect_style, transition_style, rhy
2913
 
2914
  def _create_rhythmic_remix_impl(video_path, audio_path, cut_style, beat_sync, resolution_choice, custom_w, custom_h, progress: Progress):
2915
  """Internal implementation of the auto-rhythmic video remixer."""
 
 
2916
  if not video_path: raise gr.Error("Please upload a source video.")
2917
  if not audio_path: raise gr.Error("Please upload an audio track.")
2918
 
@@ -3408,6 +3630,7 @@ with gr.Blocks(
3408
  clear_assets_btn.click(lambda: ([], gr.update(value=None), None), outputs=[assets_state, asset_gallery, asset_preview_gallery])
3409
  clear_timeline_btn.click(lambda: [], outputs=[timeline_state])
3410
  keep_audio_checkbox.change(fn=lambda x: gr.update(interactive=not x), inputs=keep_audio_checkbox, outputs=animatic_audio)
 
3411
  generate_animatic_btn.click(fn=create_animatic, inputs=[timeline_state, animatic_audio, animatic_out_w, animatic_out_h, keep_audio_checkbox], outputs=animatic_output_video).then(fn=None, js=fire_confetti_and_sound_js)
3412
  analyze_bpm_btn.click(detect_bpm, animatic_audio, bpm_display)
3413
  generate_rhythmic_btn.click(fn=create_rhythmic_animatic, inputs=[timeline_state, animatic_audio, measure_dropdown, animatic_out_w, animatic_out_h], outputs=animatic_output_video).then(fn=None, js=fire_confetti_and_sound_js)
@@ -3536,6 +3759,91 @@ with gr.Blocks(
3536
  outputs=trailer_output_video
3537
  ).then(fn=None, js=fire_confetti_and_sound_js)
3538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3539
  with gr.TabItem("🎡 Audio Waveform"):
3540
  gr.Markdown("## Generate & Overlay Audio Waveforms")
3541
  gr.Info("Upload a video with an audio track to generate a dynamic waveform visualization.")
@@ -3605,22 +3913,6 @@ with gr.Blocks(
3605
  outputs=meme_output_image
3606
  ).then(fn=None, js=fire_confetti_and_sound_js)
3607
 
3608
- with gr.TabItem("πŸ€– FLUX.1 API"):
3609
- gr.Markdown("### Generate an image using `FLUX.1` models via Gradio Client.")
3610
- gr.Info("Requires a Hugging Face User Access Token.")
3611
- with gr.Row():
3612
- with gr.Column():
3613
- hf_token_input = gr.Textbox(label="HF Token", type="password", placeholder="Enter hf_... token")
3614
- flux_model_dropdown = gr.Dropdown(list(FLUX_MODELS.keys()), value="FLUX.1-schnell (Fast)", label="Select FLUX Model")
3615
- prompt_input_flux = gr.Textbox(label="Prompt", lines=3, placeholder="A cinematic photo...")
3616
- with gr.Row():
3617
- flux_width_slider = gr.Slider(256, 2048, 1024, step=64, label="Width")
3618
- flux_height_slider = gr.Slider(256, 2048, 1024, step=64, label="Height")
3619
- flux_btn = gr.Button("β˜„οΈ Generate Image", variant="primary")
3620
- with gr.Column():
3621
- output_image_flux = gr.Image(label="Generated Image", show_download_button=True, height=UNIFIED_HEIGHT)
3622
- flux_btn.click(call_flux_api, [prompt_input_flux, flux_model_dropdown, flux_width_slider, flux_height_slider, hf_token_input], output_image_flux).then(fn=None, js=fire_confetti_and_sound_js)
3623
-
3624
  with gr.TabItem("πŸ–ΌοΈ Image Utilities", elem_id="image_tab"):
3625
  with gr.Tabs():
3626
  with gr.TabItem("✨ Manipulate"):
@@ -3794,67 +4086,29 @@ with gr.Blocks(
3794
  output_zip_wm = gr.File(label="Download All as .zip", interactive=False)
3795
  watermark_btn.click(apply_watermark_batch, [input_images_wm, watermark_text, watermark_pos, watermark_opacity], [output_gallery_wm, output_zip_wm]).then(fn=None, js=fire_confetti_and_sound_js)
3796
 
3797
- with gr.TabItem("πŸ“ Batch Resizer & Converter"):
3798
  gr.Markdown("### Convert, resize, and compress a batch of images.")
3799
- gr.Info("Choose a preset for quick resizing or select 'Custom' to enter your own dimensions.")
3800
  with gr.Row():
3801
  with gr.Column():
3802
  brc_input_images = gr.File(label="Upload Images", file_count="multiple", file_types=["image"])
3803
  with gr.Accordion("βš™οΈ Output Settings", open=True):
3804
- brc_preset = gr.Dropdown(
3805
- label="Resolution Presets",
3806
- choices=[
3807
- "1024x1024 (Square)", "768x768 (Square)", "720x720 (Square)",
3808
- "1280x720 (Landscape 16:9)", "720x1280 (Portrait 9:16)",
3809
- "768x512 (Landscape 3:2)", "512x768 (Portrait 2:3)",
3810
- "Custom"
3811
- ],
3812
- value="1024x1024 (Square)"
3813
- )
3814
- with gr.Row(visible=False) as brc_custom_size_row:
3815
- brc_max_w = gr.Number(label="Width", value=1024)
3816
- brc_max_h = gr.Number(label="Height", value=1024)
3817
-
3818
- brc_resize_mode = gr.Radio(["Fit (preserve aspect ratio)", "Stretch to Fit"], value="Fit (preserve aspect ratio)", label="Resize Mode")
3819
  brc_format = gr.Dropdown(["JPG", "PNG", "WEBP"], value="JPG", label="Output Format")
3820
  brc_quality = gr.Slider(1, 100, 90, step=1, label="JPG/WEBP Quality", interactive=True)
3821
-
 
 
 
 
3822
  brc_btn = gr.Button("πŸš€ Process Images", variant="primary")
3823
  with gr.Column():
3824
  brc_output_gallery = gr.Gallery(label="Processed Images Preview", columns=4, object_fit="contain", height="auto")
3825
  brc_output_zip = gr.File(label="Download All as .zip", interactive=False)
3826
-
3827
- def update_resizer_from_preset(preset_str):
3828
- if preset_str == "Custom":
3829
- return gr.update(visible=True), gr.update(), gr.update()
3830
-
3831
- match = re.search(r'(\d+)\s*x\s*(\d+)', preset_str)
3832
- if match:
3833
- w, h = int(match.group(1)), int(match.group(2))
3834
- return gr.update(visible=False), w, h
3835
-
3836
- # Fallback to a default if parsing fails for some reason
3837
- return gr.update(visible=False), 1024, 1024
3838
-
3839
- brc_preset.change(
3840
- fn=update_resizer_from_preset,
3841
- inputs=brc_preset,
3842
- outputs=[brc_custom_size_row, brc_max_w, brc_max_h]
3843
- )
3844
-
3845
- # Initialize the values on load
3846
- demo.load(
3847
- fn=update_resizer_from_preset,
3848
- inputs=brc_preset,
3849
- outputs=[brc_custom_size_row, brc_max_w, brc_max_h]
3850
- )
3851
 
3852
  brc_format.change(lambda f: gr.update(visible=f in ["JPG", "WEBP"]), brc_format, brc_quality)
3853
-
3854
  brc_btn.click(
3855
- # The 'enable_resize' parameter is now implicitly True
3856
- lambda files, out_f, qual, w, h, mode: batch_resize_convert_images(files, out_f, qual, True, w, h, mode),
3857
- [brc_input_images, brc_format, brc_quality, brc_max_w, brc_max_h, brc_resize_mode],
3858
  [brc_output_gallery, brc_output_zip]
3859
  ).then(fn=None, js=fire_confetti_and_sound_js)
3860
 
@@ -3892,7 +4146,7 @@ with gr.Blocks(
3892
  with gr.Column():
3893
  output_gallery_v2f = gr.Gallery(label="Extracted Frames Preview (max 100 shown)", columns=8, object_fit="contain", height="auto")
3894
  output_zip_v2f = gr.File(label="Download All Frames (.zip)", interactive=False)
3895
- input_video_v2f.upload(lambda v: f"{get_video_fps(v):.2f} FPS", input_video_v2f, v2f_fps_display)
3896
  v2f_resize.change(lambda x: [gr.update(interactive=x), gr.update(interactive=x)], v2f_resize, [v2f_width, v2f_height])
3897
  v2f_format.change(lambda x: gr.update(interactive=(x=="JPG")), v2f_format, v2f_jpg_quality)
3898
  extract_v2f_btn.click(video_to_frames_extractor, [input_video_v2f, v2f_skip_rate, v2f_rotation, v2f_resize, v2f_width, v2f_height, v2f_format, v2f_jpg_quality], [output_gallery_v2f, output_zip_v2f]).then(fn=None, js=fire_confetti_and_sound_js)
@@ -4118,7 +4372,9 @@ with gr.Blocks(
4118
  with gr.Row():
4119
  output_video_trim = gr.Video(label="Trimmed Video", interactive=True, show_download_button=True, height=UNIFIED_HEIGHT)
4120
  get_current_time_js = """()=>{const e=document.querySelector("#video-trim-input video");return e?e.currentTime:0}"""
4121
- def get_frame_from_time_wrapper(v,t): return get_frame_at_time(v,t), f"{t:.3f}"
 
 
4122
  set_start_btn.click(fn=None, js=get_current_time_js, outputs=[trim_start_time])
4123
  set_end_btn.click(fn=None, js=get_current_time_js, outputs=[trim_end_time])
4124
  trim_start_time.change(fn=get_frame_from_time_wrapper, inputs=[input_video_trim, trim_start_time], outputs=[start_frame_img, trim_start_time_display])
@@ -4151,10 +4407,11 @@ with gr.Blocks(
4151
  video_crop_output_video = gr.Video(label="Cropped Video", interactive=True, show_download_button=True, height=UNIFIED_HEIGHT)
4152
 
4153
  def setup_video_crop_preview(video_path):
4154
- if not video_path:
 
4155
  return None, None, gr.update(), gr.update(), gr.update(), gr.update()
4156
  try:
4157
- img = get_frame_at_time(video_path, 0)
4158
  w, h = img.size
4159
  return img, img, gr.update(maximum=w, value=w), gr.update(maximum=h, value=h), gr.update(maximum=w), gr.update(maximum=h)
4160
  except Exception as e:
@@ -4212,6 +4469,7 @@ with gr.Blocks(
4212
  with gr.TabItem("🎨 Color Grading"):
4213
  gr.Markdown("### Adjust Video Color, Contrast, and Sharpness")
4214
  gr.Info("Upload a video, load a preview frame, adjust the sliders for a live preview, and then apply the changes to the full video. The preview is 100% accurate to the final render.")
 
4215
  with gr.Row(equal_height=False):
4216
  with gr.Column(scale=1):
4217
  color_grade_input_video = gr.Video(label="Input Video", height=UNIFIED_HEIGHT)
@@ -4233,14 +4491,15 @@ with gr.Blocks(
4233
 
4234
  grading_inputs = [cg_before_preview, cg_brightness, cg_contrast, cg_saturation, cg_sharpness]
4235
 
4236
- cg_brightness.release(preview_color_grading_ffmpeg, inputs=grading_inputs, outputs=cg_after_preview)
4237
- cg_contrast.release(preview_color_grading_ffmpeg, inputs=grading_inputs, outputs=cg_after_preview)
4238
- cg_saturation.release(preview_color_grading_ffmpeg, inputs=grading_inputs, outputs=cg_after_preview)
4239
- cg_sharpness.release(preview_color_grading_ffmpeg, inputs=grading_inputs, outputs=cg_after_preview)
 
4240
 
4241
  load_preview_btn.click(
4242
- fn=get_frame_at_time,
4243
- inputs=color_grade_input_video,
4244
  outputs=cg_before_preview
4245
  ).then(
4246
  fn=preview_color_grading_ffmpeg,
@@ -4248,18 +4507,21 @@ with gr.Blocks(
4248
  outputs=cg_after_preview
4249
  )
4250
  color_grade_input_video.upload(
4251
- fn=get_frame_at_time,
4252
- inputs=color_grade_input_video,
4253
- outputs=cg_before_preview
4254
  ).then(
4255
  fn=preview_color_grading_ffmpeg,
4256
  inputs=grading_inputs,
4257
  outputs=cg_after_preview
4258
  )
 
 
 
4259
 
4260
  apply_grading_btn.click(
4261
  fn=apply_color_grading,
4262
- inputs=[color_grade_input_video, cg_brightness, cg_contrast, cg_saturation, cg_sharpness],
4263
  outputs=color_grade_output_video
4264
  ).then(fn=None, js=fire_confetti_and_sound_js)
4265
 
@@ -4482,16 +4744,12 @@ with gr.Blocks(
4482
  conv_btn.click(fn=convert_compress_video, inputs=[conv_input_video, conv_format, conv_vcodec, conv_crf, conv_scale, conv_acodec, conv_abitrate], outputs=conv_output_video).then(fn=None, js=fire_confetti_and_sound_js)
4483
 
4484
  with gr.TabItem("πŸ”— Transfer", elem_id="transfer_tab"):
4485
- gr.Markdown("## Image & Link Transfer Utility")
4486
- gr.Info("Drop images below, manage URL presets, and open the target application in a new tab.")
4487
-
4488
- link_presets = gr.State(DEFAULT_LINK_PRESETS.copy())
4489
-
4490
- with gr.Row():
4491
- with gr.Column(scale=1):
4492
- transfer_gallery = gr.Gallery(label="Drop Images Here", height=300, columns=3, object_fit="contain")
4493
- with gr.Column(scale=2):
4494
- gr.Markdown("### Link Preset Management")
4495
  target_url = gr.Textbox(label="Target URL", value="https://huggingface.co/spaces/bep40/FramePack_rotate_landscape", interactive=True, elem_id="transfer_target_url")
4496
  search_bar = gr.Textbox(label="Search Presets", placeholder="Type to filter...", interactive=True)
4497
  with gr.Row():
@@ -4506,18 +4764,34 @@ with gr.Blocks(
4506
  new_preset_name = gr.Textbox(label="New Preset Name", placeholder="e.g., My Favorite App")
4507
  save_preset_btn = gr.Button("πŸ’Ύ Save")
4508
  open_link_btn = gr.Button("πŸš€ Open in New Tab", variant="primary")
4509
-
4510
- search_bar.input(fn=filter_presets, inputs=[search_bar, link_presets], outputs=[preset_dropdown])
4511
- preset_dropdown.change(fn=load_preset, inputs=[link_presets, preset_dropdown], outputs=[target_url])
4512
- save_preset_btn.click(
4513
- fn=save_preset, inputs=[link_presets, new_preset_name, target_url], outputs=[link_presets, preset_dropdown]
4514
- ).then(lambda: ("", ""), outputs=[new_preset_name, search_bar])
4515
- delete_confirm_js = """(name) => { if (!name) { alert('Please select a preset to delete.'); return false; } return confirm(`Are you sure you want to delete the preset: '` + name + `'?`); }"""
4516
- delete_preset_btn.click(fn=None, js=delete_confirm_js, inputs=[preset_dropdown]).then(
4517
- fn=delete_preset, inputs=[link_presets, preset_dropdown], outputs=[link_presets, preset_dropdown, target_url]
4518
- ).then(lambda: "", outputs=[search_bar])
4519
- open_link_btn.click(fn=None, js="()=>{const url=document.getElementById('transfer_target_url').querySelector('textarea').value;if(url){window.open(url,'_blank')}else{alert('Target URL is empty.')}}")
4520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4521
  main_tabs.select(fn=None, inputs=main_tabs, js="(tab) => { window.skriptz_bling.update_title(tab); }")
4522
 
4523
  gr.HTML('<a href="https://linktr.ee/skylinkd" target="_blank" style="color: #94a3b8; text-decoration: none;">skylinkd production 2025 (c)</a>', elem_id="custom-footer")
@@ -4529,4 +4803,4 @@ if __name__ == "__main__":
4529
  os.makedirs(TEMP_DIR, exist_ok=True)
4530
  if whisper:
4531
  load_whisper_model("base") # Pre-load the default model on startup
4532
- demo.launch(inbrowser=True)
 
1
+ # -*- coding: utf-8 -*-
2
  import os
3
  import sys
4
  import re
 
259
  with model_load_lock:
260
  if whisper_model is None or whisper_model_name != model_name:
261
  print(f"Loading Whisper model '{model_name}'... (This may download files on first run)")
262
+ whisper_model = whisper.load_model(model_name)
263
  whisper_model_name = model_name
264
  print("Whisper model loaded.")
265
  return whisper_model
 
282
 
283
 
284
  # --- Utility Functions ---
285
+
286
+ # ### --- PERMISSION ERROR FIX --- ###
287
+ def safe_copy_to_temp(file_path):
288
+ """Copies a file to the app's central temp directory to avoid permission errors."""
289
+ if file_path is None or not os.path.exists(file_path):
290
+ return None
291
+
292
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
293
+ filename = os.path.basename(file_path)
294
+ safe_path = os.path.join(TEMP_DIR, f"{timestamp}_{filename}")
295
+
296
+ try:
297
+ shutil.copy(file_path, safe_path)
298
+ return safe_path
299
+ except Exception as e:
300
+ print(f"Warning: Could not create a safe copy of {filename}. Error: {e}")
301
+ # Fallback to using the original path, though it may cause errors.
302
+ return file_path
303
+
304
  def parse_color(color_str):
305
  """
306
  Parses a color string from Gradio's ColorPicker.
 
351
  return image
352
 
353
  def manipulate_video(video_path, operation):
354
+ video_path = safe_copy_to_temp(video_path)
355
  if not video_path:
356
  raise gr.Error("Please upload a video first.")
357
 
 
502
 
503
  output_path = os.path.join(job_temp_dir, output_filename)
504
 
505
+ # Use safe copy for each file in the batch
506
+ safe_input_path = safe_copy_to_temp(file_obj.name)
507
+ if not safe_input_path:
508
+ print(f"Skipping file {file_obj.name} as it could not be accessed.")
509
+ continue
510
+
511
+ processing_function(input_path=safe_input_path, output_path=output_path, **kwargs)
512
  output_paths.append(output_path)
513
 
514
  except Exception as e:
 
535
  return output_paths, zip_path
536
 
537
  def process_video_with_detector(video_path, detector_name):
538
+ video_path = safe_copy_to_temp(video_path)
539
  if not video_path: raise gr.Error("Please upload a video first.")
540
+
541
  detector = get_detector(detector_name)
542
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
543
  job_temp_dir = os.path.join(TEMP_DIR, f"job_{timestamp}")
 
563
  return output_video_path
564
 
565
  def extract_first_last_frame(video_path):
566
+ if not video_path:
567
+ raise gr.Error("Please upload a video first.")
568
+
569
  cap = cv2.VideoCapture(video_path)
570
+ if not cap.isOpened():
571
+ raise gr.Error("Failed to open video file.")
572
+
573
  frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
574
+ if frame_count < 1:
575
  cap.release()
576
  raise gr.Error("Video has no frames.")
 
 
 
 
 
 
 
577
 
578
+ # Set position to the first frame and read it
579
+ cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
580
  success, first_frame_img = cap.read()
581
+ if not success:
582
+ cap.release()
583
+ raise gr.Error("Could not read the first frame.")
584
+
585
+ # --- FIX for Last Frame (Robust Method) ---
586
+ # Direct seeking to frame_count - 1 can be unreliable.
587
+ # This method seeks near the end and then reads sequentially to find the true last frame.
588
+ last_frame_img = None
589
 
590
+ # Start checking from a few frames before the reported end to be safe.
591
+ start_frame_for_last = max(1, frame_count - 10)
592
+ cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame_for_last)
593
+
594
+ # Loop through the last few frames to ensure we get the very last one
595
+ while True:
596
+ success, frame = cap.read()
597
+ if not success:
598
+ break
599
+ last_frame_img = frame
600
+
601
  cap.release()
602
+
603
+ # If the loop fails (e.g., for very short videos), fall back to using the first frame as the last.
604
+ if last_frame_img is None:
605
+ last_frame_img = first_frame_img
606
+
607
+ # --- FIX for saving with proper extension ---
608
+ # The function now saves the images to temporary files with correct names (.png) and returns the paths.
609
+ # Gradio's Gallery will display these files, and downloading them will use the correct filename.
610
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
611
+ first_frame_path = os.path.join(TEMP_DIR, f"first_frame_{timestamp}.png")
612
+ last_frame_path = os.path.join(TEMP_DIR, f"last_frame_{timestamp}.png")
613
 
614
+ # Convert from OpenCV's BGR format to RGB before saving with the PIL library
615
+ Image.fromarray(cv2.cvtColor(first_frame_img, cv2.COLOR_BGR2RGB)).save(first_frame_path)
616
+ Image.fromarray(cv2.cvtColor(last_frame_img, cv2.COLOR_BGR2RGB)).save(last_frame_path)
617
+
618
+ # Return the list of file paths to be displayed in the gallery
619
+ return [first_frame_path, last_frame_path]
620
+
621
  def video_to_frames_extractor(video_path, skip_rate, rotation, do_resize, out_w, out_h, out_format, jpg_quality):
622
+ video_path = safe_copy_to_temp(video_path)
623
  if not video_path: raise gr.Error("Please upload a video first.")
624
+
625
  if do_resize and (out_w <= 0 or out_h <= 0): raise gr.Error("If resizing, width and height must be positive.")
626
  cap = cv2.VideoCapture(video_path)
627
  if not cap.isOpened(): raise gr.Error("Failed to open video file.")
 
677
 
678
  def image_to_looping_video(image_array, duration, audio_path=None):
679
  if image_array is None: raise gr.Error("Please upload an image first.")
680
+
681
+ audio_path = safe_copy_to_temp(audio_path)
682
+
683
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
684
  temp_image_path = os.path.join(TEMP_DIR, f"temp_image_{timestamp}.png")
685
  output_video_path = os.path.join(TEMP_DIR, f"looping_video_{timestamp}.mp4")
 
703
  def create_zoom_videos(files, duration, zoom_ratio, zoom_direction, combine_videos, audio_path=None):
704
  if not files:
705
  raise gr.Error("Please upload at least one image.")
706
+
707
+ audio_path = safe_copy_to_temp(audio_path)
708
 
709
  fps = 30
710
  total_frames = int(duration * fps)
 
762
 
763
 
764
  def change_video_speed(video_path, speed_multiplier):
765
+ video_path = safe_copy_to_temp(video_path)
766
  if not video_path: raise gr.Error("Please upload a video first.")
767
+
768
  if speed_multiplier <= 0: raise gr.Error("Speed multiplier must be positive.")
769
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
770
  output_video_path = os.path.join(TEMP_DIR, f"speed_change_{timestamp}.mp4")
 
796
  """
797
  Processes a single video for slow-motion and enhancement.
798
  """
799
+ video_path = safe_copy_to_temp(video_path)
800
  if not video_path:
801
  raise gr.Error("Missing video path for processing.")
802
 
 
893
  base, _ = os.path.splitext(os.path.basename(video_file.name))
894
  output_path = os.path.join(job_temp_dir, f"{base}_slowmo_{slowdown_factor}x.mp4")
895
 
896
+ # Use safe copy for each file in the batch
897
+ safe_input_path = safe_copy_to_temp(video_file.name)
898
+ if not safe_input_path:
899
+ print(f"Skipping video {video_file.name} as it could not be accessed.")
900
+ continue
901
+
902
+ process_slowmo_enhance_video(safe_input_path, output_path, slowdown_factor, method, progress)
903
  output_paths.append(output_path)
904
 
905
  if not output_paths:
 
912
  return output_paths, zip_path
913
 
914
  def change_audio_speed(audio_path, speed_multiplier):
915
+ audio_path = safe_copy_to_temp(audio_path)
916
  if not audio_path:
917
  raise gr.Error("Please upload an audio file.")
918
+
919
  if speed_multiplier <= 0:
920
  raise gr.Error("Speed multiplier must be a positive number.")
921
 
 
939
  return output_audio_path
940
 
941
  def reverse_video(video_path, audio_option):
942
+ video_path = safe_copy_to_temp(video_path)
943
  if not video_path: raise gr.Error("Please upload a video first.")
944
+
945
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
946
  output_video_path = os.path.join(TEMP_DIR, f"reversed_video_{timestamp}.mp4")
947
  filters = ["reverse"]
 
954
  return output_video_path
955
 
956
  def add_audio_to_video(video_path, audio_path):
957
+ video_path = safe_copy_to_temp(video_path)
958
+ audio_path = safe_copy_to_temp(audio_path)
959
  if not video_path: raise gr.Error("Please upload a video.")
960
  if not audio_path: raise gr.Error("Please upload an audio file.")
961
+
962
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
963
  output_video_path = os.path.join(TEMP_DIR, f"video_with_audio_{timestamp}.mp4")
964
  cmd = ["ffmpeg", "-i", video_path, "-i", audio_path, "-c:v", "copy", "-c:a", "aac", "-shortest", "-y", output_video_path]
 
966
  return output_video_path
967
 
968
  def extract_audio(video_path, audio_format="mp3"):
969
+ video_path = safe_copy_to_temp(video_path)
970
  if not video_path: raise gr.Error("Please upload a video first.")
971
+
972
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
973
  output_audio_path = os.path.join(TEMP_DIR, f"extracted_audio_{timestamp}.{audio_format}")
974
  cmd = ["ffmpeg", "-i", video_path, "-vn"] # -vn strips video
 
980
  return output_audio_path
981
 
982
  def create_gif_from_video(video_path, start_time, end_time):
983
+ video_path = safe_copy_to_temp(video_path)
984
  if not video_path: raise gr.Error("Please upload a video first.")
985
+
986
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
987
  output_gif_path, palette_path = os.path.join(TEMP_DIR, f"video_to_gif_{timestamp}.gif"), os.path.join(TEMP_DIR, f"palette_{timestamp}.png")
988
  duration_filter = []
 
999
 
1000
  def get_frame_at_time(video_path, time_in_seconds=0):
1001
  if not video_path: return None
1002
+ # No safe_copy here, as this function is a helper. The caller should handle the safe copy.
1003
  try:
1004
  command = ['ffmpeg', '-ss', str(time_in_seconds), '-i', video_path, '-vframes', '1', '-f', 'image2pipe', '-c:v', 'png', '-']
1005
  pipe = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
 
1012
  return None
1013
 
1014
  def crop_video(video_path, x, y, w, h, do_resize, out_w, out_h):
1015
+ video_path = safe_copy_to_temp(video_path)
1016
  if not video_path: raise gr.Error("Please upload a video first.")
1017
+
1018
  w, h, x, y = int(w), int(h), int(x), int(y)
1019
  w -= w % 2; h -= h % 2
1020
  if w <= 0 or h <= 0: raise gr.Error("Crop dimensions must be positive.")
 
1031
  return output_video_path
1032
 
1033
  def trim_video(video_path, start_time, end_time):
1034
+ video_path = safe_copy_to_temp(video_path)
1035
  if not video_path: raise gr.Error("Please upload a video first.")
1036
+
1037
  if start_time < 0: start_time = 0
1038
  if end_time <= start_time: end_time = 0
1039
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
 
1045
  return output_video_path
1046
 
1047
  def apply_video_watermark(video_path, text, position, opacity, size_scale, color):
1048
+ video_path = safe_copy_to_temp(video_path)
1049
  if not video_path: raise gr.Error("Please upload a video first.")
1050
+
1051
  if not text: raise gr.Error("Watermark text cannot be empty.")
1052
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1053
  output_video_path = os.path.join(TEMP_DIR, f"watermarked_video_{timestamp}.mp4")
 
1081
  return output_video_path
1082
 
1083
  def remove_video_background(video_path):
1084
+ video_path = safe_copy_to_temp(video_path)
1085
  if not video_path: raise gr.Error("Please upload a video first.")
1086
+
1087
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1088
  job_temp_dir = os.path.join(TEMP_DIR, f"bg_rem_job_{timestamp}"); input_frames_dir, output_frames_dir = os.path.join(job_temp_dir, "input_frames"), os.path.join(job_temp_dir, "output_frames")
1089
  os.makedirs(input_frames_dir, exist_ok=True); os.makedirs(output_frames_dir, exist_ok=True)
 
1139
 
1140
  return "\n".join(ass_content)
1141
 
1142
+ def transcribe_media(media_file_obj, model_name):
1143
+ if media_file_obj is None: raise gr.Error("Please upload a video or audio file first.")
1144
+
1145
+ media_path = safe_copy_to_temp(media_file_obj.name)
1146
+ if not media_path: raise gr.Error("Could not access the uploaded file.")
1147
+
1148
  model = load_whisper_model(model_name)
1149
  if model is None: raise gr.Error("Whisper model is not available.")
1150
 
1151
+ audio_path = media_path
1152
+ base_name = os.path.splitext(os.path.basename(media_path))[0]
1153
 
1154
  if audio_path.lower().endswith(('.mp4', '.mov', '.mkv', '.avi', '.webm')):
1155
  audio_path_temp = os.path.join(TEMP_DIR, f"{base_name}.mp3")
 
1185
 
1186
  def transcribe_and_prep_burn(media_file, model_name):
1187
  if not media_file: raise gr.Error("Please upload a file first.")
1188
+
1189
+ safe_media_path = safe_copy_to_temp(media_file.name)
1190
+ if not safe_media_path: raise gr.Error("Could not access uploaded file.")
1191
+
1192
+ is_video = safe_media_path.lower().endswith(('.mp4', '.mov', '.mkv', '.avi', '.webm'))
1193
  text, files = transcribe_media(media_file, model_name)
1194
+
1195
+ if is_video:
1196
+ return text, files, safe_media_path, gr.update(visible=True)
1197
+ else:
1198
+ return text, files, None, gr.update(visible=False)
1199
 
1200
  def reformat_srt_for_word_wrap(original_srt_path, words_per_line):
1201
  if not original_srt_path or not os.path.exists(original_srt_path):
 
1229
  return reformatted_path
1230
 
1231
  def burn_block_subtitles(video_path, srt_file_obj, font_size_scale, font_color, words_per_line):
1232
+ # This function is called with a safe path already
1233
+ if not video_path: raise gr.Error("Video path is missing for subtitle burning.")
1234
+
1235
  original_srt_path = srt_file_obj[0].name
1236
  reformatted_srt_path = None
1237
  try:
 
1257
  os.remove(reformatted_srt_path)
1258
 
1259
  def burn_karaoke_subtitles(video_path, subtitle_files, font_size_scale, base_color, highlight_color):
1260
+ # This function is called with a safe path already
1261
+ if not video_path: raise gr.Error("Video path is missing for subtitle burning.")
1262
+
1263
  ass_file_path = subtitle_files[2].name
1264
  temp_ass_path = None
1265
  try:
 
1354
  job_name = "resized_converted"
1355
  job_temp_dir = os.path.join(TEMP_DIR, f"{job_name}_{timestamp}"); os.makedirs(job_temp_dir, exist_ok=True)
1356
  output_paths = []
 
 
 
 
 
1357
  processing_kwargs = {
1358
  'output_format': output_format, 'quality': quality, 'enable_resize': enable_resize,
1359
  'max_w': max_w, 'max_h': max_h, 'resize_mode': resize_mode
 
1363
  base, _ = os.path.splitext(os.path.basename(file_obj.name))
1364
  output_filename = f"{base}.{output_format.lower()}"
1365
  output_path = os.path.join(job_temp_dir, output_filename)
1366
+
1367
+ safe_input_path = safe_copy_to_temp(file_obj.name)
1368
+ if not safe_input_path: continue
1369
+
1370
+ resize_convert_single_image(safe_input_path, output_path, **processing_kwargs)
1371
  output_paths.append(output_path)
1372
  except Exception as e: print(f"Skipping file {file_obj.name} due to error: {e}"); continue
1373
  if not output_paths: shutil.rmtree(job_temp_dir); raise gr.Error("No images could be processed.")
 
1395
  return output_paths, zip_path
1396
 
1397
  def convert_compress_video(video_path, out_format, v_codec, crf_value, scale_option, a_codec, a_bitrate):
1398
+ video_path = safe_copy_to_temp(video_path)
1399
+ if not video_path: raise gr.Error("Please upload a video to convert.")
1400
+
1401
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1402
  output_filename = f"converted_{timestamp}.{out_format.lower()}"
1403
  output_path = os.path.join(TEMP_DIR, output_filename)
 
1404
  cmd = ["ffmpeg", "-i", video_path]
1405
  vf_filters = []
 
 
1406
  if scale_option != "Original":
1407
  w, h = get_video_dimensions(video_path)
1408
  if w > 0 and h > 0:
1409
  target_h = int(scale_option.replace('p', ''))
1410
+ target_w = round(w * target_h / h / 2) * 2
1411
  vf_filters.append(f"scale={target_w}:{target_h}")
1412
+ if vf_filters: cmd.extend(["-vf", ",".join(vf_filters)])
 
 
 
 
 
 
 
1413
  cmd.extend(["-c:v", v_codec])
1414
+ if v_codec in ["libx264", "libx265"]: cmd.extend(["-crf", str(crf_value)])
 
 
1415
  cmd.extend(["-pix_fmt", "yuv420p"])
1416
+ if a_codec == "copy": cmd.extend(["-c:a", "copy"])
1417
+ else: cmd.extend(["-c:a", a_codec, "-b:a", f"{a_bitrate}k"])
 
 
 
 
 
 
 
 
1418
  cmd.extend(["-y", output_path])
1419
+ run_ffmpeg_command(cmd, "Converting and Compressing Video...")
1420
  return output_path
 
1421
 
1422
  def apply_video_fade(video_path, fade_in_duration, fade_out_duration):
1423
+ video_path = safe_copy_to_temp(video_path)
1424
  if not video_path: raise gr.Error("Please upload a video.")
1425
+
1426
  video_duration = get_media_duration(video_path)
1427
  if fade_in_duration + fade_out_duration > video_duration: raise gr.Error("The sum of fade durations cannot be greater than the video duration.")
1428
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
 
1481
 
1482
  def apply_color_grading(video_path, brightness, contrast, saturation, sharpness):
1483
  """Applies color grading to a full video using FFMPEG."""
1484
+ video_path = safe_copy_to_temp(video_path)
1485
  if not video_path:
1486
  raise gr.Error("Please upload a video first.")
1487
 
 
1510
  # --- END ACCURATE Color Grading Functions ---
1511
 
1512
  def trim_and_fade_audio(audio_path, start_time, end_time, fade_in_duration, fade_out_duration):
1513
+ audio_path = safe_copy_to_temp(audio_path)
1514
  if not audio_path: raise gr.Error("Please upload an audio file.")
1515
+
1516
  audio_duration = get_media_duration(audio_path)
1517
  if start_time < 0: start_time = 0
1518
  if end_time <= 0 or end_time > audio_duration: end_time = audio_duration
 
1545
  2. For videos >= 2.0s: The original advanced segmentation logic is used to create a
1546
  more detailed and noticeable ramp effect.
1547
  """
1548
+ video_path = safe_copy_to_temp(video_path)
1549
  if not video_path:
1550
  raise gr.Error("Please upload a video to process.")
1551
 
 
1720
 
1721
  # --- Join/Beat-Sync/Etc Video Feature Functions ---
1722
  def ping_pong_video(video_path, audio_option):
1723
+ video_path = safe_copy_to_temp(video_path)
1724
  if not video_path: raise gr.Error("Please upload a video.")
1725
+
1726
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1727
  job_temp_dir = os.path.join(TEMP_DIR, f"pingpong_{timestamp}"); os.makedirs(job_temp_dir, exist_ok=True)
1728
  reversed_video_path = os.path.join(job_temp_dir, "reversed_temp.mp4")
 
1751
  Pass 1: Detects motion vectors.
1752
  Pass 2: Uses the motion vectors to smooth the video.
1753
  """
1754
+ video_path = safe_copy_to_temp(video_path)
1755
  if not video_path:
1756
  raise gr.Error("Please upload a video to stabilize.")
1757
 
 
1788
  # ### --- NEW FEATURE: AUTO JUMP-CUT & WAVEFORM PREVIEW --- ###
1789
  def generate_waveform_preview(video_path):
1790
  """Generates a PNG image of the audio waveform."""
1791
+ video_path = safe_copy_to_temp(video_path)
1792
  if not video_path or not has_audio_stream(video_path):
1793
  return None # Return None if no video or no audio
1794
 
 
1815
  """
1816
  Automatically removes silent parts from a video.
1817
  """
1818
+ video_path = safe_copy_to_temp(video_path)
1819
  if not video_path:
1820
  raise gr.Error("Please upload a video to process.")
1821
  if not has_audio_stream(video_path):
 
2166
  if not timeline_data:
2167
  raise gr.Error("Timeline is empty. Please add assets to the timeline.")
2168
 
2169
+ audio_path = safe_copy_to_temp(audio_path)
2170
+
2171
  out_w, out_h = int(out_w), int(out_h)
2172
  if out_w <= 0 or out_h <= 0:
2173
  raise gr.Error("Output width and height must be positive numbers.")
 
2280
  return final_output_path
2281
 
2282
  def detect_bpm(audio_path):
2283
+ audio_path = safe_copy_to_temp(audio_path)
2284
  if not audio_path:
2285
  return "Please upload an audio track first."
2286
  try:
 
2318
 
2319
  def create_rhythmic_animatic(timeline_data, audio_path, measure_choice, out_w, out_h):
2320
  if not timeline_data: raise gr.Error("Timeline is empty.")
2321
+
2322
+ audio_path = safe_copy_to_temp(audio_path)
2323
  if not audio_path: raise gr.Error("An audio track is required for rhythmic editing.")
2324
 
2325
  try:
 
2357
 
2358
  return create_animatic(rhythmic_timeline, audio_path, out_w, out_h, keep_original_audio=False)
2359
 
2360
+ # ### --- NEW FEATURE: MARKER STITCHER --- ###
2361
+ def stitch_clips_from_markers(video_path, marker_times, clip_duration, progress=gr.Progress(track_tqdm=True)):
2362
+ """
2363
+ Creates a new video by stitching together clips defined by markers.
2364
+ Each clip STARTS at a marker and lasts for the specified duration.
2365
+ """
2366
+ if not video_path:
2367
+ raise gr.Error("Please upload a source video.")
2368
+
2369
+ if not marker_times:
2370
+ raise gr.Error("No markers have been added. Please play the video and add markers.")
2371
+ if clip_duration <= 0:
2372
+ raise gr.Error("Clip duration must be a positive number.")
2373
+
2374
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
2375
+ output_video_path = os.path.join(TEMP_DIR, f"marker_stitch_{timestamp}.mp4")
2376
+
2377
+ progress(0, desc="Analyzing source video...")
2378
+ video_duration = get_media_duration(video_path)
2379
+ if video_duration == 0:
2380
+ raise gr.Error("Could not determine video duration. The file may be corrupt.")
2381
+ has_audio = has_audio_stream(video_path)
2382
+
2383
+ # --- 1. Calculate and validate segments to keep (MODIFIED LOGIC) ---
2384
+ progress(0.1, desc="Calculating video cuts...")
2385
+
2386
+ segments = []
2387
+ for marker_time in sorted(marker_times): # Sort markers to process in order
2388
+ # New Logic: Clip starts AT the marker time.
2389
+ start_time = max(0.0, marker_time)
2390
+ end_time = min(video_duration, marker_time + clip_duration)
2391
+
2392
+ # Ensure the clip has a valid, non-zero duration
2393
+ if end_time > start_time:
2394
+ segments.append({'start': start_time, 'end': end_time})
2395
+
2396
+ if not segments:
2397
+ raise gr.Error("No valid video segments could be created from the markers. Check if the clip duration is too large or markers are too close to video ends.")
2398
 
2399
+ # --- 2. Build the FFMPEG Filter Complex Command ---
2400
+ progress(0.3, desc="Building FFMPEG command...")
2401
+ filter_complex_parts = []
2402
+ video_outputs = []
2403
+ audio_outputs = []
2404
+ num_segments = len(segments)
2405
+
2406
+ for i, seg in enumerate(progress.tqdm(segments, desc="Processing segments")):
2407
+ # Video stream segment
2408
+ filter_complex_parts.append(f"[0:v]trim=start={seg['start']}:end={seg['end']},setpts=PTS-STARTPTS[v{i}]")
2409
+ video_outputs.append(f"[v{i}]")
2410
+
2411
+ # Audio stream segment (if it exists)
2412
+ if has_audio:
2413
+ filter_complex_parts.append(f"[0:a]atrim=start={seg['start']}:end={seg['end']},asetpts=PTS-STARTPTS[a{i}]")
2414
+ audio_outputs.append(f"[a{i}]")
2415
+
2416
+ # --- THIS IS THE FIX: Use two separate concat filters for robustness ---
2417
+ if has_audio:
2418
+ # First, concat all video parts
2419
+ video_concat_str = f"{''.join(video_outputs)}concat=n={num_segments}:v=1:a=0[vout]"
2420
+ filter_complex_parts.append(video_concat_str)
2421
+
2422
+ # Second, concat all audio parts
2423
+ audio_concat_str = f"{''.join(audio_outputs)}concat=n={num_segments}:v=0:a=1[aout]"
2424
+ filter_complex_parts.append(audio_concat_str)
2425
+
2426
+ map_streams = ["-map", "[vout]", "-map", "[aout]"]
2427
+ else: # Video only
2428
+ video_concat_str = f"{''.join(video_outputs)}concat=n={num_segments}:v=1:a=0[vout]"
2429
+ filter_complex_parts.append(video_concat_str)
2430
+ map_streams = ["-map", "[vout]"]
2431
+
2432
+ filter_complex_str = ";".join(filter_complex_parts)
2433
+
2434
+ # --- 3. Execute the Final Command ---
2435
+ final_cmd = [
2436
+ "ffmpeg", "-i", video_path,
2437
+ "-filter_complex", filter_complex_str
2438
+ ]
2439
+ final_cmd.extend(map_streams)
2440
+ final_cmd.extend([
2441
+ "-c:v", "libx264", "-pix_fmt", "yuv420p",
2442
+ "-c:a", "aac",
2443
+ "-y", output_video_path
2444
+ ])
2445
+
2446
+ progress(0.7, desc="Generating final stitched video...")
2447
+ run_ffmpeg_command(final_cmd, desc="Stitching video clips...")
2448
+
2449
+ return output_video_path
2450
+
2451
  def _create_auto_trailer_impl(video_path, trailer_duration, clip_duration, analysis_method, transition_style, music_path, out_w, out_h, progress: Progress):
2452
  """Internal implementation of the auto-trailer creator."""
2453
+ video_path = safe_copy_to_temp(video_path)
2454
+ music_path = safe_copy_to_temp(music_path)
2455
  if not video_path: raise gr.Error("Please upload a source video.")
2456
 
2457
  source_duration = get_media_duration(video_path)
 
2583
 
2584
 
2585
  def generate_waveform_video(video_path, style, size, position, color):
2586
+ video_path = safe_copy_to_temp(video_path)
2587
  if not video_path: raise gr.Error("Please upload a video first.")
2588
 
2589
  if not has_audio_stream(video_path):
 
2617
  return output_video_path
2618
 
2619
  def create_pip_video(main_video, overlay_media, position, scale):
2620
+ main_video = safe_copy_to_temp(main_video)
2621
  if not main_video: raise gr.Error("Please upload a main video.")
2622
+
2623
+ overlay_media_path = safe_copy_to_temp(overlay_media.name)
2624
+ if not overlay_media_path: raise gr.Error("Please upload an overlay video or image.")
2625
 
2626
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
2627
  output_video_path = os.path.join(TEMP_DIR, f"pip_video_{timestamp}.mp4")
 
2641
  }
2642
  overlay_filter = f"[0:v][scaled_overlay]overlay={pos_map[position]}"
2643
 
2644
+ cmd = ["ffmpeg", "-i", main_video, "-i", overlay_media_path]
2645
 
2646
  cmd.extend([
2647
  "-filter_complex", f"{scale_filter};{overlay_filter}",
 
2781
  job_temp_dir = os.path.join(TEMP_DIR, f"merge_{timestamp}")
2782
  os.makedirs(job_temp_dir, exist_ok=True)
2783
 
2784
+ safe_video_paths = [safe_copy_to_temp(v.name) for v in videos]
2785
+ safe_video_paths = [p for p in safe_video_paths if p is not None]
2786
+
2787
+ if len(safe_video_paths) < 2:
2788
+ raise gr.Error("Not enough valid videos to merge.")
2789
+
2790
+ first_video_path = safe_video_paths[0]
2791
  w, h = get_video_dimensions(first_video_path)
2792
  fps = get_video_fps(first_video_path)
2793
  w -= w % 2
2794
  h -= h % 2
2795
 
2796
  processed_clips = []
2797
+ for i, video_path in enumerate(safe_video_paths):
2798
  clip_path = os.path.join(job_temp_dir, f"clip_{i}.mp4")
2799
  cmd = [
2800
+ "ffmpeg", "-i", video_path,
2801
  "-vf", f"scale={w}:{h},setsar=1", "-r", str(fps),
2802
  "-c:v", "libx264", "-pix_fmt", "yuv420p",
2803
  "-c:a", "aac", "-ar", "44100",
 
2866
  raise gr.Error("Please upload images to create a collage.")
2867
 
2868
  bg_color = parse_color(bg_color_hex)
2869
+ images = [Image.open(f.name).convert("RGBA") for f in files]
2870
  n = len(images)
2871
 
2872
  if layout == "Grid":
 
2928
 
2929
  cmd = ["ffmpeg", "-y"]
2930
  input_count = 0
2931
+
2932
+ safe_video_paths = [safe_copy_to_temp(v.name) for v in videos]
2933
+ safe_video_paths = [p for p in safe_video_paths if p is not None]
2934
+
2935
+ if len(safe_video_paths) != num_videos:
2936
+ raise gr.Error("Could not access one or more of the uploaded videos.")
2937
+
2938
+ for video_path in safe_video_paths:
2939
+ cmd.extend(["-i", video_path])
2940
  input_count += 1
2941
 
2942
+ safe_music_path = safe_copy_to_temp(music_path)
2943
+ if safe_music_path:
2944
+ cmd.extend(["-i", safe_music_path])
2945
 
2946
  filter_complex_parts = []
2947
 
 
2984
  cmd.extend(["-map", "[vout]"])
2985
 
2986
  # Audio mapping logic
2987
+ if safe_music_path:
2988
  cmd.extend(["-map", f"{input_count}:a?"]) # Map the external audio track
2989
  cmd.extend(["-c:a", "aac", "-shortest"])
2990
  elif audio_choice != "None":
 
3006
  def _create_automated_slideshow_impl(images, audio_path, kb_effect_style, transition_style, rhythm_choice, out_w, out_h, progress: Progress):
3007
  """Internal implementation of the slideshow creator with progress tracking."""
3008
  if not images: raise gr.Error("Please upload at least one image.")
3009
+
3010
+ audio_path = safe_copy_to_temp(audio_path)
3011
  if not audio_path: raise gr.Error("Please upload an audio track for rhythmic editing.")
3012
 
3013
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
 
3057
 
3058
  output_clip_path = os.path.join(job_temp_dir, f"kb_clip_{i:04d}.mp4")
3059
 
3060
+ safe_image_path = safe_copy_to_temp(looped_image_paths[i])
3061
+ if not safe_image_path: continue
3062
+
3063
+ with Image.open(safe_image_path) as img:
3064
  iw, ih = img.size
3065
 
3066
  zoom_levels = {"Subtle": (1.1, 1.15), "Standard": (1.1, 1.25), "Dynamic": (1.2, 1.5)}
 
3087
 
3088
  zoompan_filter = f"zoompan=z='{z_expr}':x='{x_expr}':y='{y_expr}':d={total_frames}:s={output_res_str}:fps={fps}"
3089
 
3090
+ cmd = ["ffmpeg", "-y", "-loop", "1", "-i", safe_image_path, "-vf", zoompan_filter, "-t", str(clip_duration), "-c:v", "libx264", "-pix_fmt", "yuv420p", output_clip_path]
3091
  run_ffmpeg_command(cmd)
3092
  kb_clips.append({"path": output_clip_path, "duration": clip_duration})
3093
  current_step += 1
 
3133
 
3134
  def _create_rhythmic_remix_impl(video_path, audio_path, cut_style, beat_sync, resolution_choice, custom_w, custom_h, progress: Progress):
3135
  """Internal implementation of the auto-rhythmic video remixer."""
3136
+ video_path = safe_copy_to_temp(video_path)
3137
+ audio_path = safe_copy_to_temp(audio_path)
3138
  if not video_path: raise gr.Error("Please upload a source video.")
3139
  if not audio_path: raise gr.Error("Please upload an audio track.")
3140
 
 
3630
  clear_assets_btn.click(lambda: ([], gr.update(value=None), None), outputs=[assets_state, asset_gallery, asset_preview_gallery])
3631
  clear_timeline_btn.click(lambda: [], outputs=[timeline_state])
3632
  keep_audio_checkbox.change(fn=lambda x: gr.update(interactive=not x), inputs=keep_audio_checkbox, outputs=animatic_audio)
3633
+ # THIS IS THE FIX
3634
  generate_animatic_btn.click(fn=create_animatic, inputs=[timeline_state, animatic_audio, animatic_out_w, animatic_out_h, keep_audio_checkbox], outputs=animatic_output_video).then(fn=None, js=fire_confetti_and_sound_js)
3635
  analyze_bpm_btn.click(detect_bpm, animatic_audio, bpm_display)
3636
  generate_rhythmic_btn.click(fn=create_rhythmic_animatic, inputs=[timeline_state, animatic_audio, measure_dropdown, animatic_out_w, animatic_out_h], outputs=animatic_output_video).then(fn=None, js=fire_confetti_and_sound_js)
 
3759
  outputs=trailer_output_video
3760
  ).then(fn=None, js=fire_confetti_and_sound_js)
3761
 
3762
+ with gr.TabItem("🎬 Marker Stitcher"):
3763
+ gr.Markdown("## Manual Clip Stitcher")
3764
+ gr.Info("Play your video and click 'Add Marker' at key moments. This tool will extract a short clip around each marker and stitch them together into a new video.")
3765
+
3766
+ marker_times_state = gr.State([])
3767
+ new_marker_time_value = gr.Number(label="Last Marker Time", visible=False)
3768
+ # FIX 1: Add a state to hold the path to our own, safe copy of the video file.
3769
+ safe_video_path_state = gr.State(None)
3770
+
3771
+ with gr.Row():
3772
+ with gr.Column(scale=2):
3773
+ marker_input_video = gr.Video(label="Input Video", elem_id="marker_stitcher_input_video", height=UNIFIED_HEIGHT)
3774
+ with gr.Row():
3775
+ marker_add_btn = gr.Button("βž• Add Marker at Current Time")
3776
+ marker_clip_duration = gr.Slider(0.5, 10.0, 3.0, step=0.1, label="Clip Duration per Marker (s)")
3777
+
3778
+ marker_stitch_btn = gr.Button("🎬 Stitch Marked Clips", variant="primary")
3779
+
3780
+ with gr.Column(scale=1):
3781
+ gr.Markdown("#### Current Markers")
3782
+ marker_df = gr.DataFrame(headers=["Marker Time (s)"], datatype=["number"], interactive=False, row_count=10)
3783
+ marker_clear_btn = gr.Button("πŸ—‘οΈ Clear All Markers")
3784
+
3785
+ marker_output_video = gr.Video(label="Stitched Video Output", show_download_button=True, height=UNIFIED_HEIGHT, width="100%")
3786
+
3787
+ # --- Marker Stitcher Logic ---
3788
+
3789
+ marker_stitch_get_time_js = "() => { const v = document.querySelector('#marker_stitcher_input_video video'); return v ? v.currentTime : 0; }"
3790
+
3791
+ def add_marker_to_list(current_markers, new_time):
3792
+ new_marker_list = list(current_markers)
3793
+ if new_time is not None and (not new_marker_list or new_marker_list[-1] != round(new_time, 2)):
3794
+ new_marker_list.append(round(new_time, 2))
3795
+ new_marker_list.sort()
3796
+ return new_marker_list
3797
+
3798
+ def update_marker_df_from_list(marker_list):
3799
+ if not marker_list:
3800
+ return gr.update(value=None)
3801
+ df_data = [[t] for t in marker_list]
3802
+ return gr.update(value=df_data)
3803
+
3804
+ def clear_all_markers():
3805
+ return [], gr.update(value=None)
3806
+
3807
+ # --- Event Wiring ---
3808
+
3809
+ # FIX 2: When a video is uploaded, immediately create a safe copy of it.
3810
+ marker_input_video.upload(
3811
+ fn=safe_copy_to_temp,
3812
+ inputs=[marker_input_video],
3813
+ outputs=[safe_video_path_state]
3814
+ )
3815
+
3816
+ marker_add_btn.click(
3817
+ fn=None,
3818
+ js=marker_stitch_get_time_js,
3819
+ outputs=[new_marker_time_value]
3820
+ )
3821
+
3822
+ new_marker_time_value.change(
3823
+ fn=add_marker_to_list,
3824
+ inputs=[marker_times_state, new_marker_time_value],
3825
+ outputs=[marker_times_state]
3826
+ )
3827
+
3828
+ marker_times_state.change(
3829
+ fn=update_marker_df_from_list,
3830
+ inputs=marker_times_state,
3831
+ outputs=marker_df
3832
+ )
3833
+
3834
+ marker_clear_btn.click(
3835
+ fn=clear_all_markers,
3836
+ outputs=[marker_times_state, marker_df]
3837
+ )
3838
+
3839
+ # FIX 3: Use the 'safe_video_path_state' for processing, not the direct component value.
3840
+ marker_stitch_btn.click(
3841
+ fn=stitch_clips_from_markers,
3842
+ inputs=[safe_video_path_state, marker_times_state, marker_clip_duration],
3843
+ outputs=marker_output_video,
3844
+ show_progress="full"
3845
+ ).then(fn=None, js=fire_confetti_and_sound_js)
3846
+
3847
  with gr.TabItem("🎡 Audio Waveform"):
3848
  gr.Markdown("## Generate & Overlay Audio Waveforms")
3849
  gr.Info("Upload a video with an audio track to generate a dynamic waveform visualization.")
 
3913
  outputs=meme_output_image
3914
  ).then(fn=None, js=fire_confetti_and_sound_js)
3915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3916
  with gr.TabItem("πŸ–ΌοΈ Image Utilities", elem_id="image_tab"):
3917
  with gr.Tabs():
3918
  with gr.TabItem("✨ Manipulate"):
 
4086
  output_zip_wm = gr.File(label="Download All as .zip", interactive=False)
4087
  watermark_btn.click(apply_watermark_batch, [input_images_wm, watermark_text, watermark_pos, watermark_opacity], [output_gallery_wm, output_zip_wm]).then(fn=None, js=fire_confetti_and_sound_js)
4088
 
4089
+ with gr.TabItem("↔️ Batch Resizer"):
4090
  gr.Markdown("### Convert, resize, and compress a batch of images.")
 
4091
  with gr.Row():
4092
  with gr.Column():
4093
  brc_input_images = gr.File(label="Upload Images", file_count="multiple", file_types=["image"])
4094
  with gr.Accordion("βš™οΈ Output Settings", open=True):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4095
  brc_format = gr.Dropdown(["JPG", "PNG", "WEBP"], value="JPG", label="Output Format")
4096
  brc_quality = gr.Slider(1, 100, 90, step=1, label="JPG/WEBP Quality", interactive=True)
4097
+ brc_enable_resize = gr.Checkbox(label="Enable Resizing", value=False)
4098
+ with gr.Row():
4099
+ brc_max_w = gr.Number(label="Max Width", value=1920, interactive=False)
4100
+ brc_max_h = gr.Number(label="Max Height", value=1080, interactive=False)
4101
+ brc_resize_mode = gr.Radio(["Fit (preserve aspect ratio)", "Stretch to Fit"], value="Fit (preserve aspect ratio)", label="Resize Mode", interactive=False)
4102
  brc_btn = gr.Button("πŸš€ Process Images", variant="primary")
4103
  with gr.Column():
4104
  brc_output_gallery = gr.Gallery(label="Processed Images Preview", columns=4, object_fit="contain", height="auto")
4105
  brc_output_zip = gr.File(label="Download All as .zip", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4106
 
4107
  brc_format.change(lambda f: gr.update(visible=f in ["JPG", "WEBP"]), brc_format, brc_quality)
4108
+ brc_enable_resize.change(lambda x: [gr.update(interactive=x), gr.update(interactive=x), gr.update(interactive=x)], brc_enable_resize, [brc_max_w, brc_max_h, brc_resize_mode])
4109
  brc_btn.click(
4110
+ batch_resize_convert_images,
4111
+ [brc_input_images, brc_format, brc_quality, brc_enable_resize, brc_max_w, brc_max_h, brc_resize_mode],
 
4112
  [brc_output_gallery, brc_output_zip]
4113
  ).then(fn=None, js=fire_confetti_and_sound_js)
4114
 
 
4146
  with gr.Column():
4147
  output_gallery_v2f = gr.Gallery(label="Extracted Frames Preview (max 100 shown)", columns=8, object_fit="contain", height="auto")
4148
  output_zip_v2f = gr.File(label="Download All Frames (.zip)", interactive=False)
4149
+ input_video_v2f.upload(lambda v: f"{get_video_fps(safe_copy_to_temp(v)):.2f} FPS" if v else "N/A", input_video_v2f, v2f_fps_display)
4150
  v2f_resize.change(lambda x: [gr.update(interactive=x), gr.update(interactive=x)], v2f_resize, [v2f_width, v2f_height])
4151
  v2f_format.change(lambda x: gr.update(interactive=(x=="JPG")), v2f_format, v2f_jpg_quality)
4152
  extract_v2f_btn.click(video_to_frames_extractor, [input_video_v2f, v2f_skip_rate, v2f_rotation, v2f_resize, v2f_width, v2f_height, v2f_format, v2f_jpg_quality], [output_gallery_v2f, output_zip_v2f]).then(fn=None, js=fire_confetti_and_sound_js)
 
4372
  with gr.Row():
4373
  output_video_trim = gr.Video(label="Trimmed Video", interactive=True, show_download_button=True, height=UNIFIED_HEIGHT)
4374
  get_current_time_js = """()=>{const e=document.querySelector("#video-trim-input video");return e?e.currentTime:0}"""
4375
+ def get_frame_from_time_wrapper(v,t):
4376
+ v_safe = safe_copy_to_temp(v)
4377
+ return get_frame_at_time(v_safe,t), f"{t:.3f}"
4378
  set_start_btn.click(fn=None, js=get_current_time_js, outputs=[trim_start_time])
4379
  set_end_btn.click(fn=None, js=get_current_time_js, outputs=[trim_end_time])
4380
  trim_start_time.change(fn=get_frame_from_time_wrapper, inputs=[input_video_trim, trim_start_time], outputs=[start_frame_img, trim_start_time_display])
 
4407
  video_crop_output_video = gr.Video(label="Cropped Video", interactive=True, show_download_button=True, height=UNIFIED_HEIGHT)
4408
 
4409
  def setup_video_crop_preview(video_path):
4410
+ safe_path = safe_copy_to_temp(video_path)
4411
+ if not safe_path:
4412
  return None, None, gr.update(), gr.update(), gr.update(), gr.update()
4413
  try:
4414
+ img = get_frame_at_time(safe_path, 0)
4415
  w, h = img.size
4416
  return img, img, gr.update(maximum=w, value=w), gr.update(maximum=h, value=h), gr.update(maximum=w), gr.update(maximum=h)
4417
  except Exception as e:
 
4469
  with gr.TabItem("🎨 Color Grading"):
4470
  gr.Markdown("### Adjust Video Color, Contrast, and Sharpness")
4471
  gr.Info("Upload a video, load a preview frame, adjust the sliders for a live preview, and then apply the changes to the full video. The preview is 100% accurate to the final render.")
4472
+ color_grade_safe_video_path = gr.State(None)
4473
  with gr.Row(equal_height=False):
4474
  with gr.Column(scale=1):
4475
  color_grade_input_video = gr.Video(label="Input Video", height=UNIFIED_HEIGHT)
 
4491
 
4492
  grading_inputs = [cg_before_preview, cg_brightness, cg_contrast, cg_saturation, cg_sharpness]
4493
 
4494
+ def setup_cg_preview(video_path):
4495
+ safe_path = safe_copy_to_temp(video_path)
4496
+ if not safe_path: return None, None
4497
+ preview_frame = get_frame_at_time(safe_path, 0)
4498
+ return safe_path, preview_frame
4499
 
4500
  load_preview_btn.click(
4501
+ fn=lambda v: get_frame_at_time(v, 0),
4502
+ inputs=color_grade_safe_video_path,
4503
  outputs=cg_before_preview
4504
  ).then(
4505
  fn=preview_color_grading_ffmpeg,
 
4507
  outputs=cg_after_preview
4508
  )
4509
  color_grade_input_video.upload(
4510
+ fn=setup_cg_preview,
4511
+ inputs=color_grade_input_video,
4512
+ outputs=[color_grade_safe_video_path, cg_before_preview]
4513
  ).then(
4514
  fn=preview_color_grading_ffmpeg,
4515
  inputs=grading_inputs,
4516
  outputs=cg_after_preview
4517
  )
4518
+
4519
+ for slider in [cg_brightness, cg_contrast, cg_saturation, cg_sharpness]:
4520
+ slider.release(preview_color_grading_ffmpeg, inputs=grading_inputs, outputs=cg_after_preview)
4521
 
4522
  apply_grading_btn.click(
4523
  fn=apply_color_grading,
4524
+ inputs=[color_grade_safe_video_path, cg_brightness, cg_contrast, cg_saturation, cg_sharpness],
4525
  outputs=color_grade_output_video
4526
  ).then(fn=None, js=fire_confetti_and_sound_js)
4527
 
 
4744
  conv_btn.click(fn=convert_compress_video, inputs=[conv_input_video, conv_format, conv_vcodec, conv_crf, conv_scale, conv_acodec, conv_abitrate], outputs=conv_output_video).then(fn=None, js=fire_confetti_and_sound_js)
4745
 
4746
  with gr.TabItem("πŸ”— Transfer", elem_id="transfer_tab"):
4747
+ with gr.Tabs():
4748
+ with gr.TabItem("πŸ”— Link Manager"):
4749
+ gr.Markdown("## Link Preset Management")
4750
+ gr.Info("Manage URL presets, and open the target application in a new tab.")
4751
+ link_presets = gr.State(DEFAULT_LINK_PRESETS.copy())
4752
+
 
 
 
 
4753
  target_url = gr.Textbox(label="Target URL", value="https://huggingface.co/spaces/bep40/FramePack_rotate_landscape", interactive=True, elem_id="transfer_target_url")
4754
  search_bar = gr.Textbox(label="Search Presets", placeholder="Type to filter...", interactive=True)
4755
  with gr.Row():
 
4764
  new_preset_name = gr.Textbox(label="New Preset Name", placeholder="e.g., My Favorite App")
4765
  save_preset_btn = gr.Button("πŸ’Ύ Save")
4766
  open_link_btn = gr.Button("πŸš€ Open in New Tab", variant="primary")
4767
+
4768
+ search_bar.input(fn=filter_presets, inputs=[search_bar, link_presets], outputs=[preset_dropdown])
4769
+ preset_dropdown.change(fn=load_preset, inputs=[link_presets, preset_dropdown], outputs=[target_url])
4770
+ save_preset_btn.click(
4771
+ fn=save_preset, inputs=[link_presets, new_preset_name, target_url], outputs=[link_presets, preset_dropdown]
4772
+ ).then(lambda: ("", ""), outputs=[new_preset_name, search_bar])
4773
+ delete_confirm_js = """(name) => { if (!name) { alert('Please select a preset to delete.'); return false; } return confirm(`Are you sure you want to delete the preset: '` + name + `'?`); }"""
4774
+ delete_preset_btn.click(fn=None, js=delete_confirm_js, inputs=[preset_dropdown]).then(
4775
+ fn=delete_preset, inputs=[link_presets, preset_dropdown], outputs=[link_presets, preset_dropdown, target_url]
4776
+ ).then(lambda: "", outputs=[search_bar])
4777
+ open_link_btn.click(fn=None, js="()=>{const url=document.getElementById('transfer_target_url').querySelector('textarea').value;if(url){window.open(url,'_blank')}else{alert('Target URL is empty.')}}")
4778
 
4779
+ with gr.TabItem("πŸ€– FLUX.1 API"):
4780
+ gr.Markdown("### Generate an image using `FLUX.1` models via Gradio Client.")
4781
+ gr.Info("Requires a Hugging Face User Access Token.")
4782
+ with gr.Row():
4783
+ with gr.Column():
4784
+ hf_token_input = gr.Textbox(label="HF Token", type="password", placeholder="Enter hf_... token")
4785
+ flux_model_dropdown = gr.Dropdown(list(FLUX_MODELS.keys()), value="FLUX.1-schnell (Fast)", label="Select FLUX Model")
4786
+ prompt_input_flux = gr.Textbox(label="Prompt", lines=3, placeholder="A cinematic photo...")
4787
+ with gr.Row():
4788
+ flux_width_slider = gr.Slider(256, 2048, 1024, step=64, label="Width")
4789
+ flux_height_slider = gr.Slider(256, 2048, 1024, step=64, label="Height")
4790
+ flux_btn = gr.Button("β˜„οΈ Generate Image", variant="primary")
4791
+ with gr.Column():
4792
+ output_image_flux = gr.Image(label="Generated Image", show_download_button=True, height=UNIFIED_HEIGHT)
4793
+ flux_btn.click(call_flux_api, [prompt_input_flux, flux_model_dropdown, flux_width_slider, flux_height_slider, hf_token_input], output_image_flux).then(fn=None, js=fire_confetti_and_sound_js)
4794
+
4795
  main_tabs.select(fn=None, inputs=main_tabs, js="(tab) => { window.skriptz_bling.update_title(tab); }")
4796
 
4797
  gr.HTML('<a href="https://linktr.ee/skylinkd" target="_blank" style="color: #94a3b8; text-decoration: none;">skylinkd production 2025 (c)</a>', elem_id="custom-footer")
 
4803
  os.makedirs(TEMP_DIR, exist_ok=True)
4804
  if whisper:
4805
  load_whisper_model("base") # Pre-load the default model on startup
4806
+ demo.launch(inbrowser=True)