Skip to content

Commit 83c3434

Browse files
Merge pull request #2548 from andoriyaprashant/branch20
AI Code Reviewer Script Added
2 parents dd37743 + 22f585e commit 83c3434

File tree

3 files changed

+106
-0
lines changed

3 files changed

+106
-0
lines changed

AI Code Reviewer/README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# AI Code Reviewer
2+
3+
The AI Code Reviewer is a Python script that analyzes and provides feedback on programming code. It utilizes a combination of rule-based checks and code style analysis to detect common coding errors, suggest improvements, and evaluate the overall code quality. Additionally, it performs comment analysis to identify areas where code comments may need improvement.
4+
5+
## Features
6+
7+
- Indentation Error Detection: The code reviewer checks for indentation errors in loops, conditionals, and functions.
8+
- Undefined Variable Detection: It identifies variables that are used but not defined within the code.
9+
- Code Style Checking: The script uses the `pycodestyle` library to check for code style violations and provides feedback on code formatting.
10+
- Comment Analysis: The script examines code comments and suggests improvements for better readability and clarity.
11+
12+
## Prerequisites
13+
14+
Before running the script, make sure you have Python installed on your system. Also, ensure you have the `pycodestyle` library installed by running the following command:
15+
16+
```bash
17+
pip install pycodestyle
18+
```
19+
20+
## Usage
21+
- Clone the repository or download the "ai_code_reviewer.py" script.
22+
- Run the script, and it will analyze the Python code provided within the script.
23+
- The AI Code Reviewer will output feedback on any coding errors, style issues, or comment suggestions.

AI Code Reviewer/ai_code_reviewer.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import ast
2+
import pycodestyle
3+
4+
class CodeReviewer:
5+
def __init__(self):
6+
self.feedback = []
7+
8+
def analyze_python_code(self, code):
9+
try:
10+
# Parse the Python code into an Abstract Syntax Tree (AST)
11+
tree = ast.parse(code)
12+
except SyntaxError as e:
13+
self.feedback.append(f"Syntax Error: {e}")
14+
return
15+
16+
# Check for indentation errors and undefined variables
17+
self._check_indentation(tree)
18+
self._check_undefined_vars(tree)
19+
20+
# Check code style using pycodestyle
21+
self._check_code_style(code)
22+
23+
# Check code comments
24+
self._check_comments(code)
25+
26+
def _check_indentation(self, tree):
27+
for node in ast.walk(tree):
28+
if isinstance(node, ast.FunctionDef):
29+
if node.body and not isinstance(node.body[0], ast.Expr):
30+
self.feedback.append(f"Function '{node.name}' should have a docstring or 'pass' statement.")
31+
elif isinstance(node, (ast.For, ast.While, ast.If, ast.With)):
32+
if not isinstance(node.body[0], ast.Expr):
33+
self.feedback.append(f"Indentation Error: Missing 'pass' statement for '{ast.dump(node)}'.")
34+
35+
def _check_undefined_vars(self, tree):
36+
undefined_vars = set()
37+
for node in ast.walk(tree):
38+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
39+
undefined_vars.discard(node.id)
40+
elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
41+
undefined_vars.add(node.id)
42+
43+
for var in undefined_vars:
44+
self.feedback.append(f"Variable '{var}' is used but not defined.")
45+
46+
def _check_code_style(self, code):
47+
style_guide = pycodestyle.StyleGuide()
48+
result = style_guide.check_code(code)
49+
if result.total_errors:
50+
self.feedback.append("Code style issues found. Please check and fix them.")
51+
52+
def _check_comments(self, code):
53+
lines = code.split('\n')
54+
for i, line in enumerate(lines):
55+
if line.strip().startswith('#'):
56+
# Check for empty comments or comments without space after '#'
57+
if len(line.strip()) == 1 or line.strip()[1] != ' ':
58+
self.feedback.append(f"Improve comment style in line {i + 1}: '{line.strip()}'")
59+
60+
def get_feedback(self):
61+
return self.feedback
62+
63+
if __name__ == "__main__":
64+
# Example Python code to analyze
65+
python_code = """
66+
def add(a, b):
67+
result = a + b
68+
print(result)
69+
"""
70+
71+
code_reviewer = CodeReviewer()
72+
code_reviewer.analyze_python_code(python_code)
73+
74+
feedback = code_reviewer.get_feedback()
75+
76+
if feedback:
77+
print("Code Review Feedback:")
78+
for msg in feedback:
79+
print(f"- {msg}")
80+
else:
81+
print("No coding errors found. Code looks good!")

AI Code Reviewer/requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
ast
2+
pycodestyle

0 commit comments

Comments
 (0)