from pathlib import Path import sys import subprocess import traceback import psutil import shlex import shutil import os import gradio as gr # ── File Save ────────────────────────────────────────────── def save_file(file): if file is None: return "❌ No file uploaded." dest = os.path.join(".", os.path.basename(file.name)) shutil.copy(file.name, dest) return f"✅ Saved to: {dest}" # ── Streaming runner ──────────────────────────────────────── def run_stream(cmd, timeout=300): try: process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, # stderr alag text=True, bufsize=1 ) output = "" while True: line = process.stdout.readline() if not line and process.poll() is not None: break if line: output += line yield output stderr_out = process.stderr.read() if stderr_out: output += f"\n⚠️ STDERR:\n{stderr_out}" yield output try: process.wait(timeout=timeout) yield output + "\n✅ Finished" except subprocess.TimeoutExpired: process.kill() yield output + "\n⏰ Timeout — Process killed" except Exception: yield f"❌ Error:\n{traceback.format_exc()}" # ── Tabs ──────────────────────────────────────────────────── def run_python(code): yield from run_stream([sys.executable, "-u", "-c", code]) def install_package(pkgs): if not pkgs.strip(): yield "❌ No package name entered." return yield from run_stream(["pip", "install"] + pkgs.split()) def run_linux(cmd): yield from run_stream(shlex.split(cmd)) def file_func(paths, op): if not paths: return None if op == "download": return paths elif op == "remove": removed, failed = [], [] for p in paths: try: Path(p).unlink(missing_ok=True) removed.append(p) except Exception as e: failed.append(f"{p}: {e}") msg = "" if removed: msg += "✅ Removed:\n" + "\n".join(removed) if failed: msg += "\n❌ Failed:\n" + "\n".join(failed) return msg def system_monitor(): vm = psutil.virtual_memory() disk = psutil.disk_usage("/") lines = [ f"🖥️ CPU Usage : {psutil.cpu_percent(interval=1)}%", f"🧠 RAM Usage : {vm.percent}% ({vm.used//1024**2} MB / {vm.total//1024**2} MB)", f"💾 Disk Usage : {disk.percent}% ({disk.used//1024**3} GB / {disk.total//1024**3} GB)", "\n⚙️ Top Processes (by CPU):", ] procs = sorted(psutil.process_iter(['pid','name','cpu_percent','memory_percent']), key=lambda p: p.info['cpu_percent'] or 0, reverse=True)[:10] for p in procs: lines.append(f" PID {p.info['pid']:>6} | {p.info['name']:<25} | " f"CPU {p.info['cpu_percent']:>5.1f}% | RAM {p.info['memory_percent']:>5.1f}%") return "\n".join(lines) # ── UI ────────────────────────────────────────────────────── tabs = gr.TabbedInterface( [ gr.Interface(save_file, gr.File(), gr.Textbox(label="Status"), title="Upload"), gr.Interface(run_linux, gr.Code(language="shell", label="Shell Command"), gr.Textbox(lines=20, label="Output")), gr.Interface(install_package, gr.Textbox(label="Package(s) e.g. numpy pandas"), gr.Textbox(lines=10, label="pip Output")), gr.Interface(file_func, [gr.FileExplorer(label="Files"), gr.Dropdown(["download","remove"], label="Action")], gr.Files(label="Result")), gr.Interface(run_python, gr.Code(language="python", label="Python Code"), gr.Textbox(lines=20, label="Output")), gr.Interface(system_monitor, None, gr.Textbox(lines=15, label="System Info")), ], tab_names=["📁 File Upload", "🐧 Shell", "📦 Pip Install", "📂 File Manager", "🐍 Python Runner", "⚙️ System Monitor"] ) tabs.launch()