@@ -3,6 +3,7 @@ import itertools import logging import subprocess import time +import openpyxl from django.utils.translation import gettext_lazy as _ from datetime import timedelta @@ -116,6 +117,8 @@ class Chatgpt(SimpleService): chunks = self.split_text_to_chunks(self.get_pdf_data(file)) elif file_extension in ('.doc', '.docx'): chunks = self.split_text_to_chunks(self.get_word_data(file_extension, file)) + elif file_extension == '.xlsx': + chunks = self.split_text_to_chunks(self.get_xlsx_data(file)) else: image = file if image: @@ -440,6 +443,24 @@ class Chatgpt(SimpleService): else: return 'Файл пуст или содержит изображения, из которых невозможно извлечь текст.' + def get_xlsx_data(self, xlsx_file: UploadedFile) -> str: + """ + Extracting text from xlsx-file + :param xlsx_file: uploaded xlsx file + :return: xlsx_file content + """ + try: + xlsx_content = BytesIO(xlsx_file.read()) + workbook = openpyxl.load_workbook(xlsx_content) + raw_text = '' + for sheet_name in workbook.sheetnames: + sheet = workbook[sheet_name] + for row in sheet.iter_rows(values_only=True): + raw_text += f'Данные ряда: {row}\n' + except Exception: + raw_text = 'Произошла ошибка во время чтения файла' + return f'Содержимое файла: {raw_text}' + def get_word_data(self, extension: str, word_file: UploadedFile) -> str: """ Extracting text from word-file