File size: 4,708 Bytes
5440093
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d7e52e
5440093
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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()