improve_code.py 925 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import sys, re
  2. from pathlib import Path
  3. from os import path
  4. sys.path.append(str(Path(__file__).parent.parent.parent))
  5. import g4f
  6. def read_code(text):
  7. if match := re.search(r"```(python|py|)\n(?P<code>[\S\s]+?)\n```", text):
  8. return match.group("code")
  9. path = input("Path: ")
  10. with open(path, "r") as file:
  11. code = file.read()
  12. prompt = f"""
  13. Improve the code in this file:
  14. ```py
  15. {code}
  16. ```
  17. Don't remove anything.
  18. Add typehints if possible.
  19. Don't add any typehints to kwargs.
  20. Don't remove license comments.
  21. """
  22. print("Create code...")
  23. response = []
  24. for chunk in g4f.ChatCompletion.create(
  25. model=g4f.models.gpt_35_long,
  26. messages=[{"role": "user", "content": prompt}],
  27. timeout=300,
  28. stream=True
  29. ):
  30. response.append(chunk)
  31. print(chunk, end="", flush=True)
  32. print()
  33. response = "".join(response)
  34. if code := read_code(response):
  35. with open(path, "w") as file:
  36. file.write(code)