Spaces:
Sleeping
Sleeping
File size: 4,643 Bytes
cd17841 cabdfd8 cd17841 3931bae cd17841 3931bae cd17841 cabdfd8 3931bae cd17841 23babd4 cd17841 3931bae 03ef85a eeb9ef0 b7ae6f8 cd17841 b7ae6f8 fcaa9eb 920d46b 8207997 3931bae 8207997 fcaa9eb 920d46b cd17841 b7ae6f8 ace1941 b7ae6f8 3931bae cd17841 197b089 b7ae6f8 9ab2418 cd17841 3931bae ace1941 7038c0b cd17841 eeb9ef0 b7ae6f8 ace1941 eeb9ef0 cd17841 23babd4 cd17841 3931bae cd17841 3931bae cd17841 3931bae c56e5fe cd17841 a6b75be cd17841 | 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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | import gradio as gr
import subprocess
def valid(code:str) -> bool:
import re
strre = r"\"([^\"\r\n\\]*(\\.[^\"\r\n\\]*)*)\"|'([^'\r\n\\]*(\\.[^'\r\n\\]*)*)'"
illre = r"(?:\b|\s)(?:system|fpsystem|executeprocess|shellexecute|runcommand|process\.execute|tprocess\.execute|\.execute|createprocess|winexec|shellexecuteex|getenvironmentvariable|getenv|fpgetenv|tprocess\.environment|\.environment|getenvironmentstrings)\b"
checkcode = re.sub(strre, '', code)
return re.search(illre, checkcode, re.IGNORECASE) is None
def run_code_with_inputs(code: str, inputs: str) -> str:
"""
Runs the provided Pseudocode as a console program with the given inputs.
Parameters:
code (str): pseudocode to execute.
inputs (str): User inputs separated by newlines.
Returns:
str: Combined output from the program execution.
"""
if not valid(code):
raise Exception("Code contains keywords which violate Pseudocode+'s security protocol.")
filename = 'my_program.pseudo'
import os
pseudokey = os.getenv("pseudokey")
try:
with open(filename.removesuffix('.pseudo')+'.pseudo','wb') as file:
file.write(code.encode('utf-8'))
file_path = file.name
input_data = inputs.replace("\\n", "\n")
processes, outputs, errors = [], [], []
try:
processes.append(subprocess.run(
["./pseudocode", file_path, pseudokey, '--echo-inputs'],
text=True,
capture_output=True,
timeout=10
))
outputs.append(processes[-1].stdout)
except: pass
pasfile = file_path.removesuffix('.pseudo')+'.pas'
processes.append(subprocess.run(
["fpc", pasfile],
text=True,
capture_output=True,
timeout=10
))
outputs.append(processes[-1].stdout)
errors.append(processes[-1].stderr)
binfile = './'+file_path.removesuffix('.pseudo')
# print(file_path, os.path.exists(binfile))
subprocess.run(["chmod", "x+", binfile])
processes.append(subprocess.run(
[binfile],
input=input_data,
text=True,
capture_output=True,
timeout=10
))
ctime1 = os.path.getctime(pasfile)
ctime2 = os.path.getctime(binfile)
binfile_compiled = ctime1 < ctime2
# print(ctime1, ctime2, ctime1 < ctime2)
if binfile_compiled:
outputs.append(processes[-1].stdout)
errors.append(processes[-1].stderr)
else:
outputs.append("""Could not compile the pseudocode.
Please check for the following kind of errors
> Syntax Error
> Undefined Identifiers/Keywords
> Wrong or Mismatched Spellings
""")
if any(errors):
nl='\n'
return f"Error in Subprocess\nErrors:\n{nl.join(errors)}\n\nOutput:\n{nl.join(outputs)}"
return outputs[-1]
except Exception as e:
return f"An error occurred: {str(e)}"
# Define the Gradio interface
description = (
"""# Welcome to Pseudocode+!
### Pseudocode+ runs pseudocode based on the [CAIE Pseudocode Guide](https://www.cambridgeinternational.org/Images/697401-2026-pseudocode-guide-for-teachers.pdf), applicable for exams on 2025-2029.
"""#If you find any errors, repo"""
)
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="Pseudocode", language="typescript", value="""DECLARE yourname: STRING
OUTPUT "What is your name?"
INPUT yourname
OUTPUT "Hello, ",yourname,'!'
OUTPUT "You're using Pseudocode+ ",__version__,'.' """),
gr.Code(label="User Inputs", value='Alice\nBob', language=None, elem_id="input-box"),
],
outputs=gr.Code(
label="Program Output",
value="",
elem_id="output-box",
language=None
),
title="Pseudocode+ | by raufoon",
description=description,
submit_btn=">_ Run",
clear_btn=None
)
demo.css = """
#output-box, #input-box {
background-color: black;
font-family: monospace;
padding: 10px;
}
"""
if __name__ == "__main__":
subprocess.run("""chmod +x ./pseudocode
wget https://downloads.freepascal.org/fpc/dist/3.2.2/x86_64-linux/fpc-3.2.2.x86_64-linux.tar -O fpc.tar
tar -xvf fpc.tar
cd fpc-3.2.2.x86_64-linux
./install.sh --prefix=$HOME/fpc
export PATH=$HOME/fpc/bin:$PATH
""", shell=True, text=True)
demo.launch() |