Sodoku_Puzzle_Generator / Colab_INFO_Tool_&_Monitor.py
MartialTerran's picture
Create Colab_INFO_Tool_&_Monitor.py
11618f1 verified
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Colab INFO Tool & Monitor
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Author: [Martia L. Terran]
# Version: 1.0.0
# License: MIT License
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# ==============================================================================
# === I. DESCRIPTION ===
# ==============================================================================
#
# This script is a comprehensive, interactive Command-Line Interface (CLI) tool
# designed to provide a wealth of information about your current Google Colab
# session. It acts as a one-stop dashboard for monitoring hardware resources,
# estimating costs, exploring the software environment, and accessing helpful
# documentation.
#
# It also features a unique, non-interfering, real-time "popup" monitor that
# displays live CPU, RAM, and GPU usage in a floating box on your screen,
# allowing you to keep an eye on resource consumption while other cells run.
#
# --- The Problem It Solves ---
#
# - Colab's resource information is scattered and requires running multiple
# shell commands (`!nvidia-smi`, `!lscpu`, etc.).
# - Estimating the cost of a session is a manual calculation.
# - Finding a list of all installed packages or specific documentation links
# can be tedious.
# - There is no built-in, persistent monitor to watch resource usage spikes
# during a long training job.
#
# --- Key Features ---
#
# 📊 Live Dashboard: A main menu showing current CPU, RAM, Disk, and GPU
# (if available) usage, along with elapsed time and estimated cost.
# 🛰️ Floating Monitor: A real-time, on-screen display of resource usage
# that runs in the background without blocking other notebook cells.
# 💰 Cost Estimation: Calculates the approximate cost of the session based on
# the detected hardware and elapsed time, using configurable price estimates.
# 📚 Resource & Doc Hub: Provides a browsable menu of available Colab hardware
# tiers, their estimated prices, and direct links to official documentation.
# 🐍 Python Environment Explorer: Lists all installed Python packages.
# 🧭 Session Info & History: Explains and provides direct links to Colab's
# "Manage Sessions" and "View usage history" pages.
#
# ==============================================================================
# === II. USER MANUAL ===
# ==============================================================================
#
# --- Getting Started ---
#
# 1. Paste the entire script into a single Google Colab code cell.
# 2. Run the cell. The CLI tool will start, and the floating monitor will
# appear in the bottom-right corner of your screen.
#
# --- The Interface ---
#
# - The tool is menu-driven. Type a number or letter and press Enter to select
# an option.
# - The Floating Monitor can be closed by clicking the '[x]' in its corner.
# It will not reappear unless you restart the script.
#
# --- Main Menu Commands ---
#
# [1] Live System Dashboard (Default View)
# [2] Hardware Pricing & Tiers
# [3] Documentation & Useful Links
# [4] List All Installed Python Packages
# [5] Session Management & History Info
# [q] Quit
#
# Use 'm' from any submenu to return to the Main Menu.
#
# ==============================================================================
import os
import sys
import time
import subprocess
import shutil
import psutil
from IPython.display import display, HTML, Javascript
from google.colab import output
# --- CONFIGURATION ---
# Prices are estimates in USD per hour. These are subject to change by Google.
# Users on Colab Pro/Pro+ may have different compute unit costs.
CONFIG = {
'PRICING': {
'CPU (Standard)': 0.00, # Free tier
'T4 GPU (Standard)': 0.00, # Free tier often provides a T4
'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/',
}
}
# --- GLOBAL STATE ---
start_time = time.time()
active_hardware = "CPU"
detected_price = CONFIG['PRICING']['CPU (Standard)']
# --- HELPER FUNCTIONS ---
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:
# Use CSV format for reliable parsing
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()
# Determine active hardware and price
active_hardware = name
for key, price in CONFIG['PRICING'].items():
# Match 'T4' in 'Tesla T4' with 'T4 GPU'
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)}
# --- DISPLAY FUNCTIONS (MENUS) ---
def display_dashboard():
"""Shows the main information dashboard."""
output.clear()
print("=" * 60)
print(" 📊 Colab Live System Dashboard 📊")
print("=" * 60)
# Runtime Info
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 Info
cpu = get_cpu_info()
print(f"\n💻 CPU: {cpu['model']}")
print(f" Usage: {cpu['usage']:>5.1f}% | Cores: {cpu['cores']} | Threads: {cpu['threads']}")
# RAM Info
ram = get_ram_info()
print(f"\n🧠 RAM: {ram['used']:.2f} GB / {ram['total']:.2f} GB ({ram['percent']:.1f}%)")
# GPU Info
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 Info
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() # Clear the "fetching" message
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.")
# --- FLOATING MONITOR IMPLEMENTATION ---
def register_monitor_callback():
"""Registers the Python function to be called by JS."""
# The error was here: register_callback needs the function object as the second argument.
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' # Added check for total memory > 0
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))
# --- MAIN CLI LOOP ---
def main():
"""Main function to run the CLI tool."""
# Initialize hardware info once at the start
get_gpu_info()
# Register the callback function
register_monitor_callback()
# Launch the JS popup monitor
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()