Luis-Filipe/pc-basic
0
1import gradio as gr
2import subprocess
3import tempfile
4import os
5import io
6from PIL import Image
7
8def run_pcbasic_code(code, timeout=60):
9 """Executa o código PCBasic e captura a saída gráfica."""
10 with tempfile.TemporaryDirectory() as tmpdir:
11 code_path = os.path.join(tmpdir, "code.bas")
12 img_path = os.path.join(tmpdir, "output.png")
13
14 # Salva o código BASIC num arquivo temporário
15 with open(code_path, "w") as f:
16 f.write(code)
17
18 try:
19 process = subprocess.Popen(
20 [
21 "pcbasic",
22 f"--run={code_path}",
23 "--interface=sdl2",
24 "--video=SDL2",
25 ],
26 stdout=subprocess.PIPE,
27 stderr=subprocess.PIPE
28 )
29
30 text_output, _ = process.communicate(timeout=timeout)
31 text_output = text_output.decode('utf-8', errors='replace')
32
33 if os.path.exists(img_path):
34 img = Image.open(img_path)
35 return text_output, img
36 else:
37 return text_output, None
38 except subprocess.TimeoutExpired:
39 process.kill()
40 return "Erro: Tempo limite de execução excedido", None
41 except Exception as e:
42 return f"Erro: {str(e)}", None
43
44def process_basic_code(code):
45 """Processa o código BASIC e prepara as saídas para exibição no Gradio."""
46 text, img = run_pcbasic_code(code)
47
48 if img:
49 img_byte = io.BytesIO()
50 img.save(img_byte, format="PNG")
51 return text, img_byte.getvalue()
52 return text, None
53
54# Configuração da interface Gradio
55with gr.Blocks(title="PCBasic Interpreter") as demo:
56 gr.Markdown("# PCBasic Interpreter Online")
57
58 with gr.Row():
59 with gr.Column():
60 code_input = gr.Textbox(
61 label="Código BASIC",
62 placeholder="Digite seu código aqui...",
63 lines=15
64 )
65 run_btn = gr.Button("Executar")
66 with gr.Column():
67 text_out = gr.Textbox(label="Saída de Texto", lines=10)
68 image_out = gr.Image(label="Saída Gráfica", type="filepath")
69
70 examples = gr.Examples(
71 examples=[
72 ["10 PRINT \"OLÁ MUNDO!\""],
73 ["10 FOR I=1 TO 10\n20 PRINT I*2\n30 NEXT I"],
74 ["10 SCREEN 1\n20 CIRCLE (160,100),50\n30 PAINT (160,100)"]
75 ],
76 inputs=code_input
77 )
78
79 run_btn.click(
80 fn=process_basic_code,
81 inputs=code_input,
82 outputs=[text_out, image_out]
83 )
84
85demo.launch()