| |
|
|
| |
| |
| |
| |
| |
|
|
| ROOT_CLEANUP_DIRECTORY = './runs' |
|
|
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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': |
| |
| shutil.make_archive( |
| base_name=os.path.splitext(final_zip_path)[0], |
| format='zip', |
| root_dir=item['path'] |
| ) |
| else: |
| |
| 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.") |
|
|
| |
| if __name__ == "__main__": |
| interactive_tool(ROOT_CLEANUP_DIRECTORY) |