File size: 31,946 Bytes
fb61471
1
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1762634251304},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1762004412712},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1761124521078},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1760628088876},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1756712618300},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1747490904984},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1740037333374},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1736477078136},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1725365086834}]},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"},"widgets":{"application/vnd.jupyter.widget-state+json":{"7021240f18e64d2d9ecffb4960655aa6":{"model_module":"@jupyter-widgets/controls","model_name":"HBoxModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"HBoxModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"HBoxView","box_style":"","children":["IPY_MODEL_24117c32ef1e43d3a8340e2fea2c032d","IPY_MODEL_b9a062706e394c68a954819052b65efb","IPY_MODEL_7b24c8672ec349a8ac0332082bf45b6d"],"layout":"IPY_MODEL_03437d6c3a9145de82e12c72c78a5dc7"}},"24117c32ef1e43d3a8340e2fea2c032d":{"model_module":"@jupyter-widgets/controls","model_name":"HTMLModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"HTMLView","description":"","description_tooltip":null,"layout":"IPY_MODEL_8b2c6685f32949cea06733e887c0d830","placeholder":"​","style":"IPY_MODEL_a2fa31f7e2bb466c9bbf7ba4e0c435a5","value":"Thumbs: 100%"}},"b9a062706e394c68a954819052b65efb":{"model_module":"@jupyter-widgets/controls","model_name":"FloatProgressModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"FloatProgressModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"ProgressView","bar_style":"success","description":"","description_tooltip":null,"layout":"IPY_MODEL_1fd3e789bb2947b3906ff9707f831e92","max":2,"min":0,"orientation":"horizontal","style":"IPY_MODEL_186f380d870c4254b1b41ddf2b036af0","value":2}},"7b24c8672ec349a8ac0332082bf45b6d":{"model_module":"@jupyter-widgets/controls","model_name":"HTMLModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"HTMLView","description":"","description_tooltip":null,"layout":"IPY_MODEL_72a74ddd44604833a5a19686208edb13","placeholder":"​","style":"IPY_MODEL_4d8760ddc11d4fc89f38ddf8c9e1c27b","value":" 2/2 [00:00&lt;00:00,  5.18thumb/s]"}},"03437d6c3a9145de82e12c72c78a5dc7":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"8b2c6685f32949cea06733e887c0d830":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"a2fa31f7e2bb466c9bbf7ba4e0c435a5":{"model_module":"@jupyter-widgets/controls","model_name":"DescriptionStyleModel","model_module_version":"1.5.0","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"DescriptionStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","description_width":""}},"1fd3e789bb2947b3906ff9707f831e92":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"186f380d870c4254b1b41ddf2b036af0":{"model_module":"@jupyter-widgets/controls","model_name":"ProgressStyleModel","model_module_version":"1.5.0","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"ProgressStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","bar_color":null,"description_width":""}},"72a74ddd44604833a5a19686208edb13":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"4d8760ddc11d4fc89f38ddf8c9e1c27b":{"model_module":"@jupyter-widgets/controls","model_name":"DescriptionStyleModel","model_module_version":"1.5.0","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"DescriptionStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","description_width":""}}}}},"cells":[{"cell_type":"markdown","source":["This Notebook will take a Youtube Playlist and convert all videos to MP3:s , which will be stored on a folder on your Google Drive.\n","\n","⚠️Note: YT did some obfuscation mumbo jumbo yesterday so downloads will run slower than usual until the yt-dlp guys fix it\n","\n","https://github.com/yt-dlp/yt-dlp/issues/14680"],"metadata":{"id":"I64oSgGJxki5"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"KXsmL_npl5Zf"},"outputs":[],"source":["#Initialize\n","import os\n","def my_mkdirs(folder):\n","  if os.path.exists(folder)==False:\n","    os.makedirs(folder)\n","my_mkdirs('/content/tmp/')"]},{"cell_type":"code","source":["#\n","!python3 -m pip install --force-reinstall https://github.com/yt-dlp/yt-dlp/archive/master.tar.gz\n","import yt_dlp as youtube_dl\n"],"metadata":{"id":"CT8O2CJYl-Cb"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Mount Google Drive\n","from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"vxae5FCml-0A","executionInfo":{"status":"ok","timestamp":1762004364476,"user_tz":-60,"elapsed":15017,"user":{"displayName":"","userId":""}},"outputId":"7da0a205-7a25-413d-fa6c-0271a0f1f4b3","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Mounted at /content/drive\n"]}]},{"cell_type":"code","source":["# @markdown download video or playlist as audio file mp3\n","youtube_link = '' # @param {type:'string'}\n","playlist_start = 1\n","## @param {type:'number'}\n","playlist_end = 9999\n","## @param {type:'number'}\n","\n","#Extract all videos in YT playlist mp3 files\n","#Aborting this code is fine if list is latge ( You will keep downloaded mp3:s)\n","%cd /content/drive/MyDrive/Saved from Chrome/\n","for playlist_URL in youtube_link.split(','):\n","  !yt-dlp --extractor-args \"youtube:player_js_version=actual\" --cookies /content/drive/MyDrive/ytcookies.txt --playlist-end {playlist_end} --playlist-start {playlist_start} --extract-audio --audio-format mp3 -o \"%(title)s.%(ext)s\" {playlist_URL}"],"metadata":{"id":"0K9n3HM6l-7x"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["\n","# @markdown Download video or playlist as highest video quality mp4\n","youtube_link = '' # @param {type:'string'}\n","playlist_start = 1\n","## @param {type:'number'}\n","playlist_end = 9999\n","## @param {type:'number'}\n","\n","#Extract all videos in YT playlist mp3 files\n","#Aborting this code is fine if list is latge ( You will keep downloaded mp3:s)\n","%cd /content/drive/MyDrive/Saved from Chrome/\n","for playlist_URL in youtube_link.split(','):\n","  !yt-dlp --extractor-args \"youtube:player_js_version=actual\" --cookies /content/drive/MyDrive/ytcookies.txt --playlist-end {playlist_end} --playlist-start {playlist_start} --merge-output-format mp4 -f \"bestvideo+bestaudio[ext=m4a]/best\"  -o \"%(title)s.%(ext)s\" {playlist_URL}"],"metadata":{"id":"EWZ4sO7NfdA6"},"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"metadata":{"id":"wTbO9mWbDXNr"},"outputs":[],"source":["\n","# @markdown 🌊 Rapid keyframe processing\n","# @markdown <br> ------ <br> Extract Keyframes from ALL mp4 / webm videos found on Google Drive\n","# @markdown <br> Be mindful of Google Drive Terms of Service\n","# @markdown <br> This cell will process all mp4 videos found under\n","# @markdown <br> /content/drive/MyDrive/Saved from Chrome/\n","delete_mp4_when_done = True # @param {type:'boolean'}\n","# @markdown <br> deleted mp4/webm files will be found under 'trash' in your Google drive\n","# @markdown <br> -------\n","# @markdown <br>  (Optional) Add a direct video link to below field.\n","# @markdown <br>  Multiple links can be written in this field\n","# @markdown <br> separated by comma.  Like this: <br> ' https:\\\\\\my_video.mp4  ,  https:\\\\\\second_video.webm ,  ....  '\n","import os\n","import shutil\n","!pip install video-kf\n","!pip install ffmpeg-python\n","!pip install wget\n","!pip install moviepy\n","import wget\n","import videokf as vf\n","import time\n","proc_keyframes=True # @param {type:'boolean'}\n","proc_audio=False # @param {type:'boolean'}\n","#def mkdirs(folder):\n","#  if not os.path.exists(folder):os.makedirs(folder)\n","#----#\n","direct_link = '' # @param {type:'string'}\n","# @markdown The linked videos will be downloaded to the Google drive prior to running the script.\n","# @markdown <br> This feature is useful for direct processing .webm from 4chan threads into keyframes\n","use_link = False # @param {type:'boolean'}\n","if direct_link.find('http')>-1: use_link = True\n","if use_link:\n","  %cd '/content/drive/MyDrive/Saved from Chrome/'\n","  for link in direct_link.split(','):\n","    if not link.find('http')>-1:continue\n","    wget.download(link.strip())\n","    time.sleep(5)\n","  %cd '/content/'\n","#-----#\n","filenames = []\n","srcpath = '/content/drive/MyDrive/Saved from Chrome/'\n","destpath = '/content/drive/MyDrive/'\n","localpath = '/content/'\n","converted = ''\n","for filename in os.listdir(f'{srcpath}'):\n","  if filename.find('.zip')>-1:\n","    %cd {srcpath}\n","    !unzip {filename}\n","    os.remove(filename)\n","    filename = filename.replace('.zip','')\n","  for suffix in ['.mkv','.mp4','.webm']:\n","    if filename.find(f'{suffix}')>-1: filenames.append(filename)\n","#Rename the downloaded video to 'tgt0' before running this cell\n","def my_mkdirs(folder):\n","  if os.path.exists(folder):shutil.rmtree(folder)\n","  os.makedirs(folder)\n","#----#\n","# @markdown Write a funny name for the folder(s) containing the keyframes\n","name_keyframes_as='' # @param {type:'string'}\n","# @markdown Created .zip files will not be overwritten\n","#NUM_ITEMS = 1 # @param {type:'slider', min:1 , max:20,step:1}\n","if name_keyframes_as.strip()=='': name_keyframes_as='keyframes'\n","num = 0\n","savepath = ''\n","%cd {localpath}\n","for filename in filenames:\n","  tgt_folder = f'/content/tmp'\n","  my_mkdirs(f'{tgt_folder}')\n","  print(f'Now processing video {filename}...')\n","  if proc_keyframes:\n","    vf.extract_keyframes(f'{srcpath}{filename}',output_dir_keyframes=f'{tgt_folder}')\n","    savepath = f'{destpath}{name_keyframes_as}_v{num}_kf'\n","    #---#\n","    while os.path.exists(f'{savepath}.zip'):\n","      #print(f'{savepath}.zip already exists...')\n","      num = num+1\n","      savepath = f'{destpath}{name_keyframes_as}_v{num}_kf'\n","    #---#\n","    shutil.make_archive(savepath,'zip' , f'{tgt_folder}')\n","    #from moviepy.editor import VideoFileClip\n","  if proc_audio:\n","    from moviepy.editor import VideoFileClip\n","    # Load the WebM file\n","    video = VideoFileClip(f\"{srcpath}{filename}\")\n","\n","    # Extract audio and save as MP3 (or WAV, etc.)\n","    audio = video.audio\n","    savepath = f\"{destpath}_audio_v{num}.mp3\"\n","\n","    while os.path.exists(savepath):\n","      num = num+1\n","      savepath= f\"{destpath}_audio_v{num}.mp3\"\n","    #----#\n","    if audio:\n","      audio.write_audiofile(f'{savepath}')\n","      # Close the files to free resources\n","      audio.close()\n","      video.close()\n","  #----#\n","  if delete_mp4_when_done: os.remove(f'{srcpath}{filename}')\n","  num = num+1\n"]},{"cell_type":"code","source":["import os\n","import zipfile\n","import glob\n","from google.colab import drive\n","import shutil\n","from pathlib import Path\n","\n","# Mount Google Drive\n","drive.mount('/content/drive')\n","\n","# Define the directory containing the zip files\n","zip_dir = '/content/drive/MyDrive/'\n","zip_pattern = 'keyframes_v*_kf.zip'\n","output_zip = '/content/drive/MyDrive/all_keyframes_combined.zip'\n","\n","# Temporary extraction directory\n","temp_dir = '/content/temp_extracted'\n","os.makedirs(temp_dir, exist_ok=True)\n","\n","# Function to check if file is an image\n","def is_image_file(filename):\n","    image_extensions = {\n","        '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.tif',\n","        '.webp', '.ico', '.svg', '.heic', '.heif', '.raw', '.cr2',\n","        '.nef', '.arw', '.dng', '.jpe', '.jp2', '.j2k'\n","    }\n","    ext = Path(filename).suffix.lower()\n","    return ext in image_extensions\n","\n","# Store original zip files for cleanup\n","original_zip_files = []\n","\n","print(\"Finding zip files...\")\n","zip_files = glob.glob(os.path.join(zip_dir, zip_pattern))\n","original_zip_files = zip_files.copy()  # Keep for cleanup\n","print(f\"Found {len(zip_files)} zip files: {[os.path.basename(z) for z in zip_files]}\")\n","\n","# Extract each zip file\n","image_txt_pairs = []\n","for zip_path in zip_files:\n","    print(f\"\\nπŸ”“ Extracting: {os.path.basename(zip_path)}\")\n","\n","    with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n","        # Extract to temporary directory with unique subfolder\n","        unique_subdir = os.path.join(temp_dir, Path(zip_path).stem)\n","        zip_ref.extractall(unique_subdir)\n","\n","        # Find all files in the extracted content\n","        for root, dirs, files in os.walk(unique_subdir):\n","            for file in files:\n","                file_path = os.path.join(root, file)\n","                base_name = Path(file).stem\n","                ext = Path(file).suffix.lower()\n","\n","                if is_image_file(file):\n","                    # Look for corresponding txt file\n","                    txt_path = None\n","                    possible_txt_names = [\n","                        f\"{base_name}.txt\",\n","                        f\"{base_name.lower()}.txt\",\n","                        f\"{base_name.upper()}.txt\"\n","                    ]\n","\n","                    for txt_name in possible_txt_names:\n","                        potential_txt = os.path.join(root, txt_name)\n","                        if os.path.exists(potential_txt):\n","                            txt_path = potential_txt\n","                            break\n","\n","                    image_txt_pairs.append({\n","                        'image_path': file_path,\n","                        'txt_path': txt_path,\n","                        'base_name': base_name\n","                    })\n","\n","print(f\"\\nπŸ“Š Total image-txt pairs found: {len(image_txt_pairs)}\")\n","print(f\"   Images with matching txt: {sum(1 for p in image_txt_pairs if p['txt_path'])}\")\n","print(f\"   Images without txt: {sum(1 for p in image_txt_pairs if not p['txt_path'])}\")\n","\n","# Create the output zip file\n","print(\"\\nπŸ—œοΈ Creating combined zip file...\")\n","combined_zip_created = False\n","\n","try:\n","    with zipfile.ZipFile(output_zip, 'w', zipfile.ZIP_DEFLATED) as output_zip_file:\n","        for i, pair in enumerate(image_txt_pairs, 1):\n","            try:\n","                # Create new image filename (keep original extension)\n","                original_ext = Path(pair['image_path']).suffix.lower()\n","                new_image_name = f\"{i}{original_ext}\"\n","\n","                # Add image\n","                with open(pair['image_path'], 'rb') as img_file:\n","                    img_data = img_file.read()\n","                output_zip_file.writestr(new_image_name, img_data)\n","\n","                # Add corresponding txt file if exists\n","                if pair['txt_path'] and os.path.exists(pair['txt_path']):\n","                    new_txt_name = f\"{i}.txt\"\n","                    with open(pair['txt_path'], 'rb') as txt_file:\n","                        txt_data = txt_file.read()\n","                    output_zip_file.writestr(new_txt_name, txt_data)\n","\n","                if i % 50 == 0:\n","                    print(f\"Processed {i}/{len(image_txt_pairs)} items...\")\n","\n","            except Exception as e:\n","                print(f\"❌ Error processing item {i}: {e}\")\n","                continue\n","\n","    # Verify the output zip was created successfully\n","    if os.path.exists(output_zip) and os.path.getsize(output_zip) > 0:\n","        combined_zip_created = True\n","        print(\"βœ… Combined zip file created successfully!\")\n","    else:\n","        print(\"❌ Failed to create combined zip file!\")\n","        combined_zip_created = False\n","\n","except Exception as e:\n","    print(f\"❌ Error creating combined zip: {e}\")\n","    combined_zip_created = False\n","\n","# Clean up temporary directory\n","try:\n","    shutil.rmtree(temp_dir, ignore_errors=True)\n","    print(\"🧹 Temporary extraction files cleaned up\")\n","except:\n","    print(\"⚠️ Could not clean up temporary extraction files\")\n","\n","# Remove original zip files ONLY if combined zip was created successfully\n","if combined_zip_created and original_zip_files:\n","    print(f\"\\nπŸ—‘οΈ Removing {len(original_zip_files)} original zip files...\")\n","    removed_count = 0\n","\n","    for zip_path in original_zip_files:\n","        try:\n","            if os.path.exists(zip_path):\n","                os.remove(zip_path)\n","                print(f\"   πŸ—‘οΈ Removed: {os.path.basename(zip_path)}\")\n","                removed_count += 1\n","            else:\n","                print(f\"   ⚠️ File not found: {os.path.basename(zip_path)}\")\n","        except Exception as e:\n","            print(f\"   ❌ Failed to remove {os.path.basename(zip_path)}: {e}\")\n","\n","    print(f\"βœ… Successfully removed {removed_count}/{len(original_zip_files)} original zip files\")\n","else:\n","    print(\"\\n⚠️ Skipping removal of original files - combined zip creation failed!\")\n","    print(\"   Original files preserved for safety.\")\n","\n","# Final verification\n","if os.path.exists(output_zip):\n","    with zipfile.ZipFile(output_zip, 'r') as z:\n","        file_list = z.namelist()\n","        print(f\"\\nπŸ” Final verification:\")\n","        print(f\"   πŸ“ Combined zip: {output_zip}\")\n","        print(f\"   πŸ“Š Total files: {len(file_list)}\")\n","\n","        images_count = len([f for f in file_list if is_image_file(f)])\n","        txts_count = len([f for f in file_list if f.endswith('.txt')])\n","        print(f\"   πŸ–ΌοΈ Images: {images_count}\")\n","        print(f\"   πŸ“„ Text files: {txts_count}\")\n","\n","        # Check for matching pairs\n","        image_numbers = set()\n","        txt_numbers = set()\n","        for f in file_list:\n","            if is_image_file(f):\n","                try:\n","                    num = int(Path(f).stem)\n","                    image_numbers.add(num)\n","                except:\n","                    pass\n","            elif f.endswith('.txt'):\n","                try:\n","                    num = int(Path(f).stem)\n","                    txt_numbers.add(num)\n","                except:\n","                    pass\n","\n","        matched_pairs = len(image_numbers & txt_numbers)\n","        print(f\"   πŸ”— Matched image-txt pairs: {matched_pairs}\")\n","        print(f\"   πŸ’Ύ Size: {os.path.getsize(output_zip) / (1024*1024):.1f} MB\")\n","\n","print(f\"\\nπŸŽ‰ Process completed!\")\n","print(f\"πŸ“ Final output: {output_zip}\")\n","if combined_zip_created:\n","    print(\"βœ… All original zip files have been removed.\")\n","else:\n","    print(\"⚠️ Original files preserved due to error.\")"],"metadata":{"id":"uZXUfKefmCIv"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["from google.colab import runtime\n","runtime.unassign()\n","\n","\n"],"metadata":{"id":"1JlaBNIKODCT"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# @title Download YouTube Thumbnails (recursive playlists) β†’ ZIP\n","# @markdown **Paste one or more YouTube URLs** (video, playlist **or channel**).\n","# @markdown Separate several links with a comma.\n","# @markdown The script will walk *all* nested playlists (Videos, Shorts, Live …) and stop after the chosen limit.\n","\n","!pip install --quiet --force-reinstall https://github.com/yt-dlp/yt-dlp/archive/master.tar.gz\n","import yt_dlp as youtube_dl\n","import os, re, shutil, json, time\n","from google.colab import drive\n","from tqdm.auto import tqdm\n","\n","drive.mount('/content/drive', force_remount=False)\n","\n","# ---------- USER PARAMETERS ----------\n","youtube_links = 'https://youtube.com/@kaitaisurale1990?si=y9w3IZa5FsFtwGX9'          # @param {type:\"string\"}\n","zip_filename  = 'yt_thumbs' # @param {type:\"string\"}\n","max_thumbs    = 501         # @param {type:\"slider\", min:1, max:2000, step:10}\n","\n","# ---------- PATHS ----------\n","save_dir   = '/content/drive/MyDrive/Saved from Chrome'\n","thumb_dir  = '/content/yt_thumbs_temp'\n","os.makedirs(thumb_dir, exist_ok=True)\n","\n","# clean previous run\n","for f in os.listdir(thumb_dir): os.remove(os.path.join(thumb_dir, f))\n","\n","zip_path = os.path.join(save_dir, re.sub(r'[<>:\"/\\\\|?*]', '_', zip_filename.strip() or 'yt_thumbs') + '.zip')\n","\n","# ---------- yt-dlp base options ----------\n","base_opts = {\n","    'quiet'        : True,\n","    'no_warnings'  : True,\n","    'extract_flat' : True,          # we only need URLs + titles for the recursion\n","    'skip_download': True,\n","    'cookiefile'   : '/content/drive/MyDrive/ytcookies.txt'  # optional – remove if you don’t have one\n","}\n","\n","# ---------- Helper functions ----------\n","def sanitize(name: str) -> str:\n","    return re.sub(r'[<>:\"/\\\\|?*]', '_', name)[:180]\n","\n","def download_one_thumb(info: dict, idx: int) -> bool:\n","    \"\"\"Download the best thumbnail for a single entry.\"\"\"\n","    # pick highest-resolution thumbnail\n","    thumbs = info.get('thumbnails') or []\n","    thumb_url = None\n","    if thumbs:\n","        thumb_url = max(thumbs, key=lambda t: t.get('width',0)*t.get('height',0)).get('url')\n","    if not thumb_url:\n","        thumb_url = info.get('thumbnail')\n","    if not thumb_url:\n","        return False\n","\n","    ext = thumb_url.split('?')[0].split('.')[-1]\n","    if ext not in {'jpg','jpeg','png','webp'}: ext = 'jpg'\n","    title = info.get('title') or info.get('id') or f'video_{idx}'\n","    fname = f\"{sanitize(title)}.{ext}\"\n","    fpath = os.path.join(thumb_dir, fname)\n","\n","    !curl -s -L -o \"{fpath}\" \"{thumb_url}\"\n","    return os.path.exists(fpath)\n","\n","def extract_recursive(url: str, collected: list, limit: int):\n","    \"\"\"Recursively extract video entries from playlists (including channel tabs).\"\"\"\n","    if len(collected) >= limit:\n","        return\n","\n","    ydl = youtube_dl.YoutubeDL({**base_opts, 'extract_flat': True})\n","    try:\n","        info = ydl.extract_info(url, download=False)\n","    except Exception as e:\n","        print(f\"Warning: Failed to process {url}: {e}\")\n","        return\n","\n","    # ---- single video -------------------------------------------------\n","    if info.get('_type') == 'video' or 'entries' not in info:\n","        if len(collected) < limit:\n","            collected.append(info)\n","        return\n","\n","    # ---- playlist / channel -------------------------------------------\n","    entries = info.get('entries') or []\n","    for entry in entries:\n","        if entry is None: continue\n","\n","        # If the entry itself is a playlist (e.g. a channel tab) β†’ recurse\n","        if entry.get('_type') == 'playlist' and entry.get('url'):\n","            sub_url = entry['url']\n","            if not sub_url.startswith('http'):\n","                sub_url = f\"https://www.youtube.com{sub_url}\"\n","            extract_recursive(sub_url, collected, limit)\n","        else:\n","            # Normal video entry\n","            if len(collected) < limit:\n","                collected.append(entry)\n","\n","# ---------- MAIN ---------------------------------------------------------\n","urls = [u.strip() for u in youtube_links.split(',') if u.strip()]\n","if not urls:\n","    raise ValueError(\"Please fill **youtube_links** with at least one URL.\")\n","\n","video_infos = []\n","for u in urls:\n","    print(f\"\\nScanning: {u}\")\n","    extract_recursive(u, video_infos, max_thumbs)\n","\n","print(f\"\\nCollected {len(video_infos)} video entries (capped at {max_thumbs}).\")\n","print(\"Downloading thumbnails …\")\n","\n","pbar = tqdm(total=len(video_infos), desc=\"Thumbs\", unit=\"thumb\")\n","downloaded = 0\n","for i, info in enumerate(video_infos):\n","    if download_one_thumb(info, i+1):\n","        downloaded += 1\n","    pbar.update(1)\n","pbar.close()\n","\n","print(f\"\\nDownloaded {downloaded}/{len(video_infos)} thumbnails.\")\n","\n","# ---------- ZIP ---------------------------------------------------------\n","print(\"Creating ZIP …\")\n","shutil.make_archive(zip_path.replace('.zip',''), 'zip', thumb_dir)\n","print(f\"ZIP ready β†’ {zip_path}\")\n","\n","# clean temp folder\n","shutil.rmtree(thumb_dir)"],"metadata":{"id":"Ujzfv1yEMAId","colab":{"base_uri":"https://localhost:8080/","height":339,"referenced_widgets":["7021240f18e64d2d9ecffb4960655aa6","24117c32ef1e43d3a8340e2fea2c032d","b9a062706e394c68a954819052b65efb","7b24c8672ec349a8ac0332082bf45b6d","03437d6c3a9145de82e12c72c78a5dc7","8b2c6685f32949cea06733e887c0d830","a2fa31f7e2bb466c9bbf7ba4e0c435a5","1fd3e789bb2947b3906ff9707f831e92","186f380d870c4254b1b41ddf2b036af0","72a74ddd44604833a5a19686208edb13","4d8760ddc11d4fc89f38ddf8c9e1c27b"]},"executionInfo":{"status":"ok","timestamp":1762634355132,"user_tz":-60,"elapsed":44846,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"94e941bb-003d-4aec-a468-813f05276e9b"},"execution_count":1,"outputs":[{"output_type":"stream","name":"stdout","text":["\u001b[2K     \u001b[32m/\u001b[0m \u001b[32m2.9 MB\u001b[0m \u001b[31m10.0 MB/s\u001b[0m \u001b[33m0:00:00\u001b[0m\n","\u001b[?25h  Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n","  Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n","  Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n","  Building wheel for yt-dlp (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n","Mounted at /content/drive\n","\n","Scanning: https://youtube.com/@kaitaisurale1990?si=y9w3IZa5FsFtwGX9\n","\n","Collected 2 video entries (capped at 501).\n","Downloading thumbnails …\n"]},{"output_type":"display_data","data":{"text/plain":["Thumbs:   0%|          | 0/2 [00:00<?, ?thumb/s]"],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"7021240f18e64d2d9ecffb4960655aa6"}},"metadata":{}},{"output_type":"stream","name":"stdout","text":["\n","Downloaded 2/2 thumbnails.\n","Creating ZIP …\n","ZIP ready β†’ /content/drive/MyDrive/Saved from Chrome/yt_thumbs.zip\n"]}]}]}