Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import subprocess | |
| import tempfile | |
| import os | |
| import io | |
| from PIL import Image | |
| def run_pcbasic_code(code, timeout=60): | |
| """Executa o código PCBasic e captura a saída gráfica.""" | |
| with tempfile.TemporaryDirectory() as tmpdir: | |
| code_path = os.path.join(tmpdir, "code.bas") | |
| img_path = os.path.join(tmpdir, "output.png") | |
| # Salva o código BASIC num arquivo temporário | |
| with open(code_path, "w") as f: | |
| f.write(code) | |
| try: | |
| process = subprocess.Popen( | |
| [ | |
| "pcbasic", | |
| f"--run={code_path}", | |
| "--interface=sdl2", | |
| "--video=SDL2", | |
| ], | |
| stdout=subprocess.PIPE, | |
| stderr=subprocess.PIPE | |
| ) | |
| text_output, _ = process.communicate(timeout=timeout) | |
| text_output = text_output.decode('utf-8', errors='replace') | |
| if os.path.exists(img_path): | |
| img = Image.open(img_path) | |
| return text_output, img | |
| else: | |
| return text_output, None | |
| except subprocess.TimeoutExpired: | |
| process.kill() | |
| return "Erro: Tempo limite de execução excedido", None | |
| except Exception as e: | |
| return f"Erro: {str(e)}", None | |
| def process_basic_code(code): | |
| """Processa o código BASIC e prepara as saídas para exibição no Gradio.""" | |
| text, img = run_pcbasic_code(code) | |
| if img: | |
| img_byte = io.BytesIO() | |
| img.save(img_byte, format="PNG") | |
| return text, img_byte.getvalue() | |
| return text, None | |
| # Configuração da interface Gradio | |
| with gr.Blocks(title="PCBasic Interpreter") as demo: | |
| gr.Markdown("# PCBasic Interpreter Online") | |
| with gr.Row(): | |
| with gr.Column(): | |
| code_input = gr.Textbox( | |
| label="Código BASIC", | |
| placeholder="Digite seu código aqui...", | |
| lines=15 | |
| ) | |
| run_btn = gr.Button("Executar") | |
| with gr.Column(): | |
| text_out = gr.Textbox(label="Saída de Texto", lines=10) | |
| image_out = gr.Image(label="Saída Gráfica", type="filepath") | |
| examples = gr.Examples( | |
| examples=[ | |
| ["10 PRINT \"OLÁ MUNDO!\""], | |
| ["10 FOR I=1 TO 10\n20 PRINT I*2\n30 NEXT I"], | |
| ["10 SCREEN 1\n20 CIRCLE (160,100),50\n30 PAINT (160,100)"] | |
| ], | |
| inputs=code_input | |
| ) | |
| run_btn.click( | |
| fn=process_basic_code, | |
| inputs=code_input, | |
| outputs=[text_out, image_out] | |
| ) | |
| demo.launch() |