Spaces:
Sleeping

File size: 3,496 Bytes
a4aaeaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
639bd8b
 
a4aaeaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f4a2f
a4aaeaa
 
 
 
 
 
 
 
 
 
 
 
9e8ad45
a4aaeaa
c4f4a2f
 
a4aaeaa
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import subprocess

def sub_pattern_with_exclusion(fullpattern, excludedsubpattern, targetpattern, replacement, text):
  import re
  class emptymatch:
      def __init__(self):
          minus1 = lambda: -1
          self.group = minus1; self.start = minus1; self.end = minus1;

  matches1 = list(re.finditer(fullpattern, text))
  matches2 = list(re.finditer(excludedsubpattern, text))

  matches1.extend([emptymatch()]*(len(matches2)-len(matches1)))
  matches2.extend([emptymatch()]*(len(matches1)-len(matches2)))

  matches = []
  for match1, match2 in zip(matches1, matches2):
      if match1.start()>=0 and match1.start() == match2.start() and match1.end() == match2.end():
          matches.append(match1)

  modified_text = text

  for match in reversed(matches):    
      modified_text = modified_text[:match.start()] + re.sub(targetpattern, replacement, match.group()) + modified_text[match.end():]
  return modified_text

def run_code_with_inputs(code: str, inputs: str) -> str:
    """
    Runs the provided Python code as a console program with the given inputs.
    
    Parameters:
        code (str): Python code to execute.
        inputs (str): User inputs separated by newlines.
    
    Returns:
        str: Combined output from the program execution.
    """    
    filename = 'my_program.py'
    echo = ''
    fullpattern = r"\.? *input *\("
    excludedsubpattern = r" *input *\("
    targetpattern = "input"
    replacement = "Input"
    modified_code = sub_pattern_with_exclusion(fullpattern, excludedsubpattern, targetpattern, replacement, code)
    modified_code = """
def Input(prompt=""):
  res = input(prompt)
  print(res)
  return res
"""+modified_code

    try:
        with open(filename.removesuffix('.py')+'.py','wb') as file:
            file.write(modified_code.encode('utf-8'))
            file_path = file.name

        input_data = inputs.replace("\\n", "\n")

        process = subprocess.run(
            ["python", file_path],
            input=input_data,
            text=True,
            capture_output=True,
            timeout=10
        )

        output = ''.join(echo)+process.stdout
        errors = process.stderr

        if errors:
            return f"Errors:\n{errors}\n\nOutput:\n{output}"
        return output

    except Exception as e:
        return f"An error occurred: {str(e)}"

# Define the Gradio interface
description = (
    "This app allows you to input Python code for a console program "
    "and provide a list of inputs separated by newlines. It will run the code "
    "and return the entire program output."
)



with gr.Blocks(theme=gr.themes.Default(text_size=gr.themes.sizes.text_lg)) as demo:
    gr.Interface(
        fn=run_code_with_inputs,
        inputs=[
            gr.Code(label="Python Code", language="python", value="name=input(\"What's your name? \")\nprint(f\"Hello, {name}!\")"),
            gr.Textbox(label="User Inputs", lines=5, value='Alice\nBob',placeholder="Enter inputs separated by newlines...")
        ],
        outputs=gr.Code(
            label="Program Output",
            lines=10,
            elem_id="output-box",
            language=None
        ),
        title="Python Console",
        description=description,
        submit_btn=">_ Run",
        clear_btn=None
    )
   
    demo.css = """
    #output-box {
        background-color: black;
        font-family: monospace;
        padding: 10px;
    }
    """
if __name__ == "__main__":
    demo.launch()