MartialTerran commited on
Commit
11618f1
ยท
verified ยท
1 Parent(s): 373b98b

Create Colab_INFO_Tool_&_Monitor.py

Browse files

============================================================
๐Ÿ“Š Colab Live System Dashboard ๐Ÿ“Š
============================================================

๐Ÿ•’ Session Runtime: 00:00:58
๐Ÿ’ฒ Estimated Cost: $0.0000 (at $0.0/hr for CPU)

๐Ÿ’ป CPU: Intel(R) Xeon(R) CPU @ 2.20GHz
Usage: 5.0% | Cores: 1 | Threads: 2

๐Ÿง  RAM: 1.72 GB / 12.67 GB (15.8%)

๐ŸŽฎ GPU: Not Detected (Standard CPU Runtime)

๐Ÿ’พ Disk: 37.78 GB / 107.72 GB
------------------------------------------------------------
Main Menu: [1] Dashboard [2] Pricing [3] Docs [4] Packages [5] Sessions

Files changed (1) hide show
  1. Colab_INFO_Tool_&_Monitor.py +374 -0
Colab_INFO_Tool_&_Monitor.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
2
+ #
3
+ # Colab INFO Tool & Monitor
4
+ #
5
+ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
6
+ #
7
+ # Author: [Martia L. Terran]
8
+ # Version: 1.0.0
9
+ # License: MIT License
10
+ #
11
+ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
12
+
13
+ # ==============================================================================
14
+ # === I. DESCRIPTION ===
15
+ # ==============================================================================
16
+ #
17
+ # This script is a comprehensive, interactive Command-Line Interface (CLI) tool
18
+ # designed to provide a wealth of information about your current Google Colab
19
+ # session. It acts as a one-stop dashboard for monitoring hardware resources,
20
+ # estimating costs, exploring the software environment, and accessing helpful
21
+ # documentation.
22
+ #
23
+ # It also features a unique, non-interfering, real-time "popup" monitor that
24
+ # displays live CPU, RAM, and GPU usage in a floating box on your screen,
25
+ # allowing you to keep an eye on resource consumption while other cells run.
26
+ #
27
+ # --- The Problem It Solves ---
28
+ #
29
+ # - Colab's resource information is scattered and requires running multiple
30
+ # shell commands (`!nvidia-smi`, `!lscpu`, etc.).
31
+ # - Estimating the cost of a session is a manual calculation.
32
+ # - Finding a list of all installed packages or specific documentation links
33
+ # can be tedious.
34
+ # - There is no built-in, persistent monitor to watch resource usage spikes
35
+ # during a long training job.
36
+ #
37
+ # --- Key Features ---
38
+ #
39
+ # ๐Ÿ“Š Live Dashboard: A main menu showing current CPU, RAM, Disk, and GPU
40
+ # (if available) usage, along with elapsed time and estimated cost.
41
+ # ๐Ÿ›ฐ๏ธ Floating Monitor: A real-time, on-screen display of resource usage
42
+ # that runs in the background without blocking other notebook cells.
43
+ # ๐Ÿ’ฐ Cost Estimation: Calculates the approximate cost of the session based on
44
+ # the detected hardware and elapsed time, using configurable price estimates.
45
+ # ๐Ÿ“š Resource & Doc Hub: Provides a browsable menu of available Colab hardware
46
+ # tiers, their estimated prices, and direct links to official documentation.
47
+ # ๐Ÿ Python Environment Explorer: Lists all installed Python packages.
48
+ # ๐Ÿงญ Session Info & History: Explains and provides direct links to Colab's
49
+ # "Manage Sessions" and "View usage history" pages.
50
+ #
51
+ # ==============================================================================
52
+ # === II. USER MANUAL ===
53
+ # ==============================================================================
54
+ #
55
+ # --- Getting Started ---
56
+ #
57
+ # 1. Paste the entire script into a single Google Colab code cell.
58
+ # 2. Run the cell. The CLI tool will start, and the floating monitor will
59
+ # appear in the bottom-right corner of your screen.
60
+ #
61
+ # --- The Interface ---
62
+ #
63
+ # - The tool is menu-driven. Type a number or letter and press Enter to select
64
+ # an option.
65
+ # - The Floating Monitor can be closed by clicking the '[x]' in its corner.
66
+ # It will not reappear unless you restart the script.
67
+ #
68
+ # --- Main Menu Commands ---
69
+ #
70
+ # [1] Live System Dashboard (Default View)
71
+ # [2] Hardware Pricing & Tiers
72
+ # [3] Documentation & Useful Links
73
+ # [4] List All Installed Python Packages
74
+ # [5] Session Management & History Info
75
+ # [q] Quit
76
+ #
77
+ # Use 'm' from any submenu to return to the Main Menu.
78
+ #
79
+ # ==============================================================================
80
+
81
+ import os
82
+ import sys
83
+ import time
84
+ import subprocess
85
+ import shutil
86
+ import psutil
87
+ from IPython.display import display, HTML, Javascript
88
+ from google.colab import output
89
+
90
+ # --- CONFIGURATION ---
91
+ # Prices are estimates in USD per hour. These are subject to change by Google.
92
+ # Users on Colab Pro/Pro+ may have different compute unit costs.
93
+ CONFIG = {
94
+ 'PRICING': {
95
+ 'CPU (Standard)': 0.00, # Free tier
96
+ 'T4 GPU (Standard)': 0.00, # Free tier often provides a T4
97
+ 'L4 GPU (Pay-as-you-go)': 0.44,
98
+ 'V100 GPU (Pay-as-you-go)': 1.25,
99
+ 'A100 GPU (Pay-as-you-go)': 4.08,
100
+ 'TPU v2 (Pay-as-you-go)': 1.35,
101
+ },
102
+ 'DOCS': {
103
+ 'Colab FAQ': 'https://research.google.com/colaboratory/faq.html',
104
+ 'Colab Pro pricing': 'https://colab.research.google.com/signup',
105
+ 'NVIDIA-SMI Manual': 'https://developer.nvidia.com/nvidia-system-management-interface',
106
+ 'Jupyter/IPython Cheatsheet': 'https://www.cheatography.com/weidadeyue/cheat-sheets/jupyter-notebook/',
107
+ }
108
+ }
109
+
110
+ # --- GLOBAL STATE ---
111
+ start_time = time.time()
112
+ active_hardware = "CPU"
113
+ detected_price = CONFIG['PRICING']['CPU (Standard)']
114
+
115
+ # --- HELPER FUNCTIONS ---
116
+ def run_command(command):
117
+ """Runs a shell command and returns its output."""
118
+ try:
119
+ return subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT).decode('utf-8').strip()
120
+ except subprocess.CalledProcessError as e:
121
+ return f"Error executing command: {e.output.decode('utf-8').strip()}"
122
+
123
+ def get_gpu_info():
124
+ """Gets detailed GPU information using nvidia-smi."""
125
+ global active_hardware, detected_price
126
+ if shutil.which('nvidia-smi') is None:
127
+ return None
128
+ try:
129
+ # Use CSV format for reliable parsing
130
+ query = "name,memory.total,memory.used,utilization.gpu"
131
+ result = run_command(f'nvidia-smi --query-gpu={query} --format=csv,noheader,nounits')
132
+ if "error" in result.lower(): return None
133
+
134
+ parts = result.split(',')
135
+ name = parts[0].strip()
136
+
137
+ # Determine active hardware and price
138
+ active_hardware = name
139
+ for key, price in CONFIG['PRICING'].items():
140
+ # Match 'T4' in 'Tesla T4' with 'T4 GPU'
141
+ if name.split(' ')[-1] in key:
142
+ detected_price = price
143
+ break
144
+
145
+ return {
146
+ "name": name,
147
+ "mem_total": int(parts[1]),
148
+ "mem_used": int(parts[2]),
149
+ "gpu_util": int(parts[3]),
150
+ }
151
+ except Exception:
152
+ return None
153
+
154
+ def get_ram_info():
155
+ """Gets system RAM information."""
156
+ mem = psutil.virtual_memory()
157
+ return {"total": mem.total / (1024**3), "used": mem.used / (1024**3), "percent": mem.percent}
158
+
159
+ def get_cpu_info():
160
+ """Gets CPU information."""
161
+ return {"model": run_command("lscpu | grep 'Model name' | sed 's/Model name:[ \t]*//'"),
162
+ "cores": psutil.cpu_count(logical=False),
163
+ "threads": psutil.cpu_count(logical=True),
164
+ "usage": psutil.cpu_percent(interval=0.1)}
165
+
166
+ def get_disk_info():
167
+ """Gets disk space information for the root directory."""
168
+ total, used, free = shutil.disk_usage('/')
169
+ return {"total": total / (1024**3), "used": used / (1024**3)}
170
+
171
+ # --- DISPLAY FUNCTIONS (MENUS) ---
172
+ def display_dashboard():
173
+ """Shows the main information dashboard."""
174
+ output.clear()
175
+ print("=" * 60)
176
+ print(" ๐Ÿ“Š Colab Live System Dashboard ๐Ÿ“Š")
177
+ print("=" * 60)
178
+
179
+ # Runtime Info
180
+ elapsed_seconds = time.time() - start_time
181
+ elapsed_time_str = time.strftime("%H:%M:%S", time.gmtime(elapsed_seconds))
182
+ estimated_cost = (elapsed_seconds / 3600) * detected_price
183
+ print(f"\n๐Ÿ•’ Session Runtime: {elapsed_time_str}")
184
+ print(f"๐Ÿ’ฒ Estimated Cost: ${estimated_cost:.4f} (at ${detected_price}/hr for {active_hardware})")
185
+
186
+ # CPU Info
187
+ cpu = get_cpu_info()
188
+ print(f"\n๐Ÿ’ป CPU: {cpu['model']}")
189
+ print(f" Usage: {cpu['usage']:>5.1f}% | Cores: {cpu['cores']} | Threads: {cpu['threads']}")
190
+
191
+ # RAM Info
192
+ ram = get_ram_info()
193
+ print(f"\n๐Ÿง  RAM: {ram['used']:.2f} GB / {ram['total']:.2f} GB ({ram['percent']:.1f}%)")
194
+
195
+ # GPU Info
196
+ gpu = get_gpu_info()
197
+ if gpu:
198
+ print(f"\n๐ŸŽฎ GPU: {gpu['name']}")
199
+ print(f" VRAM: {gpu['mem_used']/1024:.2f} GB / {gpu['mem_total']/1024:.2f} GB ({gpu['mem_used']/gpu['mem_total']*100:.1f}%)")
200
+ print(f" GPU Utilization: {gpu['gpu_util']}%")
201
+ else:
202
+ print("\n๐ŸŽฎ GPU: Not Detected (Standard CPU Runtime)")
203
+
204
+ # Disk Info
205
+ disk = get_disk_info()
206
+ print(f"\n๐Ÿ’พ Disk: {disk['used']:.2f} GB / {disk['total']:.2f} GB")
207
+
208
+ def display_pricing():
209
+ """Shows the hardware pricing menu."""
210
+ output.clear()
211
+ print("=" * 60)
212
+ print(" ๐Ÿ’ฐ Hardware Pricing & Tiers (Estimates) ๐Ÿ’ฐ")
213
+ print("=" * 60)
214
+ print("\nPrices are Google's pay-as-you-go estimates in USD/hour.\nFree tier resources are marked as $0.00.\n")
215
+ for name, price in CONFIG['PRICING'].items():
216
+ print(f" - {name:<25s}: ${price:.2f} / hr")
217
+ print("\nNote: Actual cost is based on 'compute units' and may vary.")
218
+
219
+ def display_docs():
220
+ """Shows the documentation and links menu."""
221
+ output.clear()
222
+ print("=" * 60)
223
+ print(" ๐Ÿ“š Documentation & Useful Links ๐Ÿ“š")
224
+ print("=" * 60)
225
+ print("\nClickable links for official docs and resources:\n")
226
+ for name, link in CONFIG['DOCS'].items():
227
+ print(f" - {name:<30s}: {link}")
228
+
229
+ def display_packages():
230
+ """Lists all installed Python packages."""
231
+ output.clear()
232
+ print("=" * 60)
233
+ print(" ๐Ÿ Installed Python Packages ๐Ÿ")
234
+ print("=" * 60)
235
+ print("\nFetching package list, this may take a moment...")
236
+ packages = run_command("pip freeze")
237
+ output.clear() # Clear the "fetching" message
238
+ print("=" * 60)
239
+ print(" ๐Ÿ Installed Python Packages ๐Ÿ")
240
+ print("=" * 60)
241
+ print(f"\n{packages}")
242
+
243
+ def display_session_info():
244
+ """Provides info and links for session management."""
245
+ output.clear()
246
+ print("=" * 60)
247
+ print(" ๐Ÿ“… Session Management & History ๐Ÿ“…")
248
+ print("=" * 60)
249
+ print("\nColab does not provide a programmatic API to list sessions or history.")
250
+ print("However, you can manage them directly in the UI:\n")
251
+ print(" - To see all active sessions across all notebooks:")
252
+ print(" Go to 'Runtime' -> 'Manage sessions'")
253
+ print(" Direct Link: https://colab.research.google.com/drive/1TmJ230eM5sA8gL8YyPPRX6kM0CS16g6_#scrollTo=yS4J523Jk5k0\n")
254
+ print(" - To see prior usage for THIS notebook:")
255
+ print(" Go to 'Runtime' -> 'View usage history'\n")
256
+ print("This history shows which hardware you were assigned and for how long.")
257
+
258
+ # --- FLOATING MONITOR IMPLEMENTATION ---
259
+ def register_monitor_callback():
260
+ """Registers the Python function to be called by JS."""
261
+ # The error was here: register_callback needs the function object as the second argument.
262
+ output.register_callback('update_monitor_data', update_monitor_data)
263
+
264
+ def update_monitor_data():
265
+ """Python function to provide resource data to the JS monitor."""
266
+ cpu_usage = psutil.cpu_percent(interval=None)
267
+ ram_info = get_ram_info()
268
+ gpu_info = get_gpu_info()
269
+ gpu_util = gpu_info['gpu_util'] if gpu_info else 'N/A'
270
+ vram_perc = (gpu_info['mem_used'] / gpu_info['mem_total'] * 100) if gpu_info and gpu_info['mem_total'] > 0 else 'N/A' # Added check for total memory > 0
271
+
272
+ return {
273
+ 'cpu': f'{cpu_usage:.1f}',
274
+ 'ram': f'{ram_info["percent"]:.1f}',
275
+ 'gpu': f'{gpu_util}',
276
+ 'vram': f'{vram_perc:.1f}' if isinstance(vram_perc, float) else 'N/A'
277
+ }
278
+
279
+
280
+ def launch_monitor_popup():
281
+ """Injects JS to create and manage the floating monitor."""
282
+ js_code = """
283
+ async function updateMonitor() {
284
+ try {
285
+ const data = await google.colab.kernel.invokeFunction('update_monitor_data', [], {});
286
+ const stats = data.data['application/json'];
287
+ document.getElementById('colab-monitor-cpu').innerText = stats.cpu;
288
+ document.getElementById('colab-monitor-ram').innerText = stats.ram;
289
+ document.getElementById('colab-monitor-gpu').innerText = stats.gpu;
290
+ document.getElementById('colab-monitor-vram').innerText = stats.vram;
291
+ } catch (e) {
292
+ // If kernel is busy, just skip the update
293
+ }
294
+ }
295
+
296
+ function createMonitor() {
297
+ if (document.getElementById('colab-monitor-div')) {
298
+ return; // Already exists
299
+ }
300
+ const monitorDiv = document.createElement('div');
301
+ monitorDiv.id = 'colab-monitor-div';
302
+ monitorDiv.style = `
303
+ position: fixed;
304
+ bottom: 10px;
305
+ right: 10px;
306
+ background-color: #2f3e46;
307
+ color: #cad2c5;
308
+ border: 1px solid #84a98c;
309
+ border-radius: 8px;
310
+ padding: 10px;
311
+ font-family: monospace;
312
+ font-size: 12px;
313
+ z-index: 9999;
314
+ box-shadow: 0 4px 8px rgba(0,0,0,0.3);
315
+ min-width: 160px;
316
+ `;
317
+ monitorDiv.innerHTML = `
318
+ <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #52796f; padding-bottom: 5px; margin-bottom: 5px;">
319
+ <span style="font-weight: bold;">๐Ÿ›ฐ๏ธ Live Monitor</span>
320
+ <span id="close-monitor" style="cursor: pointer; font-weight: bold; color: #ff6b6b;"
321
+ onclick="document.getElementById('colab-monitor-div').remove(); clearInterval(window.colabMonitorInterval);">
322
+ [x]
323
+ </span>
324
+ </div>
325
+ <div>CPU: <span id="colab-monitor-cpu" style="color: #ffffff;">...</span>%</div>
326
+ <div>RAM: <span id="colab-monitor-ram" style="color: #ffffff;">...</span>%</div>
327
+ <div>GPU: <span id="colab-monitor-gpu" style="color: #ffffff;">...</span>%</div>
328
+ <div>VRAM: <span id="colab-monitor-vram" style="color: #ffffff;">...</span>%</div>
329
+ `;
330
+ document.body.appendChild(monitorDiv);
331
+ window.colabMonitorInterval = setInterval(updateMonitor, 2000); // Update every 2 seconds
332
+ }
333
+ createMonitor();
334
+ """
335
+ display(Javascript(js_code))
336
+
337
+ # --- MAIN CLI LOOP ---
338
+ def main():
339
+ """Main function to run the CLI tool."""
340
+ # Initialize hardware info once at the start
341
+ get_gpu_info()
342
+ # Register the callback function
343
+ register_monitor_callback()
344
+ # Launch the JS popup monitor
345
+ launch_monitor_popup()
346
+
347
+ menu_map = {
348
+ '1': display_dashboard,
349
+ '2': display_pricing,
350
+ '3': display_docs,
351
+ '4': display_packages,
352
+ '5': display_session_info,
353
+ }
354
+
355
+ current_view_func = display_dashboard
356
+
357
+ while True:
358
+ current_view_func()
359
+ print("\n" + "-" * 60)
360
+ print("Main Menu: [1] Dashboard [2] Pricing [3] Docs [4] Packages [5] Sessions")
361
+ choice = input("Enter your choice ('m' for menu, 'q' to quit): ").lower().strip()
362
+
363
+ if choice == 'q':
364
+ print("\nExiting Colab INFO Tool. The floating monitor will remain until the page is reloaded.")
365
+ break
366
+ elif choice in menu_map:
367
+ current_view_func = menu_map[choice]
368
+ elif choice == 'm':
369
+ current_view_func = display_dashboard
370
+ else:
371
+ input("Invalid choice. Press Enter to continue...")
372
+
373
+ if __name__ == "__main__":
374
+ main()