diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..b6b70ae --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,10 @@ +# What issue did you fix? + +Fixes: # + +## Quick description of your approach: + +### Checklist before requesting a review: +- [ ] Remove all uneccessary debug print statements +- [ ] Make sure all tests pass +- [ ] Make sure there are enough comments to understand your code \ No newline at end of file diff --git a/.github/workflows/accuracy_up_or_down_test.yml b/.github/workflows/accuracy_up_or_down_test.yml new file mode 100644 index 0000000..9397cf7 --- /dev/null +++ b/.github/workflows/accuracy_up_or_down_test.yml @@ -0,0 +1,27 @@ +name: Test Accuracy Check + +on: + pull_request: + branches: [ main ] + +jobs: + test_accuracy: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v3 + with: + fetch-depth: 0 # Fetch all history for all branches and tags + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.x' + + - name: Install dependencies + run: | + pip install -r requirements.txt + + - name: Run Accuracy Test + run: python test_accuracy_up_or_down.py diff --git a/.github/workflows/get_function_data_test.yml b/.github/workflows/get_function_data_test.yml new file mode 100644 index 0000000..d509314 --- /dev/null +++ b/.github/workflows/get_function_data_test.yml @@ -0,0 +1,46 @@ +name: Python Test Workflow + +on: + pull_request: + branches: [ main ] + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + with: + path: 'functionRetriever' # Specify a path for the main repo + + - name: Clone testRepo repository + run: | + mkdir -p ${{ github.workspace }}/inputData # Create inputData directory + git clone https://github.com/RapidReview-ai/testRepo ${{ github.workspace }}/inputData/testRepo + + - name: Create outputData directory + run: mkdir -p ${{ github.workspace }}/functionRetriever/dataForTesting + + - name: Set up Python 3.x + uses: actions/setup-python@v2 + with: + python-version: '3.11.1' + + - name: Set up Node.js + uses: actions/setup-node@v2 + with: + node-version: '18.12.1' + + - name: Install npm dependencies + run: npm install + working-directory: ${{ github.workspace }}/functionRetriever + + - name: Install Python dependencies + run: | + pip install --upgrade pip + pip install -r requirements.txt + working-directory: ${{ github.workspace }}/functionRetriever + + - name: Run tests + run: python test_get_function_data.py + working-directory: ${{ github.workspace }}/functionRetriever diff --git a/.gitignore b/.gitignore index 921a029..e9be986 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,10 @@ .env -function_changes.json \ No newline at end of file +test_function_changes.json +package-lock.json +path +.DS_Store +**/__pycache__ +node_modules +temp.js +testing.json +dataForTesting/ \ No newline at end of file diff --git a/Embeddings/createEmbeddings.py b/Embeddings/createEmbeddings.py deleted file mode 100644 index 2205532..0000000 --- a/Embeddings/createEmbeddings.py +++ /dev/null @@ -1,41 +0,0 @@ -import openai -import requests -import json -import os -import dotenv - -# Set the OpenAI API key using the environment variable -dotenv.load_dotenv() -openai.api_key = os.getenv("OPENAI_API_KEY") - -# Load the JSON data from the file -json_file_path = '../outputData/function_changes.json' -with open(json_file_path, 'r') as file: - json_data = json.load(file) - -# Specify the embedding model -model = "text-embedding-ada-002" - -# Process each function in the JSON data -for function_name, function_data in json_data.items(): - input_text = function_data['first_version'] - - # Create the data for the POST request - data = { - "input": input_text, - "model": model - } - - # Make the API request - response = requests.post( - 'https://api.openai.com/v1/embeddings', - headers={ - 'Content-Type': 'application/json', - 'Authorization': f'Bearer {openai.api_key}' - }, - data=json.dumps(data) - ) - - # Extract and print the embedding from the response - embedding = response.json()['data'][0]['embedding'] - print(f"Embedding for {function_name}:", embedding) diff --git a/README.md b/README.md index 12c528b..3a5e35f 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,39 @@ -# Problems I had: -- oututdata did not exist, I had to manually create the folder and the file function_changes.json -- inputdata had not been cloned: - - inputdata needs to be cloned from our test repository on github into specifically the folder inputdata - - \ No newline at end of file +# What is CodeReviewer? +CodeReviewer is a tool that uses machine learning to help developers reviewing code. It is trained on a dataset of code from the [hlxsites](https://github.com/hlxsites) repositories and is able to predict how likely a given function is going to break in the future. + +## Current Accuracy: 73.19% + +## How does it work? +We save each functions first version(When it was first merged) and how often it was changed in the future. We then use this data to create embeddings for each function. We then use these embeddings to create a database using Qdrant. +When a user uploads a function, we use the embeddings to find the 5 most similar functions in the database. We then use the number of times these functions were changed to predict how likely the user's function is to break in the future. + +--- + +# Quickstart Guide +## Installation +- run `pip install -r requirements.txt` to install all dependencies all Python dependencies +- run `npm install` to install all Node dependencies +- Install [Docker](https://www.docker.com/get-started/) +- Install [Qdrant](https://qdrant.tech/documentation/quick-start/): + + - run this command to pull the latest docker image: `docker pull qdrant/qdrant` + - run this command to start the docker container: + - ```Bash + docker run -p 6333:6333 -p 6334:6334 \ + -v $(pwd)/qdrant_storage:/qdrant/storage:z \ + qdrant/qdrant + ``` +## Setup +- create a 'outputData' folder in the root of the directory +- create a .env file in the root of the directory containing the following variable: + - OPENAI_API_KEY +- create a folder called 'inputData' outside of the root directory. It should be accessible with this path: `../inputData`. +- clone this [repository](https://github.com/RapidReview-ai/testRepo) into the 'inputData' folder. + +## Running the app +- Enter the functions you want to test on in the testing.json file. And run evaluate_performance.py to see how well the model performs. +- Inside of main.py you can pass the repo_path variable to the get_function_data function to change the training data. +- run `python main.py` to run the whole app including, getting the data from the git repo, generating embeddings, creating the database, and running the query. + - If you only want to run one of these steps, run the corresponding file on their own. +- You can run the tests by running `pyththon test_getFuntionData.py` + diff --git a/babelParser.js b/babelParser.js new file mode 100644 index 0000000..d1f9121 --- /dev/null +++ b/babelParser.js @@ -0,0 +1,24 @@ +const babel = require('@babel/parser'); + +process.stdin.setEncoding('utf8'); + +let code = ''; + +process.stdin.on('readable', () => { + let chunk; + while ((chunk = process.stdin.read()) !== null) { + code += chunk; + } +}); + +process.stdin.on('end', () => { + try { + const ast = babel.parse(code, { + sourceType: "module", + plugins: [], + }); + console.log(JSON.stringify(ast)); + } catch (error) { + console.error("Parsing error:", error); + } +}); diff --git a/dataAnalysis/analyseDistribution.py b/dataAnalysis/analyseDistribution.py new file mode 100644 index 0000000..5fac8d2 --- /dev/null +++ b/dataAnalysis/analyseDistribution.py @@ -0,0 +1,55 @@ +import json +import numpy as np +from collections import Counter + +def log_normalize_change_counts(repos): + # Apply logarithmic normalization + all_changes = [func['changes_after_merge'] + 1 for repo in repos.values() for func in repo.values()] + log_changes = np.log(all_changes) + min_log, max_log = min(log_changes), max(log_changes) + + for repo_name, functions in repos.items(): + for func_key, func_info in functions.items(): + adjusted_change = np.log(func_info['changes_after_merge'] + 1) + normalized_score = 2 * ((adjusted_change - min_log) / (max_log - min_log)) - 1 + func_info['score'] = normalized_score + return repos + +def analyze_changes_distribution(file_path): + with open(file_path, 'r') as f: + data = json.load(f) + + normalized_data = log_normalize_change_counts(data) + + # Original changes + original_changes = [func['changes_after_merge'] for repo in data.values() for func in repo.values()] + # Normalized scores + normalized_scores = [func['score'] for repo in normalized_data.values() for func in repo.values()] + + # Statistics for original changes + min_changes, max_changes = min(original_changes), max(original_changes) + mean_changes, median_changes = np.mean(original_changes), np.median(original_changes) + changes_counter = Counter(original_changes) + + # Statistics for normalized scores + min_score, max_score = min(normalized_scores), max(normalized_scores) + mean_score, median_score = np.mean(normalized_scores), np.median(normalized_scores) + score_counter = Counter(normalized_scores) + + # Print statistics + print(f"File: {file_path}") + print("Original 'changes_after_merge' statistics:") + print(f" Min: {min_changes}, Max: {max_changes}, Mean: {mean_changes:.2f}, Median: {median_changes}") + print(" Distribution of changes:") + for change, freq in changes_counter.items(): + print(f" Changes: {change}, Frequency: {freq}") + + print("\nNormalized score statistics:") + print(f" Min: {min_score:.2f}, Max: {max_score:.2f}, Mean: {mean_score:.2f}, Median: {median_score:.2f}") + print(" Distribution of scores:") + for score, freq in score_counter.items(): + print(f" Score: {score:.2f}, Frequency: {freq}") + +if __name__ == '__main__': + analyze_changes_distribution('../dataForTesting/training.json') + analyze_changes_distribution('../dataForTesting/testing.json') diff --git a/embed_training_data.py b/embed_training_data.py new file mode 100644 index 0000000..f483529 --- /dev/null +++ b/embed_training_data.py @@ -0,0 +1,81 @@ +import openai +import requests +import json +import os +import random +import time +import dotenv +from qdrant_client import QdrantClient +from qdrant_client.models import CollectionDescription, Distance, VectorParams, Record + +def embed_repos_functions(json_data): + client = QdrantClient(host='localhost', port=6333) + dotenv.load_dotenv() + openai.api_key = os.getenv("OPENAI_API_KEY") + model = "text-embedding-ada-002" + + if not client.get_collections().collections.__contains__(CollectionDescription(name='functions')): + client.create_collection( + collection_name="functions", + vectors_config=VectorParams( + size=1536, + distance=Distance.COSINE + ) + ) + + for repo_name, functions in json_data.items(): + for function_key, function_data in functions.items(): + merged_function = function_data['merged_function'] + + print(f"Processing function '{function_key}' from repo '{repo_name}'") + + attempt = 0 + max_attempts = 5 + while attempt < max_attempts: + try: + response = requests.post( + 'https://api.openai.com/v1/embeddings', + headers={ + 'Content-Type': 'application/json', + 'Authorization': f'Bearer {openai.api_key}' + }, + data=json.dumps({ + "input": merged_function, + "model": model + }), + timeout=30 # Timeout for the request + ) + + if response.status_code != 200: + raise Exception(f"Failed to embed: Status {response.status_code}, Response: {response.text}") + + embedding = response.json()['data'][0]['embedding'] + id = random.randint(0, 1000000) + payload = { + "function_key": function_key, + "score": function_data.get('score', 0), + } + + print(f"Uploading function '{function_key}' to Qdrant") + + client.upload_records( + collection_name="functions", + records=[ + Record( + id=id, + vector=embedding, + payload=payload + ) + ] + ) + print(f"Added function '{function_key}' from repo '{repo_name}' to Qdrant with ID {id}") + break + + except Exception as e: + print(f"Exception occurred for '{function_key}' from '{repo_name}': {str(e)}. Retrying in 30 seconds...") + time.sleep(30) + attempt += 1 + + if attempt == max_attempts: + print(f"Failed to process '{function_key}' from '{repo_name}' after {max_attempts} attempts.") + diff --git a/evaluate_performance.py b/evaluate_performance.py new file mode 100644 index 0000000..7d1f117 --- /dev/null +++ b/evaluate_performance.py @@ -0,0 +1,49 @@ +import json +from userInput.process_user_input import process_user_input + +def evaluate_model_accuracy(test_data_path, merge_threshold=-0.6): + with open(test_data_path, 'r') as file: + test_data = json.load(file) + + correct_predictions = 0 + baseline_correct_predictions = 0 + total_predictions = 0 + + for repo, functions in test_data.items(): + for function_key, function_data in functions.items(): + merged_function = function_data['merged_function'] + actual_decision = "🎉 Merge the function 🎉" if function_data['score'] <= merge_threshold else "🙅 Do not merge the function 🙅" + predicted_decision = process_user_input(merged_function) + + # Update correct predictions for the model + if predicted_decision == actual_decision: + correct_predictions += 1 + + # Update correct predictions for the baseline (always predict "🎉 Merge the function 🎉") + if actual_decision == "🎉 Merge the function 🎉": + baseline_correct_predictions += 1 + + total_predictions += 1 + print(f"Actual: {actual_decision}, Predicted: {predicted_decision}") + + # Calculate accuracies + accuracy = correct_predictions / total_predictions if total_predictions > 0 else 0 + baseline_accuracy = baseline_correct_predictions / total_predictions if total_predictions > 0 else 0 + + return accuracy, baseline_accuracy + +def update_readme_with_accuracy(accuracy): + with open('README.md', 'r') as file: + lines = file.readlines() + + for i, line in enumerate(lines): + if '## Current Accuracy:' in line: + lines[i] = f'## Current Accuracy: {accuracy:.2f}%\n' + + with open('README.md', 'w') as file: + file.writelines(lines) + +if __name__ == '__main__': + accuracy = evaluate_model_accuracy('./dataForTesting/testing.json') + print(f"Current Accuracy: {accuracy * 100:.2f}%") + update_readme_with_accuracy(accuracy * 100) \ No newline at end of file diff --git a/function_data.py b/function_data.py new file mode 100644 index 0000000..496ad4d --- /dev/null +++ b/function_data.py @@ -0,0 +1,209 @@ +import os +import git +import json +import time +import subprocess + +def get_function_data(repo_path='../inputData/testRepo', output_path='./dataForTesting/test_function_changes.json'): + script_dir = os.path.dirname(os.path.abspath(__file__)) + repo_path = os.path.join(script_dir, repo_path) + repo_name = os.path.basename(repo_path) # Extract the repository name + repo = git.Repo(repo_path) + + repo.git.checkout('main') + repo.git.pull() + + merge_commits = [commit for commit in repo.iter_commits('main') if commit.parents and len(commit.parents) > 1] + merge_commits.reverse() + + ast_cache = {} + + def get_ast_from_js(file_content): + # Generate a hash of the file content + content_hash = hash(file_content) + + # Check if the AST is already in the cache + if content_hash in ast_cache: + return ast_cache[content_hash] + + process = subprocess.Popen(['node', 'babelParser.js'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + stdout, stderr = process.communicate(input=file_content) + if stderr: + print("Error in parsing:", stderr) + return None + + # Parse the output and store the AST in the cache + ast = json.loads(stdout) + ast_cache[content_hash] = ast + return ast + + def get_functions_from_file(file_content): + # create ast from file content + ast = get_ast_from_js(file_content) + + functions = [] + try: + # Traverse the AST to find function declarations + def traverse(node): + if not isinstance(node, dict): + return + + if 'type' in node: + # Check for arrow functions or function expressions assigned to variables + if node['type'] in ['VariableDeclarator'] and 'init' in node: + init_node = node['init'] + if init_node and 'type' in init_node and init_node['type'] in ['FunctionExpression', 'ArrowFunctionExpression']: + function_name = None + if 'name' in node['id']: + function_name = node['id']['name'] + if function_name: + functions.append(function_name) + + # Existing checks for FunctionDeclaration, etc. + elif node['type'] in ['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']: + function_name = None + if 'id' in node and node['id'] is not None: + function_name = node['id']['name'] + elif 'key' in node and 'name' in node['key']: + function_name = node['key']['name'] + if function_name: + functions.append(function_name) + + # Check for methods in classes + if node['type'] == 'MethodDefinition' and 'key' in node and node['key']['type'] == 'Identifier': + functions.append(node['key']['name']) + + # Recursively traverse child nodes + for key, value in node.items(): + if isinstance(value, dict): + traverse(value) + elif isinstance(value, list): + for item in value: + if isinstance(item, dict): + traverse(item) + + traverse(ast['program']) + except Exception as e: + print(f"Error processing AST: {e}") + return functions + + def get_full_function_at_commit(repo, commit_hash, function_name, file_path): + commit = repo.commit(commit_hash) + blob = commit.tree / file_path + file_content = blob.data_stream.read().decode('utf-8') + + # create ast from file content + ast = get_ast_from_js(file_content) + + try: + # Define a function to recursively search for the function + def find_function(node, function_name): + if not isinstance(node, dict): + return None + + # Handle different types of function nodes + if node.get('type') == 'FunctionDeclaration' and node.get('id', {}).get('name') == function_name: + return node.get('start'), node.get('end') + + if node.get('type') == 'VariableDeclarator': + init_node = node.get('init') + if isinstance(init_node, dict) and init_node.get('type') in ['FunctionExpression', 'ArrowFunctionExpression']: + if node.get('id', {}).get('name') == function_name: + return node.get('start'), node.get('end') + + # Recursive traversal + for key, value in node.items(): + if isinstance(value, dict): + result = find_function(value, function_name) + if result: + return result + elif isinstance(value, list): + for item in value: + result = find_function(item, function_name) + if result: + return result + return None + + # Search for the function in the AST + start_end = find_function(ast['program'], function_name) # Pass function_name here + if start_end: + start, end = start_end + return file_content[start:end] + except Exception as e: + print(f"Error processing AST: {e}") + + return None + + functions = {} + + for commit in merge_commits: + print(f"Processing merge commit {commit.hexsha}") + for file_path in commit.stats.files: + if file_path.endswith('.js'): + try: + blob = commit.tree / file_path + file_content = blob.data_stream.read().decode('utf-8') + for func_name in get_functions_from_file(file_content): + full_function = get_full_function_at_commit(repo, commit.hexsha, func_name, file_path) + if full_function: + func_key = f"{file_path}::{func_name}" + if func_key not in functions: + functions[func_key] = { + 'function_name': func_name, + 'merged_function': full_function, + 'commit': commit.hexsha, + 'changes_after_merge': 0, + 'latest_function': full_function, + 'time_first_merged': commit.authored_datetime, + 'file_path': file_path + } + except Exception as e: + print(f"Error processing commit {commit.hexsha}: {e}") + continue + + for commit in repo.iter_commits('main', reverse=True): # Iterate from the oldest to newest commit + print(f"Processing commit {commit.hexsha}") + for file_path in commit.stats.files: + if file_path.endswith('.js'): + try: + blob = commit.tree / file_path + file_content = blob.data_stream.read().decode('utf-8') + current_functions = get_functions_from_file(file_content) + + for func_key, func_info in functions.items(): + if func_info['file_path'] == file_path: + if func_info['function_name'] in current_functions: + new_content = get_full_function_at_commit(repo, commit.hexsha, func_info['function_name'], file_path) + if new_content and new_content.strip() != func_info['latest_function'].strip() and commit.authored_datetime > func_info['time_first_merged']: + func_info['changes_after_merge'] += 1 + func_info['latest_function'] = new_content + except Exception as e: + print(f"Error processing commit {commit.hexsha}: {e}") + continue + + + # Convert datetime objects to string before saving + for func in functions.values(): + func['time_first_merged'] = func['time_first_merged'].isoformat() + + # Filtered data structured by repository + repo_data = {repo_name: {}} + for func_key, func_info in functions.items(): + repo_data[repo_name][func_key] = { + 'changes_after_merge': func_info['changes_after_merge'], + 'file_path': func_info['file_path'], + 'function_name': func_info['function_name'], + 'merged_function': func_info['merged_function'], + } + + # Save to the specified output path + with open(output_path, 'w') as f: + json.dump(repo_data, f, indent=4) + +if __name__ == '__main__': + start_time = time.time() + get_function_data() #pass this variable if you want to run another repo than testRepo: repo_path='../inputData/elixirsolutions' + end_time = time.time() + elapsed_time = round((end_time - start_time) / 60, 2) # convert to minutes and round to 2 decimal places + print('✅ Printed function data to outputData/test_function_changes.json ✅') + print(f'⏰ The program took {elapsed_time} minutes to run. ⏰') \ No newline at end of file diff --git a/inputData/testRepository b/inputData/testRepository deleted file mode 160000 index 7d17121..0000000 --- a/inputData/testRepository +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 7d17121ac61f5cefb5f9dd6357db3e895d71e57c diff --git a/inputData/walgreens b/inputData/walgreens deleted file mode 160000 index d6bbd33..0000000 --- a/inputData/walgreens +++ /dev/null @@ -1 +0,0 @@ -Subproject commit d6bbd33083c9bd672639b1f20f4f8d0ff4943bc6 diff --git a/main.py b/main.py index be0673f..da53d67 100644 --- a/main.py +++ b/main.py @@ -1,116 +1,61 @@ -""" -How to improve this Code: -1. Account for functions that are renamed -2. Account for functions with the same name but different bodies -3. Filter comment and whitespace changes -4. Start increasing the number of commits only after the first merge commit -5. Use a more sophisticated hashing algorithm -6. Use a more sophisticated regular expression to match function declarations and bodies -7. Add more tests -8. Write the full function along with the commit into a json file -""" -import subprocess -import re +import time import json -from hashlib import sha256 - -def get_js_commits(repo_path): - command = ["git", "-C", repo_path, "log", "--pretty=format:%H", "--", "*.js"] - result = subprocess.run(command, stdout=subprocess.PIPE, text=True) - return result.stdout.strip().split('\n') - -def get_commit_diff(repo_path, commit_hash): - command = ["git", "-C", repo_path, "show", commit_hash, "--", "*.js"] - result = subprocess.run(command, stdout=subprocess.PIPE, text=True) - return result.stdout - -def extract_functions(diff): - # Regular expression to match the function declarations and bodies in the format: 'function () {}' - function_regex = r"function\s+([a-zA-Z_$][0-9a-zA-Z_$]*)\s*\([^)]*\)\s*\{[\s\S]*?\}" - return re.findall(function_regex, diff) - -def hash_function_body(function_body): - return sha256(function_body.encode('utf-8')).hexdigest() - -def get_merge_commits(repo_path, commits): - merge_commits = [] - - for commit in commits: - # Use Git command to check if the commit has more than one parent, indicating a merge commit - command = ["git", "-C", repo_path, "rev-list", "--parents", "-n", "1", commit] - result = subprocess.run(command, stdout=subprocess.PIPE, text=True) - - # Check if the commit has more than one parent - if len(result.stdout.strip().split()) > 2: - merge_commits.append(commit) - - return merge_commits - -def get_commit_timestamp(repo_path, commit): - return subprocess.run(["git", "-C", repo_path, "log", "--pretty=format:%ct", "-n", "1", commit], - stdout=subprocess.PIPE, text=True).stdout.strip() - -def process_commit(repo_path, commit, function_changes, is_merge_commit): - diff = get_commit_diff(repo_path, commit) - functions = extract_functions(diff) - - for function_name in functions: - full_function = 'function ' + function_name + diff.split(function_name)[1].split('}')[0] + '}' - function_hash = hash_function_body(full_function) - commit_timestamp = get_commit_timestamp(repo_path, commit) - - if function_name not in function_changes: - function_changes[function_name] = { - 'count': 0, - 'hashes': set(), - 'first_version': full_function if not is_merge_commit else None, - 'merge_commit': commit_timestamp if is_merge_commit else None, - 'count_before_merge': 0 - } - else: - # Update first_version only if it's a regular commit and first_version is not set - if not is_merge_commit and function_changes[function_name]['first_version'] is None: - function_changes[function_name]['first_version'] = full_function - - if is_merge_commit and int(commit_timestamp) < int(function_changes[function_name]['merge_commit']): - function_changes[function_name]['count_before_merge'] += 1 - - if function_hash not in function_changes[function_name]['hashes']: - function_changes[function_name]['count'] += 1 - function_changes[function_name]['hashes'].add(function_hash) - -def analyze_commits(repo_path, commits): - function_changes = {} - - # Get merge commits - merge_commits = get_merge_commits(repo_path, commits) - - # Process merge commits - for merge_commit in reversed(merge_commits): - process_commit(repo_path, merge_commit, function_changes, is_merge_commit=True) - - # Process regular commits - for commit in reversed(commits): - process_commit(repo_path, commit, function_changes, is_merge_commit=False) - - return function_changes - -def main(): - repo_path = './inputData/testRepository' - commits = get_js_commits(repo_path) - function_changes = analyze_commits(repo_path, commits) - - # Prepare data for JSON output - output_data = {function_name: {'count': data['count'], 'first_version': data['first_version']} - for function_name, data in function_changes.items()} - - # Write to JSON file - with open('./outputData/function_changes.json', 'w') as json_file: - json.dump(output_data, json_file, indent=4) - - for function_name, data in function_changes.items(): - print(f"Function '{function_name}' changed {data['count']} times") - -if __name__ == "__main__": - main() - +import function_data +import normalize_scores +import embed_training_data +import evaluate_performance +from userInput.process_user_input import process_user_input + +def main(repos_info): + for repo_info in repos_info: + repo_path, data_type = repo_info['path'], repo_info['type'] + + # Determine the output path based on data type + if data_type == 'training': + output_path = './dataForTesting/training.json' + else: # Default to test + output_path = './dataForTesting/testing.json' + + # Run the main function from getFunctionData with the specified output path + print(f"Processing repository: {repo_path}, Data type: {data_type}") + function_data.get_function_data(repo_path, output_path) + print(f"Done processing repository: {repo_path}, Data type: {data_type}") + + # Normalize the scores for all data + normalize_scores.normalize_and_save_change_counts('dataForTesting/training.json') + normalize_scores.normalize_and_save_change_counts('dataForTesting/testing.json') + print("Done normalizing scores") + + # Load the function data from the file + with open('dataForTesting/training.json', 'r') as f: + training_data = json.load(f) + + # Save the embeddings + embed_training_data.embed_repos_functions(training_data) + + # Get the performance metrics + accuracy, baseline_accuracy = evaluate_performance.evaluate_model_accuracy('./dataForTesting/testing.json') + print(f"Model Accuracy: {accuracy * 100:.2f}%") + print(f"Baseline Accuracy: {baseline_accuracy * 100:.2f}%") + evaluate_performance.update_readme_with_accuracy(accuracy * 100) + +if __name__ == '__main__': + start_time = time.time() + + # List of repositories and their types + repos_info = [ + {'path': '../inputData/trainingData/24petwatch', 'type': 'training'}, + #{'path': '../inputData/trainingData/danaher-ls-aem', 'type': 'training'}, + #{'path': '../inputData/trainingData/mammotome', 'type': 'training'}, + #{'path': '../inputData/trainingData/moleculardevices', 'type': 'training'}, + #{'path': '../inputData/trainingData/petplace', 'type': 'training'}, + #{'path': '../inputData/trainingData/theplayers', 'type': 'training'}, + #{'path': '../inputData/trainingData/walgreens', 'type': 'training'}, + {'path': '../inputData/testData/elixirsolutions', 'type': 'testing'}, + ] + + main(repos_info) + + end_time = time.time() + elapsed_time = round((end_time - start_time) / 60, 2) # convert to minutes and round to 2 decimal places + print(f'⏰ The program took {elapsed_time} minutes to run. ⏰') diff --git a/normalize_scores.py b/normalize_scores.py new file mode 100644 index 0000000..a58ed68 --- /dev/null +++ b/normalize_scores.py @@ -0,0 +1,34 @@ +import json +import numpy as np + +def log_normalize_change_counts(repos): + # Extract all changes and adjust by adding 1 + all_changes = [func['changes_after_merge'] + 1 for repo in repos.values() for func in repo.values()] + + # Apply logarithmic transformation + log_changes = np.log(all_changes) + min_log, max_log = min(log_changes), max(log_changes) + + # Normalize each repository's changes + for repo_name, functions in repos.items(): + for func_key, func_info in functions.items(): + adjusted_change = np.log(func_info['changes_after_merge'] + 1) + normalized_score = 2 * ((adjusted_change - min_log) / (max_log - min_log)) - 1 + func_info['score'] = normalized_score + + return repos + +def normalize_and_save_change_counts(file_path): + with open(file_path, 'r') as f: + data = json.load(f) + + normalized_data = log_normalize_change_counts(data) + + with open(file_path, 'w') as f: + json.dump(normalized_data, f, indent=4) + + return normalized_data + +if __name__ == '__main__': + normalize_and_save_change_counts('dataForTesting/training.json') + normalize_and_save_change_counts('dataForTesting/testing.json') diff --git a/package.json b/package.json new file mode 100644 index 0000000..c8870bf --- /dev/null +++ b/package.json @@ -0,0 +1,17 @@ +{ + "name": "functionretriever", + "version": "1.0.0", + "description": "- How do I run the database locally? - install docker - install qdrant - run qdrant", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "@babel/core": "^7.23.7", + "@babel/parser": "^7.23.6", + "babel": "^6.23.0" + } +} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..f884b1a --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +GitPython +openai +python-dotenv +qdrant-client +requests \ No newline at end of file diff --git a/test_accuracy_up_or_down.py b/test_accuracy_up_or_down.py new file mode 100644 index 0000000..a493f74 --- /dev/null +++ b/test_accuracy_up_or_down.py @@ -0,0 +1,42 @@ +import subprocess +import re +import sys + +# ANSI escape codes for colors +GREEN = '\033[92m' # Green text +RED = '\033[91m' # Red text +ENDC = '\033[0m' # Reset color + +def get_last_commit_on_main(): + return subprocess.check_output(['git', 'rev-parse', 'main']).decode().strip() + +def get_diff_of_readme(last_commit): + return subprocess.check_output(['git', 'diff', last_commit, 'README.md']).decode() + +def parse_accuracy_from_diff(diff): + pattern = r"## Current Accuracy: (\d+\.\d+)%" + accuracies = re.findall(pattern, diff) + return [float(acc) for acc in accuracies] + +def test_accuracy_increase(): + try: + last_commit = get_last_commit_on_main() + diff = get_diff_of_readme(last_commit) + if '## Current Accuracy:' in diff: + old_accuracy, new_accuracy = parse_accuracy_from_diff(diff) + assert new_accuracy > old_accuracy, "Accuracy must be increased in PR" + return True + else: + print("No accuracy update in README.md 🤷‍♂️") + return False + except Exception as e: + print(f"Test failed due to an error: {e} ❌") + return False + +if __name__ == '__main__': + result = test_accuracy_increase() + if result: + print(GREEN + "Test passed: Accuracy has been increased! 🎉" + ENDC) + else: + print(RED + "Test failed: Accuracy has not been increased or no accuracy update was found. 😢" + ENDC) + sys.exit(1) # Exit with a non-zero status code to indicate failure \ No newline at end of file diff --git a/test_get_function_data.py b/test_get_function_data.py new file mode 100644 index 0000000..0f28853 --- /dev/null +++ b/test_get_function_data.py @@ -0,0 +1,108 @@ +import unittest +import json +import sys + +sys.path.append('../') +import function_data + +class TestFunctionData(unittest.TestCase): + + @classmethod + def setUpClass(cls): + # Execute the script to update the function data + function_data.get_function_data(output_path='./dataForTesting/test_function_changes.json') + + # Load the function changes data + with open('./dataForTesting/test_function_changes.json', 'r') as file: + cls.function_data = json.load(file)['testRepo'] # Access the data within 'testRepo' + + def test_createdWithMergeAndNotChangedAfter(self): + # Define the expected function key and content + expected_key = 'blocks/test.js::createdWithMergeAndNotChangedAfter' + expected_function = { + 'function_name': 'createdWithMergeAndNotChangedAfter', + 'merged_function': "function createdWithMergeAndNotChangedAfter() {\n console.log('This creates the function on test branch')\n console.log('Second change on test branch')\n}", + 'changes_after_merge': 0 + } + + # Check if the function data contains the expected function with the correct data + self.assertIn(expected_key, self.function_data) + self.assertEqual(self.function_data[expected_key]['function_name'], expected_function['function_name']) + + # Check if the function data contains the expected function with the correct data + self.assertIn(expected_key, self.function_data) + self.assertEqual(self.function_data[expected_key]['function_name'], expected_function['function_name']) + self.assertEqual(self.function_data[expected_key]['merged_function'].strip(), expected_function['merged_function'].strip()) + self.assertEqual(self.function_data[expected_key]['changes_after_merge'], expected_function['changes_after_merge']) + + def test_CreatedOnMainAndNotChangedAfterMerge(self): + # Define the expected function key and content + expected_key = 'blocks/test.js::CreatedOnMainAndNotChangedAfterMerge' + expected_function = { + 'function_name': 'CreatedOnMainAndNotChangedAfterMerge', + 'merged_function': "function CreatedOnMainAndNotChangedAfterMerge() {\n console.log('This creates the function on main branch')\n console.log('First change on test branch')\n console.log('Second change on test branch')\n}", + 'changes_after_merge': 0 + } + + # Check if the function data contains the expected function with the correct data + self.assertIn(expected_key, self.function_data) + self.assertEqual(self.function_data[expected_key]['function_name'], expected_function['function_name']) + self.assertEqual(self.function_data[expected_key]['merged_function'].strip(), expected_function['merged_function'].strip()) + self.assertEqual(self.function_data[expected_key]['changes_after_merge'], expected_function['changes_after_merge']) + + + def test_createdWithMergeAndChangedAfterMerge(self): + # Define the expected function key and content + expected_key = 'blocks/test.js::createdWithMergeAndChangedAfterMerge' + expected_function = { + 'function_name': 'createdWithMergeAndChangedAfterMerge', + 'merged_function': "function createdWithMergeAndChangedAfterMerge() {\n console.log('This creates the function on test branch')\n console.log('second change on test branch')\n}", + 'changes_after_merge': 1 + } + + # Check if the function data contains the expected function with the correct data + self.assertIn(expected_key, self.function_data) + self.assertEqual(self.function_data[expected_key]['function_name'], expected_function['function_name']) + self.assertEqual(self.function_data[expected_key]['merged_function'].strip(), expected_function['merged_function'].strip()) + self.assertEqual(self.function_data[expected_key]['changes_after_merge'], expected_function['changes_after_merge']) + + def test_createdOnMainAndChangedAfterWithMerge(self): + # Define the expected function key and content + expected_key = 'blocks/test.js::createdOnMainAndChangedAfterWithMerge' + expected_function = { + 'function_name': 'createdOnMainAndChangedAfterWithMerge', + 'merged_function': "function createdOnMainAndChangedAfterWithMerge() {\n console.log('This creates the function on main branch')\n console.log('First change on test branch')\n console.log('Second change on test branch')\n}", + 'changes_after_merge': 1 + } + + # Check if the function data contains the expected function with the correct data + self.assertIn(expected_key, self.function_data) + self.assertEqual(self.function_data[expected_key]['function_name'], expected_function['function_name']) + self.assertEqual(self.function_data[expected_key]['merged_function'].strip(), expected_function['merged_function'].strip()) + self.assertEqual(self.function_data[expected_key]['changes_after_merge'], expected_function['changes_after_merge']) + + def test_changedAfterMergeWithMerge(self): + # Define the expected function key and content + expected_key = 'blocks/test.js::test_changedAfterMergeWithMerge' + expected_function = { + 'function_name': 'test_changedAfterMergeWithMerge', + 'merged_function': "function test_changedAfterMergeWithMerge() {\n console.log('This creates the function')\n console.log('Second change on test branch')\n}", + 'changes_after_merge': 2 + } + + # Check if the function data contains the expected function with the correct data + self.assertIn(expected_key, self.function_data) + self.assertEqual(self.function_data[expected_key]['function_name'], expected_function['function_name']) + self.assertEqual(self.function_data[expected_key]['merged_function'].strip(), expected_function['merged_function'].strip()) + self.assertEqual(self.function_data[expected_key]['changes_after_merge'], expected_function['changes_after_merge']) + +class CustomTestRunner(unittest.TextTestRunner): + def run(self, test): + result = super(CustomTestRunner, self).run(test) + if result.wasSuccessful(): + # ANSI escape code for green text + print("\033[92m" + "All tests passed successfully!" + "\033[0m 🚀 🚀 🚀") + return result + +if __name__ == '__main__': + unittest.main(testRunner=CustomTestRunner()) diff --git a/userInput/process_user_input.py b/userInput/process_user_input.py new file mode 100644 index 0000000..5973d34 --- /dev/null +++ b/userInput/process_user_input.py @@ -0,0 +1,69 @@ +import openai +import requests +import json +import os +import time +import dotenv +from qdrant_client import QdrantClient +from qdrant_client.http import models + +def process_user_input(input_function): + dotenv.load_dotenv() + openai.api_key = os.getenv("OPENAI_API_KEY") + + def embedUserInput(retry_attempts=3, retry_delay=5): + model = "text-embedding-ada-002" + input_text = input_function + data = {"input": input_text, "model": model} + + for attempt in range(retry_attempts): + try: + response = requests.post( + 'https://api.openai.com/v1/embeddings', + headers={'Content-Type': 'application/json', 'Authorization': f'Bearer {openai.api_key}'}, + data=json.dumps(data), + timeout=30 # Timeout for the request + ) + if response.status_code == 200: + return response.json()['data'][0]['embedding'] + else: + print(f"Failed to get embedding, status code: {response.status_code}. Retrying...") + except Exception as e: + print(f"Exception during embedding request: {e}. Retrying...") + + time.sleep(retry_delay) + + raise Exception("Failed to embed input after multiple attempts.") + + def performKNNSearch(embedding, k=5, merge_threshold=-0.6, retry_attempts=3, retry_delay=5): + client = QdrantClient(host='localhost', port=6333) + for attempt in range(retry_attempts): + try: + search_results = client.search( + collection_name="functions", + query_vector=embedding, + search_params=models.SearchParams(hnsw_ef=128, exact=False), + limit=k + ) + + if 'result' in search_results: + results = search_results['result'] + else: + results = search_results + + total_score = sum(result.payload.get('score', 0) for result in results) + average_score = total_score / k + return "🎉 Merge the function 🎉" if average_score <= merge_threshold else "🙅 Do not merge the function 🙅" + except Exception as e: + print(f"Exception during KNN search: {e}. Retrying...") + + time.sleep(retry_delay) + + raise Exception("Failed to perform KNN search after multiple attempts.") + + embedding = embedUserInput() + return performKNNSearch(embedding) + +if __name__ == '__main__': + function_input = "async function buildBlogFeed(ul, pageNum, pageControl) {...}" # truncated for brevity + print(process_user_input(function_input))