|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import os |
|
import sys |
|
import time |
|
import subprocess |
|
import shutil |
|
import psutil |
|
from IPython.display import display, HTML, Javascript |
|
from google.colab import output |
|
|
|
|
|
|
|
|
|
CONFIG = { |
|
'PRICING': { |
|
'CPU (Standard)': 0.00, |
|
'T4 GPU (Standard)': 0.00, |
|
'L4 GPU (Pay-as-you-go)': 0.44, |
|
'V100 GPU (Pay-as-you-go)': 1.25, |
|
'A100 GPU (Pay-as-you-go)': 4.08, |
|
'TPU v2 (Pay-as-you-go)': 1.35, |
|
}, |
|
'DOCS': { |
|
'Colab FAQ': 'https://research.google.com/colaboratory/faq.html', |
|
'Colab Pro pricing': 'https://colab.research.google.com/signup', |
|
'NVIDIA-SMI Manual': 'https://developer.nvidia.com/nvidia-system-management-interface', |
|
'Jupyter/IPython Cheatsheet': 'https://www.cheatography.com/weidadeyue/cheat-sheets/jupyter-notebook/', |
|
} |
|
} |
|
|
|
|
|
start_time = time.time() |
|
active_hardware = "CPU" |
|
detected_price = CONFIG['PRICING']['CPU (Standard)'] |
|
|
|
|
|
def run_command(command): |
|
"""Runs a shell command and returns its output.""" |
|
try: |
|
return subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT).decode('utf-8').strip() |
|
except subprocess.CalledProcessError as e: |
|
return f"Error executing command: {e.output.decode('utf-8').strip()}" |
|
|
|
def get_gpu_info(): |
|
"""Gets detailed GPU information using nvidia-smi.""" |
|
global active_hardware, detected_price |
|
if shutil.which('nvidia-smi') is None: |
|
return None |
|
try: |
|
|
|
query = "name,memory.total,memory.used,utilization.gpu" |
|
result = run_command(f'nvidia-smi --query-gpu={query} --format=csv,noheader,nounits') |
|
if "error" in result.lower(): return None |
|
|
|
parts = result.split(',') |
|
name = parts[0].strip() |
|
|
|
|
|
active_hardware = name |
|
for key, price in CONFIG['PRICING'].items(): |
|
|
|
if name.split(' ')[-1] in key: |
|
detected_price = price |
|
break |
|
|
|
return { |
|
"name": name, |
|
"mem_total": int(parts[1]), |
|
"mem_used": int(parts[2]), |
|
"gpu_util": int(parts[3]), |
|
} |
|
except Exception: |
|
return None |
|
|
|
def get_ram_info(): |
|
"""Gets system RAM information.""" |
|
mem = psutil.virtual_memory() |
|
return {"total": mem.total / (1024**3), "used": mem.used / (1024**3), "percent": mem.percent} |
|
|
|
def get_cpu_info(): |
|
"""Gets CPU information.""" |
|
return {"model": run_command("lscpu | grep 'Model name' | sed 's/Model name:[ \t]*//'"), |
|
"cores": psutil.cpu_count(logical=False), |
|
"threads": psutil.cpu_count(logical=True), |
|
"usage": psutil.cpu_percent(interval=0.1)} |
|
|
|
def get_disk_info(): |
|
"""Gets disk space information for the root directory.""" |
|
total, used, free = shutil.disk_usage('/') |
|
return {"total": total / (1024**3), "used": used / (1024**3)} |
|
|
|
|
|
def display_dashboard(): |
|
"""Shows the main information dashboard.""" |
|
output.clear() |
|
print("=" * 60) |
|
print(" 📊 Colab Live System Dashboard 📊") |
|
print("=" * 60) |
|
|
|
|
|
elapsed_seconds = time.time() - start_time |
|
elapsed_time_str = time.strftime("%H:%M:%S", time.gmtime(elapsed_seconds)) |
|
estimated_cost = (elapsed_seconds / 3600) * detected_price |
|
print(f"\n🕒 Session Runtime: {elapsed_time_str}") |
|
print(f"💲 Estimated Cost: ${estimated_cost:.4f} (at ${detected_price}/hr for {active_hardware})") |
|
|
|
|
|
cpu = get_cpu_info() |
|
print(f"\n💻 CPU: {cpu['model']}") |
|
print(f" Usage: {cpu['usage']:>5.1f}% | Cores: {cpu['cores']} | Threads: {cpu['threads']}") |
|
|
|
|
|
ram = get_ram_info() |
|
print(f"\n🧠 RAM: {ram['used']:.2f} GB / {ram['total']:.2f} GB ({ram['percent']:.1f}%)") |
|
|
|
|
|
gpu = get_gpu_info() |
|
if gpu: |
|
print(f"\n🎮 GPU: {gpu['name']}") |
|
print(f" VRAM: {gpu['mem_used']/1024:.2f} GB / {gpu['mem_total']/1024:.2f} GB ({gpu['mem_used']/gpu['mem_total']*100:.1f}%)") |
|
print(f" GPU Utilization: {gpu['gpu_util']}%") |
|
else: |
|
print("\n🎮 GPU: Not Detected (Standard CPU Runtime)") |
|
|
|
|
|
disk = get_disk_info() |
|
print(f"\n💾 Disk: {disk['used']:.2f} GB / {disk['total']:.2f} GB") |
|
|
|
def display_pricing(): |
|
"""Shows the hardware pricing menu.""" |
|
output.clear() |
|
print("=" * 60) |
|
print(" 💰 Hardware Pricing & Tiers (Estimates) 💰") |
|
print("=" * 60) |
|
print("\nPrices are Google's pay-as-you-go estimates in USD/hour.\nFree tier resources are marked as $0.00.\n") |
|
for name, price in CONFIG['PRICING'].items(): |
|
print(f" - {name:<25s}: ${price:.2f} / hr") |
|
print("\nNote: Actual cost is based on 'compute units' and may vary.") |
|
|
|
def display_docs(): |
|
"""Shows the documentation and links menu.""" |
|
output.clear() |
|
print("=" * 60) |
|
print(" 📚 Documentation & Useful Links 📚") |
|
print("=" * 60) |
|
print("\nClickable links for official docs and resources:\n") |
|
for name, link in CONFIG['DOCS'].items(): |
|
print(f" - {name:<30s}: {link}") |
|
|
|
def display_packages(): |
|
"""Lists all installed Python packages.""" |
|
output.clear() |
|
print("=" * 60) |
|
print(" 🐍 Installed Python Packages 🐍") |
|
print("=" * 60) |
|
print("\nFetching package list, this may take a moment...") |
|
packages = run_command("pip freeze") |
|
output.clear() |
|
print("=" * 60) |
|
print(" 🐍 Installed Python Packages 🐍") |
|
print("=" * 60) |
|
print(f"\n{packages}") |
|
|
|
def display_session_info(): |
|
"""Provides info and links for session management.""" |
|
output.clear() |
|
print("=" * 60) |
|
print(" 📅 Session Management & History 📅") |
|
print("=" * 60) |
|
print("\nColab does not provide a programmatic API to list sessions or history.") |
|
print("However, you can manage them directly in the UI:\n") |
|
print(" - To see all active sessions across all notebooks:") |
|
print(" Go to 'Runtime' -> 'Manage sessions'") |
|
print(" Direct Link: https://colab.research.google.com/drive/1TmJ230eM5sA8gL8YyPPRX6kM0CS16g6_#scrollTo=yS4J523Jk5k0\n") |
|
print(" - To see prior usage for THIS notebook:") |
|
print(" Go to 'Runtime' -> 'View usage history'\n") |
|
print("This history shows which hardware you were assigned and for how long.") |
|
|
|
|
|
def register_monitor_callback(): |
|
"""Registers the Python function to be called by JS.""" |
|
|
|
output.register_callback('update_monitor_data', update_monitor_data) |
|
|
|
def update_monitor_data(): |
|
"""Python function to provide resource data to the JS monitor.""" |
|
cpu_usage = psutil.cpu_percent(interval=None) |
|
ram_info = get_ram_info() |
|
gpu_info = get_gpu_info() |
|
gpu_util = gpu_info['gpu_util'] if gpu_info else 'N/A' |
|
vram_perc = (gpu_info['mem_used'] / gpu_info['mem_total'] * 100) if gpu_info and gpu_info['mem_total'] > 0 else 'N/A' |
|
|
|
return { |
|
'cpu': f'{cpu_usage:.1f}', |
|
'ram': f'{ram_info["percent"]:.1f}', |
|
'gpu': f'{gpu_util}', |
|
'vram': f'{vram_perc:.1f}' if isinstance(vram_perc, float) else 'N/A' |
|
} |
|
|
|
|
|
def launch_monitor_popup(): |
|
"""Injects JS to create and manage the floating monitor.""" |
|
js_code = """ |
|
async function updateMonitor() { |
|
try { |
|
const data = await google.colab.kernel.invokeFunction('update_monitor_data', [], {}); |
|
const stats = data.data['application/json']; |
|
document.getElementById('colab-monitor-cpu').innerText = stats.cpu; |
|
document.getElementById('colab-monitor-ram').innerText = stats.ram; |
|
document.getElementById('colab-monitor-gpu').innerText = stats.gpu; |
|
document.getElementById('colab-monitor-vram').innerText = stats.vram; |
|
} catch (e) { |
|
// If kernel is busy, just skip the update |
|
} |
|
} |
|
|
|
function createMonitor() { |
|
if (document.getElementById('colab-monitor-div')) { |
|
return; // Already exists |
|
} |
|
const monitorDiv = document.createElement('div'); |
|
monitorDiv.id = 'colab-monitor-div'; |
|
monitorDiv.style = ` |
|
position: fixed; |
|
bottom: 10px; |
|
right: 10px; |
|
background-color: #2f3e46; |
|
color: #cad2c5; |
|
border: 1px solid #84a98c; |
|
border-radius: 8px; |
|
padding: 10px; |
|
font-family: monospace; |
|
font-size: 12px; |
|
z-index: 9999; |
|
box-shadow: 0 4px 8px rgba(0,0,0,0.3); |
|
min-width: 160px; |
|
`; |
|
monitorDiv.innerHTML = ` |
|
<div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #52796f; padding-bottom: 5px; margin-bottom: 5px;"> |
|
<span style="font-weight: bold;">🛰️ Live Monitor</span> |
|
<span id="close-monitor" style="cursor: pointer; font-weight: bold; color: #ff6b6b;" |
|
onclick="document.getElementById('colab-monitor-div').remove(); clearInterval(window.colabMonitorInterval);"> |
|
[x] |
|
</span> |
|
</div> |
|
<div>CPU: <span id="colab-monitor-cpu" style="color: #ffffff;">...</span>%</div> |
|
<div>RAM: <span id="colab-monitor-ram" style="color: #ffffff;">...</span>%</div> |
|
<div>GPU: <span id="colab-monitor-gpu" style="color: #ffffff;">...</span>%</div> |
|
<div>VRAM: <span id="colab-monitor-vram" style="color: #ffffff;">...</span>%</div> |
|
`; |
|
document.body.appendChild(monitorDiv); |
|
window.colabMonitorInterval = setInterval(updateMonitor, 2000); // Update every 2 seconds |
|
} |
|
createMonitor(); |
|
""" |
|
display(Javascript(js_code)) |
|
|
|
|
|
def main(): |
|
"""Main function to run the CLI tool.""" |
|
|
|
get_gpu_info() |
|
|
|
register_monitor_callback() |
|
|
|
launch_monitor_popup() |
|
|
|
menu_map = { |
|
'1': display_dashboard, |
|
'2': display_pricing, |
|
'3': display_docs, |
|
'4': display_packages, |
|
'5': display_session_info, |
|
} |
|
|
|
current_view_func = display_dashboard |
|
|
|
while True: |
|
current_view_func() |
|
print("\n" + "-" * 60) |
|
print("Main Menu: [1] Dashboard [2] Pricing [3] Docs [4] Packages [5] Sessions") |
|
choice = input("Enter your choice ('m' for menu, 'q' to quit): ").lower().strip() |
|
|
|
if choice == 'q': |
|
print("\nExiting Colab INFO Tool. The floating monitor will remain until the page is reloaded.") |
|
break |
|
elif choice in menu_map: |
|
current_view_func = menu_map[choice] |
|
elif choice == 'm': |
|
current_view_func = display_dashboard |
|
else: |
|
input("Invalid choice. Press Enter to continue...") |
|
|
|
if __name__ == "__main__": |
|
main() |