2023-03-18 22:16:47 +00:00
|
|
|
import difflib
|
2023-04-08 19:38:14 +00:00
|
|
|
import fire
|
2023-03-18 22:16:47 +00:00
|
|
|
import json
|
|
|
|
import os
|
|
|
|
import shutil
|
|
|
|
import subprocess
|
|
|
|
import sys
|
|
|
|
import openai
|
|
|
|
from termcolor import cprint
|
|
|
|
|
2023-04-14 14:28:34 +00:00
|
|
|
# Load the OpenAI API key
|
|
|
|
def load_openai_key():
|
|
|
|
with open("openai_key.txt") as f:
|
|
|
|
return f.read().strip()
|
2023-03-18 22:16:47 +00:00
|
|
|
|
2023-04-14 14:28:34 +00:00
|
|
|
# Run the provided script and return the output and return code
|
2023-04-08 19:38:14 +00:00
|
|
|
def run_script(script_name, script_args):
|
|
|
|
script_args = [str(arg) for arg in script_args]
|
2023-03-18 22:16:47 +00:00
|
|
|
try:
|
|
|
|
result = subprocess.check_output(
|
2023-04-08 19:38:14 +00:00
|
|
|
[sys.executable, script_name, *script_args], stderr=subprocess.STDOUT
|
2023-03-18 22:16:47 +00:00
|
|
|
)
|
|
|
|
except subprocess.CalledProcessError as e:
|
|
|
|
return e.output.decode("utf-8"), e.returncode
|
|
|
|
return result.decode("utf-8"), 0
|
|
|
|
|
2023-04-14 14:28:34 +00:00
|
|
|
# Send the error to GPT and receive suggestions
|
|
|
|
def send_error_to_gpt(file_path, args, error_message, model, prompt_length_limit=4096):
|
2023-03-18 22:16:47 +00:00
|
|
|
with open(file_path, "r") as f:
|
|
|
|
file_lines = f.readlines()
|
|
|
|
|
|
|
|
file_with_lines = []
|
|
|
|
for i, line in enumerate(file_lines):
|
|
|
|
file_with_lines.append(str(i + 1) + ": " + line)
|
|
|
|
file_with_lines = "".join(file_with_lines)
|
|
|
|
|
|
|
|
with open("prompt.txt") as f:
|
|
|
|
initial_prompt_text = f.read()
|
|
|
|
|
|
|
|
prompt = (
|
|
|
|
initial_prompt_text +
|
|
|
|
"\n\n"
|
|
|
|
"Here is the script that needs fixing:\n\n"
|
|
|
|
f"{file_with_lines}\n\n"
|
|
|
|
"Here are the arguments it was provided:\n\n"
|
|
|
|
f"{args}\n\n"
|
|
|
|
"Here is the error message:\n\n"
|
|
|
|
f"{error_message}\n"
|
|
|
|
"Please provide your suggested changes, and remember to stick to the "
|
|
|
|
"exact format as described above."
|
|
|
|
)
|
|
|
|
|
2023-04-14 14:28:34 +00:00
|
|
|
# Truncate the prompt if it exceeds the limit
|
|
|
|
if len(prompt) > prompt_length_limit:
|
|
|
|
prompt = prompt[:prompt_length_limit]
|
2023-03-18 22:16:47 +00:00
|
|
|
|
|
|
|
response = openai.ChatCompletion.create(
|
2023-04-08 19:38:14 +00:00
|
|
|
model=model,
|
2023-03-18 22:16:47 +00:00
|
|
|
messages=[
|
|
|
|
{
|
|
|
|
"role": "user",
|
|
|
|
"content": prompt,
|
|
|
|
}
|
|
|
|
],
|
|
|
|
temperature=1.0,
|
|
|
|
)
|
|
|
|
|
|
|
|
return response.choices[0].message.content.strip()
|
|
|
|
|
2023-04-14 14:28:34 +00:00
|
|
|
# Apply the changes suggested by GPT
|
2023-03-18 22:16:47 +00:00
|
|
|
def apply_changes(file_path, changes_json):
|
2023-04-14 14:28:34 +00:00
|
|
|
try:
|
|
|
|
with open(file_path, "r") as f:
|
|
|
|
original_file_lines = f.readlines()
|
|
|
|
|
|
|
|
changes = json.loads(changes_json)
|
|
|
|
|
|
|
|
operation_changes = [change for change in changes if "operation" in change]
|
|
|
|
explanations = [
|
|
|
|
change["explanation"] for change in changes if "explanation" in change
|
|
|
|
]
|
|
|
|
|
|
|
|
operation_changes.sort(key=lambda x: x["line"], reverse=True)
|
|
|
|
|
|
|
|
file_lines = original_file_lines.copy()
|
|
|
|
for change in operation_changes:
|
|
|
|
operation = change["operation"]
|
|
|
|
line = change["line"]
|
|
|
|
content = change["content"]
|
|
|
|
|
|
|
|
if operation == "Replace":
|
|
|
|
file_lines[line - 1] = content + "\n"
|
|
|
|
elif operation == "Delete":
|
|
|
|
del file_lines[line - 1]
|
|
|
|
elif operation == "InsertAfter":
|
|
|
|
file_lines.insert(line, content + "\n")
|
|
|
|
|
|
|
|
with open(file_path, "w") as f:
|
|
|
|
f.writelines(file_lines)
|
|
|
|
|
|
|
|
# Print explanations
|
|
|
|
cprint("Explanations:", "blue")
|
|
|
|
for explanation in explanations:
|
|
|
|
cprint(f"- {explanation}", "blue")
|
|
|
|
|
|
|
|
# Show the diff
|
|
|
|
print("\nChanges:")
|
|
|
|
print_diff(original_file_lines, file_lines)
|
|
|
|
except Exception as e:
|
|
|
|
raise Exception(f"Failed to apply changes: {str(e)}")
|
2023-04-14 14:58:10 +00:00
|
|
|
|
|
|
|
# Apply a single change suggested by GPT interactively
|
|
|
|
def apply_change_interactive(file_path, change):
|
|
|
|
with open(file_path, "r") as f:
|
|
|
|
original_file_lines = f.readlines()
|
|
|
|
|
|
|
|
operation = change["operation"]
|
|
|
|
line = change["line"]
|
|
|
|
content = change["content"]
|
|
|
|
|
|
|
|
file_lines = original_file_lines.copy()
|
|
|
|
if operation == "Replace":
|
|
|
|
file_lines[line - 1] = content + "\n"
|
|
|
|
elif operation == "Delete":
|
|
|
|
del file_lines[line - 1]
|
|
|
|
elif operation == "InsertAfter":
|
|
|
|
file_lines.insert(line, content + "\n")
|
|
|
|
|
|
|
|
print("\nSuggested change:")
|
|
|
|
print_diff(original_file_lines, file_lines)
|
|
|
|
|
|
|
|
while True:
|
|
|
|
decision = input("Do you want to apply this change? (y/n): ").lower()
|
|
|
|
if decision == "y":
|
|
|
|
with open(file_path, "w") as f:
|
|
|
|
f.writelines(file_lines)
|
|
|
|
return True
|
|
|
|
elif decision == "n":
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
print("Invalid input. Please enter 'y' or 'n'.")
|
2023-04-14 14:28:34 +00:00
|
|
|
|
|
|
|
# Print the differences between two file contents
|
|
|
|
def print_diff(original_file_lines, file_lines):
|
2023-03-18 22:16:47 +00:00
|
|
|
diff = difflib.unified_diff(original_file_lines, file_lines, lineterm="")
|
|
|
|
for line in diff:
|
|
|
|
if line.startswith("+"):
|
|
|
|
cprint(line, "green", end="")
|
|
|
|
elif line.startswith("-"):
|
|
|
|
cprint(line, "red", end="")
|
|
|
|
else:
|
|
|
|
print(line, end="")
|
|
|
|
|
2023-04-14 14:58:10 +00:00
|
|
|
def main(script_name, *script_args, revert=False, model="gpt-4", interactive=False):
|
2023-04-14 14:28:34 +00:00
|
|
|
openai.api_key = load_openai_key()
|
|
|
|
|
2023-04-08 19:38:14 +00:00
|
|
|
if revert:
|
2023-03-18 22:16:47 +00:00
|
|
|
backup_file = script_name + ".bak"
|
|
|
|
if os.path.exists(backup_file):
|
|
|
|
shutil.copy(backup_file, script_name)
|
|
|
|
print(f"Reverted changes to {script_name}")
|
2023-04-14 14:28:34 +00:00
|
|
|
return
|
2023-03-18 22:16:47 +00:00
|
|
|
else:
|
2023-04-14 14:28:34 +00:00
|
|
|
raise Exception(f"No backup file found for {script_name}")
|
2023-03-18 22:16:47 +00:00
|
|
|
|
|
|
|
# Make a backup of the original script
|
|
|
|
shutil.copy(script_name, script_name + ".bak")
|
|
|
|
|
|
|
|
while True:
|
2023-04-08 19:38:14 +00:00
|
|
|
output, returncode = run_script(script_name, script_args)
|
2023-03-18 22:16:47 +00:00
|
|
|
|
|
|
|
if returncode == 0:
|
|
|
|
cprint("Script ran successfully.", "blue")
|
|
|
|
print("Output:", output)
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
cprint("Script crashed. Trying to fix...", "blue")
|
|
|
|
print("Output:", output)
|
|
|
|
|
2023-04-08 19:49:10 +00:00
|
|
|
json_response = send_error_to_gpt(
|
2023-04-08 19:38:14 +00:00
|
|
|
file_path=script_name,
|
|
|
|
args=script_args,
|
|
|
|
error_message=output,
|
|
|
|
model=model,
|
|
|
|
)
|
2023-04-14 14:58:10 +00:00
|
|
|
if interactive:
|
|
|
|
changes = json.loads(json_response)
|
|
|
|
operation_changes = [change for change in changes if "operation" in change]
|
|
|
|
explanations = [
|
|
|
|
change["explanation"] for change in changes if "explanation" in change
|
|
|
|
]
|
|
|
|
|
|
|
|
for change in operation_changes:
|
|
|
|
if apply_change_interactive(script_name, change):
|
|
|
|
cprint("Change applied.", "green")
|
|
|
|
else:
|
|
|
|
cprint("Change rejected.", "red")
|
|
|
|
cprint("Finished applying changes. Rerunning...", "blue")
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
apply_changes(script_name, json_response)
|
|
|
|
cprint("Changes applied. Rerunning...", "blue")
|
|
|
|
except Exception as e:
|
|
|
|
raise Exception(f"Failed to fix the script: {str(e)}")
|
2023-03-18 22:16:47 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2023-04-14 14:28:34 +00:00
|
|
|
try:
|
|
|
|
fire.Fire(main)
|
|
|
|
except Exception as e:
|
|
|
|
print(str(e))
|
|
|
|
sys.exit(1)
|
|
|
|
|