christopi commited on
Commit
4fffc9f
·
1 Parent(s): aaecb23

add video scheduler cleanup

Browse files
services/scoring/server.py CHANGED
@@ -665,13 +665,17 @@ async def score_upscaling_synthetics(request: UpscalingScoringRequest) -> Upscal
665
  os.unlink(ref_y4m_path)
666
  if dist_path and os.path.exists(dist_path):
667
  os.unlink(dist_path)
668
- if ref_path and os.path.exists(ref_path):
669
- os.unlink(ref_path)
670
 
671
  # Delete the uploaded object
672
  storage_client.delete_file(uploaded_object_name)
673
-
674
- delete_videos_with_fileid(video_id)
 
 
 
 
675
 
676
  tmp_directory = "/tmp"
677
  try:
 
665
  os.unlink(ref_y4m_path)
666
  if dist_path and os.path.exists(dist_path):
667
  os.unlink(dist_path)
668
+ # if ref_path and os.path.exists(ref_path):
669
+ # os.unlink(ref_path)
670
 
671
  # Delete the uploaded object
672
  storage_client.delete_file(uploaded_object_name)
673
+
674
+ # delete_videos_with_fileid(video_id)
675
+
676
+ for ref_path in request.reference_paths:
677
+ if os.path.exists(ref_path):
678
+ os.unlink(ref_path)
679
 
680
  tmp_directory = "/tmp"
681
  try:
services/video_scheduler/video_utils.py CHANGED
@@ -12,6 +12,7 @@ import tempfile
12
  import threading
13
  from dotenv import load_dotenv
14
  import random
 
15
 
16
  load_dotenv()
17
 
@@ -170,6 +171,13 @@ def apply_video_transformations(video_path: str, output_path: str = None, transf
170
  video_path_obj = Path(video_path)
171
  output_path = str(video_path_obj.parent / f"{video_path_obj.stem}_transformed{video_path_obj.suffix}")
172
 
 
 
 
 
 
 
 
173
  # Slight rotation, commented for now
174
  # rotation_angle_deg = random.uniform(-5, 5) # -5 to 5 degrees
175
  # transformations.append(f"rotate={2*math.pi*rotation_angle_deg/360}")
@@ -206,6 +214,12 @@ def apply_video_transformations(video_path: str, output_path: str = None, transf
206
  # Verify the output file was created and is not empty
207
  if not os.path.exists(output_path) or os.path.getsize(output_path) == 0:
208
  print(f"Warning: Output file is empty or doesn't exist: {output_path}")
 
 
 
 
 
 
209
  return video_path
210
 
211
  # Remove original file to save space only if transformation was successful and preserve_original is False
@@ -222,10 +236,26 @@ def apply_video_transformations(video_path: str, output_path: str = None, transf
222
  print(f"FFmpeg error applying video transformation: {e}")
223
  if e.stderr:
224
  print(f"FFmpeg stderr: {e.stderr}")
225
- # If transformation fails, return the original path
 
 
 
 
 
 
 
226
  return None
 
227
  except Exception as e:
228
  print(f"Unexpected error applying video transformation: {e}")
 
 
 
 
 
 
 
 
229
  return None
230
 
231
  def download_transform_and_trim_downscale_video(
@@ -322,6 +352,14 @@ def download_transform_and_trim_downscale_video(
322
  clipped_path = Path(output_dir) / f"{final_video_id}_trim.mp4"
323
  downscale_path = Path(output_dir) / f"{final_video_id}_downscale.mp4"
324
 
 
 
 
 
 
 
 
 
325
  chunk_start_time = time.time()
326
  safe_print(f"Processing chunk {i+1} from transformed video: {start_time_clip:.1f}s to {end_time_clip:.1f}s")
327
 
@@ -345,9 +383,22 @@ def download_transform_and_trim_downscale_video(
345
  print(f"Trimming chunk {i+1} to {actual_duration}s")
346
  subprocess.run(trim_cmd, check=True)
347
 
 
 
 
 
 
 
348
  if use_downscale_video:
349
  print(f"Downscaling chunk {i+1} to {downscale_height}p")
350
  subprocess.run(scale_cmd, check=True)
 
 
 
 
 
 
 
351
  else:
352
  downscale_path = None
353
 
@@ -355,8 +406,36 @@ def download_transform_and_trim_downscale_video(
355
  safe_print(f"Time taken to process chunk {i+1}: {chunk_elapsed_time:.2f} seconds")
356
 
357
  return (i, str(downscale_path), final_video_id, str(clipped_path))
 
358
  except subprocess.SubprocessError as e:
359
  safe_print(f"Error processing chunk {i+1}: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
  return None
361
 
362
  def generate_chunk_timestamps(total_duration, clip_duration):
@@ -555,10 +634,18 @@ def download_transform_and_trim_downscale_video(
555
  print(f"\n Creating {transformations_per_video} transformed versions of the original video...")
556
 
557
  transformed_video_paths = []
 
 
558
 
559
  transform_idx = 0
560
- while len(transformed_video_paths) < transformations_per_video:
561
  transformed_path = Path(output_dir) / f"{vid}_transform_{transform_idx}.mp4"
 
 
 
 
 
 
562
 
563
  transformed_result = apply_video_transformations(
564
  str(temp_path),
@@ -571,10 +658,20 @@ def download_transform_and_trim_downscale_video(
571
  transform_idx += 1
572
  print(f"✅ Created transformed version {len(transformed_video_paths)}: {transformed_result}")
573
  else:
574
- print(f"❌ Failed to create transformed version {transform_idx + 1}, retrying...")
575
-
 
 
 
 
 
 
576
 
577
- if not transformed_video_paths:
 
 
 
 
578
  print("❌ No transformed versions created successfully, falling back to original")
579
  transformed_video_paths = [str(temp_path)]
580
  transformations_per_video = 1
@@ -698,6 +795,68 @@ def delete_videos_with_fileid(file_id: int, dir_path: str = "videos") -> None:
698
  except Exception as e:
699
  print(f"Error deleting {file_path}: {e}")
700
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
701
  def download_trim_downscale_youtube_video(
702
  clip_duration: int,
703
  youtube_video_id: str,
@@ -778,6 +937,14 @@ def download_trim_downscale_youtube_video(
778
  clipped_path = Path(output_dir) / f"{video_id}_trim.mp4"
779
  downscale_path = Path(output_dir) / f"{video_id}_downscale.mp4"
780
 
 
 
 
 
 
 
 
 
781
  chunk_start_time = time.time()
782
  safe_print(f"Processing YouTube chunk {i+1}: {start_time_clip:.1f}s to {end_time_clip:.1f}s")
783
 
@@ -803,8 +970,23 @@ def download_trim_downscale_youtube_video(
803
  safe_print(f"Time taken to process YouTube chunk {i+1}: {chunk_elapsed_time:.2f} seconds")
804
 
805
  return (i, str(downscale_path), video_id, str(clipped_path))
 
806
  except subprocess.SubprocessError as e:
807
  safe_print(f"Error processing YouTube chunk {i+1}: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
808
  return None
809
 
810
  def generate_chunk_timestamps(total_duration, clip_duration):
@@ -986,7 +1168,7 @@ if __name__ == "__main__":
986
  CLIP_DURATION = 2
987
  vid = 2257054
988
 
989
- result = download_trim_downscale_video(
990
  clip_duration=CLIP_DURATION,
991
  vid=vid,
992
  task_type="HD24K",
 
12
  import threading
13
  from dotenv import load_dotenv
14
  import random
15
+ import glob
16
 
17
  load_dotenv()
18
 
 
171
  video_path_obj = Path(video_path)
172
  output_path = str(video_path_obj.parent / f"{video_path_obj.stem}_transformed{video_path_obj.suffix}")
173
 
174
+ if os.path.exists(output_path):
175
+ try:
176
+ os.remove(output_path)
177
+ print(f"Cleaned up existing output file before transformation: {output_path}")
178
+ except OSError as e:
179
+ print(f"Warning: Could not remove existing output file {output_path}: {e}")
180
+
181
  # Slight rotation, commented for now
182
  # rotation_angle_deg = random.uniform(-5, 5) # -5 to 5 degrees
183
  # transformations.append(f"rotate={2*math.pi*rotation_angle_deg/360}")
 
214
  # Verify the output file was created and is not empty
215
  if not os.path.exists(output_path) or os.path.getsize(output_path) == 0:
216
  print(f"Warning: Output file is empty or doesn't exist: {output_path}")
217
+ if os.path.exists(output_path):
218
+ try:
219
+ os.remove(output_path)
220
+ print(f"Removed empty/invalid output file: {output_path}")
221
+ except OSError as e:
222
+ print(f"Warning: Could not remove invalid output file {output_path}: {e}")
223
  return video_path
224
 
225
  # Remove original file to save space only if transformation was successful and preserve_original is False
 
236
  print(f"FFmpeg error applying video transformation: {e}")
237
  if e.stderr:
238
  print(f"FFmpeg stderr: {e.stderr}")
239
+
240
+ if os.path.exists(output_path):
241
+ try:
242
+ os.remove(output_path)
243
+ print(f"Cleaned up failed transformation output: {output_path}")
244
+ except OSError as cleanup_error:
245
+ print(f"Warning: Could not clean up failed output {output_path}: {cleanup_error}")
246
+
247
  return None
248
+
249
  except Exception as e:
250
  print(f"Unexpected error applying video transformation: {e}")
251
+
252
+ if os.path.exists(output_path):
253
+ try:
254
+ os.remove(output_path)
255
+ print(f"Cleaned up output file after unexpected error: {output_path}")
256
+ except OSError as cleanup_error:
257
+ print(f"Warning: Could not clean up output after error {output_path}: {cleanup_error}")
258
+
259
  return None
260
 
261
  def download_transform_and_trim_downscale_video(
 
352
  clipped_path = Path(output_dir) / f"{final_video_id}_trim.mp4"
353
  downscale_path = Path(output_dir) / f"{final_video_id}_downscale.mp4"
354
 
355
+ for cleanup_path in [clipped_path, downscale_path]:
356
+ if os.path.exists(cleanup_path):
357
+ try:
358
+ os.remove(cleanup_path)
359
+ safe_print(f"Cleaned up existing chunk file: {cleanup_path}")
360
+ except OSError as e:
361
+ safe_print(f"Warning: Could not remove existing chunk file {cleanup_path}: {e}")
362
+
363
  chunk_start_time = time.time()
364
  safe_print(f"Processing chunk {i+1} from transformed video: {start_time_clip:.1f}s to {end_time_clip:.1f}s")
365
 
 
383
  print(f"Trimming chunk {i+1} to {actual_duration}s")
384
  subprocess.run(trim_cmd, check=True)
385
 
386
+ if not os.path.exists(clipped_path) or os.path.getsize(clipped_path) == 0:
387
+ safe_print(f"Warning: Trim output is empty or invalid: {clipped_path}")
388
+ if os.path.exists(clipped_path):
389
+ os.remove(clipped_path)
390
+ return None
391
+
392
  if use_downscale_video:
393
  print(f"Downscaling chunk {i+1} to {downscale_height}p")
394
  subprocess.run(scale_cmd, check=True)
395
+
396
+ if not os.path.exists(downscale_path) or os.path.getsize(downscale_path) == 0:
397
+ safe_print(f"Warning: Downscale output is empty or invalid: {downscale_path}")
398
+ for cleanup_path in [clipped_path, downscale_path]:
399
+ if os.path.exists(cleanup_path):
400
+ os.remove(cleanup_path)
401
+ return None
402
  else:
403
  downscale_path = None
404
 
 
406
  safe_print(f"Time taken to process chunk {i+1}: {chunk_elapsed_time:.2f} seconds")
407
 
408
  return (i, str(downscale_path), final_video_id, str(clipped_path))
409
+
410
  except subprocess.SubprocessError as e:
411
  safe_print(f"Error processing chunk {i+1}: {e}")
412
+
413
+ cleanup_files = []
414
+ if os.path.exists(clipped_path):
415
+ cleanup_files.append(clipped_path)
416
+ if os.path.exists(downscale_path):
417
+ cleanup_files.append(downscale_path)
418
+
419
+ for cleanup_file in cleanup_files:
420
+ try:
421
+ os.remove(cleanup_file)
422
+ safe_print(f"Cleaned up failed chunk processing file: {cleanup_file}")
423
+ except OSError as cleanup_error:
424
+ safe_print(f"Warning: Could not clean up chunk file {cleanup_file}: {cleanup_error}")
425
+
426
+ return None
427
+
428
+ except Exception as e:
429
+ safe_print(f"Unexpected error processing chunk {i+1}: {e}")
430
+
431
+ for cleanup_path in [clipped_path, downscale_path]:
432
+ if os.path.exists(cleanup_path):
433
+ try:
434
+ os.remove(cleanup_path)
435
+ safe_print(f"Cleaned up file after unexpected error: {cleanup_path}")
436
+ except OSError as cleanup_error:
437
+ safe_print(f"Warning: Could not clean up file {cleanup_path}: {cleanup_error}")
438
+
439
  return None
440
 
441
  def generate_chunk_timestamps(total_duration, clip_duration):
 
634
  print(f"\n Creating {transformations_per_video} transformed versions of the original video...")
635
 
636
  transformed_video_paths = []
637
+ failed_attempts = 0
638
+ max_failed_attempts = transformations_per_video * 2 # Allow some retries but prevent infinite loops
639
 
640
  transform_idx = 0
641
+ while len(transformed_video_paths) < transformations_per_video and failed_attempts < max_failed_attempts:
642
  transformed_path = Path(output_dir) / f"{vid}_transform_{transform_idx}.mp4"
643
+ if os.path.exists(transformed_path):
644
+ try:
645
+ os.remove(transformed_path)
646
+ print(f"Cleaned up existing transformation file: {transformed_path}")
647
+ except OSError as e:
648
+ print(f"Warning: Could not clean up existing file {transformed_path}: {e}")
649
 
650
  transformed_result = apply_video_transformations(
651
  str(temp_path),
 
658
  transform_idx += 1
659
  print(f"✅ Created transformed version {len(transformed_video_paths)}: {transformed_result}")
660
  else:
661
+ failed_attempts += 1
662
+ print(f"❌ Failed to create transformed version {transform_idx + 1} (attempt {failed_attempts}/{max_failed_attempts})")
663
+ if os.path.exists(transformed_path):
664
+ try:
665
+ os.remove(transformed_path)
666
+ print(f"Cleaned up failed transformation file: {transformed_path}")
667
+ except OSError as e:
668
+ print(f"Warning: Could not clean up failed file {transformed_path}: {e}")
669
 
670
+ if failed_attempts >= max_failed_attempts:
671
+ print(f"⚠️ Exceeded maximum failed attempts ({max_failed_attempts}), falling back to original")
672
+ transformed_video_paths = [str(temp_path)]
673
+ transformations_per_video = 1
674
+ elif not transformed_video_paths:
675
  print("❌ No transformed versions created successfully, falling back to original")
676
  transformed_video_paths = [str(temp_path)]
677
  transformations_per_video = 1
 
795
  except Exception as e:
796
  print(f"Error deleting {file_path}: {e}")
797
 
798
+ def cleanup_orphaned_files(output_dir: str = "videos", max_age_hours: int = 720) -> None:
799
+ """
800
+ Cleanup function to remove orphaned files that may have been left behind by failed operations.
801
+ This acts as a safety net to prevent storage issues from accumulating files.
802
+
803
+ Args:
804
+ output_dir (str): Directory to clean up
805
+ max_age_hours (int): Maximum age in hours for files to keep
806
+ """
807
+ if not os.path.exists(output_dir):
808
+ print(f"Output directory does not exist: {output_dir}")
809
+ return
810
+
811
+ print(f"\nCleaning up orphaned files in {output_dir} older than {max_age_hours} hours...")
812
+
813
+ patterns = [
814
+ "*_transform_*.mp4",
815
+ "*_trim.mp4",
816
+ "*_downscale.mp4",
817
+ "*_original.mp4",
818
+ "*_ytransform_*.mp4"
819
+ ]
820
+
821
+ now = time.time()
822
+ max_age_seconds = max_age_hours * 3600
823
+
824
+ total_cleaned = 0
825
+ total_size_cleaned = 0
826
+
827
+ for pattern in patterns:
828
+ pattern_path = os.path.join(output_dir, pattern)
829
+ try:
830
+ for file_path in glob.glob(pattern_path):
831
+ try:
832
+ # Check file age
833
+ file_age = now - os.path.getmtime(file_path)
834
+ if file_age > max_age_seconds:
835
+ # Get file size before deleting
836
+ try:
837
+ file_size = os.path.getsize(file_path)
838
+ except OSError:
839
+ file_size = 0
840
+
841
+ try:
842
+ os.remove(file_path)
843
+ total_cleaned += 1
844
+ total_size_cleaned += file_size
845
+ print(f"Cleaned up orphaned file: {file_path} (Age: {file_age/3600:.1f} hours, Size: {file_size/1024/1024:.1f} MB)")
846
+ except OSError as e:
847
+ print(f"Warning: Could not remove orphaned file {file_path}: {e}")
848
+
849
+ except OSError as e:
850
+ print(f"Warning: Error checking file {file_path}: {e}")
851
+
852
+ except glob.error as e:
853
+ print(f"Warning: Error processing pattern {pattern}: {e}")
854
+
855
+ if total_cleaned > 0:
856
+ print(f"\nCleanup complete! Removed {total_cleaned} orphaned files (Total: {total_size_cleaned/1024/1024:.1f} MB)")
857
+ else:
858
+ print("\nNo orphaned files found to clean up")
859
+
860
  def download_trim_downscale_youtube_video(
861
  clip_duration: int,
862
  youtube_video_id: str,
 
937
  clipped_path = Path(output_dir) / f"{video_id}_trim.mp4"
938
  downscale_path = Path(output_dir) / f"{video_id}_downscale.mp4"
939
 
940
+ for cleanup_path in [clipped_path, downscale_path]:
941
+ if os.path.exists(cleanup_path):
942
+ try:
943
+ os.remove(cleanup_path)
944
+ safe_print(f"Cleaned up existing chunk file: {cleanup_path}")
945
+ except OSError as e:
946
+ safe_print(f"Warning: Could not remove existing chunk file {cleanup_path}: {e}")
947
+
948
  chunk_start_time = time.time()
949
  safe_print(f"Processing YouTube chunk {i+1}: {start_time_clip:.1f}s to {end_time_clip:.1f}s")
950
 
 
970
  safe_print(f"Time taken to process YouTube chunk {i+1}: {chunk_elapsed_time:.2f} seconds")
971
 
972
  return (i, str(downscale_path), video_id, str(clipped_path))
973
+
974
  except subprocess.SubprocessError as e:
975
  safe_print(f"Error processing YouTube chunk {i+1}: {e}")
976
+
977
+ cleanup_files = []
978
+ if os.path.exists(clipped_path):
979
+ cleanup_files.append(clipped_path)
980
+ if os.path.exists(downscale_path):
981
+ cleanup_files.append(downscale_path)
982
+
983
+ for cleanup_file in cleanup_files:
984
+ try:
985
+ os.remove(cleanup_file)
986
+ safe_print(f"Cleaned up failed chunk processing file: {cleanup_file}")
987
+ except OSError as cleanup_error:
988
+ safe_print(f"Warning: Could not clean up chunk file {cleanup_file}: {cleanup_error}")
989
+
990
  return None
991
 
992
  def generate_chunk_timestamps(total_duration, clip_duration):
 
1168
  CLIP_DURATION = 2
1169
  vid = 2257054
1170
 
1171
+ result = download_transform_and_trim_downscale_video(
1172
  clip_duration=CLIP_DURATION,
1173
  vid=vid,
1174
  task_type="HD24K",
services/video_scheduler/worker.py CHANGED
@@ -38,6 +38,11 @@ from video_utils import download_transform_and_trim_downscale_video
38
  from services.google_drive.google_drive_manager import GoogleDriveManager
39
  from vidaio_subnet_core import CONFIG
40
  from vidaio_subnet_core.utilities.storage_client import storage_client
 
 
 
 
 
41
 
42
  load_dotenv()
43
 
@@ -131,7 +136,7 @@ async def get_synthetic_urls(hotkey: str, num_needed: int) -> Optional[List[str]
131
  logger.error(f"Unexpected error fetching synthetic URLs: {str(e)}", exc_info=True)
132
  return None
133
 
134
- def clean_old_files(directory: str, age_limit_in_hours: int, check_interval_in_seconds: int = 100):
135
  """
136
  Continuously checks the given directory and deletes files older than the specified age (in hours).
137
 
@@ -557,7 +562,7 @@ async def get_compression_requests_paths(num_needed: int, redis_conn: redis.Redi
557
 
558
  return uploaded_video_chunks
559
 
560
- async def main():
561
  """
562
  Main service function that manages video processing workflow and queue maintenance.
563
 
@@ -677,8 +682,22 @@ async def main():
677
  except Exception as e:
678
  logger.error(f"Critical error in main service loop: {str(e)}")
679
  logger.exception("Exception details:")
680
- raise
 
681
 
 
 
 
 
 
 
 
 
 
 
 
 
 
682
 
683
  async def initialize_environment(redis_conn):
684
  """Initialize the processing environment by clearing queues and cached data."""
 
38
  from services.google_drive.google_drive_manager import GoogleDriveManager
39
  from vidaio_subnet_core import CONFIG
40
  from vidaio_subnet_core.utilities.storage_client import storage_client
41
+ from video_utils import (
42
+ download_transform_and_trim_downscale_video,
43
+ download_trim_downscale_youtube_video,
44
+ cleanup_orphaned_files
45
+ )
46
 
47
  load_dotenv()
48
 
 
136
  logger.error(f"Unexpected error fetching synthetic URLs: {str(e)}", exc_info=True)
137
  return None
138
 
139
+ async def clean_old_files(directory: str, age_limit_in_hours: int):
140
  """
141
  Continuously checks the given directory and deletes files older than the specified age (in hours).
142
 
 
562
 
563
  return uploaded_video_chunks
564
 
565
+ async def main_loop():
566
  """
567
  Main service function that manages video processing workflow and queue maintenance.
568
 
 
682
  except Exception as e:
683
  logger.error(f"Critical error in main service loop: {str(e)}")
684
  logger.exception("Exception details:")
685
+ finally:
686
+ logger.info("Main service loop exited. Cleaning up resources if necessary.")
687
 
688
+ async def manage_cleanup_loop(cleanup_interval: int = 24):
689
+ """
690
+ Manage the cleanup loop.
691
+ """
692
+ while True:
693
+ await asyncio.sleep(cleanup_interval * 3600)
694
+ logger.info("Cleaning up old files...")
695
+ await clean_old_files("videos", 720)
696
+
697
+ async def main():
698
+ cleanup_task = asyncio.create_task(manage_cleanup_loop())
699
+ main_task = asyncio.create_task(main_loop())
700
+ await asyncio.gather(cleanup_task, main_task)
701
 
702
  async def initialize_environment(redis_conn):
703
  """Initialize the processing environment by clearing queues and cached data."""
services/video_scheduler/youtube_requests.py CHANGED
@@ -195,6 +195,13 @@ def download_video(
195
  """Download video from YouTube"""
196
  print(f"Downloading video {video_url} to {output_path}")
197
 
 
 
 
 
 
 
 
198
  if cookie_file is None:
199
  print(f"Getting YouTube cookies from {FETCH_URL}")
200
  cookie_file = fetch_cookies()
@@ -214,10 +221,26 @@ def download_video(
214
  "fixup": "never",
215
  }
216
 
217
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
218
- ydl.download([video_url])
219
-
220
- return output_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
 
223
  def fetch_video_metadata(
@@ -344,11 +367,21 @@ class YouTubeHandler:
344
  time.sleep(0.1) # wait for cookies to stop refreshing
345
 
346
  attempt = 0
 
347
  while attempt < self.max_retries:
348
  try:
349
  if attempt:
350
  print(f"Starting download attempt {attempt}")
351
 
 
 
 
 
 
 
 
 
 
352
  result = download_video(self.vid_to_url(vid), *args, cookie_file=self.cookie_file, **kw)
353
  return result
354
 
@@ -356,6 +389,13 @@ class YouTubeHandler:
356
  error_str = str(e)
357
  print(f"Download attempt {attempt + 1} failed: {error_str}")
358
 
 
 
 
 
 
 
 
359
  # If it's a bot detection error, try refreshing cookies
360
  if "Sign in to confirm you're not a bot" in error_str or "blocked" in error_str.lower():
361
  print("🤖 Bot detection triggered, refreshing cookies...")
 
195
  """Download video from YouTube"""
196
  print(f"Downloading video {video_url} to {output_path}")
197
 
198
+ if os.path.exists(output_path):
199
+ try:
200
+ os.remove(output_path)
201
+ print(f"Cleaned up existing file before download: {output_path}")
202
+ except OSError as e:
203
+ print(f"Warning: Could not clean up existing file {output_path}: {e}")
204
+
205
  if cookie_file is None:
206
  print(f"Getting YouTube cookies from {FETCH_URL}")
207
  cookie_file = fetch_cookies()
 
221
  "fixup": "never",
222
  }
223
 
224
+ try:
225
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
226
+ ydl.download([video_url])
227
+
228
+ if not os.path.exists(output_path) or os.path.getsize(output_path) == 0:
229
+ print(f"Warning: Download produced empty or invalid file: {output_path}")
230
+ if os.path.exists(output_path):
231
+ os.remove(output_path)
232
+ raise Exception("Download failed or file is empty")
233
+
234
+ return output_path
235
+
236
+ except Exception as e:
237
+ if os.path.exists(output_path):
238
+ try:
239
+ os.remove(output_path)
240
+ print(f"Cleaned up failed download file: {output_path}")
241
+ except OSError as cleanup_error:
242
+ print(f"Warning: Could not clean up failed download {output_path}: {cleanup_error}")
243
+ raise e # Re-raise the original exception
244
 
245
 
246
  def fetch_video_metadata(
 
367
  time.sleep(0.1) # wait for cookies to stop refreshing
368
 
369
  attempt = 0
370
+ output_path = None
371
  while attempt < self.max_retries:
372
  try:
373
  if attempt:
374
  print(f"Starting download attempt {attempt}")
375
 
376
+ if 'output_path' in kw:
377
+ output_path = kw['output_path']
378
+ if os.path.exists(output_path):
379
+ try:
380
+ os.remove(output_path)
381
+ print(f"Cleaned up existing file before retry: {output_path}")
382
+ except OSError as e:
383
+ print(f"Warning: Could not clean up existing file {output_path}: {e}")
384
+
385
  result = download_video(self.vid_to_url(vid), *args, cookie_file=self.cookie_file, **kw)
386
  return result
387
 
 
389
  error_str = str(e)
390
  print(f"Download attempt {attempt + 1} failed: {error_str}")
391
 
392
+ if output_path and os.path.exists(output_path):
393
+ try:
394
+ os.remove(output_path)
395
+ print(f"Cleaned up failed download attempt: {output_path}")
396
+ except OSError as cleanup_error:
397
+ print(f"Warning: Could not clean up failed attempt {output_path}: {cleanup_error}")
398
+
399
  # If it's a bot detection error, try refreshing cookies
400
  if "Sign in to confirm you're not a bot" in error_str or "blocked" in error_str.lower():
401
  print("🤖 Bot detection triggered, refreshing cookies...")
vidaio_subnet_core/validating/managing/miner_manager.py CHANGED
@@ -32,7 +32,7 @@ class MinerManager:
32
  )
33
 
34
  # Clean up old database files before connecting to new database
35
- self._cleanup_old_database_files()
36
 
37
  # Download database from URL if needed
38
  db_url = self._download_database_from_url()
 
32
  )
33
 
34
  # Clean up old database files before connecting to new database
35
+ # self._cleanup_old_database_files()
36
 
37
  # Download database from URL if needed
38
  db_url = self._download_database_from_url()