Upload YT-playlist-to-mp3.ipynb
Browse files- YT-playlist-to-mp3.ipynb +1 -1
YT-playlist-to-mp3.ipynb
CHANGED
@@ -1 +1 @@
|
|
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":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"}},"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."],"metadata":{"id":"I64oSgGJxki5"}},{"cell_type":"code","execution_count":1,"metadata":{"id":"KXsmL_npl5Zf","executionInfo":{"status":"ok","timestamp":1756712516347,"user_tz":-120,"elapsed":5,"user":{"displayName":"","userId":""}}},"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":["#NOTE: you need to download cookies from youtube to your drive folder because of recent Youtubr BS restrictions\n","#Reinstall youtube_dl because the version on Colab is outdated\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"},"execution_count":null,"outputs":[]},{"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/tmp\n","for playlist_URL in youtube_link.split(','):\n"," !yt-dlp --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 = 'https://youtu.be/qxzbh6vPRZg?si=Ov2zBKly95fn-xGr' # @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 --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 ['.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":["\n","drive_folder_name = 'my_zip_folder' # @param {type:'string'}\n","\n","%cd /content/\n","!zip -r /content/drive/MyDrive/{drive_folder_name}.zip /content/tmp"],"metadata":{"id":"D04FssOTma-2"},"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":[]}]}
|
|
|
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":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"}},"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."],"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":["#NOTE: you need to download cookies from youtube to your drive folder because of recent Youtubr BS restrictions\n","#Reinstall youtube_dl because the version on Colab is outdated\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":1760625146213,"user_tz":-120,"elapsed":15691,"user":{"displayName":"","userId":""}},"outputId":"b8912905-dae9-4afe-ec9b-da1135ee5ac3","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/tmp\n","for playlist_URL in youtube_link.split(','):\n"," !yt-dlp --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 --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 ['.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":["\n","drive_folder_name = 'yt_music' # @param {type:'string'}\n","\n","%cd /content/\n","!zip -r /content/drive/MyDrive/{drive_folder_name}.zip /content/tmp"],"metadata":{"id":"D04FssOTma-2"},"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":[]}]}
|