MartialTerran commited on
Commit
373b98b
Β·
verified Β·
1 Parent(s): cfec946

Create Colab_ZIP_Cleanup_Tool_V1.2.0.py

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