-
Notifications
You must be signed in to change notification settings - Fork 7
/
fileconverter.py
77 lines (58 loc) · 1.93 KB
/
fileconverter.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import os
import sys
import platform
from pathlib import Path
def pdfsupport():
# I decided to reuse "pdftotext.exe" from Xpdf tools (http://www.xpdfreader.com/about.html)
# which is already installed on my PC.
# Python package equivalents are too hard to set up on Windows.
# https://github.com/jalan/pdftotext/issues/16#issuecomment-399963100
cmd = 'pdftotext -v > /dev/null'
wincmd = 'pdftotext -v > NUL'
return runcmd(cmd, wincmd=wincmd)
def hwpsupport():
cmd = 'hwp5txt -h > /dev/null'
wincmd = 'hwp5txt -h > NUL'
return runcmd(cmd, wincmd= wincmd)
def pdftotext(infile):
print(f'Converting {infile} to txt...')
cmd = 'pdftotext "{infile}" > /dev/null'
wincmd = 'pdftotext "{infile}" > NUL'
return runcmd(cmd, wincmd=wincmd, infile=infile)
def hwptotext(infile):
print(f'Converting {infile} to txt...')
cmd = 'hwp5txt "{infile}" > "{outfile}"'
return runcmd(cmd, infile=infile)
def runcmd(cmd, wincmd=None, infile=None):
d = {}
if infile:
d['infile'] = infile
d['outfile'] = Path(infile).stem + ".txt"
if platform.system() == 'Windows':
d['cmd'] = wincmd if wincmd else cmd
else:
d['cmd'] = cmd
cmd = cmd.format(**d)
rc = os.system(cmd)
if rc == 0:
return True
else:
return False
def convert(filename):
result = None
ext = Path(filename).suffix
if ext == '.pdf':
if not pdfsupport():
sys.exit('Failed!!! PDF support is not enabled.')
if pdftotext(filename):
result = Path(filename).stem + '.txt'
elif ext == '.hwp':
if not hwpsupport():
sys.exit('Failed!!! HWP support is not enabled.')
if hwptotext(filename):
result = Path(filename).stem + '.txt'
elif ext in ['.docx', '.txt', '.yaml', '']:
result = filename
else:
sys.exit(f'Failed!!! {ext} is not supported')
return result