File size: 15,806 Bytes
373b98b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 |
# Colab_ZIP_Cleanup_Tool_V1.2.0.py
# ==============================================================================
# === CONFIGURATION ============================================================
# ==============================================================================
# The top-level directory you want to manage. The script will not allow you
# to navigate *above* this directory for safety.
ROOT_CLEANUP_DIRECTORY = './runs'
# ==============================================================================
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Advanced Colab File Manager & Toolkit
#
# # # # # # # # # # # # # # # # # # #_# # # # # # # # # # # # # # # # # # # #
#
# Author: [Martia L. Terran]
# Version: 1.2.0
# License: MIT License
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# ==============================================================================
# === I. DESCRIPTION ===
# ==============================================================================
#
# This script is a powerful, interactive, terminal-style file manager designed
# specifically to overcome the file management limitations of Google Colab and
# other Jupyter-like notebook environments. Standard Colab interfaces make it
# tedious to delete non-empty folders, navigate directory structures, or
# perform bulk operations like zipping and deletion. This tool provides a
# safe and efficient command-line interface directly within a notebook cell
# to perform these tasks with ease.
#
# It is ideal for users who run frequent experiments (e.g., machine learning
# training runs) and need to clean up, archive, or inspect the resulting
# nested directories of logs, checkpoints, and plot outputs.
#
# --- The Problem It Solves ---
#
# - Deleting a folder with contents in Colab requires recursive code; there
# is no simple "right-click -> delete" for non-empty directories.
# - Navigating deep into sub-sub-folders to inspect or manage files is
# cumbersome, requiring many `os.listdir()` or `!ls` commands.
# - Archiving multiple experiment folders for download is a manual,
# repetitive process.
# - Accidental deletion with `shutil.rmtree()` is easy and irreversible.
# This tool adds a confirmation layer to prevent mistakes.
#
# --- Key Features ---
#
# π Interactive Navigation: Seamlessly move up and down directory trees.
# ποΈ Safe, Confirmed Deletion: Delete multiple files or entire folders
# (recursively) with a clear confirmation prompt to prevent accidents.
# π¦ Easy & Smart Archiving: Select any number of files or folders and
# compress them into uniquely named .zip files, preventing overwrites.
# π Detailed Information View: Instantly see item sizes, modification
# dates, and folder contents (file/subfolder counts).
# π§ Safety Rails: The tool is sandboxed to the specified root directory,
# preventing accidental navigation into system-critical paths.
#
# ==============================================================================
# === II. USER MANUAL ===
# ==============================================================================
#
# --- Getting Started ---
#
# 1. Paste the entire script into a single Google Colab code cell.
# 2. (Optional) Modify the `ROOT_CLEANUP_DIRECTORY` variable to your target
# folder (e.g., './runs', '/content/drive/MyDrive/my_project').
# 3. Run the cell. The interactive tool will start.
#
# --- The Interface ---
#
# - You Are Here: The top of the display always shows your current absolute path.
# - Item List: The main view lists all folders π and files π in the
# current directory. Each item is assigned a number `[##]`.
# - Command Prompt: At the bottom, a `π Your choice:` prompt awaits your command.
#
# --- Command Reference ---
#
# Enter commands at the prompt. Commands are case-insensitive.
#
# πΉ cd <number>
# Changes the current directory to the folder specified by the number.
# Example: `cd 3` - Enters the folder listed as [03].
#
# πΉ del <number(s)>
# Marks one or more items for PERMANENT deletion. You can list multiple
# numbers separated by spaces.
# Example: `del 2 5 8` - Selects items [02], [05], and [08] for deletion.
# π¨ A confirmation prompt will appear. You MUST type 'DELETE' to proceed.
# This is your final chance to cancel the operation.
#
# πΉ zip <number(s)>
# Compresses the selected items into .zip archives in the current directory.
# - If you zip a FOLDER, it creates a zip of its entire contents.
# - If you zip a FILE, it creates a zip containing that single file.
# - Automatically avoids overwrites by appending a number if the zip
# file already exists (e.g., `my_run.zip` -> `my_run_1.zip`).
# Example: `zip 1 4` - Creates two separate zip files for items [01] and [04].
#
# πΉ .. (or 'up')
# Navigates up to the parent directory. You cannot go above the configured
# root directory.
#
# πΉ home
# Instantly returns you to the top-level `ROOT_CLEANUP_DIRECTORY`.
#
# πΉ r
# Refreshes the view of the current directory. Useful after a zip operation
# or if files were changed by another process.
#
# πΉ q
# Exits the tool safely.
#
# ==============================================================================
# === III. BEST PRACTICES & TIPS ===
# ==============================================================================
#
# - Zip Before You Delete: As a safety net, consider zipping a folder
# before deleting it. This gives you a backup.
# - Downloading Files: After zipping, use the standard Colab file browser
# on the left-hand side to find your newly created .zip file, right-click
# it, and select "Download".
# - Be Careful with `del`: The deletion is permanent and bypasses any
# "trash" or "recycle bin" functionality. Always double-check the
# confirmation list before typing 'DELETE'.
#
import os
import shutil
import datetime
import zipfile
from google.colab import output
def get_item_info(item_path):
"""Gathers detailed information about a file or a folder."""
try:
mod_time = os.path.getmtime(item_path)
mod_date = datetime.datetime.fromtimestamp(mod_time).strftime('%Y-%m-%d %H:%M:%S')
if os.path.isdir(item_path):
total_size = 0
file_count = 0
folder_count = 0
for dirpath, dirnames, filenames in os.walk(item_path):
file_count += len(filenames)
folder_count += len(dirnames)
for f in filenames:
fp = os.path.join(dirpath, f)
if not os.path.exists(fp): continue
total_size += os.path.getsize(fp)
return {
'type': 'folder', 'size': total_size,
'files': file_count, 'folders': folder_count,
'modified': mod_date
}
else:
size = os.path.getsize(item_path)
return {'type': 'file', 'size': size, 'modified': mod_date}
except FileNotFoundError:
return None
def format_size(byte_size):
"""Converts bytes into a human-readable format."""
if byte_size is None: return "N/A"
if byte_size < 1024: return f"{byte_size} B"
elif byte_size < 1024**2: return f"{byte_size/1024**2:.2f} MB"
else: return f"{byte_size/1024**3:.2f} GB"
def get_unique_filename(path):
"""
Checks if a file exists. If so, appends a number to make it unique.
Example: 'my_file.zip' -> 'my_file_1.zip'
"""
if not os.path.exists(path):
return path
directory, full_filename = os.path.split(path)
filename, extension = os.path.splitext(full_filename)
counter = 1
while True:
new_filename = f"{filename}_{counter}{extension}"
new_path = os.path.join(directory, new_filename)
if not os.path.exists(new_path):
return new_path
counter += 1
def display_directory_contents(current_path):
"""Lists the contents of the given path and returns an indexed list."""
print("\n[INFO] Analyzing contents...\n")
try:
all_items = sorted(os.listdir(current_path))
except FileNotFoundError:
print(f"β Error: Directory '{current_path}' not found.")
return []
folders = [item for item in all_items if os.path.isdir(os.path.join(current_path, item))]
files = [item for item in all_items if os.path.isfile(os.path.join(current_path, item))]
listed_items = []
item_index = 1
for name in folders:
path = os.path.join(current_path, name)
info = get_item_info(path)
if not info: continue
display_name = f"π [{item_index:02d}] {name}"
display_size = f"Size: {format_size(info['size']):>10s}"
display_contents = f"({info['files']} files, {info['folders']} folders)"
print(f"{display_name:<40} | {display_size} | {display_contents}")
listed_items.append({'name': name, 'path': path, 'type': 'folder'})
item_index += 1
for name in files:
path = os.path.join(current_path, name)
info = get_item_info(path)
if not info: continue
display_name = f"π [{item_index:02d}] {name}"
display_size = f"Size: {format_size(info['size']):>10s}"
display_modified = f"Modified: {info['modified']}"
print(f"{display_name:<40} | {display_size} | {display_modified}")
listed_items.append({'name': name, 'path': path, 'type': 'file'})
item_index += 1
if not listed_items:
print("This directory is empty.")
return listed_items
def interactive_tool(root_dir):
"""Main function for the interactive command-line tool."""
if not os.path.isdir(root_dir):
print(f"β Error: The root directory '{root_dir}' does not exist.")
return
safe_root = os.path.abspath(root_dir)
current_path = safe_root
while True:
output.clear()
print("="*80)
print(" π§Ή Advanced Navigable Colab Cleanup & Compression Tool π§Ή")
print(f"You are here: {current_path}")
print("="*80)
listed_items = display_directory_contents(current_path)
print("\n" + "-"*80)
print("Commands:")
print(" cd <num> -> Enter a directory (e.g., 'cd 1')")
print(" zip <nums> -> Compress items to .zip (e.g., 'zip 1 4')")
print(" del <nums> -> PERMANENTLY delete items (e.g., 'del 2 5')")
print(" .. or up -> Go to parent directory")
print(" home -> Go back to the root")
print(" r -> Refresh current view")
print(" q -> Quit")
print("-"*80)
try:
user_input = input("π Your choice: ").strip().lower()
parts = user_input.split()
command = parts[0] if parts else ''
if command == 'cd' and len(parts) > 1 and parts[1].isdigit():
index = int(parts[1]) - 1
if 0 <= index < len(listed_items) and listed_items[index]['type'] == 'folder':
current_path = os.path.abspath(listed_items[index]['path'])
else:
input("β Invalid number or not a directory. Press Enter.")
elif command in ['..', 'up']:
if os.path.abspath(current_path) != safe_root:
current_path = os.path.dirname(current_path)
else:
input("β
Already at root. Cannot go up. Press Enter.")
elif command == 'home':
current_path = safe_root
elif command == 'zip' and len(parts) > 1:
indices_to_process = [int(p) - 1 for p in parts[1:] if p.isdigit()]
valid_items = [listed_items[i] for i in indices_to_process if 0 <= i < len(listed_items)]
if not valid_items:
input("β No valid items selected for zipping. Press Enter.")
continue
print("\n[ACTION] Preparing to compress the following:")
for item in valid_items:
print(f" - {item['name']}")
print("\nCompressing...")
for item in valid_items:
base_zip_path = os.path.join(current_path, f"{item['name']}.zip")
final_zip_path = get_unique_filename(base_zip_path)
try:
print(f" π¦ Compressing {item['name']} -> {os.path.basename(final_zip_path)}...", end="")
if item['type'] == 'folder':
# Use shutil for directories
shutil.make_archive(
base_name=os.path.splitext(final_zip_path)[0],
format='zip',
root_dir=item['path']
)
else: # It's a file
# Use zipfile for single files
with zipfile.ZipFile(final_zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
zf.write(item['path'], arcname=item['name'])
print(" Done.")
except Exception as e:
print(f" FAILED. Error: {e}")
input("\nCompression finished. Press Enter to continue.")
elif command == 'del' and len(parts) > 1:
indices_to_process = [int(p) - 1 for p in parts[1:] if p.isdigit()]
valid_items = [listed_items[i] for i in indices_to_process if 0 <= i < len(listed_items)]
if not valid_items:
input("β No valid items selected for deletion. Press Enter.")
continue
print("\n" + "!"*60)
print("π¨ WARNING: You will PERMANENTLY DELETE:")
for item in valid_items:
print(f" - {item['name']} ({item['type']})")
print("This action CANNOT be undone.")
print("!"*60)
if input("Type 'DELETE' in all caps to confirm: ") == "DELETE":
print("\n[ACTION] Deleting...")
for item in valid_items:
try:
if item['type'] == 'folder':
shutil.rmtree(item['path'])
else:
os.remove(item['path'])
print(f" ποΈ Deleted {item['path']}")
except Exception as e:
print(f" β FAILED to delete {item['path']}: {e}")
input("\nDeletion finished. Press Enter to continue.")
else:
input("\nβ Deletion cancelled. Press Enter to continue.")
elif command == 'q':
print("\nExiting tool.")
break
elif command in ['r', '']:
continue
else:
input("β Unknown command. Press Enter to try again.")
except (ValueError, IndexError) as e:
input(f"\nβ Invalid input: {e}. Press Enter to try again.")
except Exception as e:
input(f"\nAn unexpected error occurred: {e}. Press Enter to try again.")
# --- Main execution ---
if __name__ == "__main__":
interactive_tool(ROOT_CLEANUP_DIRECTORY) |