Files
anti-plagiarism/services/worker-indexer/app/extractors/docx.py
jze9 2daaa8c8a4 chore(lint): ruff-гейт в CI + фиксы (0 находок) — блокирует кривой деплой
Второй CI-гейт после тестов: ruff как статический анализатор всего Python-кода
(services + scripts). Раньше ни линта, ни проверки типов в CI не было вовсе.

Конфиг ruff.toml: правила E/F/W/I/UP/B/SIM/C4, line-length 100. Осознанно
выключены E501 (длину держит форматтер; длинные RU-комментарии — норма),
B008 (Depends()/Query() в дефолтах — идиома FastAPI, не баг) и UP042
((str, Enum)→StrEnum меняет __str__/сериализацию — не трогаем).

Починено под ноль находок:
- B904 (11): raise ... from exc / from None — читаемые цепочки исключений в
  Celery-ретраях и HTTPException, ошибки обработки не маскируют исходные.
- SIM105 (5): try/except/pass → contextlib.suppress (faiss remove_ids, lsh.remove,
  сброс кэша, ws-disconnect, парс года).
- C416/SIM108/B905/F841/UP035/UP017/F401/I001: dict(rows), тернарник, zip strict,
  мёртвая переменная, устаревшие импорты, timezone.utc→UTC, чистка/сортировка.

Обвязка: scripts/run_lint.sh (ruff в изолированном python:3.11-slim), шаг «Линт»
в job test перед юнит-тестами (падаем раньше). make lint / make lint-fix.
Все 41 юнит-тест по-прежнему зелёные, изменённые файлы компилируются.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-11 17:20:24 +05:00

69 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Извлечение текста из DOCX файлов через python-docx."""
import io
import logging
logger = logging.getLogger(__name__)
def extract_text_from_docx(data: bytes) -> str:
"""
Извлечь текст из DOCX файла.
Обрабатывает параграфы, таблицы и заголовки.
Args:
data: Байты DOCX файла
Returns:
Извлечённый текст
Raises:
ValueError: Если не удалось открыть DOCX
"""
from docx import Document as DocxDocument
try:
doc = DocxDocument(io.BytesIO(data))
except Exception as e:
raise ValueError(f"Не удалось открыть DOCX: {e}") from e
texts: list[str] = []
# Основной текст из параграфов
for para in doc.paragraphs:
text = para.text.strip()
if text:
texts.append(text)
# Текст из таблиц
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
cell_text = cell.text.strip()
if cell_text:
texts.append(cell_text)
return "\n".join(texts)
def extract_text_from_txt(data: bytes) -> str:
"""
Извлечь текст из TXT файла с определением кодировки.
Args:
data: Байты TXT файла
Returns:
Текст файла
"""
# Пробуем UTF-8, затем cp1251 (Windows-1251 для русских текстов)
for encoding in ("utf-8", "cp1251", "latin-1"):
try:
return data.decode(encoding)
except UnicodeDecodeError:
continue
# Последний вариант — игнорировать ошибки
return data.decode("utf-8", errors="ignore")