-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPublish.py
207 lines (179 loc) · 7.62 KB
/
Publish.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#!/usr/bin/python
import argparse, datetime, shlex, yaml
from string import Template
from subprocess import call
from os import path, listdir, walk, mkdir, rmdir, rename
from os.path import isfile, join
CONFIG_FILE = 'publish-config.yml'
cfg = ''
def loadConfig():
global cfg
with open(CONFIG_FILE, 'r') as ymlfile:
cfg = yaml.load(ymlfile)
def publish():
# mv the files to the web location
for dirname, dirnames, filenames in walk(cfg['draftDir']):
for filename in filenames:
if filename.endswith(cfg['ext']):
rename(join(dirname, filename),join(cfg['webLocation'],filename))
print("Published to web: "+join(cfg['webLocation'],filename))
elif filename.endswith('.epub'):
rename(join(dirname, filename),join(cfg['webLocation'],cfg['book-name']+".epub"))
print("Published to web: "+join(cfg['webLocation'],cfg['book-name']+".epub"))
elif filename.endswith('.mobi'):
rename(join(dirname, filename),join(cfg['webLocation'],cfg['book-name']+".mobi"))
print("Published to web: "+join(cfg['webLocation'],cfg['book-name']+".mobi"))
def mobi(_chapters):
print("Output to mobi (Kindle) format, number of chapters: "+_chapters)
if not path.exists(cfg['draftDir']):
mkdir(cfg['draftDir'])
# Find the epub and convert
epubfound = False
for dirname, dirnames, filenames in walk(cfg['draftDir']):
for filename in filenames:
if filename.endswith('.epub'):
epubfound = True
print("Got epub file to convert: "+filename)
break
if not epubfound:
epub(_chapters)
args = 'kindlegen '+join('.',cfg['draftDir'],"*.epub")
print("Converting .epub...")
try:
call(args.split())
except:
print("Kindlegen not found or not functioning. Is it installed?")
exit(-1)
print("...done.")
print("Published book as .mobi")
def epub(_chapters):
print("Output to epub format, number of chapters: "+_chapters)
if not path.exists(cfg['draftDir']):
mkdir(cfg['draftDir'])
fileList = [join(cfg['publishDir'],cfg['epub-frontmatter'])]
for dirname, dirnames, filenames in walk(cfg['sourceDir']):
for counter, filename in enumerate(filenames):
if _chapters != 'all':
if int(counter) == int(_chapters):
break
fileList += [(join(dirname, filename))]
fileList += [join(cfg['publishDir'],cfg['epub-endmatter'])]
print "Publishing as epub the following: "+' '.join(fileList)
date = datetime.date.today()
fileName = join(cfg['draftDir'],cfg['book-name']+'-draft-'+str(date)+'.epub ')
args = 'pandoc -S --toc-depth=1 -o '+fileName+' '+' '.join(fileList)
try:
call(args.split())
except:
print("Pandoc not found or not functioning. Is it installed?")
exit(-1)
print("Published book as: "+fileName)
# TODO: Delete all files in the web publish location
# TODO: Select single chapters
# add range - so 1:2 will publish markdown chapters 1 and 2
# 4:5 will publish only markdown chapters 4 and 5
# The call to mobi (and epub) will send all chapters - so 4:5 will send to mobi() highest chapter (in this case, 5)
def web(_chapters):
# Split the param and take the highest number to pass through.
chapts = _chapters.split(':')
mobi(chapts[-1]) # Send the last element
firstChapt = 0
lastChapt = 0
if len(chapts) != 1:
firstChapt = int(chapts[0])
lastChapt = int(chapts[1])
else:
lastChapt = int(chapts[0])
print("Publish to web location, chapters: "+str(firstChapt)+" to "+str(lastChapt))
# Create a tmp dir
if not path.exists(cfg['draftDir']):
mkdir(cfg['draftDir'])
# suck in frontmatter into template
frontmatter = []
with open(join(cfg['publishDir'],cfg['web-frontmatter']), 'r') as fmfile:
frontmatter=fmfile.read()
# Create the file list
fileList = []
for dirname, dirnames, filenames in walk(cfg['sourceDir']):
for filename in filenames:
fileList += [(join(dirname, filename))]
# Trim according to num chapters
if _chapters != 'all':
fileList = fileList[firstChapt:lastChapt+1]
print "Publishing to web location the following: "+str(fileList)
# Loop over files to be created
filecount = firstChapt
for filename in fileList:
chapter = ""
# overwrite values in frontmatter str
fm = Template(str(frontmatter))
if filecount == 0:
chapter = fm.substitute(FILENAME=cfg['firstFile'], TIMESTAMP='00:0'+str(filecount+1)+':0'+str(filecount+1))
else:
chapter = fm.substitute(FILENAME=cfg['fileNameBase']+' '+str(filecount), TIMESTAMP='00:0'+str(filecount+1)+':0'+str(filecount+1))
# concat
with open(filename, 'r') as chaptfile:
chapter += chaptfile.read()
chaptfile.close()
# TODO: Fix horrible hack - write out chapter file
chaptname = ""
if filecount == 0:
chaptname = cfg['firstFile']+cfg['ext']
chaptfile = open(join(cfg['draftDir'],chaptname), "w")
chaptfile.write(chapter)
chaptfile.close()
else:
chaptname = cfg['fileNameBase']+'-'+str(filecount)+cfg['ext']
chaptfile = open(join(cfg['draftDir'],chaptname), "w")
chaptfile.write(chapter)
chaptfile.close()
# increment counter
filecount += 1
# Add end matter chapter
chapter = fm.substitute(FILENAME=cfg['endmatter-title'], TIMESTAMP='00:0'+str(filecount+1)+':0'+str(filecount+1))
with open(join(cfg['publishDir'],cfg['web-endmatter']), 'r') as chaptfile:
chapter += chaptfile.read()
chaptfile.close()
# write out chapter file
chaptfileStr = join(cfg['draftDir'],cfg['fileNameBase']+'-'+str(filecount)+cfg['ext'])
chaptfile = open(chaptfileStr, "w")
chaptfile.write(chapter)
chaptfile.close()
publish()
def word(_chapters):
print("Output to MS Word format, number of chapters: "+_chapters)
# Create epub and use calibre ebook-convert to create docx
epub(_chapters)
epubFilename = ''
for dirname, dirnames, filenames in walk(cfg['draftDir']):
for filename in filenames:
if filename.endswith('epub'):
epubFilename = filename
break
fileName = join(cfg['draftDir'],epubFilename.split('.')[0]+'.docx')
args = 'ebook-convert '+join(cfg['draftDir'],epubFilename)+' '+fileName
try:
call(args.split())
except:
print("Pandoc not found or not functioning. Is it installed?")
exit(-1)
print("Published book as: "+fileName)
# TODO: - Add PDF generator
# Handle input and pass to publish functions
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Publishes book content to multiple formats")
parser.add_argument('format', help="The format to output (default: %(default)s)", nargs='?', choices=["epub", "mobi", "word", "web"], default="epub")
parser.add_argument('chapters', help="Number of chapters (e.g. 5, , or a range, 4:5 gives only 4 and 5 (web only) or \"all\") (default: %(default)s)", nargs='?', default="all")
args = parser.parse_args()
if args.format == "epub":
loadConfig()
epub(args.chapters)
elif args.format == "mobi":
loadConfig()
mobi(args.chapters)
elif args.format == "word":
loadConfig()
word(args.chapters)
elif args.format == "web":
loadConfig()
web(args.chapters)