Spaces:
Running
Running
rmayormartins
commited on
Commit
·
c4ab76a
1
Parent(s):
accea70
Subindo arquivos7
Browse files
app.py
CHANGED
@@ -5,7 +5,6 @@ import re
|
|
5 |
import traceback
|
6 |
import math
|
7 |
|
8 |
-
#
|
9 |
def preprocessar_codigos(portugol_code):
|
10 |
replacements = {
|
11 |
r"\bSENAO\b": "ELSE",
|
@@ -61,139 +60,132 @@ def traduzir_para_python(portugol_code):
|
|
61 |
contexto_bloco = []
|
62 |
tipos_variaveis = {}
|
63 |
avisos = []
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
|
68 |
for i, line in enumerate(lines, 1):
|
69 |
-
original_line = line
|
70 |
line = line.strip()
|
71 |
|
72 |
-
|
73 |
-
line = line_parts[0].strip()
|
74 |
-
comentario = f" # {line_parts[1].strip()}" if len(line_parts) > 1 else ""
|
75 |
-
|
76 |
-
if not line and comentario:
|
77 |
-
codigo_python.append(f"{' ' * indentacao}{comentario.strip()}")
|
78 |
-
continue
|
79 |
-
|
80 |
-
if line.upper().startswith("ALGORITMO"):
|
81 |
-
in_algoritmo = True
|
82 |
-
algoritmo_iniciado = True
|
83 |
-
continue
|
84 |
-
if line.upper() in ["VARIAVEIS", "VARIAVEL"]:
|
85 |
-
in_variaveis = True
|
86 |
-
algoritmo_iniciado = True
|
87 |
-
continue
|
88 |
-
if line.upper() == "INICIO":
|
89 |
-
in_variaveis = False
|
90 |
-
in_algoritmo = False
|
91 |
-
algoritmo_iniciado = True
|
92 |
-
continue
|
93 |
-
if line.upper() == "FIM":
|
94 |
-
break
|
95 |
-
|
96 |
-
if not algoritmo_iniciado and line:
|
97 |
-
in_variaveis = False
|
98 |
-
in_algoritmo = False
|
99 |
-
algoritmo_iniciado = True
|
100 |
-
|
101 |
-
if in_variaveis or (not algoritmo_iniciado and (":" in line or "=" in line)):
|
102 |
-
if ":" in line:
|
103 |
-
parts = line.split(":", 1)
|
104 |
-
var_name = parts[0].strip()
|
105 |
-
var_type_and_value = parts[1].strip()
|
106 |
-
|
107 |
-
if "=" in var_type_and_value:
|
108 |
-
var_type, var_value = var_type_and_value.split("=", 1)
|
109 |
-
var_type = var_type.strip().upper()
|
110 |
-
var_value = var_value.strip()
|
111 |
-
else:
|
112 |
-
var_type = var_type_and_value.upper()
|
113 |
-
var_value = None
|
114 |
-
|
115 |
-
tipos_variaveis[var_name] = var_type
|
116 |
-
|
117 |
-
if var_value:
|
118 |
-
codigo_python.append(f"{var_name} = {var_value}")
|
119 |
-
else:
|
120 |
-
if var_type == "INTEIRO":
|
121 |
-
codigo_python.append(f"{var_name} = 0")
|
122 |
-
elif var_type == "REAL":
|
123 |
-
codigo_python.append(f"{var_name} = 0.0")
|
124 |
-
elif var_type == "LOGICO":
|
125 |
-
codigo_python.append(f"{var_name} = False")
|
126 |
-
elif var_type == "STRING":
|
127 |
-
codigo_python.append(f"{var_name} = ''")
|
128 |
-
elif var_type == "CARACTERE":
|
129 |
-
codigo_python.append(f"{var_name} = ''")
|
130 |
-
elif "=" in line:
|
131 |
-
var_name, valor = line.split("=", 1)
|
132 |
-
var_name = var_name.strip()
|
133 |
-
valor = valor.strip()
|
134 |
-
codigo_python.append(f"{var_name} = {valor}")
|
135 |
continue
|
136 |
|
137 |
-
if not
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
|
|
|
|
|
|
|
|
155 |
else:
|
156 |
codigo_python.append(f"{var_name} = input('Digite um valor para {var_name}: ')")
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
162 |
indentacao += 1
|
|
|
|
|
163 |
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
178 |
|
179 |
-
|
180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
181 |
|
182 |
-
|
183 |
-
|
184 |
-
var_name = var_name.strip()
|
185 |
-
valor = valor.strip()
|
186 |
-
aviso = verificar_tipo(var_name, valor, tipos_variaveis, i)
|
187 |
-
if aviso:
|
188 |
-
avisos.append(aviso)
|
189 |
-
codigo_python.append(f"{' ' * indentacao}{line}{comentario}")
|
190 |
|
191 |
-
|
192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
193 |
|
194 |
return "\n".join(codigo_python), avisos
|
195 |
|
196 |
-
#
|
197 |
def interpretador(portugol_code):
|
198 |
codigo_python = "# Código Python não gerado devido a um erro"
|
199 |
try:
|
@@ -204,7 +196,8 @@ def interpretador(portugol_code):
|
|
204 |
with contextlib.redirect_stdout(output):
|
205 |
exec(codigo_python, globals())
|
206 |
|
207 |
-
resultado = ""
|
|
|
208 |
if avisos:
|
209 |
resultado += "Avisos:\n" + "\n".join(avisos) + "\n\n"
|
210 |
resultado += f"Saída:\n{output.getvalue().strip()}"
|
@@ -216,14 +209,12 @@ def interpretador(portugol_code):
|
|
216 |
def interpretar(portugol_code):
|
217 |
return interpretador(portugol_code)
|
218 |
|
219 |
-
#
|
220 |
description_html = """
|
221 |
<p>Interpretador de pseudocodigo:</p>
|
222 |
<p>Ramon Mayor Martins: <a href="https://rmayormartins.github.io/" target="_blank">Website</a> | <a href="https://huggingface.co/rmayormartins" target="_blank">Spaces</a></p>
|
223 |
<p><a href="https://huggingface.co/spaces/rmayormartins/pseudocodelab/blob/main/Manual_PseudocodeLab.pdf" target="_blank">Clique aqui para visualizar o Manual do PseudocodeLab</a></p>
|
224 |
"""
|
225 |
|
226 |
-
#
|
227 |
iface = gr.Interface(
|
228 |
fn=interpretar,
|
229 |
inputs=gr.Textbox(lines=20, label="Pseudocodigo"),
|
@@ -232,6 +223,5 @@ iface = gr.Interface(
|
|
232 |
description=description_html
|
233 |
)
|
234 |
|
235 |
-
#
|
236 |
if __name__ == "__main__":
|
237 |
-
iface.launch(debug=True)
|
|
|
5 |
import traceback
|
6 |
import math
|
7 |
|
|
|
8 |
def preprocessar_codigos(portugol_code):
|
9 |
replacements = {
|
10 |
r"\bSENAO\b": "ELSE",
|
|
|
60 |
contexto_bloco = []
|
61 |
tipos_variaveis = {}
|
62 |
avisos = []
|
63 |
+
in_switch = False
|
64 |
+
switch_var = ""
|
65 |
+
first_case = True
|
66 |
|
67 |
for i, line in enumerate(lines, 1):
|
|
|
68 |
line = line.strip()
|
69 |
|
70 |
+
if not line or line.upper() in ["VARIAVEIS:", "ALGORITMO", "INICIO", "FIM"]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
continue
|
72 |
|
73 |
+
if ":" in line and not line.upper().startswith("CASE"):
|
74 |
+
var_name, var_type = line.split(":", 1)
|
75 |
+
var_name = var_name.strip()
|
76 |
+
var_type = var_type.strip().upper()
|
77 |
+
tipos_variaveis[var_name] = var_type
|
78 |
+
if var_type == "INTEIRO":
|
79 |
+
codigo_python.append(f"{var_name} = 0")
|
80 |
+
elif var_type == "REAL":
|
81 |
+
codigo_python.append(f"{var_name} = 0.0")
|
82 |
+
elif var_type == "LOGICO":
|
83 |
+
codigo_python.append(f"{var_name} = False")
|
84 |
+
elif var_type in ["STRING", "CARACTERE"]:
|
85 |
+
codigo_python.append(f"{var_name} = ''")
|
86 |
+
|
87 |
+
elif line.upper().startswith("LEIA"):
|
88 |
+
var_name = line.split("(")[1].split(")")[0].strip()
|
89 |
+
if var_name in tipos_variaveis:
|
90 |
+
tipo = tipos_variaveis[var_name]
|
91 |
+
if tipo == "INTEIRO":
|
92 |
+
codigo_python.append(f"{var_name} = int(input('Digite um valor para {var_name}: '))")
|
93 |
+
elif tipo == "REAL":
|
94 |
+
codigo_python.append(f"{var_name} = float(input('Digite um valor para {var_name}: '))")
|
95 |
else:
|
96 |
codigo_python.append(f"{var_name} = input('Digite um valor para {var_name}: ')")
|
97 |
+
else:
|
98 |
+
codigo_python.append(f"{var_name} = input('Digite um valor para {var_name}: ')")
|
99 |
+
|
100 |
+
elif line.upper().startswith("SE"):
|
101 |
+
condicao = line[2:].split("THEN")[0].strip()
|
102 |
+
codigo_python.append(f"{' ' * indentacao}if {condicao}:")
|
103 |
+
contexto_bloco.append("if")
|
104 |
+
indentacao += 1
|
105 |
+
|
106 |
+
elif line.upper() == "ELSE":
|
107 |
+
if contexto_bloco and contexto_bloco[-1] == "if":
|
108 |
+
indentacao -= 1
|
109 |
+
codigo_python.append(f"{' ' * indentacao}else:")
|
110 |
indentacao += 1
|
111 |
+
else:
|
112 |
+
codigo_python.append(f"# Aviso: 'ELSE' sem 'SE' correspondente: {line}")
|
113 |
|
114 |
+
elif line.upper() == "ENDIF":
|
115 |
+
if contexto_bloco and contexto_bloco[-1] in ["if", "else"]:
|
116 |
+
indentacao -= 1
|
117 |
+
contexto_bloco.pop()
|
118 |
+
else:
|
119 |
+
codigo_python.append(f"# Aviso: 'ENDIF' sem 'SE' correspondente: {line}")
|
120 |
+
|
121 |
+
elif line.upper().startswith("ESCOLHA") or line.upper().startswith("SWITCH"):
|
122 |
+
in_switch = True
|
123 |
+
switch_var = line.split("(")[1].split(")")[0].strip()
|
124 |
+
first_case = True
|
125 |
+
|
126 |
+
elif line.upper().startswith("CASO") and in_switch:
|
127 |
+
case_value = line.split(":")[0].split()[1]
|
128 |
+
if first_case:
|
129 |
+
codigo_python.append(f"{' ' * indentacao}if {switch_var} == {case_value}:")
|
130 |
+
first_case = False
|
131 |
+
else:
|
132 |
+
indentacao -= 1
|
133 |
+
codigo_python.append(f"{' ' * indentacao}elif {switch_var} == {case_value}:")
|
134 |
+
indentacao += 1
|
135 |
+
|
136 |
+
elif (line.upper().startswith("CASO CONTRARIO") or line.upper() == "DEFAULT") and in_switch:
|
137 |
+
indentacao -= 1
|
138 |
+
codigo_python.append(f"{' ' * indentacao}else:")
|
139 |
+
indentacao += 1
|
140 |
+
|
141 |
+
elif line.upper() == "FIM-ESCOLHA" or line.upper() == "ENDSWITCH":
|
142 |
+
in_switch = False
|
143 |
+
indentacao -= 1
|
144 |
+
|
145 |
+
elif line.upper().startswith("PARA") or line.upper().startswith("FOR"):
|
146 |
+
match = re.match(r"(PARA|FOR)\s+(\w+)\s*=\s*(\d+)\s*(ATE|TO)\s*(\d+)", line, re.IGNORECASE)
|
147 |
+
if match:
|
148 |
+
_, var, start, _, end = match.groups()
|
149 |
+
codigo_python.append(f"{' ' * indentacao}for {var} in range({start}, {int(end)+1}):")
|
150 |
+
indentacao += 1
|
151 |
+
contexto_bloco.append("for")
|
152 |
+
else:
|
153 |
+
codigo_python.append(f"# Aviso: Estrutura 'PARA' mal formatada: {line}")
|
154 |
|
155 |
+
elif line.upper() == "FIM-PARA" or line.upper() == "ENDFOR":
|
156 |
+
if contexto_bloco and contexto_bloco[-1] == "for":
|
157 |
+
indentacao -= 1
|
158 |
+
contexto_bloco.pop()
|
159 |
+
else:
|
160 |
+
codigo_python.append(f"# Aviso: 'FIM-PARA' sem 'PARA' correspondente: {line}")
|
161 |
+
|
162 |
+
elif line.upper().startswith("ENQUANTO") or line.upper().startswith("WHILE"):
|
163 |
+
condicao = line.split(None, 1)[1].strip()
|
164 |
+
codigo_python.append(f"{' ' * indentacao}while {condicao}:")
|
165 |
+
indentacao += 1
|
166 |
+
contexto_bloco.append("while")
|
167 |
+
|
168 |
+
elif line.upper() == "FIM-ENQUANTO" or line.upper() == "ENDWHILE":
|
169 |
+
if contexto_bloco and contexto_bloco[-1] == "while":
|
170 |
+
indentacao -= 1
|
171 |
+
contexto_bloco.pop()
|
172 |
+
else:
|
173 |
+
codigo_python.append(f"# Aviso: 'FIM-ENQUANTO' sem 'ENQUANTO' correspondente: {line}")
|
174 |
|
175 |
+
elif line.upper().startswith("ESCREVA") or line.upper().startswith("ESCREVER"):
|
176 |
+
codigo_python.append(f"{' ' * indentacao}{processar_escreva(line)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
|
178 |
+
elif "=" in line:
|
179 |
+
var_name, valor = line.split("=", 1)
|
180 |
+
var_name = var_name.strip()
|
181 |
+
valor = valor.strip()
|
182 |
+
aviso = verificar_tipo(var_name, valor, tipos_variaveis, i)
|
183 |
+
if aviso:
|
184 |
+
avisos.append(aviso)
|
185 |
+
codigo_python.append(f"{' ' * indentacao}{line}")
|
186 |
|
187 |
return "\n".join(codigo_python), avisos
|
188 |
|
|
|
189 |
def interpretador(portugol_code):
|
190 |
codigo_python = "# Código Python não gerado devido a um erro"
|
191 |
try:
|
|
|
196 |
with contextlib.redirect_stdout(output):
|
197 |
exec(codigo_python, globals())
|
198 |
|
199 |
+
resultado = f"Código Python Gerado:\n{codigo_python}\n\n"
|
200 |
+
|
201 |
if avisos:
|
202 |
resultado += "Avisos:\n" + "\n".join(avisos) + "\n\n"
|
203 |
resultado += f"Saída:\n{output.getvalue().strip()}"
|
|
|
209 |
def interpretar(portugol_code):
|
210 |
return interpretador(portugol_code)
|
211 |
|
|
|
212 |
description_html = """
|
213 |
<p>Interpretador de pseudocodigo:</p>
|
214 |
<p>Ramon Mayor Martins: <a href="https://rmayormartins.github.io/" target="_blank">Website</a> | <a href="https://huggingface.co/rmayormartins" target="_blank">Spaces</a></p>
|
215 |
<p><a href="https://huggingface.co/spaces/rmayormartins/pseudocodelab/blob/main/Manual_PseudocodeLab.pdf" target="_blank">Clique aqui para visualizar o Manual do PseudocodeLab</a></p>
|
216 |
"""
|
217 |
|
|
|
218 |
iface = gr.Interface(
|
219 |
fn=interpretar,
|
220 |
inputs=gr.Textbox(lines=20, label="Pseudocodigo"),
|
|
|
223 |
description=description_html
|
224 |
)
|
225 |
|
|
|
226 |
if __name__ == "__main__":
|
227 |
+
iface.launch(debug=True)
|