-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_code_data.py
182 lines (156 loc) · 5.88 KB
/
create_code_data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import ast
import os
import json
import tiktoken
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
class CodeVisitor(ast.NodeVisitor):
def __init__(self, source_lines, file_path):
self.source_lines = source_lines
self.file_path = file_path
self.code_data = []
# Visit function definitions
def visit_FunctionDef(self, node):
start_line = node.lineno - 1
end_line = (
node.body[-1].end_lineno
if hasattr(node.body[-1], "end_lineno")
else start_line
)
code_lines = self.source_lines[start_line : end_line + 1]
code = "".join(code_lines).strip()
decorators = [d.id for d in node.decorator_list if isinstance(d, ast.Name)]
args = [arg.arg for arg in node.args.args]
code_info = {
"type": "function",
"name": node.name,
"decorators": decorators,
"args": args,
"code": code,
"file_path": self.file_path,
"start_line": start_line + 1,
"end_line": end_line + 1,
"start_col": node.col_offset,
"end_col": node.end_col_offset if hasattr(node, "end_col_offset") else None,
}
self.code_data.append(code_info)
for child_node in ast.iter_child_nodes(node):
self.visit(child_node)
# Visit class definitions
def visit_ClassDef(self, node):
start_line = node.lineno - 1
end_line = (
node.body[-1].end_lineno
if hasattr(node.body[-1], "end_lineno")
else start_line
)
code_lines = self.source_lines[start_line : end_line + 1]
code = "".join(code_lines).strip()
decorators = [d.id for d in node.decorator_list if isinstance(d, ast.Name)]
bases = [base.id for base in node.bases if isinstance(base, ast.Name)]
code_info = {
"type": "class",
"name": node.name,
"decorators": decorators,
"bases": bases,
"code": code,
"file_path": self.file_path,
"start_line": start_line + 1,
"end_line": end_line + 1,
"start_col": node.col_offset,
"end_col": node.end_col_offset if hasattr(node, "end_col_offset") else None,
}
self.code_data.append(code_info)
for child_node in ast.iter_child_nodes(node):
self.visit(child_node)
# Visit variable assignments
def visit_Assign(self, node):
for target in node.targets:
if isinstance(target, ast.Name):
start_line = node.lineno - 1
end_line = (
node.end_lineno if hasattr(node, "end_lineno") else start_line
)
code_lines = self.source_lines[start_line : end_line + 1]
code = "".join(code_lines).strip()
code_info = {
"type": "variable",
"name": target.id,
"code": code,
"file_path": self.file_path,
"start_line": start_line + 1,
"end_line": end_line + 1,
"start_col": target.col_offset,
"end_col": target.end_col_offset
if hasattr(target, "end_col_offset")
else None,
}
self.code_data.append(code_info)
for child_node in ast.iter_child_nodes(node):
self.visit(child_node)
# Visit other nodes
def generic_visit(self, node):
for child_node in ast.iter_child_nodes(node):
self.visit(child_node)
# Print the AST of a given file
def print_ast(filename):
with open(filename, "r") as source:
source_lines = source.readlines()
source.seek(0)
tree = ast.parse(source.read())
visitor = CodeVisitor(source_lines, filename)
visitor.visit(tree)
return visitor.code_data
# Get all Python files in a given directory
def get_python_files(directory):
python_files = []
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(".py"):
python_files.append(os.path.join(root, file))
return python_files
# Function to estimate the number of tokens for a given code snippet
def estimate_tokens(code_snippet):
# Get the tokenizer for GPT-4
tokenizer = tiktoken.encoding_for_model("gpt-4")
tokens = tokenizer.encode(
code_snippet,
allowed_special={"<|endoftext|>"},
)
return len(tokens)
# Main function to process the files and generate code data
def main():
directory = os.environ.get("CODESEER_CODE_PATH", None)
if directory is None:
directory = input("Please enter the directory path: ")
if not os.path.isdir(directory):
print("Invalid directory path. Please try again.")
return
python_files = get_python_files(directory)
all_code_data = []
for file in python_files:
print(f"\nProcessing file: {file}")
code_data = print_ast(file)
all_code_data.extend(code_data)
# Iterate through the code data and estimate tokens for each code snippet
for item in all_code_data:
code_snippet = item["code"]
num_tokens = estimate_tokens(code_snippet)
item["num_tokens"] = num_tokens
# Log the results
print(
f"Type: {item['type']}, Name: {item['name']}, File: {item['file_path']}, "
f"Lines: {item['start_line']} - {item['end_line']}, Tokens: {num_tokens}"
)
with open("code_data.json", "w") as output_file:
json.dump(all_code_data, output_file, indent=2)
# Function to be called from another Python file
def run(directory=None):
if directory is None:
main()
else:
os.environ["CODESEER_CODE_PATH"] = directory
main()
if __name__ == "__main__":
main()