shethjenil commited on
Commit
5440093
Β·
verified Β·
1 Parent(s): 43fdb9e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -0
app.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import sys
3
+ import subprocess
4
+ import traceback
5
+ import psutil
6
+ import shlex
7
+ import shutil
8
+ import os
9
+ import gradio as gr
10
+
11
+ # ── File Save ──────────────────────────────────────────────
12
+ def save_file(file):
13
+ if file is None:
14
+ return "❌ No file uploaded."
15
+ dest = os.path.join(".", os.path.basename(file.name))
16
+ shutil.copy(file.name, dest)
17
+ return f"βœ… Saved to: {dest}"
18
+
19
+ # ── Streaming runner ────────────────────────────────────────
20
+ def run_stream(cmd, timeout=300):
21
+ try:
22
+ process = subprocess.Popen(
23
+ cmd,
24
+ stdout=subprocess.PIPE,
25
+ stderr=subprocess.PIPE, # stderr alag
26
+ text=True,
27
+ bufsize=1
28
+ )
29
+ output = ""
30
+ while True:
31
+ line = process.stdout.readline()
32
+ if not line and process.poll() is not None:
33
+ break
34
+ if line:
35
+ output += line
36
+ yield output
37
+
38
+ stderr_out = process.stderr.read()
39
+ if stderr_out:
40
+ output += f"\n⚠️ STDERR:\n{stderr_out}"
41
+ yield output
42
+
43
+ try:
44
+ process.wait(timeout=timeout)
45
+ yield output + "\nβœ… Finished"
46
+ except subprocess.TimeoutExpired:
47
+ process.kill()
48
+ yield output + "\n⏰ Timeout β€” Process killed"
49
+
50
+ except Exception:
51
+ yield f"❌ Error:\n{traceback.format_exc()}"
52
+
53
+ # ── Tabs ────────────────────────────────────────────────────
54
+ def run_python(code):
55
+ yield from run_stream([sys.executable, "-u", "-c", code])
56
+
57
+ def install_package(pkgs):
58
+ if not pkgs.strip():
59
+ yield "❌ No package name entered."
60
+ return
61
+ yield from run_stream(["pip", "install"] + pkgs.split())
62
+
63
+ def run_linux(cmd):
64
+ yield from run_stream(shlex.split(cmd))
65
+
66
+ def file_func(paths, op):
67
+ if not paths:
68
+ return None
69
+ if op == "download":
70
+ return paths
71
+ elif op == "remove":
72
+ removed, failed = [], []
73
+ for p in paths:
74
+ try:
75
+ Path(p).unlink(missing_ok=True)
76
+ removed.append(p)
77
+ except Exception as e:
78
+ failed.append(f"{p}: {e}")
79
+ msg = ""
80
+ if removed: msg += "βœ… Removed:\n" + "\n".join(removed)
81
+ if failed: msg += "\n❌ Failed:\n" + "\n".join(failed)
82
+ return msg
83
+
84
+ def system_monitor():
85
+ vm = psutil.virtual_memory()
86
+ disk = psutil.disk_usage("/")
87
+ lines = [
88
+ f"πŸ–₯️ CPU Usage : {psutil.cpu_percent(interval=1)}%",
89
+ f"🧠 RAM Usage : {vm.percent}% ({vm.used//1024**2} MB / {vm.total//1024**2} MB)",
90
+ f"πŸ’Ύ Disk Usage : {disk.percent}% ({disk.used//1024**3} GB / {disk.total//1024**3} GB)",
91
+ "\nβš™οΈ Top Processes (by CPU):",
92
+ ]
93
+ procs = sorted(psutil.process_iter(['pid','name','cpu_percent','memory_percent']),
94
+ key=lambda p: p.info['cpu_percent'] or 0, reverse=True)[:10]
95
+ for p in procs:
96
+ lines.append(f" PID {p.info['pid']:>6} | {p.info['name']:<25} | "
97
+ f"CPU {p.info['cpu_percent']:>5.1f}% | RAM {p.info['memory_percent']:>5.1f}%")
98
+ return "\n".join(lines)
99
+
100
+ # ── UI ──────────────────────────────────────────────────────
101
+ tabs = gr.TabbedInterface(
102
+ [
103
+ gr.Interface(save_file, gr.File(), gr.Textbox(label="Status"), title="Upload"),
104
+ gr.Interface(run_linux, gr.Code(language="shell", label="Shell Command"), gr.Textbox(lines=20, label="Output")),
105
+ gr.Interface(install_package, gr.Textbox(label="Package(s) e.g. numpy pandas"), gr.Textbox(lines=10, label="pip Output")),
106
+ gr.Interface(file_func, [gr.FileExplorer(label="Files"),
107
+ gr.Dropdown(["download","remove"], label="Action")],
108
+ gr.Textbox(lines=5, label="Result")),
109
+ gr.Interface(run_python, gr.Code(language="python", label="Python Code"), gr.Textbox(lines=20, label="Output")),
110
+ gr.Interface(system_monitor, None, gr.Textbox(lines=15, label="System Info")),
111
+ ],
112
+ tab_names=["πŸ“ File Upload", "🐧 Shell", "πŸ“¦ Pip Install", "πŸ“‚ File Manager", "🐍 Python Runner", "βš™οΈ System Monitor"]
113
+ )
114
+
115
+ tabs.launch()