-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomtrain.py
73 lines (58 loc) · 3.2 KB
/
comtrain.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
import os
import re
def parse_comments_and_functions(directory):
data_objects = []
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(".go") and not file.endswith("_test.go"):
file_path = os.path.join(root, file)
with open(file_path, "r") as f:
content = f.read()
# Regex to match multi-line comments followed by functions or types
pattern_multi = r'(?P<comment>/\*.*?\*/)\s*(?P<code>type\s+\w+\s+struct\s*{.*?^}|func\s+\w+\s*\(.*?\)\s*{.*?^})'
matches_multi = re.finditer(pattern_multi, content, re.DOTALL | re.MULTILINE)
# Process multi-line comments with the corresponding function/type
for match in matches_multi:
comment = match.group('comment').strip()
code_block = match.group('code').strip()
prompt = clean_comment_for_prompt(comment)
response = code_block
data_objects.append({
"messages": [
{"role": "system", "content": "You are a Go developer who writes clear, readable, and idiomatic code."},
{"role": "user", "content": prompt},
{"role": "assistant", "content": response}
]
})
# Regex to match single-line comments inside functions or methods
pattern_single = r'(?P<comment>//.*?$)(?P<code>.*?(\{.*?\}|^.*$))'
matches_single = re.finditer(pattern_single, content, re.MULTILINE)
# Process single-line comments with the corresponding line or block of code
for match in matches_single:
comment = match.group('comment').strip()
code_line = match.group('code').strip()
prompt = clean_comment_for_prompt(comment)
response = code_line
data_objects.append({
"messages": [
{"role": "system", "content": "You are a Go developer who writes clear, readable, and idiomatic code."},
{"role": "user", "content": prompt},
{"role": "assistant", "content": response}
]
})
return data_objects
def clean_comment_for_prompt(comment):
"""Clean the comment to make it suitable for use as a natural language prompt."""
# Remove any stars, slashes, or other formatting characters
comment = re.sub(r'//+', '', comment)
comment = re.sub(r'/\*|\*/', '', comment)
comment = comment.strip()
return comment
# Directory to be scanned
directory_path = "./"
data_objects = parse_comments_and_functions(directory_path)
# Write the generated data objects to a file in JSONL format
import json
with open("comment_based_training_data.jsonl", "w") as output_file:
for obj in data_objects:
output_file.write(json.dumps(obj) + "\n")