File size: 2,366 Bytes
0d54674
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7045576
 
 
 
 
 
 
 
 
 
 
 
0d54674
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7045576
0d54674
 
 
 
 
 
 
 
7045576
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
import gradio as gr
import requests
from bs4 import BeautifulSoup
import subprocess

DEF_SNIPPET = "echo 'Hello, World!'"
DEF_LANG = "Python"

def execute_snippet(code_snippet: str = DEF_SNIPPET, lang: str = DEF_LANG) -> str:
    lang_param = None
    
    match lang:
        case "C++": lang_param = "cpp"
        case "C#": lang_param = "cs"
        case "Bash":  # Handle Bash code execution
            try:
                # Execute the Bash command and capture the output
                result = subprocess.run(
                    ["bash", "-c", code_snippet],
                    capture_output=True,
                    text=True,
                    check=True
                )
                return result.stdout.strip()  # Return the standard output
            except subprocess.CalledProcessError as e:
                return f"Error: {e.stderr.strip()}"
        case "Zsh":  # Handle Zsh code execution
            try:
                # Execute the Zsh command and capture the output
                result = subprocess.run(
                    ["zsh", "-c", code_snippet],
                    capture_output=True,
                    text=True,
                    check=True
                )
                return result.stdout.strip()  # Return the standard output
            except subprocess.CalledProcessError as e:
                return f"Error: {e.stderr.strip()}"
        case _: lang_param = lang.lower()

    # FIXME: ERROR HANDLING
    res = requests.request("POST", f"https://try.w3schools.com/try_{lang_param}.php", data={
        "code": code_snippet
    })
    match lang_param:
        case "php": return res.text
        case _: return BeautifulSoup(res.text, "html.parser").find_all("pre")[0].string

demo = gr.Interface(
    fn=execute_snippet,
    inputs=[
        gr.Textbox(
            show_label=True,
            label="Code",
            max_lines=4_294_967_295,
            lines=4_294_967_295,
            value=DEF_SNIPPET,
        ),
        gr.Dropdown(
            show_label=True,
            label="Language",
            choices=["Python", "Java", "C", "C++", "C#", "PHP", "Bash", "Zsh"],
            value=DEF_LANG
        ),
    ],
    outputs=gr.Textbox(label="Result"),
    title="HFChat Code Executor",
    description="Enter the code snippet and language that you want to execute.",
)

demo.launch()