# 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 # Changes the current directory to the folder specified by the number. # Example: `cd 3` - Enters the folder listed as [03]. # # ๐Ÿ”น del # 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 # 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 -> Enter a directory (e.g., 'cd 1')") print(" zip -> Compress items to .zip (e.g., 'zip 1 4')") print(" del -> 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)