File size: 9,559 Bytes
e22dc2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4ab76a
 
 
e22dc2d
 
 
 
c4ab76a
e22dc2d
 
c4ab76a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e22dc2d
 
c4ab76a
 
 
 
 
 
 
 
 
 
 
 
 
e22dc2d
c4ab76a
 
e22dc2d
c4ab76a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e22dc2d
c4ab76a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e22dc2d
c4ab76a
 
e22dc2d
c4ab76a
 
 
 
 
 
 
 
e22dc2d
 
 
 
 
 
 
 
 
 
 
 
 
f108f62
871b96d
 
 
 
c4ab76a
e22dc2d
 
f108f62
e22dc2d
 
 
 
871b96d
 
 
e22dc2d
 
 
 
 
 
accea70
e22dc2d
837bf64
e22dc2d
 
 
 
837bf64
e22dc2d
accea70
e22dc2d
 
 
 
c4ab76a
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import gradio as gr
import io
import contextlib
import re
import traceback
import math

def preprocessar_codigos(portugol_code):
    replacements = {
        r"\bSENAO\b": "ELSE",
        r"\bFIMSE\b": "ENDIF",
        r"\bENTAO\b": "THEN",
        r"\bRAIZ\(": "math.sqrt(",
        r"(\w+)\^(\w+)": r"math.pow(\1, \2)",
        r"\bE\b": "and",
        r"\bOU\b": "or",
        r"\bNAO\b": "not",
        r"\bESCOLHA\b": "SWITCH",
        r"\bCASO\b": "CASE",
        r"\bCASO CONTRARIO\b": "DEFAULT",
        r"\bFIM-ESCOLHA\b": "ENDSWITCH",
        r"\bPARA\b": "FOR",
        r"\bATÉ\b": "TO",
        r"\bATE\b": "TO",
        r"\bFIM-PARA\b": "ENDFOR",
        r"\bESCREVER\b": "ESCREVA",
        r"\bENQUANTO\b": "WHILE",
        r"\bFIM-ENQUANTO\b": "ENDWHILE"
    }
    for pattern, replacement in replacements.items():
        portugol_code = re.sub(pattern, replacement, portugol_code, flags=re.IGNORECASE)
    return portugol_code

def processar_escreva(linha):
    padrao = r'ESCREVA\s*(.*)'
    match = re.match(padrao, linha, re.IGNORECASE)
    if match:
        conteudo = match.group(1).strip()
        conteudo_parts = conteudo.split('//', 1)
        conteudo = conteudo_parts[0].strip()
        comentario = f"  # {conteudo_parts[1].strip()}" if len(conteudo_parts) > 1 else ""
        if conteudo.startswith('"') and conteudo.endswith('"'):
            return f"print({conteudo}){comentario}"
        else:
            return f"print({conteudo}){comentario}"
    return linha

def verificar_tipo(var_name, valor, tipos_variaveis, linha):
    if var_name in tipos_variaveis:
        tipo_declarado = tipos_variaveis[var_name]
        if tipo_declarado == "INTEIRO" and "/" in valor:
            return f"# Atenção: Possível atribuição de valor real à variável inteira '{var_name}' na linha: {linha}"
    return None

def traduzir_para_python(portugol_code):
    portugol_code = preprocessar_codigos(portugol_code)
    lines = portugol_code.splitlines()
    codigo_python = ["import math"]
    indentacao = 0
    contexto_bloco = []
    tipos_variaveis = {}
    avisos = []
    in_switch = False
    switch_var = ""
    first_case = True

    for i, line in enumerate(lines, 1):
        line = line.strip()

        if not line or line.upper() in ["VARIAVEIS:", "ALGORITMO", "INICIO", "FIM"]:
            continue

        if ":" in line and not line.upper().startswith("CASE"):
            var_name, var_type = line.split(":", 1)
            var_name = var_name.strip()
            var_type = var_type.strip().upper()
            tipos_variaveis[var_name] = var_type
            if var_type == "INTEIRO":
                codigo_python.append(f"{var_name} = 0")
            elif var_type == "REAL":
                codigo_python.append(f"{var_name} = 0.0")
            elif var_type == "LOGICO":
                codigo_python.append(f"{var_name} = False")
            elif var_type in ["STRING", "CARACTERE"]:
                codigo_python.append(f"{var_name} = ''")

        elif line.upper().startswith("LEIA"):
            var_name = line.split("(")[1].split(")")[0].strip()
            if var_name in tipos_variaveis:
                tipo = tipos_variaveis[var_name]
                if tipo == "INTEIRO":
                    codigo_python.append(f"{var_name} = int(input('Digite um valor para {var_name}: '))")
                elif tipo == "REAL":
                    codigo_python.append(f"{var_name} = float(input('Digite um valor para {var_name}: '))")
                else:
                    codigo_python.append(f"{var_name} = input('Digite um valor para {var_name}: ')")
            else:
                codigo_python.append(f"{var_name} = input('Digite um valor para {var_name}: ')")

        elif line.upper().startswith("SE"):
            condicao = line[2:].split("THEN")[0].strip()
            codigo_python.append(f"{'    ' * indentacao}if {condicao}:")
            contexto_bloco.append("if")
            indentacao += 1

        elif line.upper() == "ELSE":
            if contexto_bloco and contexto_bloco[-1] == "if":
                indentacao -= 1
                codigo_python.append(f"{'    ' * indentacao}else:")
                indentacao += 1
            else:
                codigo_python.append(f"# Aviso: 'ELSE' sem 'SE' correspondente: {line}")

        elif line.upper() == "ENDIF":
            if contexto_bloco and contexto_bloco[-1] in ["if", "else"]:
                indentacao -= 1
                contexto_bloco.pop()
            else:
                codigo_python.append(f"# Aviso: 'ENDIF' sem 'SE' correspondente: {line}")

        elif line.upper().startswith("ESCOLHA") or line.upper().startswith("SWITCH"):
            in_switch = True
            switch_var = line.split("(")[1].split(")")[0].strip()
            first_case = True

        elif line.upper().startswith("CASO") and in_switch:
            case_value = line.split(":")[0].split()[1]
            if first_case:
                codigo_python.append(f"{'    ' * indentacao}if {switch_var} == {case_value}:")
                first_case = False
            else:
                indentacao -= 1
                codigo_python.append(f"{'    ' * indentacao}elif {switch_var} == {case_value}:")
            indentacao += 1

        elif (line.upper().startswith("CASO CONTRARIO") or line.upper() == "DEFAULT") and in_switch:
            indentacao -= 1
            codigo_python.append(f"{'    ' * indentacao}else:")
            indentacao += 1

        elif line.upper() == "FIM-ESCOLHA" or line.upper() == "ENDSWITCH":
            in_switch = False
            indentacao -= 1

        elif line.upper().startswith("PARA") or line.upper().startswith("FOR"):
            match = re.match(r"(PARA|FOR)\s+(\w+)\s*=\s*(\d+)\s*(ATE|TO)\s*(\d+)", line, re.IGNORECASE)
            if match:
                _, var, start, _, end = match.groups()
                codigo_python.append(f"{'    ' * indentacao}for {var} in range({start}, {int(end)+1}):")
                indentacao += 1
                contexto_bloco.append("for")
            else:
                codigo_python.append(f"# Aviso: Estrutura 'PARA' mal formatada: {line}")

        elif line.upper() == "FIM-PARA" or line.upper() == "ENDFOR":
            if contexto_bloco and contexto_bloco[-1] == "for":
                indentacao -= 1
                contexto_bloco.pop()
            else:
                codigo_python.append(f"# Aviso: 'FIM-PARA' sem 'PARA' correspondente: {line}")

        elif line.upper().startswith("ENQUANTO") or line.upper().startswith("WHILE"):
            condicao = line.split(None, 1)[1].strip()
            codigo_python.append(f"{'    ' * indentacao}while {condicao}:")
            indentacao += 1
            contexto_bloco.append("while")

        elif line.upper() == "FIM-ENQUANTO" or line.upper() == "ENDWHILE":
            if contexto_bloco and contexto_bloco[-1] == "while":
                indentacao -= 1
                contexto_bloco.pop()
            else:
                codigo_python.append(f"# Aviso: 'FIM-ENQUANTO' sem 'ENQUANTO' correspondente: {line}")

        elif line.upper().startswith("ESCREVA") or line.upper().startswith("ESCREVER"):
            codigo_python.append(f"{'    ' * indentacao}{processar_escreva(line)}")

        elif "=" in line:
            var_name, valor = line.split("=", 1)
            var_name = var_name.strip()
            valor = valor.strip()
            aviso = verificar_tipo(var_name, valor, tipos_variaveis, i)
            if aviso:
                avisos.append(aviso)
            codigo_python.append(f"{'    ' * indentacao}{line}")

    return "\n".join(codigo_python), avisos

def interpretador(portugol_code):
    codigo_python = "# Código Python não gerado devido a um erro"
    try:
        codigo_python, avisos = traduzir_para_python(portugol_code)
        codigo_python = re.sub(r"\bAND\b", "and", codigo_python)

        output = io.StringIO()
        with contextlib.redirect_stdout(output):
            exec(codigo_python, globals())

        # INICIALIZE resultado COMO UMA STRING VAZIA
        resultado = ""

        # DESCOMENTE A LINHA ABAIXO PARA MOSTRAR O CÓDIGO PYTHON GERADO
        # resultado += f"Código Python Gerado:\n{codigo_python}\n\n"

        if avisos:
            resultado += "Avisos:\n" + "\n".join(avisos) + "\n\n"

        resultado += f"Saída:\n{output.getvalue().strip()}"
        return resultado
    except Exception as e:
        error_traceback = traceback.format_exc()
        # VOCÊ PODE OPTAR POR NÃO MOSTRAR O CÓDIGO PYTHON GERADO EM CASO DE ERRO
        # DESCOMENTANDO A LINHA ABAIXO E COMENTANDO A LINHA SEGUINTE
        # return f"Erro durante a execução:\n{error_traceback}"
        return f"Erro durante a execução:\n{error_traceback}\n\nCódigo Python Gerado:\n{codigo_python}"

def interpretar(portugol_code):
    return interpretador(portugol_code)

description_html = """
<p>Interpretador de pseudocodigo:</p>
<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>
<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>
"""

iface = gr.Interface(
    fn=interpretar,
    inputs=gr.Textbox(lines=20, label="Pseudocodigo"),
    outputs="text",
    title="PseudocodeLab",
    description=description_html
)

if __name__ == "__main__":
    iface.launch(debug=True)