@@ -402,13 +402,16 @@ class Chatgpt(SimpleService): :param pdf_file: uploaded pdf file :return: pdf-file content """ - pdf_content = BytesIO(pdf_file.read()) - pdfreader = PdfReader(pdf_content) - raw_text = '' - for page_num, page in enumerate(pdfreader.pages): - content = page.extract_text() - if content: - raw_text += content + try: + pdf_content = BytesIO(pdf_file.read()) + pdfreader = PdfReader(pdf_content) + raw_text = '' + for page_num, page in enumerate(pdfreader.pages): + content = page.extract_text() + if content: + raw_text += content + except Exception: + raw_text = 'Файл поврежден или не может быть прочитан.' if raw_text.strip(): return f'Содержимое файла: f{raw_text}' else: @@ -423,20 +426,23 @@ class Chatgpt(SimpleService): :param word_file: uploaded word file :return: word-file content """ - file_content = word_file.read() - if extension == '.docx': - text = docx2txt.process(BytesIO(file_content)) - elif extension == '.doc': - process = subprocess.Popen( - ['antiword', '-w', '0', '-'], - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - ) - text, _ = process.communicate(input=file_content) - text = text.decode('utf-8') - else: - text = '' + try: + file_content = word_file.read() + if extension == '.docx': + text = docx2txt.process(BytesIO(file_content)) + elif extension == '.doc': + process = subprocess.Popen( + ['antiword', '-w', '0', '-'], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + text, _ = process.communicate(input=file_content) + text = text.decode('utf-8') + else: + text = '' + except Exception: + text = 'Файл поврежден или не может быть прочитан.' if text.strip(): return f'Это текст, извлечённый из загруженного WORD-файла:\n{text}' else: