напиши pyton скрипт который соберет все файлы проекта в один текстовый файл для анализа ИИ в файл включаются файлы с расширениями html, py,yaml, в начале содержимого каждого файла его название и путь должны сканироваться поддиректории - начло сканировать в директории в которой находится сам скрипт, ну и на твой взгляд какие функции надо добавить что бы сократить количество токенов и облегчить ии анализ проекта
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Конечно! Вот простой скрипт на Python, который собирает содержимое файлов с расширениями .html, .py и .yaml в один текстовый файл. В начале содержимого каждого файла будет указано его имя и путь. Скрипт будет сканировать все поддиректории, начиная с директории, в которой он запущен.
python
import os
def gather_files(directory, output_file):
extensions = ['.html', '.py', '.yaml']
with open(output_file, 'w', encoding='utf-8') as outfile:
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(tuple(extensions)):
file_path = os.path.join(root, file)
with open(file_path, 'r', encoding='utf-8') as infile:
content = infile.read()
outfile.write(f"File: {file_path}\n")
outfile.write(f"Content:\n{content}\n\n")
if __name__ == "__main__":
current_directory = os.path.dirname(os.path.abspath(__file__))
output_file = "project_files.txt"
gather_files(current_directory, output_file)
print(f"All files have been gathered into {output_file}")
Дополнительные функции для сокращения количества токенов и облегчения анализа ИИ:
Удаление комментариев:
Для файлов Python можно удалить комментарии, чтобы сократить количество токенов.
Минификация HTML и YAML:
Удалить лишние пробелы и переносы строк в HTML и YAML файлах.
Фильтрация ненужных данных:
Удалить импорты и другие части кода, которые могут не понадобиться для анализа.
Вот обновленный скрипт с этими функциями:
python
import os
import re
def remove_comments_and_minimize(content, file_extension):
if file_extension == '.py':
# Remove comments
pattern = r'(?m)^[ \t]*(#.*)$'
content = re.sub(pattern, '', content)
# Remove import statements if needed
# pattern = r'(?m)^[ \t]*import[\s\S]*?$'
# content = re.sub(pattern, '', content)
elif file_extension == '.html':
# Remove comments and minimize spaces
content = re.sub(r '<!--.*?-->', '', content, flags=re.DOTALL)
content = re.sub(r '>\s+<', '><', content)
elif file_extension == '.yaml':
# Remove comments
content = re.sub(r '#.*$', '', content, flags=re.MULTILINE)
return content
def gather_files(directory, output_file):
extensions = ['.html', '.py', '.yaml']
with open(output_file, 'w', encoding='utf-8') as outfile:
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(tuple(extensions)):
file_path = os.path.join(root, file)
with open(file_path, 'r', encoding='utf-8') as infile:
content = infile.read()
cleaned_content = remove_comments_and_minimize(content, os.path.splitext(file)[1])
outfile.write(f"File: {file_path}\n")
outfile.write(f"Content:\n{cleaned_content}\n\n")
if __name__ == "__main__":
current_directory = os.path.dirname(os.path.abspath(__file__))
output_file = "project_files.txt"
gather_files(current_directory, output_file)
print(f"All files have been gathered and cleaned into {output_file}")
Этот скрипт удалит комментарии из Python-файлов, минифицировав HTML и YAML файлы, что поможет сократить количество токенов и облегчить анализ ИИ.
User
надо что бы пути указывались относительные, и из сканирования исключался файл сканера scanner_ai.py
Assistant
Конечно! Вот обновленный скрипт, который использует относительные пути и исключает файл сканера scanner_ai.py из сканирования.
python
import os
import re
def remove_comments_and_minimize(content, file_extension):
if file_extension == '.py':
# Remove comments
pattern = r'(?m)^[ \t]*(#.*)$'
content = re.sub(pattern, '', content)
# Remove import statements if needed
# pattern = r'(?m)^[ \t]*import[\s\S]*?$'
# content = re.sub(pattern, '', content)
elif file_extension == '.html':
# Remove comments and minimize spaces
content = re.sub(r'<!--.*?-->', '', content, flags=re.DOTALL)
content = re.sub(r'>\s+<', '><', content)
elif file_extension == '.yaml':
# Remove comments
content = re.sub(r'#.*$', '', content, flags=re.MULTILINE)
return content
def gather_files(directory, output_file, exclude_file):
extensions = ['.html', '.py', '.yaml']
relative_path = os.path.relpath(directory, os.path.dirname(os.path.abspath(__file__)))
with open(output_file, 'w', encoding='utf-8') as outfile:
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(tuple(extensions)) and file != exclude_file:
file_path = os.path.join(root, file)
relative_file_path = os.path.relpath(file_path, os.path.dirname(os.path.abspath(__file__)))
with open(file_path, 'r', encoding='utf-8') as infile:
content = infile.read()
cleaned_content = remove_comments_and_minimize(content, os.path.splitext(file)[1])
outfile.write(f"File: {relative_file_path}\n")
outfile.write(f"Content:\n{cleaned_content}\n\n")
if __name__ == "__main__":
current_directory = os.path.dirname(os.path.abspath(__file__))
output_file = "project_files.txt"
exclude_file = "scanner_ai.py"
gather_files(current_directory, output_file, exclude_file)
print(f"All files have been gathered and cleaned into {output_file}")
Объяснение изменений:
Относительные пути:
Используется os.path.relpath для получения относительного пути к файлу относительно директории, в которой находится скрипт.
Исключение файла сканера:
Добавлен параметр exclude_file в функцию gather_files и проверка, чтобы исключить файл scanner_ai.py из сканирования.
Теперь скрипт будет использовать относительные пути и не будет включать сам файл сканера в собранный файл.