Project Code Reviewer Sederhana

Melanjutkan dari modul code menggunakan ChatGPT, kali ini kita akan mengimplementasikan untuk membuat program sederhana untuk mereview program dalam Bahasa Python.

Pada project digunakan nama program reviewer.py yang menerima parameter nama file Python yang akan direview dan parameter optional –model untuk memilih model yang akan digunakan, secara default digunakan gpt-3.5-turbo.

from ast import parse
import openai
from dotenv import load_dotenv
import os
import argparse

PROMPT = """
You will receive a file's contents as text.
Generate a code review for the file.  Indicate what changes should be made to improve its style, performance, readability, and maintainability.  If there are any reputable libraries that could be introduced to improve the code, suggest them.  Be kind and constructive.  For each suggested change, include line numbers to which you are referring
"""

def code_review(file_path, model):
    with open(file_path, "r") as file:
        content = file.read()
    generated_code_review = make_code_review_request(content, model)
    print(generated_code_review)

def make_code_review_request(filecontent, model):
    messages = [
        {"role": "system", "content": PROMPT},
        {"role": "user", "content": f"Code review the following file: {filecontent}"}
    ]
    res = openai.ChatCompletion.create(
        model=model,
        messages=messages
    )

    return res["choices"][0]["message"]["content"]

def main():
    parser = argparse.ArgumentParser(description="Simple code reviewer for a file")
    parser.add_argument("file")
    parser.add_argument("--model", default="gpt-3.5-turbo")
    args = parser.parse_args()
    code_review(args.file, args.model)

if __name__ == "__main__":
    load_dotenv()
    openai.api_key = os.getenv("OPENAI_KEY")
    main()

Jika dijalankan, menggunakan code tree.py sebagai contoh program yang direview. Berikut hasilnya.

Overall, the code looks solid. Below are some suggestions to improve its style, performance, readability, and maintainability.
1. The naming convention of the classes, methods, and attributes should follow the PEP 8 style guide. For example, instead of `leftChild`, use `left_child`.
2. Add docstring to classes and methods to make the code more readable and understandable, and easier to maintain. The docstrings should describe what the class or method does, what arguments it takes, and what it returns.
3. `insert` and `search` methods can return without `return`, as it is redundant.
4. Instead of using `print` in the `PrintTree` method, add support for tree visualization libraries such as Graphviz or PyGraphviz. These libraries significantly improve visualization and make it easier to understand the tree.
5. Add more error checking, for example, if the value passed to the `search` method is not an integer or if the tree is empty, etc.       
6. Add a method to delete a node from the tree.

Here is the updated code incorporating the changes mentioned above.

```python
class Node:
    """
    Class representing a node in a binary search tree.

    Attributes:
        data (int): The data of the node.
        left_child (Node): The left child of the node.
        right_child (Node): The right child of the node.
    """
    def __init__(self, data):
        self.data = data
        self.left_child = None
        self.right_child = None

    def insert(self, data):
        """
        Insert a new node into the binary search tree.

        Args:
            data (int): The data of the new node.
        """
        if data < self.data:
            if self.left_child:
                self.left_child.insert(data)
            else:
                self.left_child = Node(data)
        else:
            if self.right_child:
                self.right_child.insert(data)
            else:
                self.right_child = Node(data)

    def search(self, val):
        """
        Search for a value in the binary search tree.

        Args:
            val (int): The value to search for.

        Returns:
            str: A message indicating whether the value was found or not.
        """
        if val == self.data:
            return str(val) + " is found in the BST"
        elif val < self.data:
            if self.left_child:
                return self.left_child.search(val)
            else:
                return str(val) + " is not found in the BST"
        else:
            if self.right_child:
                return self.right_child.search(val)
            else:
                return str(val) + " is not found in the BST"

    def print_tree(self):
        """
        Print the binary search tree in order.
        """
        if self.left_child:
            self.left_child.print_tree()
        print(self.data, end=" ")
        if self.right_child:
            self.right_child.print_tree()

root = Node(27)
root.insert(14)
root.insert(35)
root.insert(31)
root.insert(10)
root.insert(19)

print(root.search(7))
print(root.search(14))

# Tree visualization using the graphviz library
from graphviz import Digraph

def visualize_tree(node):
    """
    Visualize the given binary search tree using the graphviz library.

    Args:
        node (Node): The root node of the binary search tree.
    """
            add_nodes(node.left_child)
        if node.right_child:
            dot.node(str(node.right_child.data))
            dot.edge(str(node.data), str(node.right_child.data))
            add_nodes(node.right_child)

    dot.node(str(node.data))
    add_nodes(node)

    return dot

visualize_tree(root)
```

Line numbers are not provided in this code because the suggested changes apply to the entire code.

Anda dapat mengembangkan contoh sederhana diatas menjadi lebih intuitif, misalnya bisa memberikan pilihan replace code menggunakan code yang disarankan oleh model.

Sharing is caring: