Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions code_review_app/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Anthropic API Key for AI-powered checklist generation
# Get your API key from: https://console.anthropic.com/
ANTHROPIC_API_KEY=your_api_key_here

# Flask Secret Key (change in production)
SECRET_KEY=your-secret-key-here
29 changes: 29 additions & 0 deletions code_review_app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
venv/
env/
ENV/

# Environment variables
.env

# Data files
checklists.json

# Flask
instance/
.webassets-cache

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# OS
.DS_Store
Thumbs.db
195 changes: 195 additions & 0 deletions code_review_app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
# Code Review Checklist Application

A web-based tool for agile teams to streamline code reviews. Reviewers can enter detailed feedback in natural language, and AI automatically generates structured, actionable checklists for developers.

## Features

### For Reviewers
- Enter code review feedback in natural, long-form text
- AI-powered analysis extracts key action items
- Automatic categorization (security, performance, code quality, testing, documentation, functionality)
- Priority assignment (high, medium, low)

### For Developers
- View all code review checklists in one place
- Track progress with interactive checkboxes
- See original reviewer comments
- Filter by priority and category
- Progress tracking for each checklist

## Technology Stack

- **Backend**: Flask (Python web framework)
- **AI**: Anthropic Claude API
- **Storage**: JSON file-based (easily replaceable with database)
- **Frontend**: HTML, CSS, JavaScript (no framework dependencies)

## Installation

### Prerequisites
- Python 3.10 or higher
- Anthropic API key (get one at https://console.anthropic.com/)

### Setup Steps

1. Navigate to the application directory:
```bash
cd code_review_app
```

2. Create a virtual environment:
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```

3. Install dependencies:
```bash
pip install -r requirements.txt
```

4. Configure environment variables:
```bash
cp .env.example .env
```

Edit `.env` and add your Anthropic API key:
```
ANTHROPIC_API_KEY=your_actual_api_key_here
SECRET_KEY=your-random-secret-key-here
```

5. Run the application:
```bash
python app.py
```

6. Open your browser and navigate to:
```
http://localhost:5000
```

## Usage Guide

### Creating a Checklist (Reviewer)

1. Go to the **Reviewer** page
2. Enter the project name
3. Enter your name as the reviewer
4. Write detailed review feedback in natural language, for example:

```
The authentication module implementation needs attention:

- Password validation is too weak, needs special character requirements
- SQL queries are not parameterized, potential SQL injection risk
- Missing unit tests for the login flow
- Error messages expose too much system information
- Performance issue with N+1 queries in user profile loading
- API documentation is outdated
```

5. Click "Generate Checklist"
6. AI will process your feedback and create a structured checklist

### Viewing and Tracking Checklists (Developer)

1. Go to the **Developer** page
2. View all checklists organized by project
3. Click on "View Original Review" to see reviewer's full comments
4. Check off items as you complete them
5. Track your progress with the progress bar
6. Delete checklists when done

## AI Integration

The application uses Anthropic's Claude AI to:
- Analyze reviewer feedback
- Extract actionable items
- Assign priorities based on context
- Categorize items by type (security, performance, etc.)

### Fallback Mode
If no API key is provided, the application will use a simple text parsing fallback that creates basic checklist items from the review text.

## Data Storage

Checklists are stored in `checklists.json` in the application directory. The format is:

```json
[
{
"id": "20231215120000",
"project_name": "User Authentication",
"reviewer_name": "Jane Doe",
"review_text": "Original review comments...",
"items": [
{
"item": "Add input validation for user data",
"priority": "high",
"category": "security"
}
],
"created_at": "2023-12-15T12:00:00",
"completed_items": [0]
}
]
```

## Configuration

### Environment Variables

- `ANTHROPIC_API_KEY`: Your Anthropic API key for AI features
- `SECRET_KEY`: Flask secret key for session management

### Customization

You can customize:
- **AI model**: Change the model in `app.py` (currently using `claude-3-5-sonnet-20241022`)
- **Categories**: Modify categories in the AI prompt
- **Priorities**: Adjust priority levels
- **Styling**: Edit CSS in `templates/base.html`

## Production Deployment

For production use:

1. Use a proper database (PostgreSQL, MySQL) instead of JSON
2. Set strong `SECRET_KEY` in environment variables
3. Disable Flask debug mode
4. Use a production WSGI server (gunicorn, uWSGI)
5. Add authentication and authorization
6. Enable HTTPS
7. Add rate limiting for API endpoints
8. Implement proper error logging

Example with gunicorn:
```bash
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 app:app
```

## Troubleshooting

### AI not generating checklists
- Check that your `ANTHROPIC_API_KEY` is set correctly in `.env`
- Verify your API key has sufficient credits
- Check the console for error messages

### Can't access the application
- Ensure port 5000 is not in use
- Try accessing via `http://127.0.0.1:5000` instead of `localhost`
- Check firewall settings

### Checklist items not saving
- Ensure the application has write permissions in its directory
- Check that `checklists.json` is not corrupted

## License

This application is part of the Practice It: Python Data Structures course materials.

## Support

For issues or questions, please refer to the main course repository.
161 changes: 161 additions & 0 deletions code_review_app/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import os
import json
from datetime import datetime
from flask import Flask, render_template, request, jsonify, redirect, url_for
from anthropic import Anthropic
from dotenv import load_dotenv

load_dotenv()

app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'dev-secret-key-change-in-production')

# Data storage file
DATA_FILE = 'checklists.json'

def load_checklists():
"""Load checklists from JSON file"""
if os.path.exists(DATA_FILE):
with open(DATA_FILE, 'r') as f:
return json.load(f)
return []

def save_checklists(checklists):
"""Save checklists to JSON file"""
with open(DATA_FILE, 'w') as f:
json.dump(checklists, f, indent=2)

def generate_checklist_with_ai(review_text):
"""Use Anthropic Claude to generate checklist from review text"""
api_key = os.environ.get('ANTHROPIC_API_KEY')

if not api_key:
# Fallback: simple keyword extraction if no API key
return generate_simple_checklist(review_text)

try:
client = Anthropic(api_key=api_key)

message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{
"role": "user",
"content": f"""You are a code review assistant. A reviewer has provided the following feedback about code implementation in an agile project:

{review_text}

Please analyze this feedback and create a concise, actionable checklist for the developer. Format your response as a JSON array of checklist items, where each item has:
- "item": brief description of what to check/fix
- "priority": one of "high", "medium", or "low"
- "category": one of "security", "performance", "code_quality", "testing", "documentation", or "functionality"

Return ONLY the JSON array, no additional text.

Example format:
[
{{"item": "Add input validation for user data", "priority": "high", "category": "security"}},
{{"item": "Optimize database queries in user service", "priority": "medium", "category": "performance"}}
]"""
}]
)

# Extract the JSON from the response
response_text = message.content[0].text.strip()
checklist_items = json.loads(response_text)
return checklist_items

except Exception as e:
print(f"AI generation error: {e}")
return generate_simple_checklist(review_text)

def generate_simple_checklist(review_text):
"""Fallback: Generate simple checklist without AI"""
lines = [line.strip() for line in review_text.split('\n') if line.strip()]
return [
{
"item": line[:100],
"priority": "medium",
"category": "code_quality"
}
for line in lines[:10] # Limit to 10 items
]

@app.route('/')
def index():
"""Home page with navigation"""
return render_template('index.html')

@app.route('/reviewer')
def reviewer():
"""Reviewer page to enter review perspectives"""
return render_template('reviewer.html')

@app.route('/developer')
def developer():
"""Developer page to view checklists"""
checklists = load_checklists()
return render_template('developer.html', checklists=checklists)

@app.route('/api/create-checklist', methods=['POST'])
def create_checklist():
"""API endpoint to create a new checklist"""
data = request.get_json()
review_text = data.get('review_text', '')
reviewer_name = data.get('reviewer_name', 'Anonymous')
project_name = data.get('project_name', 'Unnamed Project')

if not review_text:
return jsonify({'error': 'Review text is required'}), 400

# Generate checklist using AI
checklist_items = generate_checklist_with_ai(review_text)

# Create checklist object
checklist = {
'id': datetime.now().strftime('%Y%m%d%H%M%S'),
'project_name': project_name,
'reviewer_name': reviewer_name,
'review_text': review_text,
'items': checklist_items,
'created_at': datetime.now().isoformat(),
'completed_items': []
}

# Save to storage
checklists = load_checklists()
checklists.append(checklist)
save_checklists(checklists)

return jsonify({'success': True, 'checklist_id': checklist['id']})

@app.route('/api/toggle-item', methods=['POST'])
def toggle_item():
"""API endpoint to toggle checklist item completion"""
data = request.get_json()
checklist_id = data.get('checklist_id')
item_index = data.get('item_index')

checklists = load_checklists()

for checklist in checklists:
if checklist['id'] == checklist_id:
if item_index in checklist['completed_items']:
checklist['completed_items'].remove(item_index)
else:
checklist['completed_items'].append(item_index)
save_checklists(checklists)
return jsonify({'success': True})

return jsonify({'error': 'Checklist not found'}), 404

@app.route('/api/delete-checklist/<checklist_id>', methods=['DELETE'])
def delete_checklist(checklist_id):
"""API endpoint to delete a checklist"""
checklists = load_checklists()
checklists = [c for c in checklists if c['id'] != checklist_id]
save_checklists(checklists)
return jsonify({'success': True})

if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
3 changes: 3 additions & 0 deletions code_review_app/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
flask==3.0.0
anthropic==0.18.1
python-dotenv==1.0.0
Loading