-
Notifications
You must be signed in to change notification settings - Fork 0
/
program_validator.py
50 lines (40 loc) · 1.4 KB
/
program_validator.py
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
import re
import textwrap
def validate_program(prog: str):
"""
validate the input program (@prog).
if the program is valid or can be corrected, return a clean and corrected version of it.
if the program contains fatal errors, return all errors.
"""
# extract python code if the llm output is in markdown format (which happens from time to time...)
if "```" in prog:
if prog.count("```") != 2:
print()
print("=>> ↓↓↓ PROGRAM VALIDATION FAILED! ↓↓↓ <<=")
print()
print(prog)
print()
print("=>> ↑↑↑ PROGRAM VALIDATION FAILED! ↑↑↑ <<=")
print()
return textwrap.dedent(prog).strip()
is_code = False
code_lines = []
for line in prog.split("\n"):
match = re.match(
r"(?:```\s*python|```\s*Python|```\s*PYTHON|```)(.*?)$",
line.strip(),
)
if match:
is_code = not is_code
continue # simply skip this line
if is_code:
# assuming no indent in the code
code_lines.append(line.strip())
prog = "\n".join(code_lines)
prog = textwrap.dedent(prog).strip()
# print("cleaned program:")
# print()
# print(prog)
# print()
# maybe we don't need a validator for now...
return prog