Create app.pu
Browse files
app.pu
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, render_template, request, Response, stream_with_context
|
2 |
+
|
3 |
+
import subprocess
|
4 |
+
import json
|
5 |
+
import os
|
6 |
+
import time
|
7 |
+
|
8 |
+
app = Flask(__name__)
|
9 |
+
|
10 |
+
|
11 |
+
def execute_command(command: str, pwd: str):
|
12 |
+
def process(command: str, pwd: str):
|
13 |
+
process = subprocess.Popen(
|
14 |
+
command,
|
15 |
+
shell=True,
|
16 |
+
stdout=subprocess.PIPE,
|
17 |
+
stderr=subprocess.STDOUT,
|
18 |
+
encoding="utf-8",
|
19 |
+
cwd=pwd,
|
20 |
+
)
|
21 |
+
yield from process.stdout
|
22 |
+
|
23 |
+
try:
|
24 |
+
|
25 |
+
# have cd command so change pwd
|
26 |
+
if command.startswith("cd") and "&&" not in command:
|
27 |
+
pwd = next(process(command + " && pwd", pwd)).strip()
|
28 |
+
yield f"data: {json.dumps({'output': pwd})}\n\n"
|
29 |
+
if not "/bin/sh:" in pwd:
|
30 |
+
yield f"data: {json.dumps({'pwd': pwd})}\n\n"
|
31 |
+
return
|
32 |
+
|
33 |
+
output = ""
|
34 |
+
start_time = time.time()
|
35 |
+
for line in process(command, pwd):
|
36 |
+
output += line
|
37 |
+
current_time = time.time()
|
38 |
+
if current_time - start_time >= 0.3:
|
39 |
+
yield f"data: {json.dumps({'output': output})}\n\n"
|
40 |
+
output = ""
|
41 |
+
start_time = current_time
|
42 |
+
if output:
|
43 |
+
yield f"data: {json.dumps({'output': output})}\n\n"
|
44 |
+
|
45 |
+
except subprocess.CalledProcessError as error:
|
46 |
+
error_message = error.stderr.strip()
|
47 |
+
yield f"data: {json.dumps({'output': error_message})}\n\n"
|
48 |
+
finally:
|
49 |
+
yield f"data: {json.dumps({'output': '[DONE]'})}\n\n"
|
50 |
+
|
51 |
+
|
52 |
+
@app.route("/")
|
53 |
+
def hello_world():
|
54 |
+
# return "Hello, World!"
|
55 |
+
|
56 |
+
# uname -a
|
57 |
+
uname = subprocess.check_output(["uname", "-a"], encoding="utf-8")
|
58 |
+
|
59 |
+
return render_template(
|
60 |
+
"terminal.html", welcome_input="uname -a", welcome_output=uname, pwd="/root"
|
61 |
+
)
|
62 |
+
|
63 |
+
|
64 |
+
# execute command
|
65 |
+
@app.route("/exec")
|
66 |
+
def exec():
|
67 |
+
command = request.args.get("command")
|
68 |
+
pwd = request.args.get("pwd")
|
69 |
+
|
70 |
+
# event stream
|
71 |
+
return Response(
|
72 |
+
stream_with_context(execute_command(command, pwd)), mimetype="text/event-stream"
|
73 |
+
)
|
74 |
+
|
75 |
+
|
76 |
+
# ping
|
77 |
+
@app.route("/ping")
|
78 |
+
def ping():
|
79 |
+
# 204
|
80 |
+
return Response(status=204)
|
81 |
+
|
82 |
+
|
83 |
+
if __name__ == "__main__":
|
84 |
+
# port huggingface space
|
85 |
+
app.run(host="0.0.0.0", port=7860, debug=True)
|