Creating a local AI tool on your Windows machine to automatically analyze Python scripts and rename them based on their functionality is an ambitious and achievable project. Below, I'll outline several solutions and approaches you can consider, including the necessary tools, frameworks, and steps to implement such a system.
1. Leveraging Local Language Models for Code Understanding
a. Choose a Suitable Language Model
To analyze and understand Python code locally, you can utilize open-source language models trained for code understanding. Some popular models include:
- GPT-Neo/GPT-J: Open-source alternatives to OpenAI's GPT-3.
- CodeBERT: Specialized for programming languages and code-related tasks.
- CodeGPT: Designed for code generation and understanding.
b. Set Up the Environment
-
Install Python and Necessary Libraries:
Ensure you have Python installed. Use pip to install required libraries.
pip install transformers torch
-
Download the Pre-trained Model:
Use Hugging Face’s transformers library to load your chosen model.
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("microsoft/codebert-base")
model = AutoModelForCausalLM.from_pretrained("microsoft/codebert-base")
Note: Some models might require significant computational resources. Ensure your hardware (CPU/GPU/RAM) can handle the chosen model.
c. Develop the Renaming Tool
Here's a high-level Python script outline to achieve your goal:
import os
from transformers import pipeline
# Initialize the text generation/prompting pipeline with your model
generator = pipeline('text-generation', model='microsoft/codebert-base')
def analyze_code(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
# Create a prompt to describe the code functionality
prompt = f"Describe the functionality of the following Python code:\n```\n{code}\n```"
# Generate a description
description = generator(prompt, max_length=150)[0]['generated_text']
return description
def generate_new_filename(description):
# Process the description to create a meaningful file name
# This can be as simple as extracting keywords or using NLP techniques
# For simplicity, we'll take the first few words
name = description.split('.')[0].replace(' ', '_').lower()
# Append .py extension
return f"{name}.py"
def rename_files(directory):
for filename in os.listdir(directory):
if filename.endswith('.py'):
file_path = os.path.join(directory, filename)
description = analyze_code(file_path)
new_name = generate_new_filename(description)
new_path = os.path.join(directory, new_name)
os.rename(file_path, new_path)
print(f"Renamed {filename} to {new_name}")
if __name__ == "__main__":
python_programs_dir = r'c:\copy\chatgptcodes\python'
rename_files(python_programs_dir)
Notes:
- Prompt Engineering: Crafting effective prompts is crucial for accurate descriptions. You might need to experiment with different prompts to get the best results.
- Output Processing: The
generate_new_filename function is simplistic. For better results, consider using NLP techniques to extract key terms or use the model to generate a concise filename directly.
- Performance Considerations: Depending on the model size and your hardware, processing each file might be time-consuming. Consider batching or optimizing the code as needed.
2. Using Static Code Analysis with Abstract Syntax Trees (AST)
If leveraging large language models locally is resource-prohibitive, you can opt for static code analysis using Python's built-in ast module or other libraries. This approach involves parsing the code to extract meaningful information about its structure and functionality.
a. Parse Python Code with AST
The ast module allows you to parse Python code into its abstract syntax tree, enabling analysis of functions, classes, and other constructs.
import os
import ast
def analyze_code_ast(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
tree = ast.parse(code)
functions = [node.name for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)]
classes = [node.name for node in ast.walk(tree) if isinstance(node, ast.ClassDef)]
# Create a descriptive name based on functions and classes
name_parts = functions + classes
if not name_parts:
return "utility_script.py"
new_name = "_".join(name_parts).lower() + ".py"
return new_name
def rename_files_ast(directory):
for filename in os.listdir(directory):
if filename.endswith('.py'):
file_path = os.path.join(directory, filename)
new_name = analyze_code_ast(file_path)
new_path = os.path.join(directory, new_name)
os.rename(file_path, new_path)
print(f"Renamed {filename} to {new_name}")
if __name__ == "__main__":
python_programs_dir = r'c:\copy\chatgptcodes\python'
rename_files_ast(python_programs_dir)
Advantages:
- Lightweight: Doesn't require heavy computational resources.
- Deterministic: Based on code structure, less variability in output.
Limitations:
- Limited Understanding: Can miss nuanced functionalities that aren't directly represented by function or class names.
- Naming Conflicts: Different scripts might have overlapping functions or classes leading to similar names.
b. Enhance AST-Based Analysis with Docstrings and Comments
To improve the descriptive accuracy, extract docstrings and comments.
def analyze_code_enhanced(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
tree = ast.parse(code)
docstrings = [ast.get_docstring(node) for node in ast.walk(tree) if isinstance(node, (ast.FunctionDef, ast.ClassDef))]
docstrings = [ds for ds in docstrings if ds]
if docstrings:
# Use the first docstring as the basis for naming
description = docstrings[0]
# Process description to generate a filename
words = description.split()
name_parts = [word.lower() for word in words[:3]] # Take first 3 words
new_name = "_".join(name_parts) + ".py"
else:
# Fallback to function and class names
new_name = analyze_code_ast(file_path)
return new_name
3. Hybrid Approach: Combining Static Analysis with Lightweight NLP
To balance resource usage and descriptive accuracy, combine static code analysis with lightweight natural language processing.
a. Extract Key Features with AST
Use AST to extract functions, classes, and other structural elements.
b. Use NLP for Name Generation
Use NLP techniques or smaller models to generate meaningful filenames based on extracted features.
import os
import ast
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
# Ensure nltk resources are downloaded
import nltk
nltk.download('punkt')
nltk.download('stopwords')
def generate_filename_nlp(features):
stop_words = set(stopwords.words('english'))
words = [word for word in features if word.lower() not in stop_words]
# Choose top 3 keywords
keywords = words[:3]
new_name = "_".join(keywords).lower() + ".py"
return new_name
def analyze_and_rename(directory):
for filename in os.listdir(directory):
if filename.endswith('.py'):
file_path = os.path.join(directory, filename)
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
tree = ast.parse(code)
functions = [node.name for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)]
classes = [node.name for node in ast.walk(tree) if isinstance(node, ast.ClassDef)]
features = functions + classes
new_name = generate_filename_nlp(features)
new_path = os.path.join(directory, new_name)
os.rename(file_path, new_path)
print(f"Renamed {filename} to {new_name}")
if __name__ == "__main__":
python_programs_dir = r'c:\copy\chatgptcodes\python'
analyze_and_rename(python_programs_dir)
Advantages:
- Resource-Efficient: Doesn't require heavy models.
- Improved Naming: Combines structural analysis with keyword optimization.
Considerations:
- NLP Library: This example uses NLTK, but you can opt for more lightweight libraries like
spaCy or even simple regex-based methods.
4. Utilizing Code Documentation Generators
You can also use existing documentation generators to understand code functionality, then extract meaningful names based on the generated documentation.
These tools can parse Python code and generate comprehensive documentation.
b. Extract Descriptive Titles from Documentation
Once documentation is generated, parse it to identify key summaries or titles that can serve as new filenames.
Implementation Steps:
- Generate Documentation:
sphinx-apidoc -o docs/ c:\copy\chatgptcodes\python
make html
- Parse Generated Documentation:
Extract headings or summaries from the HTML files to create meaningful filenames.
Pros:
- Detailed Understanding: Leverages extensive documentation capabilities.
Cons:
- Complexity: Additional steps and parsing required.
- Overkill for Simple Tasks: Might be more elaborate than necessary for renaming files.
5. Implementing Machine Learning Pipelines with Local Models
If you desire a more sophisticated AI-driven approach without relying on massive language models, consider training a lightweight machine learning model tailored to classify or describe code snippets.
a. Dataset Preparation
- Collect a Dataset: Gather Python scripts with descriptive filenames.
- Label Data: Use the existing filenames as labels or create more descriptive labels based on code functionality.
b. Feature Extraction
Use code features such as:
- Function and class names.
- Docstrings and comments.
- Import statements and library usage.
c. Model Training
Train a classification or text summarization model to predict filenames based on extracted features.
d. Integration
Use the trained model in your renaming tool to generate new filenames based on analyzed features.
Advantages:
- Customization: Tailor the model to your specific coding styles and conventions.
- Efficiency: Smaller models can run quickly on local hardware.
Challenges:
- Data Requirements: Requires a sufficiently large and labeled dataset.
- Complexity: Involves machine learning expertise.
Tools and Libraries:
- Scikit-learn: For traditional machine learning models.
- TensorFlow or PyTorch: If you prefer deep learning approaches.
- Natural Language Processing Libraries: Such as
nltk, spaCy, or gensim.
6. Automating the Workflow with a GUI or CLI Tool
To enhance usability, consider wrapping your renaming logic within a user-friendly interface.
a. Command-Line Interface (CLI)
Use libraries like argparse or click to create a CLI tool.
import argparse
def main():
parser = argparse.ArgumentParser(description="Rename Python files based on functionality.")
parser.add_argument('directory', type=str, help='Directory containing Python files.')
args = parser.parse_args()
analyze_and_rename(args.directory)
if __name__ == "__main__":
main()
b. Graphical User Interface (GUI)
Use frameworks like Tkinter, PyQt, or Kivy to build a GUI application.
import tkinter as tk
from tkinter import filedialog
def select_directory():
directory = filedialog.askdirectory()
if directory:
analyze_and_rename(directory)
tk.messagebox.showinfo("Success", f"Renaming completed in {directory}")
root = tk.Tk()
root.title("Python File Renamer")
btn = tk.Button(root, text="Select Directory", command=select_directory)
btn.pack(pady=20)
root.mainloop()
Advantages:
- Accessibility: Easier for users who prefer GUI over command-line.
- Flexibility: Add features like previewing changes before renaming.
7. Ensuring Reliability and Safety
When implementing a renaming tool, it's crucial to ensure that:
-
Backup Original Files: Before renaming, create backups to prevent data loss.
import shutil
def backup_directory(source, destination):
shutil.copytree(source, destination)
-
Handle Naming Conflicts: Check if the new filename already exists to avoid overwriting.
if not os.path.exists(new_path):
os.rename(file_path, new_path)
else:
# Handle conflict, e.g., append a number
base, ext = os.path.splitext(new_name)
counter = 1
while os.path.exists(new_path):
new_name = f"{base}_{counter}{ext}"
new_path = os.path.join(directory, new_name)
counter += 1
os.rename(file_path, new_path)
-
Log Operations: Maintain logs for tracking which files were renamed and any issues encountered.
import logging
logging.basicConfig(filename='rename_log.txt', level=logging.INFO)
# After renaming
logging.info(f"Renamed {filename} to {new_name}")
8. Performance Optimization
Processing numerous files, especially with large models, can be time-consuming. Consider the following optimizations:
-
Batch Processing: Process multiple files simultaneously if memory allows.
-
Parallel Execution: Utilize Python’s multiprocessing or concurrent.futures to parallelize tasks.
from concurrent.futures import ThreadPoolExecutor
def rename_file(file_path):
# Your renaming logic here
pass
with ThreadPoolExecutor(max_workers=4) as executor:
executor.map(rename_file, list_of_file_paths)
-
Caching Results: If files are unlikely to change often, cache the analysis results to avoid redundant processing.
9. Example: Comprehensive Implementation
Below is a more comprehensive example that integrates static analysis with NLP-based name generation, including safety checks and logging.
import os
import ast
import logging
from transformers import pipeline
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import nltk
# Initialize logging
logging.basicConfig(filename='rename_log.txt', level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s')
# Download NLTK data
nltk.download('punkt')
nltk.download('stopwords')
# Initialize the text generation pipeline
generator = pipeline('text-generation', model='microsoft/codebert-base')
def analyze_code(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
tree = ast.parse(code)
functions = [node.name for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)]
classes = [node.name for node in ast.walk(tree) if isinstance(node, ast.ClassDef)]
docstrings = [ast.get_docstring(node) for node in ast.walk(tree) if isinstance(node, (ast.FunctionDef, ast.ClassDef))]
docstrings = [ds for ds in docstrings if ds]
if docstrings:
prompt = f"Based on the following description, suggest a concise filename for the Python script:\n\"{docstrings[0]}\""
description = generator(prompt, max_length=50)[0]['generated_text']
new_name = description.strip().replace(' ', '_').lower() + ".py"
else:
# Fallback to function and class names
features = functions + classes
if features:
# Use NLP to generate name
stop_words = set(stopwords.words('english'))
words = [word for word in features if word.lower() not in stop_words]
keywords = words[:3]
new_name = "_".join(keywords).lower() + ".py"
else:
new_name = "utility_script.py"
return new_name
except Exception as e:
logging.error(f"Error processing {file_path}: {e}")
return None
def rename_files(directory):
for filename in os.listdir(directory):
if filename.endswith('.py'):
file_path = os.path.join(directory, filename)
new_name = analyze_code(file_path)
if new_name:
new_path = os.path.join(directory, new_name)
# Handle naming conflicts
if not os.path.exists(new_path):
os.rename(file_path, new_path)
logging.info(f"Renamed {filename} to {new_name}")
else:
base, ext = os.path.splitext(new_name)
counter = 1
while os.path.exists(new_path):
new_name = f"{base}_{counter}{ext}"
new_path = os.path.join(directory, new_name)
counter += 1
os.rename(file_path, new_path)
logging.info(f"Renamed {filename} to {new_name}")
if __name__ == "__main__":
python_programs_dir = r'c:\copy\chatgptcodes\python'
rename_files(python_programs_dir)
print("Renaming process completed. Check 'rename_log.txt' for details.")
Features of This Implementation:
- Static Analysis with AST: Extracts functions, classes, and docstrings.
- NLP-Based Naming: Uses a language model to generate filenames based on docstrings; falls back to feature-based naming if docstrings are absent.
- Safety Features: Handles naming conflicts by appending a counter, logs all operations, and catches exceptions to avoid halting the process.
- Logging: Maintains a log file (
rename_log.txt) for auditability.
Prerequisites:
-
Install necessary libraries:
pip install transformers torch nltk
-
Ensure your machine has sufficient resources to load and run the chosen language model.
10. Additional Recommendations
-
Model Selection: Depending on your hardware, choose a model that balances performance and resource usage. Smaller models are faster but might be less accurate.
-
Testing: Before running the tool on all files, test it on a small subset to ensure it behaves as expected.
-
Backup: Always back up your files before performing batch rename operations.
-
Extensibility: Design your tool modularly to allow future enhancements, such as integrating more sophisticated analysis or supporting additional programming languages.
-
User Feedback: Incorporate options for manual verification or confirmation before renaming, enhancing control over the process.
By following the approaches outlined above, you can develop a robust local AI tool on your Windows machine to analyze and rename Python scripts based on their functionality. Depending on your specific requirements and resource constraints, you might choose one approach over another or combine elements from multiple solutions to craft a tailored tool.