diff --git a/code_review_app/.env.example b/code_review_app/.env.example new file mode 100644 index 0000000..82b8e08 --- /dev/null +++ b/code_review_app/.env.example @@ -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 diff --git a/code_review_app/.gitignore b/code_review_app/.gitignore new file mode 100644 index 0000000..9e8a084 --- /dev/null +++ b/code_review_app/.gitignore @@ -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 diff --git a/code_review_app/README.md b/code_review_app/README.md new file mode 100644 index 0000000..0d24ae2 --- /dev/null +++ b/code_review_app/README.md @@ -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. diff --git a/code_review_app/app.py b/code_review_app/app.py new file mode 100644 index 0000000..62f8938 --- /dev/null +++ b/code_review_app/app.py @@ -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/', 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) diff --git a/code_review_app/requirements.txt b/code_review_app/requirements.txt new file mode 100644 index 0000000..22ca507 --- /dev/null +++ b/code_review_app/requirements.txt @@ -0,0 +1,3 @@ +flask==3.0.0 +anthropic==0.18.1 +python-dotenv==1.0.0 diff --git a/code_review_app/templates/base.html b/code_review_app/templates/base.html new file mode 100644 index 0000000..f53481f --- /dev/null +++ b/code_review_app/templates/base.html @@ -0,0 +1,129 @@ + + + + + + {% block title %}Code Review Checklist{% endblock %} + + + +
+
+

Code Review Checklist

+

Agile Project Code Review Assistant

+ +
+
+ {% block content %}{% endblock %} +
+
+ + diff --git a/code_review_app/templates/developer.html b/code_review_app/templates/developer.html new file mode 100644 index 0000000..e0867c6 --- /dev/null +++ b/code_review_app/templates/developer.html @@ -0,0 +1,130 @@ +{% extends "base.html" %} + +{% block title %}Developer - Code Review Checklist{% endblock %} + +{% block content %} +

Your Code Review Checklists

+ +{% if checklists %} +
+ {% for checklist in checklists|reverse %} +
+
+
+

{{ checklist.project_name }}

+

+ Reviewed by: {{ checklist.reviewer_name }}
+ Created: {{ checklist.created_at[:10] }} {{ checklist.created_at[11:19] }} +

+
+ +
+ +
+ + View Original Review + +
{{ checklist.review_text }}
+
+ +
+

Checklist Items:

+
+ {% for item in checklist.items %} + + {% endfor %} +
+
+ +
+ Progress: + + {{ checklist.completed_items|length }} / {{ checklist.items|length }} + + items completed +
+
+ {% endfor %} +
+{% else %} +
+

+ No checklists yet. Ask a reviewer to create one! +

+ + Create Your First Checklist + +
+{% endif %} + + +{% endblock %} diff --git a/code_review_app/templates/index.html b/code_review_app/templates/index.html new file mode 100644 index 0000000..956eae6 --- /dev/null +++ b/code_review_app/templates/index.html @@ -0,0 +1,41 @@ +{% extends "base.html" %} + +{% block title %}Home - Code Review Checklist{% endblock %} + +{% block content %} +

Welcome to Code Review Checklist

+ +
+
+

For Reviewers

+

+ Enter your code review feedback in natural language. Our AI will analyze your perspectives + and automatically generate an actionable checklist for developers. +

+ + Start Review + +
+ +
+

For Developers

+

+ View and track your code review checklists. Mark items as complete as you address + each review point and improve your code quality. +

+ + View Checklists + +
+
+ +
+

How It Works

+
    +
  1. Reviewer: Enter detailed code review feedback in natural text format
  2. +
  3. AI Processing: Our AI analyzes the feedback and extracts key action items
  4. +
  5. Checklist Generation: A structured checklist is created with priorities and categories
  6. +
  7. Developer Action: Developers view and track completion of each checklist item
  8. +
+
+{% endblock %} diff --git a/code_review_app/templates/reviewer.html b/code_review_app/templates/reviewer.html new file mode 100644 index 0000000..502306c --- /dev/null +++ b/code_review_app/templates/reviewer.html @@ -0,0 +1,121 @@ +{% extends "base.html" %} + +{% block title %}Reviewer - Code Review Checklist{% endblock %} + +{% block content %} +

Create Code Review Checklist

+ +
+ +
+
+ + +
+ +
+ + +
+ +
+ + + + Write your review in natural language. Our AI will extract and organize the key points. + +
+ + +
+ + +{% endblock %}