chore(release): bump version to v1.0.1
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,45 @@
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
class StringCatalog:
|
||||
"""Centralized string catalog loader for TopX applet."""
|
||||
|
||||
_instance = None
|
||||
_catalog: Dict[str, Any] = {}
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super(StringCatalog, cls).__new__(cls)
|
||||
cls._instance._load_catalog()
|
||||
return cls._instance
|
||||
|
||||
def _load_catalog(self) -> None:
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
catalog_path = os.path.join(base_dir, "catalog", "strings.json")
|
||||
if os.path.exists(catalog_path):
|
||||
with open(catalog_path, "r", encoding="utf-8") as f:
|
||||
self._catalog = json.load(f)
|
||||
else:
|
||||
self._catalog = {}
|
||||
|
||||
def get(self, key_path: str, default: str = "") -> str:
|
||||
parts = key_path.split(".")
|
||||
current = self._catalog
|
||||
for part in parts:
|
||||
if isinstance(current, dict) and part in current:
|
||||
current = current[part]
|
||||
else:
|
||||
return default
|
||||
return str(current) if current is not None else default
|
||||
|
||||
def format(self, key_path: str, **kwargs: Any) -> str:
|
||||
template = self.get(key_path, "")
|
||||
try:
|
||||
return template.format(**kwargs)
|
||||
except KeyError:
|
||||
return template
|
||||
|
||||
|
||||
catalog = StringCatalog()
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from typing import List, Optional
|
||||
|
||||
from src.catalog import catalog
|
||||
from src.sampler import MetricSampler
|
||||
from src.ui import TerminalRenderer
|
||||
|
||||
|
||||
def print_help() -> None:
|
||||
print(f"{catalog.get('app.name')} - {catalog.get('app.tagline')}")
|
||||
print()
|
||||
print(catalog.get("cli.usage"))
|
||||
print()
|
||||
print(catalog.get("cli.options_title"))
|
||||
print(f" -h, --help {catalog.get('cli.opt_help')}")
|
||||
print(f" -V, --version {catalog.get('cli.opt_version')}")
|
||||
print(f" -1, --once {catalog.get('cli.opt_once')}")
|
||||
print(f" -i, --interval <sec> {catalog.get('cli.opt_interval')}")
|
||||
|
||||
|
||||
def _check_exit_key() -> bool:
|
||||
"""Checks for non-blocking keypress ('q', 'Q', ESC, Ctrl+C)."""
|
||||
if os.name == "nt":
|
||||
try:
|
||||
import msvcrt
|
||||
if msvcrt.kbhit():
|
||||
ch = msvcrt.getch()
|
||||
if ch in [b"q", b"Q", b"\x1b", b"\x03"]:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
import select
|
||||
try:
|
||||
r, _, _ = select.select([sys.stdin], [], [], 0)
|
||||
if r:
|
||||
ch = sys.stdin.read(1)
|
||||
if ch in ["q", "Q", "\x1b", "\x03"]:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def run_cli(args: Optional[List[str]] = None) -> int:
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
raw_args = args if args is not None else sys.argv[1:]
|
||||
|
||||
if "-h" in raw_args or "--help" in raw_args:
|
||||
print_help()
|
||||
return 0
|
||||
|
||||
if "-V" in raw_args or "--version" in raw_args:
|
||||
print(catalog.format("app.version_output", name="TopX", version="1.0.0", author="BeerSlayer"))
|
||||
return 0
|
||||
|
||||
is_once = "-1" in raw_args or "--once" in raw_args
|
||||
|
||||
interval = 1.0
|
||||
for idx, arg in enumerate(raw_args):
|
||||
if arg in ["-i", "--interval"] and idx + 1 < len(raw_args):
|
||||
try:
|
||||
interval = max(0.2, float(raw_args[idx + 1]))
|
||||
except ValueError:
|
||||
interval = 1.0
|
||||
|
||||
sampler = MetricSampler()
|
||||
|
||||
# Initial sample warmup
|
||||
sampler.sample()
|
||||
time.sleep(0.1)
|
||||
|
||||
if is_once:
|
||||
metrics = sampler.sample()
|
||||
print(TerminalRenderer.render_snapshot(metrics))
|
||||
return 0
|
||||
|
||||
# Live Interactive Loop
|
||||
try:
|
||||
# Hide cursor if supported, clear screen
|
||||
sys.stdout.write("\033[?25l")
|
||||
sys.stdout.flush()
|
||||
|
||||
while True:
|
||||
metrics = sampler.sample()
|
||||
dashboard = TerminalRenderer.render_dashboard(metrics, interval)
|
||||
|
||||
# Move cursor to home and render
|
||||
sys.stdout.write(f"\033[H\033[2J{dashboard}\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
# Sleep in small slices to detect hotkeys immediately
|
||||
sleep_slices = int(interval / 0.05)
|
||||
for _ in range(max(1, sleep_slices)):
|
||||
if _check_exit_key():
|
||||
return 0
|
||||
time.sleep(0.05)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
return 0
|
||||
finally:
|
||||
# Restore cursor
|
||||
sys.stdout.write("\033[?25h\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
return 0
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional, Tuple
|
||||
|
||||
try:
|
||||
import psutil
|
||||
HAS_PSUTIL = True
|
||||
except ImportError:
|
||||
HAS_PSUTIL = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class SystemMetrics:
|
||||
cpu_percent: float
|
||||
cpu_count: int
|
||||
ram_total_gb: float
|
||||
ram_used_gb: float
|
||||
ram_percent: float
|
||||
disk_mount: str
|
||||
disk_total_gb: float
|
||||
disk_used_gb: float
|
||||
disk_percent: float
|
||||
net_down_speed: float # KB/s
|
||||
net_up_speed: float # KB/s
|
||||
net_total_recv_mb: float
|
||||
net_total_sent_mb: float
|
||||
|
||||
|
||||
class MetricSampler:
|
||||
"""Collects real-time system metrics across Windows, Linux, and macOS."""
|
||||
|
||||
def __init__(self):
|
||||
self.prev_time: float = time.time()
|
||||
self.prev_net_recv: int = 0
|
||||
self.prev_net_sent: int = 0
|
||||
self._init_network()
|
||||
|
||||
def _init_network(self) -> None:
|
||||
if HAS_PSUTIL:
|
||||
try:
|
||||
counters = psutil.net_io_counters()
|
||||
self.prev_net_recv = counters.bytes_recv
|
||||
self.prev_net_sent = counters.bytes_sent
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def sample(self) -> SystemMetrics:
|
||||
now = time.time()
|
||||
delta_time = max(0.001, now - self.prev_time)
|
||||
self.prev_time = now
|
||||
|
||||
# 1. CPU
|
||||
cpu_count = os.cpu_count() or 1
|
||||
cpu_percent = 0.0
|
||||
if HAS_PSUTIL:
|
||||
try:
|
||||
cpu_percent = psutil.cpu_percent(interval=None)
|
||||
except Exception:
|
||||
cpu_percent = 0.0
|
||||
|
||||
# 2. RAM
|
||||
ram_total_gb = 16.0
|
||||
ram_used_gb = 8.0
|
||||
ram_percent = 50.0
|
||||
|
||||
if HAS_PSUTIL:
|
||||
try:
|
||||
vmem = psutil.virtual_memory()
|
||||
ram_total_gb = vmem.total / (1024 ** 3)
|
||||
ram_used_gb = vmem.used / (1024 ** 3)
|
||||
ram_percent = vmem.percent
|
||||
except Exception:
|
||||
pass
|
||||
elif os.name == "nt":
|
||||
try:
|
||||
import ctypes
|
||||
class MEMORYSTATUSEX(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("dwLength", ctypes.c_ulong),
|
||||
("dwMemoryLoad", ctypes.c_ulong),
|
||||
("ullTotalPhys", ctypes.c_ulonglong),
|
||||
("ullAvailPhys", ctypes.c_ulonglong),
|
||||
("ullTotalPageFile", ctypes.c_ulonglong),
|
||||
("ullAvailPageFile", ctypes.c_ulonglong),
|
||||
("ullTotalVirtual", ctypes.c_ulonglong),
|
||||
("ullAvailVirtual", ctypes.c_ulonglong),
|
||||
("sullAvailExtendedVirtual", ctypes.c_ulonglong),
|
||||
]
|
||||
stat = MEMORYSTATUSEX()
|
||||
stat.dwLength = ctypes.sizeof(MEMORYSTATUSEX)
|
||||
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
|
||||
ram_total_gb = stat.ullTotalPhys / (1024 ** 3)
|
||||
ram_used_gb = (stat.ullTotalPhys - stat.ullAvailPhys) / (1024 ** 3)
|
||||
ram_percent = float(stat.dwMemoryLoad)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 3. Disk
|
||||
root_path = "C:\\" if os.name == "nt" else "/"
|
||||
disk_usage = shutil.disk_usage(root_path)
|
||||
disk_total_gb = disk_usage.total / (1024 ** 3)
|
||||
disk_used_gb = disk_usage.used / (1024 ** 3)
|
||||
disk_percent = (disk_usage.used / disk_usage.total) * 100.0 if disk_usage.total > 0 else 0.0
|
||||
|
||||
# 4. Network
|
||||
net_down_speed = 0.0
|
||||
net_up_speed = 0.0
|
||||
net_total_recv_mb = 0.0
|
||||
net_total_sent_mb = 0.0
|
||||
|
||||
if HAS_PSUTIL:
|
||||
try:
|
||||
counters = psutil.net_io_counters()
|
||||
cur_recv = counters.bytes_recv
|
||||
cur_sent = counters.bytes_sent
|
||||
|
||||
if self.prev_net_recv > 0:
|
||||
net_down_speed = max(0.0, (cur_recv - self.prev_net_recv) / delta_time / 1024.0)
|
||||
net_up_speed = max(0.0, (cur_sent - self.prev_net_sent) / delta_time / 1024.0)
|
||||
|
||||
self.prev_net_recv = cur_recv
|
||||
self.prev_net_sent = cur_sent
|
||||
net_total_recv_mb = cur_recv / (1024 ** 2)
|
||||
net_total_sent_mb = cur_sent / (1024 ** 2)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return SystemMetrics(
|
||||
cpu_percent=round(cpu_percent, 1),
|
||||
cpu_count=cpu_count,
|
||||
ram_total_gb=round(ram_total_gb, 1),
|
||||
ram_used_gb=round(ram_used_gb, 1),
|
||||
ram_percent=round(ram_percent, 1),
|
||||
disk_mount=root_path,
|
||||
disk_total_gb=round(disk_total_gb, 1),
|
||||
disk_used_gb=round(disk_used_gb, 1),
|
||||
disk_percent=round(disk_percent, 1),
|
||||
net_down_speed=round(net_down_speed, 1),
|
||||
net_up_speed=round(net_up_speed, 1),
|
||||
net_total_recv_mb=round(net_total_recv_mb, 1),
|
||||
net_total_sent_mb=round(net_total_sent_mb, 1),
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
import sys
|
||||
from src.catalog import catalog
|
||||
from src.sampler import SystemMetrics
|
||||
|
||||
|
||||
class TerminalRenderer:
|
||||
"""Renders calm, high-contrast ANSI gauges and system metric dashboards."""
|
||||
|
||||
BAR_WIDTH = 24
|
||||
|
||||
@classmethod
|
||||
def make_bar(cls, percent: float, width: int = BAR_WIDTH) -> str:
|
||||
clamped = max(0.0, min(100.0, percent))
|
||||
filled_len = int((clamped / 100.0) * width)
|
||||
empty_len = width - filled_len
|
||||
filled = "█" * filled_len
|
||||
empty = "░" * empty_len
|
||||
return f"[{filled}{empty}] {percent:>5.1f}%"
|
||||
|
||||
@classmethod
|
||||
def render_dashboard(cls, m: SystemMetrics, interval: float) -> str:
|
||||
cpu_bar = cls.make_bar(m.cpu_percent)
|
||||
ram_bar = cls.make_bar(m.ram_percent)
|
||||
disk_bar = cls.make_bar(m.disk_percent)
|
||||
|
||||
net_down_str = f"{m.net_down_speed:>7.1f} KB/s" if m.net_down_speed < 1024 else f"{(m.net_down_speed/1024):>7.2f} MB/s"
|
||||
net_up_str = f"{m.net_up_speed:>7.1f} KB/s" if m.net_up_speed < 1024 else f"{(m.net_up_speed/1024):>7.2f} MB/s"
|
||||
|
||||
lines = [
|
||||
"┌─ TOPX SYSTEM & NETWORK PULSE ──────────────────────────── [LIVE] ─┐",
|
||||
"│ │",
|
||||
f"│ CPU Usage : {cpu_bar:<35} ({m.cpu_count} Cores) │",
|
||||
f"│ Memory (RAM) : {ram_bar:<35} ({m.ram_used_gb:.1f}/{m.ram_total_gb:.1f} GB) │",
|
||||
f"│ Disk Storage : {disk_bar:<35} ({m.disk_used_gb:.1f}/{m.disk_total_gb:.1f} GB) │",
|
||||
"│ │",
|
||||
"│ Network Traffic (I/O) │",
|
||||
f"│ Download Rate : {net_down_str:<18} | Total Recv : {m.net_total_recv_mb:>7.1f} MB │",
|
||||
f"│ Upload Rate : {net_up_str:<18} | Total Sent : {m.net_total_sent_mb:>7.1f} MB │",
|
||||
"│ │",
|
||||
f"└────────────────────────────── [ Press 'q' or ESC to Exit ] {interval:.1f}s ─┘",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
@classmethod
|
||||
def render_snapshot(cls, m: SystemMetrics) -> str:
|
||||
cpu_bar = cls.make_bar(m.cpu_percent, width=20)
|
||||
ram_bar = cls.make_bar(m.ram_percent, width=20)
|
||||
disk_bar = cls.make_bar(m.disk_percent, width=20)
|
||||
|
||||
lines = [
|
||||
catalog.get("ui.snapshot_header"),
|
||||
"-" * 55,
|
||||
f" CPU ({m.cpu_count} Cores) : {cpu_bar}",
|
||||
f" RAM ({m.ram_used_gb:.1f}/{m.ram_total_gb:.1f} GB) : {ram_bar}",
|
||||
f" Disk ({m.disk_used_gb:.1f}/{m.disk_total_gb:.1f} GB): {disk_bar}",
|
||||
f" Network In/Out : {m.net_down_speed:.1f} KB/s down | {m.net_up_speed:.1f} KB/s up",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
Reference in New Issue
Block a user