Files
rmser/ocr-service/app/services/excel.py

47 lines
2.0 KiB
Python
Raw Permalink 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.

import io
import logging
import re
from openpyxl import load_workbook
logger = logging.getLogger(__name__)
def extract_text_from_excel(content: bytes) -> str:
"""
Извлекает текстовое содержимое из Excel файла (.xlsx).
Проходит по всем строкам активного листа, собирает значения ячеек
и формирует текстовую строку для передачи в LLM парсер.
Args:
content: Байтовое содержимое Excel файла
Returns:
Строка с текстовым представлением содержимого Excel файла
"""
try:
# Загружаем workbook из байтов, data_only=True берет значения, а не формулы
wb = load_workbook(filename=io.BytesIO(content), data_only=True)
sheet = wb.active
lines = []
for row in sheet.iter_rows(values_only=True):
# Собираем непустые значения в строку через разделитель
row_text = " | ".join([
str(cell).strip()
for cell in row
if cell is not None and str(cell).strip() != ""
])
# Простая эвристика: строка должна содержать хотя бы одну букву (кириллица/латиница) И хотя бы одну цифру.
# Это отсеет пустые разделители и чистые заголовки.
if row_text and re.search(r'[a-zA-Zа-яА-Я]', row_text) and re.search(r'\d', row_text):
lines.append(row_text)
result = "\n".join(lines)
logger.info(f"Extracted {len(lines)} lines from Excel file")
return result
except Exception as e:
logger.error(f"Error extracting text from Excel: {e}", exc_info=True)
raise