Files
G4F/ReactDev/__init__.py

116 lines
4.6 KiB
Python
Raw Normal View History

2025-06-02 14:16:03 +03:00
# Инициализация пакета
import os
from .core.ai_interface import AIInterface
from .core.project_map import ProjectMap
from .core.file_analyzer import FileAnalyzer
from .core.commands import CommandGenerator
from .utils.logger import log
from .utils.file_utils import read_file, write_file
from .config import REACT_PROJECT_PATH
__all__ = ["AIInterface", "ProjectMap", "FileAnalyzer", "CommandGenerator", "run_workflow"]
def ensure_default_files():
"""
Проверяет наличие необходимых файлов и создает их с базовым содержимым, если они отсутствуют.
"""
default_files = {
"workingon.md": "/path/to/react/project/src/Auth.tsx",
"prompt.md": "Добавить функцию авторизации в файл Auth.tsx",
"instructions.md": "# Инструкции для ИИ\n\n1. Функции должны быть написаны в TypeScript.\n2. Используйте современные практики React (например, хуки).\n3. При создании новых компонентов добавьте комментарии.",
}
for file_name, content in default_files.items():
if not os.path.exists(file_name):
log(f"File {file_name} not found. Creating it with default content.")
write_file(file_name, content)
def parse_workingon_content(content: str) -> dict:
"""
Парсит содержимое файла workingon.md.
Возвращает словарь с путем к файлу и дополнительным контекстом.
"""
lines = content.strip().split("\n")
result = {"file_path": None, "context": ""}
if lines:
# Первая строка — путь к файлу
result["file_path"] = lines[0].strip()
# Остальные строки — дополнительный контекст
result["context"] = "\n".join(lines[1:]).strip()
return result
def run_workflow():
"""
Основной алгоритм работы библиотеки ReactDev.
1. Создает карту структуры проекта.
2. Анализирует файлы на наличие функций.
3. Отправляет запрос к ИИ с контекстом.
4. Генерирует план модификации.
"""
log("Starting ReactDev workflow...")
# Шаг 0: Убедиться, что все необходимые файлы существуют
ensure_default_files()
# Шаг 1: Создание карты структуры проекта
project_map = ProjectMap(REACT_PROJECT_PATH)
project_structure = project_map.generate_map()
project_map.save_map()
log(f"Generated project structure:\n{project_structure}")
# Шаг 2: Чтение и парсинг workingon.md
workingon_content = read_file("workingon.md")
workingon_data = parse_workingon_content(workingon_content)
target_file = workingon_data["file_path"]
additional_context = workingon_data["context"]
if target_file and not os.path.exists(target_file):
log(f"Target file {target_file} does not exist.", level="error")
return
# Шаг 3: Анализ целевого файла (если указан)
functions_info = {}
if target_file:
file_analyzer = FileAnalyzer()
functions_info = file_analyzer.analyze_file(target_file)
log(f"Analyzed functions in {target_file}: {functions_info}")
# Шаг 4: Отправка запроса к ИИ
ai_interface = AIInterface()
user_prompt = read_file("prompt.md").strip()
# Добавляем дополнительный контекст из workingon.md
full_context = {
"project_structure": project_structure,
"target_file": target_file,
"functions_info": functions_info,
"additional_context": additional_context,
}
ai_response = ai_interface.analyze_project(user_prompt, full_context)
log(f"AI response: {ai_response}")
2025-06-02 16:43:01 +03:00
ai_response = ai_interface.get_modifications(user_prompt, full_context)
log(f"AI response: {ai_response}")
# # Шаг 5: Генерация плана модификации
# command_generator = CommandGenerator()
# modifications = ai_response.get("modifications", [])
# modification_plan = command_generator.generate_commands(modifications)
2025-06-02 14:16:03 +03:00
2025-06-02 14:22:46 +03:00
with open("modification_plan.md", "w", encoding="utf-8") as f:
2025-06-02 16:43:01 +03:00
f.write(ai_response["response"])
2025-06-02 14:16:03 +03:00
2025-06-02 16:43:01 +03:00
# log(f"Generated modification plan:\n{modification_plan}")
2025-06-02 14:16:03 +03:00
log("ReactDev workflow completed.")