Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import requests
|
3 |
+
from bs4 import BeautifulSoup
|
4 |
+
import subprocess
|
5 |
+
|
6 |
+
DEF_SNIPPET = "echo 'Hello, World!'"
|
7 |
+
DEF_LANG = "Python"
|
8 |
+
|
9 |
+
def execute_snippet(code_snippet: str = DEF_SNIPPET, lang: str = DEF_LANG) -> str:
|
10 |
+
lang_param = None
|
11 |
+
|
12 |
+
match lang:
|
13 |
+
case "C++": lang_param = "cpp"
|
14 |
+
case "C#": lang_param = "cs"
|
15 |
+
case "Bash": # Handle Bash code execution
|
16 |
+
try:
|
17 |
+
# Execute the Bash command and capture the output
|
18 |
+
result = subprocess.run(
|
19 |
+
["bash", "-c", code_snippet],
|
20 |
+
capture_output=True,
|
21 |
+
text=True,
|
22 |
+
check=True
|
23 |
+
)
|
24 |
+
return result.stdout.strip() # Return the standard output
|
25 |
+
except subprocess.CalledProcessError as e:
|
26 |
+
return f"Error: {e.stderr.strip()}"
|
27 |
+
case _: lang_param = lang.lower()
|
28 |
+
|
29 |
+
# FIXME: ERROR HANDLING
|
30 |
+
res = requests.request("POST", f"https://try.w3schools.com/try_{lang_param}.php", data={
|
31 |
+
"code": code_snippet
|
32 |
+
})
|
33 |
+
match lang_param:
|
34 |
+
case "php": return res.text
|
35 |
+
case _: return BeautifulSoup(res.text, "html.parser").find_all("pre")[0].string
|
36 |
+
|
37 |
+
demo = gr.Interface(
|
38 |
+
fn=execute_snippet,
|
39 |
+
inputs=[
|
40 |
+
gr.Textbox(
|
41 |
+
show_label=True,
|
42 |
+
label="Code",
|
43 |
+
max_lines=4_294_967_295,
|
44 |
+
lines=4_294_967_295,
|
45 |
+
value=DEF_SNIPPET,
|
46 |
+
),
|
47 |
+
gr.Dropdown(
|
48 |
+
show_label=True,
|
49 |
+
label="Language",
|
50 |
+
choices=["Python", "Java", "C", "C++", "C#", "PHP", "Bash"],
|
51 |
+
value=DEF_LANG
|
52 |
+
),
|
53 |
+
],
|
54 |
+
outputs=gr.Textbox(label="Result"),
|
55 |
+
title="HFChat Code Executor",
|
56 |
+
description="Enter the code snippet and language that you want to execute.",
|
57 |
+
)
|
58 |
+
|
59 |
+
demo.launch()
|