Перейти к основному содержимому

Проект на python для создания документации в формате md для передачи в нейросети

· 3 мин. чтения
Шамиль
Разработчик 1С

Проект на python для создания документации в формате md для передачи в нейросети

Часто необходимо отправить множество файлов в нейросеть, чтобы она проанализировала.

import os
from pathlib import Path
import sys
import traceback
import time

def generate_tree(root_dir, prefix="", is_last=True, ignore_patterns=None):
"""
Генерирует древовидную структуру директории
"""
if ignore_patterns is None:
ignore_patterns = [
'.git',
'__pycache__',
'venv',
'*.pyc',
'.vscode',
'node_modules',
'project_documentation.md',
'last_100_logs.txt'
]

lines = []
try:
name = root_dir.name or str(root_dir)
lines.append(f"{prefix}{'└── ' if is_last else '├── '}{name}/")

prefix_extension = ' ' if is_last else '│ '
new_prefix = prefix + prefix_extension

items = list(root_dir.iterdir())
items = [item for item in items if not any(
pattern in str(item) for pattern in ignore_patterns
)]
items.sort(key=lambda x: (not x.is_dir(), x.name.lower()))

for i, item in enumerate(items):
is_last_item = i == len(items) - 1
if item.is_dir():
lines.extend(generate_tree(item, new_prefix, is_last_item, ignore_patterns))
else:
lines.append(f"{new_prefix}{'└── ' if is_last_item else '├── '}{item.name}")

except Exception as e:
print(f"Ошибка при обработке директории {root_dir}: {str(e)}")
lines.append(f"{prefix}!!! Ошибка: {str(e)} !!!")

return lines

def create_markdown_documentation(root_dir='.', output_file='project_documentation.md'):
"""
Создаёт Markdown-документацию для проекта
"""
try:
root_path = Path(root_dir).resolve()
print(f"\n[1/4] Проверяем директорию проекта: {root_path}")
if not root_path.exists():
print(f"Ошибка: Директория '{root_dir}' не существует!")
return

markdown_content = []
markdown_content.append("# Документация проекта\n")
markdown_content.append(f"Корневая директория: `{root_path}`\n")

print("[2/4] Генерируем структуру проекта...")
markdown_content.append("## Структура проекта\n")
markdown_content.append("```")
tree_structure = generate_tree(root_path)
markdown_content.extend(tree_structure)
markdown_content.append("```\n")

print("[3/4] Подготавливаем описание файлов...")
markdown_content.append("## Исходный код\n")

# Поиск файлов определённых типов
supported_extensions = ['.py', '.jsx', '.html', '.js', '.css']
all_files = []

print("Ищем файлы для документирования...")
for ext in supported_extensions:
try:
files = list(root_path.rglob(f"*{ext}"))
print(f"Найдено {len(files)} файлов с расширением {ext}")
all_files.extend(files)
except Exception as e:
print(f"Ошибка при поиске файлов {ext}: {str(e)}")

ignore_patterns = [
'.git',
'__pycache__',
'venv',
'.pyc',
'.vscode',
'node_modules',
'project_documentation.md'
]

print(f"[4/4] Обрабатываем файлы...")
processed_files = 0
total_files = len(all_files)

for file_path in sorted(all_files, key=lambda x: (x.suffix, str(x))):
try:
processed_files += 1
if processed_files % 5 == 0: # Показываем прогресс каждые 5 файлов
print(f"Обработано {processed_files}/{total_files} файлов...")

# Пропускаем игнорируемые файлы
if any(pattern in str(file_path) for pattern in ignore_patterns):
continue

rel_path = os.path.relpath(str(file_path), str(root_path))
markdown_content.append(f"\n### {rel_path}\n")

# Пробуем разные кодировки
encodings = ['utf-8', 'utf-8-sig', 'cp1251', 'latin1']
content = None

for encoding in encodings:
try:
with open(file_path, 'r', encoding=encoding) as file:
content = file.read()
print(f"Успешно прочитан файл {rel_path} с кодировкой {encoding}")
break
except UnicodeDecodeError:
continue
except Exception as e:
print(f"Ошибка при чтении файла {rel_path}: {str(e)}")
break

if content is not None:
# Определяем язык для подсветки синтаксиса
file_language = file_path.suffix.lstrip('.')
markdown_content.append(f"```{file_language}")
markdown_content.append(content)
markdown_content.append("```\n")
else:
markdown_content.append(f"> Не удалось прочитать файл {rel_path}\n")

except KeyboardInterrupt:
print("\nПрервано пользователем. Сохраняем текущие результаты...")
break
except Exception as e:
print(f"Ошибка при обработке файла {file_path}: {str(e)}")
continue

print("\nСохраняем документацию...")
output_path = Path(output_file)
output_path.parent.mkdir(parents=True, exist_ok=True)

with open(output_file, 'w', encoding='utf-8') as md_file:
md_file.write('\n'.join(markdown_content))

print(f"\nДокументация успешно создана в файле: {output_file}")
print(f"Обработано файлов: {processed_files}/{total_files}")

except KeyboardInterrupt:
print("\nПрограмма прервана пользователем")
except Exception as e:
print(f"Критическая ошибка: {str(e)}")
traceback.print_exc()

if __name__ == "__main__":
try:
PROJECT_PATH = Path(__file__).parent
OUTPUT_FILE = "project_documentation.md"

print("Запуск генерации документации...")
print(f"Путь проекта: {PROJECT_PATH}")
print(f"Выходной файл: {OUTPUT_FILE}")

start_time = time.time()
create_markdown_documentation(
root_dir=PROJECT_PATH,
output_file=OUTPUT_FILE
)
duration = time.time() - start_time
print(f"\nВремя выполнения: {duration:.2f} секунд")

except Exception as e:
print(f"Фатальная ошибка: {str(e)}")
traceback.print_exc()