Last active
March 17, 2023 09:12
-
-
Save ndruger/b5e478a3312552557b35ec19a48c4fdf to your computer and use it in GitHub Desktop.
Refactor specified file using OpenAI GPT-3 API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import openai | |
| import sys | |
| import re | |
| # Refactor specified file using OpenAI GPT-3 API | |
| # Example usage | |
| # | |
| # target=/your/project/path | |
| # for i in `ls -d $target/src/*.ts $target/test/*.ts`; | |
| # do | |
| # python refactor.py $i 2>&1 | tee -a result.log | |
| # done | |
| def eprint(*args, **kwargs): | |
| print(*args, file=sys.stderr, **kwargs) | |
| def readFile(path): | |
| with open(path, "r") as f: | |
| return f.read() | |
| def writeFile(path, content): | |
| with open(path, "w") as f: | |
| f.write(content) | |
| def main(): | |
| if len(sys.argv) != 2: | |
| eprint("Usage: python3 test.py <path>") | |
| sys.exit(1) | |
| path = sys.argv[1] | |
| code = readFile(path) | |
| filename = path.split("/")[-1] | |
| print("Processing:", path) | |
| res = openai.ChatCompletion.create( | |
| # model="gpt-4", | |
| model="gpt-3.5-turbo", | |
| messages=[ | |
| {"role": "user", "content": f'Please refactor this code. However, do not change the style regarding indentation, spaces, semicolons, commas, and line breaks. filename is {filename}. ```{code}```'}, | |
| ] | |
| ) | |
| choice = res['choices'][0] | |
| if choice["finish_reason"] != 'stop': | |
| eprint("Error: ", path, res) | |
| sys.exit(1) | |
| else: | |
| try: | |
| content = choice['message']['content'] | |
| writeFile(f'{path}.txt', content) # save whole message | |
| if content.count('```') >= 2: | |
| # pick first ``` block | |
| refactored = re.sub('^typescript\n', '', content.split('```')[1], flags=re.MULTILINE) | |
| else: | |
| refactored = content | |
| writeFile(path, refactored) | |
| print("Refactored!", path) | |
| except Exception as e: | |
| eprint("Error: ", path, e, res) | |
| sys.exit(1) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment