You're Invited:Meet the Socket Team at RSAC and BSidesSF 2026, March 23–26.RSVP
Socket
Book a DemoSign in
Socket

agilecoder

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

agilecoder - pypi Package Compare versions

Comparing version
0.1.1
to
0.1.2
+1
-1
agilecoder.egg-info/PKG-INFO
Metadata-Version: 2.1
Name: agilecoder
Version: 0.1.1
Version: 0.1.2
Summary: AgileCoder

@@ -5,0 +5,0 @@ Home-page: https://github.com/FSoft-AI4Code/AgileCoder

@@ -24,3 +24,3 @@ {

"phaseType": "ComposedPhase",
"cycleNum": 2,
"cycleNum": 1,
"Composition": [

@@ -27,0 +27,0 @@ {

@@ -46,4 +46,6 @@ {

"PRODUCT_BACKLOG",
"where PRODUCT_BACKLOG is the product backlog for the user's task.",
"Importantly, you must consider the skills of the development team to write the feasible product backlog. Advanced features like sounds can not be implemented properly."
"Acceptance Criteria:",
"ACCEPTANCE_CRITERIA",
"where PRODUCT_BACKLOG is the product backlog for the user's task and ACCEPTANCE_CRITERIA is the corresponding acceptance criteria of the product backlog.",
"Importantly, you must consider the skills of the development team to write the feasible product backlog. Advanced features like AI and sounds can not be implemented properly."
]

@@ -96,5 +98,5 @@ },

"1) considering the proficiency of the members, all the tasks are feasible and finished by at least one member,",
"2) the sprint backlog must not incorporate enhanced features like AI, animations and sound effects unless explicitly specified in the user's task,",
"2) the sprint backlog must not incorporate enhanced features like AI and sound effects unless explicitly specified in the user's task,",
"3) all the items in sprint backlog are from the product backlog.",
"Now, you should check the above regulations one by one and review the sprint goals and sprint backlog in detail, propose one comment with the highest priority about them, and give me instructions on how to fix. Tell me your comment with the highest priority and corresponding suggestions on revision. If the sprint goals and sprint backlog are perfect and you have no comment on them, return only one line like \"<INFO> Finished\"."
"Now, you should check the above regulations one by one and review the sprint goals and sprint backlog in detail, propose one comment with the highest priority about them, and give me instructions on how to fix to ensure the sprint backlog aligns well with the regulations above. Tell me your comment with the highest priority and corresponding suggestions on revision. If the sprint goals and sprint backlog are perfect and you have no comment on them, return only one line like \"<INFO> Finished\"."
]

@@ -116,3 +118,3 @@ },

"We have decided to complete the task through a executable software with multiple files implemented via {language}.",
"As the {assistant_role}, to satisfy the user's demand and make the software executive and robust, and ensure that the sprint goals and sprint backlog are feasible and can be accomplished, you should modify corresponding product backlog according to the comments. Then, output the full and complete product backlog with all based on the comments. Return the output strictly following the required format:",
"As the {assistant_role}, to satisfy the user's demand and make the software executive and robust, and ensure that the sprint goals and sprint backlog are feasible and can be accomplished, you should modify corresponding sprint backlog according to the comments. Then, output the full and complete sprint backlog with all based on the comments. Return the output strictly following the required format:",
"Sprint Goals:",

@@ -136,3 +138,3 @@ "SPRINT_GOALS",

"Think step by step and reason yourself to the right decisions to make sure we get it right.",
"Your answer only has a single sprint backlog and strictly obeys the following format:",
"Your answer strictly obeys the following format:",
"Sprint Goals:",

@@ -144,7 +146,7 @@ "SPRINT_GOALS",

"You must ensure that SPRINT_GOALS and BACKLOG_DETAILS must not be empty and BACKLOG_DETAILS aligns with SPRINT_GOALS.",
"As the Product Owner, you must adhere to the following regulations:",
"As the Product Owner, you must create the first sprint and adhere to the following regulations:",
"1) considering the proficiency of the members, all the tasks are feasible and finished by at least one member,",
"2) the sprint backlog must not include enhanced features like AI, animations and sound effects,",
"3) the sprint backlog chosen sets the stage for next sprints.",
"Note that the product backlog is divided into at least 2 sprints and each sprint should contain enough workload."
"3) importantly, the product backlog should be divided into at least 2 sprints and each sprint should contain enough workload,",
"4) the first sprint backlog sets the stage for next sprints."
]

@@ -273,2 +275,8 @@ },

"The code above contains enough values for the required fields: \"FILENAME\", \"LANGUAGE\", \"DOCSTRING\" and \"CODE\". However, they are not written to follow the format properly. You should rearrange them to satisfy the requirement.",
"Example:",
"a.py",
"```python",
"def a():",
" pass",
"```",
"As the {assistant_role}, to make the code satisfy the required format, you should modify corresponding codes according to the comments and then return all codes strictly following the required format.",

@@ -275,0 +283,0 @@ "Please note that you are not allowed to write new code or change the values of any fields, meaning that the new code is only different from the original code in terms of the format."

@@ -259,3 +259,3 @@ import importlib

get_info(self.chat_env.env_dict['directory'], self.log_filepath) + "\n\n🕑**duration**={:.2f}s\n\n".format(duration))
post_info += f'Number of sprints {self.chat_env.env_dict["num-sprints"]}\n\n'
post_info += "AgileCoder Starts ({})".format(self.start_time) + "\n\n"

@@ -262,0 +262,0 @@ post_info += "AgileCoder Ends ({})".format(now_time) + "\n\n"

@@ -35,3 +35,19 @@ import os

import ast
def has_entry_point(code):
try:
tree = ast.parse(code)
# Check for if __name__ == "__main__": condition
# Check for standalone code (no functions or classes)
for node in ast.iter_child_nodes(tree):
if not isinstance(node, (ast.Module, ast.FunctionDef, ast.ClassDef)):
return True
return False
except SyntaxError:
return False
class ChatEnv:

@@ -62,4 +78,4 @@ def __init__(self, chat_env_config: ChatEnvConfig):

module = match.group(1)
subprocess.Popen("pip install {}".format(module), shell=True).wait()
log_and_print_online("**[CMD Execute]**\n\n[CMD] pip install {}".format(module))
subprocess.Popen("pip3 install {}".format(module), shell=True).wait()
log_and_print_online("**[CMD Execute]**\n\n[CMD] pip3 install {}".format(module))
return module

@@ -114,13 +130,20 @@

else:
flag = False
for file in all_files:
if not file.endswith('.py'): continue
command = "cd {}; ls -l; python3 ".format(directory) + file
process = subprocess.Popen(command,
shell=True,
preexec_fn=os.setsid,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
if len(process.stderr.read().decode('utf-8')) > 0: break
with open(os.path.join(directory, file)) as f:
code = f.read()
if has_entry_point(code):
command = "cd {}; ls -l; python3 ".format(directory) + file
flag = True
process = subprocess.Popen(command,
shell=True,
preexec_fn=os.setsid,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
break
# if len(process.stderr.read().decode('utf-8')) > 0: break
if not flag:
return False, "Error: the software lacks the entry point to start"
time.sleep(3)

@@ -165,3 +188,3 @@ return_code = process.returncode

def update_codes(self, generated_content):
self.codes._update_codes(generated_content)
return self.codes._update_codes(generated_content)

@@ -168,0 +191,0 @@ def rewrite_codes(self) -> None:

@@ -6,2 +6,9 @@ import os

import difflib
import ast
def is_valid_syntax(code):
try:
ast.parse(code)
return True
except SyntaxError:
return False
def extract_files(code_string):

@@ -13,3 +20,4 @@ """Extracts code and names for each file from the given string."""

current_code = ""
flag = False
flag1 = False
for line in code_string.splitlines():

@@ -22,9 +30,15 @@ # Check for file header lines

current_code = ""
flag1 = True
elif line.startswith('DOCSTRING') or line.startswith('CODE'): continue
elif line.startswith('```'): continue
elif line.startswith('```'):
if flag:
flag1 = False
flag = not flag
# continue
elif not line.startswith('LANGUAGE'):
current_code += line + "\n"
if flag1:
current_code += line + "\n"
# Add the last file
if current_file:
if current_file and not flag:
files[current_file] = current_code

@@ -61,30 +75,28 @@

if generated_content != "":
regex = r"(.+?\.\w+)\n```.*?\n(.*?)```"
regex = r"FILENAME\n```.*?\n(.*?)```"
matches = re.finditer(regex, self.generated_content, re.DOTALL)
unmatched_codes = []
flag = False
nonamed_codes = []
for match in matches:
code = match.group(2)
flag = True
code = match.group(1)
if "CODE" in code:
continue
flag = True
group1 = match.group(1)
filename = extract_filename_from_line(group1)
if "__main__" in code:
if "__main__" in code or 'main.py' in code:
filename = "main.py"
if filename == "": # post-processing
else:
filename = extract_filename_from_code(code)
# assert filename != ""
if filename == '.py':
scores = []
normalized_levenshtein = NormalizedLevenshtein()
formatted_code = self._format_code(code)
for filename, file_code in self.codebooks.items():
scores.append((filename, formatted_code, normalized_levenshtein.similarity(formatted_code, file_code)))
if len(scores) > 0:
scores = sorted(scores, key = lambda x: x[2], reverse = True)[0]
if scores[2] > 0.7:
self.codebooks[scores[0]] = scores[1]
elif filename is not None and code is not None and len(filename) > 0 and len(code) > 0:
if filename is not None and filename != '.py' and code is not None and len(filename) > 0 and len(code) > 0:
self.codebooks[filename] = self._format_code(code)
else:
unmatched_codes.append(self._format_code(code))
normalized_levenshtein = NormalizedLevenshtein()
for code in unmatched_codes:
scores = []
for filename, file_code in self.codebooks.items():
scores.append((filename, code, normalized_levenshtein.similarity(code, file_code)))
if len(scores) > 0:
scores = sorted(scores, key = lambda x: x[2], reverse = True)[0]
if scores[2] > 0.7:
self.codebooks[scores[0]] = scores[1]

@@ -102,33 +114,58 @@ if not flag:

if filename is not None and code is not None and len(filename) > 0 and len(code) > 0:
self.codebooks[filename] = self._format_code(code)
if filename.endswith('.py'):
if is_valid_syntax(code):
self.codebooks[filename] = self._format_code(code)
else:
self.codebooks[filename] = self._format_code(code)
if not flag:
regex = r"FILENAME\n```.*?\n(.*?)```"
regex = r"(.+?\.\w+)\n```.*?\n(.*?)```"
matches = re.finditer(regex, self.generated_content, re.DOTALL)
unmatched_codes = []
flag = False
for match in matches:
flag = True
code = match.group(1)
code = match.group(2)
if "CODE" in code:
continue
if "__main__" in code:
filename = "main.py"
else:
flag = True
group1 = match.group(1)
filename = extract_filename_from_line(group1)
old_filename = None
if "__main__" in code or 'main.py' in code:
new_filename = "main.py"
if new_filename != filename:
old_filename = filename
filename = new_filename
if filename == "": # post-processing
filename = extract_filename_from_code(code)
if filename is not None and code is not None and len(filename) > 0 and len(code) > 0:
self.codebooks[filename] = self._format_code(code)
else:
unmatched_codes.append(self._format_code(code))
normalized_levenshtein = NormalizedLevenshtein()
for code in unmatched_codes:
scores = []
for filename, file_code in self.codebooks.items():
scores.append((filename, code, normalized_levenshtein.similarity(code, file_code)))
scores = sorted(scores, key = lambda x: x[2], reverse = True)[0]
if scores[2] > 0.7:
self.codebooks[scores[0]] = scores[1]
# assert filename != ""
if filename == '.py':
scores = []
normalized_levenshtein = NormalizedLevenshtein()
formatted_code = self._format_code(code)
for _filename, file_code in self.codebooks.items():
scores.append((_filename, formatted_code, normalized_levenshtein.similarity(formatted_code, file_code)))
if len(scores) > 0:
scores = sorted(scores, key = lambda x: x[2], reverse = True)[0]
if scores[2] > 0.7:
self.codebooks[scores[0]] = scores[1]
elif filename is not None and code is not None and len(filename) > 0 and len(code) > 0:
if filename.endswith('.py'):
if is_valid_syntax(code):
self.codebooks[filename] = self._format_code(code)
if old_filename is not None and old_filename in self.codebooks:
self.codebooks.pop(old_filename)
else:
self.codebooks[filename] = self._format_code(code)
if not flag:
file_codes = extract_files(self.generated_content)
for filename, filecode in file_codes.items():
self.codebooks[filename] = self._format_code(filecode)
if filename.endswith('.py'):
if is_valid_syntax(filecode):
flag = True
self.codebooks[filename] = self._format_code(filecode)
else:
flag = True
self.codebooks[filename] = self._format_code(filecode)
self.has_correct_format = flag

@@ -143,2 +180,3 @@

differ = difflib.Differ()
flag = False
for key in new_codes.codebooks.keys():

@@ -163,2 +201,5 @@ if key not in self.codebooks.keys() or self.codebooks[key] != new_codes.codebooks[key]:

self.codebooks[key] = new_codes.codebooks[key]
flag = True
return flag
# return hasattr(new_codes, 'has_correct_format') and new_codes.has_correct_format

@@ -165,0 +206,0 @@ def _rewrite_codes(self, git_management) -> None:

@@ -148,2 +148,3 @@ import importlib

self.phases[phase].update_phase_env(chat_env)
if self.break_cycle(self.phases[phase].phase_env):

@@ -154,3 +155,4 @@ return chat_env

need_reflect)
# print('@' * 20)
# print('self.phases[phase].phase_env', self.phases[phase].phase_env)
if self.break_cycle(self.phases[phase].phase_env):

@@ -310,3 +312,4 @@ return chat_env

def break_cycle(self, phase_env) -> bool:
if phase_env.get('has_correct_format', True):
print('phase_env', 'has_correct_format' in phase_env, phase_env.get('has_correct_format', False))
if 'has_correct_format' in phase_env and phase_env['has_correct_format']:
return True

@@ -313,0 +316,0 @@ else:

@@ -350,6 +350,6 @@ import os

if re.search(pattern, text):
return True
return 1
elif text.strip().startswith('-'):
return True
return False
return 2
return 0

@@ -379,2 +379,3 @@ class ProductBacklogCreating(Phase):

acceptance_criteria.append(item)
elif item.startswith('Acceptance Criteria'): break
# else:

@@ -395,2 +396,3 @@ # flag = False

acceptance_criteria.append(item)
elif item.startswith('Acceptance Criteria'): break
# else:

@@ -424,4 +426,5 @@ # flag = False

for item in sprint_backlog_items:
if check_if_string_starts_with_number(item):
if '.' in item:
flag = check_if_string_starts_with_number(item)
if flag > 0:
if flag == 1 and '. ' in item:
list_of_sprint_backlog_items.append(item.split('.')[1].strip())

@@ -439,2 +442,3 @@ else:

chat_env.env_dict['current-sprint-goals'] = sprint_goal
chat_env.env_dict['num-sprints'] = chat_env.env_dict.get('num-sprints', 0) + 1
current_tasks = []

@@ -469,2 +473,3 @@

'all_done_tasks': all_done_tasks,
'num_sprints': chat_env.env_dict.get('num-sprints', 0),
'all_undone_tasks': all_undone_tasks})

@@ -492,4 +497,5 @@

for item in sprint_backlog_items:
if check_if_string_starts_with_number(item):
if '.' in item:
flag = check_if_string_starts_with_number(item)
if flag > 0:
if flag == 1 and '. ' in item:
list_of_sprint_backlog_items.append(item.split('.')[1].strip())

@@ -508,3 +514,3 @@ else:

current_tasks = []
chat_env.env_dict['num-sprints'] = chat_env.env_dict.get('num-sprints', 0) + 1
task_id = 1

@@ -591,4 +597,4 @@ for task in list_of_sprint_backlog_items:

def update_chat_env(self, chat_env) -> ChatEnv:
chat_env.update_codes(self.seminar_conclusion)
if hasattr(chat_env.codes, 'has_correct_format') and chat_env.codes.has_correct_format:
has_correct_format = chat_env.update_codes(self.seminar_conclusion)
if has_correct_format:
chat_env.rewrite_codes()

@@ -614,3 +620,3 @@ log_and_print_online("**[Software Info]**:\n\n {}".format(get_info(chat_env.env_dict['directory'],self.log_filepath)))

def update_phase_env(self, chat_env):
self.phase_env.update({"code": chat_env.env_dict['raw_code_conclusion']})
self.phase_env.update({"codes": chat_env.env_dict['raw_code_conclusion']})

@@ -813,6 +819,22 @@ def update_chat_env(self, chat_env) -> ChatEnv:

lists_of_backlog_items = self.seminar_conclusion.splitlines()
chat_env.env_dict['product-backlog'] = list(filter(check_if_string_starts_with_number, lists_of_backlog_items))
lst = []
flag = False
for item in lists_of_backlog_items:
if check_if_string_starts_with_number(item):
lst.append(item)
flag = True
elif len(item.strip()) and flag: break
# else: break
chat_env.env_dict['product-backlog'] = lst#list(filter(check_if_string_starts_with_number, lists_of_backlog_items))
elif 'product-backlog' not in chat_env.env_dict:
lists_of_backlog_items = self.seminar_conclusion.splitlines()
chat_env.env_dict['product-backlog'] = list(filter(check_if_string_starts_with_number, lists_of_backlog_items))
# chat_env.env_dict['product-backlog'] = list(filter(check_if_string_starts_with_number, lists_of_backlog_items))
lst = []
flag = False
for item in lists_of_backlog_items:
if check_if_string_starts_with_number(item):
lst.append(item)
flag = True
elif len(item.strip()) and flag: break
chat_env.env_dict['product-backlog'] = lst
print("chat_env.env_dict['product-backlog']", chat_env.env_dict['product-backlog'])

@@ -844,4 +866,5 @@ return chat_env

for item in sprint_backlog_items:
if check_if_string_starts_with_number(item):
if '.' in item:
flag = check_if_string_starts_with_number(item)
if flag > 0:
if flag == 1 and '. ' in item:
list_of_sprint_backlog_items.append(item.split('.')[1].strip())

@@ -1033,3 +1056,3 @@ else:

code = match.group(2).strip()
code_sections.append((language, code))
code_sections.append((language, '```' + code + '\n```'))

@@ -1110,2 +1133,3 @@ return code_sections

modules = ''
file_names = extract_file_names(test_reports)
if 'ModuleNotFoundError' in test_reports:

@@ -1139,4 +1163,9 @@ for match in re.finditer(r"No module named '(\S+)'", test_reports, re.DOTALL):

])
elif 'AttributeError' in test_reports:
error_line = test_reports.split('AttributeError')[1]
class_name = re.search(r"'(\w+)'", error_line).group(1)
for filename, code in chat_env.codes.codebooks.items():
if class_name.lower() in filename:
file_names.append(filename)
file_names = extract_file_names(test_reports)
if len(file_names) > 1:

@@ -1143,0 +1172,0 @@ all_relevant_code = []

@@ -6,2 +6,8 @@ import os

import difflib
def is_valid_syntax(code):
try:
ast.parse(code)
return True
except SyntaxError:
return False
def extract_files(code_string):

@@ -13,3 +19,4 @@ """Extracts code and names for each file from the given string."""

current_code = ""
flag = False
flag1 = False
for line in code_string.splitlines():

@@ -22,9 +29,15 @@ # Check for file header lines

current_code = ""
flag1 = True
elif line.startswith('DOCSTRING') or line.startswith('CODE'): continue
elif line.startswith('```'): continue
elif line.startswith('```'):
if flag:
flag1 = False
flag = not flag
# continue
elif not line.startswith('LANGUAGE'):
current_code += line + "\n"
if flag1:
current_code += line + "\n"
# Add the last file
if current_file:
if current_file and not flag:
files[current_file] = current_code

@@ -51,4 +64,8 @@

matches_extract = re.finditer(regex_extract, code, re.DOTALL)
count = 0
for match_extract in matches_extract:
file_name = match_extract.group(1)
count += 1
if count > 1:
return None
file_name = file_name.lower().split("(")[0] + ".py"

@@ -58,30 +75,30 @@ return file_name

if generated_content != "":
regex = r"(.+?\.\w+)\n```.*?\n(.*?)```"
regex = r"FILENAME\n```.*?\n(.*?)```"
matches = re.finditer(regex, self.generated_content, re.DOTALL)
unmatched_codes = []
flag = False
nonamed_codes = []
for match in matches:
code = match.group(2)
print('dakjdsaghsdjkas')
flag = True
code = match.group(1)
if "CODE" in code:
continue
group1 = match.group(1)
filename = extract_filename_from_line(group1)
if "__main__" in code:
filename = "main.py"
if filename == "": # post-processing
else:
filename = extract_filename_from_code(code)
# assert filename != ""
if filename == '.py':
scores = []
normalized_levenshtein = NormalizedLevenshtein()
formatted_code = self._format_code(code)
for filename, file_code in self.codebooks.items():
scores.append((filename, formatted_code, normalized_levenshtein.similarity(formatted_code, file_code)))
if len(scores) > 0:
scores = sorted(scores, key = lambda x: x[2], reverse = True)[0]
if scores[2] > 0.7:
self.codebooks[scores[0]] = scores[1]
elif filename is not None and code is not None and len(filename) > 0 and len(code) > 0:
if filename is not None and code is not None and len(filename) > 0 and len(code) > 0:
self.codebooks[filename] = self._format_code(code)
else:
unmatched_codes.append(self._format_code(code))
normalized_levenshtein = NormalizedLevenshtein()
for code in unmatched_codes:
scores = []
for filename, file_code in self.codebooks.items():
scores.append((filename, code, normalized_levenshtein.similarity(code, file_code)))
if len(scores) > 0:
scores = sorted(scores, key = lambda x: x[2], reverse = True)[0]
if scores[2] > 0.7:
self.codebooks[scores[0]] = scores[1]

@@ -99,54 +116,86 @@ if not flag:

if filename is not None and code is not None and len(filename) > 0 and len(code) > 0:
self.codebooks[filename] = self._format_code(code)
if filename.endswith('.py'):
if is_valid_syntax(code):
self.codebooks[filename] = self._format_code(code)
else:
self.codebooks[filename] = self._format_code(code)
if not flag:
regex = r"FILENAME\n```.*?\n(.*?)```"
regex = r"(.+?\.\w+)\n```.*?\n(.*?)```"
matches = re.finditer(regex, self.generated_content, re.DOTALL)
unmatched_codes = []
for match in matches:
flag = True
code = match.group(1)
print('code:', code)
print('1111')
code = match.group(2)
if "CODE" in code:
continue
filename = extract_filename_from_code(code)
if filename is not None and code is not None and len(filename) > 0 and len(code) > 0:
self.codebooks[filename] = self._format_code(code)
else:
unmatched_codes.append(self._format_code(code))
normalized_levenshtein = NormalizedLevenshtein()
for code in unmatched_codes:
scores = []
for filename, file_code in self.codebooks.items():
scores.append((filename, code, normalized_levenshtein.similarity(code, file_code)))
scores = sorted(scores, key = lambda x: x[2], reverse = True)[0]
if scores[2] > 0.7:
self.codebooks[scores[0]] = scores[1]
if not flag:
regex = r"## (\w+.py)\n\n```.*?\n(.*?)```"
matches = re.finditer(regex, self.generated_content, re.DOTALL)
unmatched_codes = []
for match in matches:
flag = True
filename = match.group(1)
code = match.group(2)
print('code:', code)
if "CODE" in code:
continue
if filename is not None and code is not None and len(filename) > 0 and len(code) > 0:
self.codebooks[filename] = self._format_code(code)
else:
unmatched_codes.append(self._format_code(code))
normalized_levenshtein = NormalizedLevenshtein()
for code in unmatched_codes:
scores = []
for filename, file_code in self.codebooks.items():
scores.append((filename, code, normalized_levenshtein.similarity(code, file_code)))
scores = sorted(scores, key = lambda x: x[2], reverse = True)[0]
if scores[2] > 0.7:
self.codebooks[scores[0]] = scores[1]
group1 = match.group(1)
print(group1)
print('code', code, '122')
filename = extract_filename_from_line(group1)
old_filename = None
if "__main__" in code or 'main.py' in code:
new_filename = "main.py"
if new_filename != filename:
old_filename = filename
filename = new_filename
if filename == "": # post-processing
filename = extract_filename_from_code(code)
# assert filename != ""
if filename == '.py':
scores = []
normalized_levenshtein = NormalizedLevenshtein()
formatted_code = self._format_code(code)
for _filename, file_code in self.codebooks.items():
scores.append((_filename, formatted_code, normalized_levenshtein.similarity(formatted_code, file_code)))
if len(scores) > 0:
scores = sorted(scores, key = lambda x: x[2], reverse = True)[0]
if scores[2] > 0.7:
self.codebooks[scores[0]] = scores[1]
elif filename is not None and code is not None and len(filename) > 0 and len(code) > 0:
if filename.endswith('.py'):
if is_valid_syntax(code):
self.codebooks[filename] = self._format_code(code)
if old_filename is not None and old_filename in self.codebooks:
self.codebooks.pop(old_filename)
else:
self.codebooks[filename] = self._format_code(code)
# regex = r"FILENAME\n```.*?\n(.*?)```"
# matches = re.finditer(regex, self.generated_content, re.DOTALL)
# unmatched_codes = []
# for match in matches:
# print('dakjdsaghsdjkas')
# flag = True
# code = match.group(1)
# if "CODE" in code:
# continue
# if "__main__" in code:
# filename = "main.py"
# else:
# filename = extract_filename_from_code(code)
# if filename is not None and code is not None and len(filename) > 0 and len(code) > 0:
# self.codebooks[filename] = self._format_code(code)
# else:
# unmatched_codes.append(self._format_code(code))
# normalized_levenshtein = NormalizedLevenshtein()
# for code in unmatched_codes:
# scores = []
# for filename, file_code in self.codebooks.items():
# scores.append((filename, code, normalized_levenshtein.similarity(code, file_code)))
# if len(scores) > 0:
# scores = sorted(scores, key = lambda x: x[2], reverse = True)[0]
# if scores[2] > 0.7:
# self.codebooks[scores[0]] = scores[1]
if not flag:
file_codes = extract_files(self.generated_content)
for filename, filecode in file_codes.items():
self.codebooks[filename] = self._format_code(filecode)
if filename.endswith('.py'):
if is_valid_syntax(filecode):
flag = True
self.codebooks[filename] = self._format_code(filecode)
else:
flag = True
self.codebooks[filename] = self._format_code(filecode)
self.has_correct_format = flag

@@ -221,156 +270,207 @@

s = """
FILENAME: main.py
LANGUAGE: Python
DOCSTRING: This module contains the code for a basic calculator application that performs addition, subtraction, multiplication, and division of two numbers with input validation and error handling. Additionally, it implements a history feature that displays previous calculations, a feature to save and load the history from a file, a feature to copy the result to the clipboard, and a feature to change the color scheme of the calculator.
CODE:
main.py
```python
'''
This module contains the code for a basic calculator application that performs addition, subtraction, multiplication, and division of two numbers with input validation and error handling. Additionally, it implements a history feature that displays previous calculations, a feature to save and load the history from a file, a feature to copy the result to the clipboard, and a feature to change the color scheme of the calculator.
This file contains the StartScreen class, which represents the start screen of the game.
'''
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as messagebox
import tkinter.filedialog as filedialog
import os
import sys
try:
import clipboard
except ModuleNotFoundError:
messagebox.showerror("Error", "The clipboard module is not installed. Copy to clipboard feature will not work.")
class Calculator:
def __init__(self, master):
self.master = master
self.master.title("Calculator")
self.master.resizable(False, False)
self.master.configure(bg="#FFFFFF")
# Create input fields for two numbers
self.num1_label = ttk.Label(self.master, text="Number 1:")
self.num1_label.grid(row=0, column=0, padx=5, pady=5, sticky="W")
self.num1_entry = ttk.Entry(self.master, width=20)
self.num1_entry.grid(row=0, column=1, padx=5, pady=5, sticky="W")
self.num2_label = ttk.Label(self.master, text="Number 2:")
self.num2_label.grid(row=1, column=0, padx=5, pady=5, sticky="W")
self.num2_entry = ttk.Entry(self.master, width=20)
self.num2_entry.grid(row=1, column=1, padx=5, pady=5, sticky="W")
# Create buttons for arithmetic operations
self.add_button = ttk.Button(self.master, text="+", command=self.add)
self.add_button.grid(row=2, column=0, padx=5, pady=5)
self.sub_button = ttk.Button(self.master, text="-", command=self.subtract)
self.sub_button.grid(row=2, column=1, padx=5, pady=5)
self.mul_button = ttk.Button(self.master, text="*", command=self.multiply)
self.mul_button.grid(row=3, column=0, padx=5, pady=5)
self.div_button = ttk.Button(self.master, text="/", command=self.divide)
self.div_button.grid(row=3, column=1, padx=5, pady=5)
# Create clear button
self.clear_button = ttk.Button(self.master, text="Clear", command=self.clear)
self.clear_button.grid(row=4, column=0, padx=5, pady=5)
# Create history button
self.history_button = ttk.Button(self.master, text="History", command=self.show_history)
self.history_button.grid(row=4, column=1, padx=5, pady=5)
# Create save button
self.save_button = ttk.Button(self.master, text="Save", command=self.save_history)
self.save_button.grid(row=5, column=0, padx=5, pady=5)
# Create load button
self.load_button = ttk.Button(self.master, text="Load", command=self.load_history)
self.load_button.grid(row=5, column=1, padx=5, pady=5)
# Create copy button
self.copy_button = ttk.Button(self.master, text="Copy", command=self.copy_result)
self.copy_button.grid(row=6, column=0, padx=5, pady=5)
# Create color scheme label
self.color_label = ttk.Label(self.master, text="Color Scheme:")
self.color_label.grid(row=6, column=1, padx=5, pady=5, sticky="E")
# Create color scheme combobox
self.color_combobox = ttk.Combobox(self.master, values=["Default", "Dark"], state="readonly")
self.color_combobox.current(0)
self.color_combobox.grid(row=6, column=2, padx=5, pady=5, sticky="W")
self.color_combobox.bind("<<ComboboxSelected>>", self.change_color_scheme)
# Initialize history list
self.history = []
def add(self):
try:
num1 = float(self.num1_entry.get())
num2 = float(self.num2_entry.get())
result = num1 + num2
self.display_result(result)
self.history.append(f"{num1} + {num2} = {result}")
except ValueError:
messagebox.showerror("Error", "Invalid input. Please enter valid numbers.")
def subtract(self):
try:
num1 = float(self.num1_entry.get())
num2 = float(self.num2_entry.get())
result = num1 - num2
self.display_result(result)
self.history.append(f"{num1} - {num2} = {result}")
except ValueError:
messagebox.showerror("Error", "Invalid input. Please enter valid numbers.")
def multiply(self):
try:
num1 = float(self.num1_entry.get())
num2 = float(self.num2_entry.get())
result = num1 * num2
self.display_result(result)
self.history.append(f"{num1} * {num2} = {result}")
except ValueError:
messagebox.showerror("Error", "Invalid input. Please enter valid numbers.")
def divide(self):
try:
num1 = float(self.num1_entry.get())
num2 = float(self.num2_entry.get())
if num2 == 0:
raise ZeroDivisionError
result = num1 / num2
self.display_result(result)
self.history.append(f"{num1} / {num2} = {result}")
except ValueError:
messagebox.showerror("Error", "Invalid input. Please enter valid numbers.")
except ZeroDivisionError:
messagebox.showerror("Error", "Division by zero is not allowed. Please enter a non-zero value for Number 2.")
def display_result(self, result):
messagebox.showinfo("Result", f"The result is {result}")
try:
clipboard.copy(result)
except NameError:
pass
def clear(self):
self.num1_entry.delete(0, tk.END)
self.num2_entry.delete(0, tk.END)
def show_history(self):
if not self.history:
messagebox.showinfo("History", "No history yet.")
else:
history_str = "\n".join(self.history)
messagebox.showinfo("History", history_str)
def save_history(self):
filename = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt")])
if filename:
with open(filename, "w") as f:
f.write("\n".join(self.history))
messagebox.showinfo("Save", "History saved successfully.")
def load_history(self):
filename = filedialog.askopenfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt")])
if filename:
with open(filename, "r") as f:
self.history = f.read().splitlines()
messagebox.showinfo("Load", "History loaded successfully.")
def copy_result(self):
result = clipboard.paste()
if result:
self.master.clipboard_clear()
self.master.clipboard_append(result)
messagebox.showinfo("Copy", "Result copied to clipboard.")
def change_color_scheme(self, event):
if self.color_combobox.get() == "Default":
self.master.configure(bg="#FFFFFF")
elif self.color_combobox.get() == "Dark":
self.master.configure(bg="#333333")
from startscreen import StartScreen
if __name__ == "__main__":
root = tk.Tk()
app = Calculator(root)
root.mainloop()
screen = StartScreen(800, 600, 30, (255, 255, 255))
screen.draw()
```
game.py
```python
'''
This class will manage the game state and logic. It will be responsible for initializing the game objects, generating food, updating the game state, and drawing the game on the GUI.
'''
class Game:
def __init__(self):
pass
```
gui.py
```python
'''
This file contains the GUI class and its methods.
'''
import pygame
class GUI:
'''
Manages the graphical user interface for the game.
'''
def __init__(self, game_window, game):
'''
Initializes the GUI with the given game window and game.
'''
self.game_window = game_window
self.game = game
self.font = pygame.font.SysFont("Arial", 24)
def draw(self):
'''
Draws the game on the GUI.
'''
# Clear the screen
self.game_window.fill((0, 0, 0))
# Draw the snake
for rect in self.game.snake.body:
pygame.draw.rect(self.game_window, self.game.snake.color, rect)
# Draw the food
self.game.food.draw(self.game_window)
# Draw the score
score_text = self.font.render("Score: " + str(self.game.score), True, (255, 255, 255))
self.game_window.blit(score_text, (10, 10))
```
snake.py
```python
'''
This class will represent the snake in the game and will be responsible for its movement, growth, collision detection, and self-collision detection.
'''
class Snake:
def __init__(self):
pass
```
gameboard.py
```python
'''
This class will represent the game board and will be responsible for drawing the game board on the GUI.
'''
class GameBoard:
def __init__(self):
pass
```
food.py
```python
'''
This class will represent the food in the game and will be responsible for generating new food objects at random locations on the game board.
'''
class Food:
def __init__(self):
pass
```
scoreboard.py
```python
'''
This class will represent the scoreboard in the game and will be responsible for keeping track of the player
'''
class Scoreboard:
def __init__(self):
pass
```
startscreen.py
```python
'''
This class will represent the start screen of the game and will be responsible for displaying the game's title and instructions to the user.
'''
class StartScreen:
def __init__(self):
pass
```
gameoverscreen.py
```python
'''
This file contains the game over screen class and its methods.
'''
import pygame
class GameOverScreen:
'''
Represents the game over screen in the game.
'''
def __init__(self, width, height, font_size, color):
'''
Initializes the game over screen with the given width, height, font size, and color.
'''
self.width = width
self.height = height
self.font = pygame.font.SysFont("Arial", font_size)
self.color = color
def draw(self, surface, score):
'''
Draws the game over screen on the given surface.
'''
# Draw the background
background = pygame.Surface((self.width, self.height))
background.set_alpha(128)
background.fill((0, 0, 0))
surface.blit(background, (0, 0))
# Draw the text
text1 = self.font.render("Game Over", True, self.color)
text1_rect = text1.get_rect(center=(self.width // 2, self.height // 2 - 20))
surface.blit(text1, text1_rect)
text2 = self.font.render("Score: " + str(score), True, self.color)
text2_rect = text2.get_rect(center=(self.width // 2, self.height // 2 + 20))
surface.blit(text2, text2_rect)
```
startscreen.py
```python
'''
This class will represent the start screen of the game and will be responsible for displaying the game's title and instructions to the user.
'''
import pygame
class StartScreen:
def __init__(self, width, height, font_size, color):
self.width = width
self.height = height
self.font = pygame.font.SysFont("Arial", font_size)
self.color = color
def draw(self, surface):
# Draw the background
surface.fill(self.color)
# Draw the text
text = self.font.render("Snake Game", True, (255, 255, 255))
text_rect = text.get_rect(center=(self.width // 2, self.height // 2 - 20))
surface.blit(text, text_rect)
text = self.font.render("Press any key to start", True, (255, 255, 255))
text_rect = text.get_rect(center=(self.width // 2, self.height // 2 + 20))
surface.blit(text, text_rect)
```
gameoverscreen.py
```python
'''
This file contains the game over screen class and its methods.
'''
import pygame
class GameOverScreen:
'''
Represents the game over screen
"""
import ast
def is_valid_syntax(code):
try:
ast.parse(code)
return True
except SyntaxError:
return False
code = """
gameoverscreen.py
```python
'''
This file contains the game over screen class and its methods.
'''
import pygame
class GameOverScreen:
'''
Represents the game over screen
"""
print(is_valid_syntax(code))
code = Codes()
code._update_codes(s)
# code._update_codes(s)
# print(code.)
Metadata-Version: 2.1
Name: agilecoder
Version: 0.1.1
Version: 0.1.2
Summary: AgileCoder

@@ -5,0 +5,0 @@ Home-page: https://github.com/FSoft-AI4Code/AgileCoder

from setuptools import setup, find_packages
setup(name='agilecoder',
version='0.1.1',
version='0.1.2',
description='AgileCoder',

@@ -5,0 +5,0 @@ url='https://github.com/FSoft-AI4Code/AgileCoder',