Skip to content

Feature/parser init#30

Closed
andreikurakin123 wants to merge 5 commits into
devfrom
feature/parser-init
Closed

Feature/parser init#30
andreikurakin123 wants to merge 5 commits into
devfrom
feature/parser-init

Conversation

@andreikurakin123

Copy link
Copy Markdown
Collaborator

я пробежался по всем требованиям, вроде все красиво.

Comment thread parser/parser.py Outdated
"text": text,
}
else:
print(f"⚠️ Страница {page_num}: текст не найден")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

убрать ИИшный контент (Смайлики и прочее)

Comment thread parser/parser.py Outdated
page.flush_cache()

if page_num % 10 == 0:
print(f"⌛ Обработано {page_num} страниц...")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тоже самое

Comment thread parser/parser.py Outdated
pdf_path, model, chapter_name="unknown", start_page=1, end_page=None
):
"""
Полный pipeline для RAG: парсинг → фильтрация → блоки → эмбеддинги.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

описание попроще - чтобы не иишный контент был

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

и на английском

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

без стрелочек

Comment thread parser/parser.py Outdated
flush_batch()

if count % 10 == 0:
print(f"✍️ Обработано и записано {count} логических блоков в SQL...")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

смайлики

Comment thread parser/parser.py Outdated
flush_batch()

print(
f"✅ SQL скрипт успешно сгенерирован: {output_file}. "

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

смайлики

Comment thread parser/main.py Outdated

def main():
print(
"⏳ Инициализация модели "

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

смайлики

Comment thread parser/main.py Outdated
cache_folder=str(models_dir),
)
except Exception as e:
print(f"❌ Ошибка при загрузке модели: {e}")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тоже

Comment thread parser/main.py Outdated
data_dir = Path(__file__).parent.parent / "data"
if not data_dir.exists():
print(
f"⚠️ Папка {data_dir} не найдена. "

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну и так далее, больше не буду

Comment thread parser/main.py Outdated

def main():
print(
"⏳ Инициализация модели "

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

... Замена но нормальный лог
print("Initializing model: sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2...")

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну и значки убери

Comment thread parser/main.py
Comment thread parser/main.py Outdated

pdf_files = list(data_dir.glob("*.pdf"))
if not pdf_files:
print(f"⚠️ В папке {data_dir} нет PDF файлов.")

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Аналогично смайлик и на английский
print(f"No PDF files found in {data_dir}.")

Comment thread parser/main.py Outdated
print(f"⚠️ В папке {data_dir} нет PDF файлов.")
return

print(f"🔍 Найдено {len(pdf_files)} PDF файлов для обработки.")

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

print(f"Found {len(pdf_files)} PDF files for processing.")

Comment thread parser/main.py Outdated

def all_pdfs_generator():
for pdf_path in pdf_files:
print(f"📖 Читаем документ: {pdf_path.name}")

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

print(f"Processing document: {pdf_path.name}")

Comment thread parser/parser.py Outdated
Comment on lines +148 to +151
kw_cleaned = [
str(kw).replace("'", "").replace('"', "") for kw in item["keywords"][:10]
]
keywords_pg = "{" + ",".join(kw_cleaned) + "}"

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

убрать

Comment thread parser/parser.py Outdated
Comment on lines +153 to +158
return (
f"('{escape_sql_string(item['chapter_name'])}', "
f"'{keywords_pg}', "
f"'{escape_sql_string(item['chunk_text'])}', "
f"'{embedding_str}')"
)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return (
        f"('{escape_sql_string(item['front_text'])}', "
        f"'{escape_sql_string(item['back_text'])}', "
        f"'{embedding_str}', "
        f"'{escape_sql_string(item['source_info'])}')"
    )

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

напоминаю, что у нас карточки, и все посмотри в миграцию

Comment thread parser/parser.py Outdated

def generate_sql(data_generator, output_file="init.sql"):
"""
Генерирует init.sql: DDL и пакетные INSERT (не по одной строке на команду).

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

доки англ

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не init.sql напоминаю

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

уточнение убрать

Comment thread parser/parser.py Outdated
Comment on lines +165 to +178
init_script = [
"-- Инициализация таблиц для RAG",
"CREATE EXTENSION IF NOT EXISTS vector;",
"CREATE TABLE IF NOT EXISTS documents (",
" id SERIAL PRIMARY KEY,",
" chapter_name TEXT,",
" keywords TEXT[],",
" chunk_text TEXT,",
" embedding vector(384)",
");",
"",
f"-- Данные: один INSERT содержит до {INSERT_VALUES_PER_STATEMENT} строк.",
"",
]

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что тут вообще просходит? Если прям так что-то хочет в инит напиши

        "-- Auto-generated seed file for card_contents",
        "-- Data is chunked into batches for performance.",
        ""

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Опять же ты миграции я тебе кидал

Comment thread parser/parser.py Outdated
Comment on lines +180 to +182
insert_header = (
"INSERT INTO documents (chapter_name, keywords, chunk_text, embedding) VALUES\n"
)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

insert_header = "INSERT INTO card_contents (front_text, back_text, embedding, source_info) VALUES\n"

@ilindan-dev

Copy link
Copy Markdown
Owner

Скрипт решает задачу, но архитектурно сейчас он выглядит как God Object (один файл делает абсолютно всё), и доки, раз уж ты взялся, нужно привести к общему стандарту.

Пожалуйста, сделай следующие правки перед мерджем:

1 Разделение ответственности (SRP)
Сейчас в parser.py смешана логика чтения бинарников, NLP-обработка (YAKE), регулярки и DDL/SQL генерация. Эту лапшу будет невозможно поддерживать и тестировать.
Пожалуйста, разбей код на пакеты/модули. Желаемая структура:

  • extractors/ - логика работы с pdfplumber и сырым текстом.
  • nlp/ - очистка текста, разбиение на блоки, извлечение ключевых слов через YAKE.
  • generators/ (или db/) - маппинг данных и генерация .sql файла.

2 Документация и Docstrings
Давай писать комментарии и докстринги на английском языке, чтобы держать кодовую базу в едином стиле.
Нужно убрать «разговорный» стиль и эмодзи из принтов/логов - в консоли и CI/CD это визуальный мусор.
Опиши докстринги в стандартном формате (например, Google Style). Обязательно укажи, что функция принимает на вход (Args) и что отдает (Returns или Yields). Сейчас по сигнатурам функций непонятно, что и в каком формате там летает.

  1. Тайп-хинтинг (Type Hints)
    Добавь строгие сигнатуры для всех функций (через модуль typing - List, Dict, Generator, Optional и т.д.).

@TToJlkoBHuK

Copy link
Copy Markdown
Collaborator

В целом - код работает, просто надо по комментариями исправить -> и поработать над качеством данных

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants