-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathparser.py
57 lines (47 loc) · 2.15 KB
/
parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import os
import logging
import tempfile
from main.presentations import PresentationPPTX
from main.reports.docx_uploader import DocxUploader
from main.reports.md_uploader import MdUploader
from utils import convert_to
logger = logging.getLogger('root_logger')
def parse(filepath, pdf_filepath):
tmp_filepath = filepath.lower()
try:
if tmp_filepath.endswith(('.odp', '.ppt', '.pptx')):
new_filepath = filepath
if tmp_filepath.endswith(('.odp', '.ppt')):
logger.info(f"Презентация {filepath} старого формата. Временно преобразована в pptx для обработки.")
new_filepath = convert_to(filepath, target_format='pptx')
file_object = PresentationPPTX(new_filepath)
elif tmp_filepath.endswith(('.doc', '.odt', '.docx', )):
new_filepath = filepath
if tmp_filepath.endswith(('.doc', '.odt')):
logger.info(f"Отчёт {filepath} старого формата. Временно преобразован в docx для обработки.")
new_filepath = convert_to(filepath, target_format='docx')
docx = DocxUploader()
docx.upload(new_filepath, pdf_filepath)
docx.parse()
file_object = docx
elif tmp_filepath.endswith('.md' ):
new_filepath = filepath
doc = MdUploader(new_filepath)
md_text = doc.upload()
doc.parse(md_text)
file_object = doc
else:
raise ValueError("Файл с недопустимым именем или недопустимого формата: " + filepath)
# Если была конвертация, то удаляем временный файл.
if new_filepath != filepath:
os.remove(new_filepath)
return file_object
except Exception as err:
logger.error(err, exc_info=True)
return None
def save_to_temp_file(file):
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.write(file.read())
temp_file.close()
file.seek(0)
return temp_file.name