summaryrefslogtreecommitdiff
path: root/project/scipycon/proceedings/booklet/mk_scipy_paper.py
blob: 7b4eca0ada02d69475cca96cfc1a5193844562fc (plain)
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# encoding: utf-8

import os
import re
import sys
import shutil
import codecs
from glob import glob

from docutils import core as docCore

conf_name = 'SciPy2009'

current_dir = '/media/python/workspace/scipycon/project/scipycon/proceedings/booklet'

outdir = current_dir + os.sep + 'output'

sourcedir = current_dir + os.sep + 'sources'
try:
    os.mkdir(outdir)
except:
    pass

outfilename = outdir + os.sep + 'booklet.tex'

##############################################################################
# Routines for supervised execution
##############################################################################

from threading import Thread
import os
import signal
from subprocess import Popen
from time import sleep

def delayed_kill(pid, delay=10):
    sleep(delay)
    try:
        os.kill(pid, signal.SIGTERM)
    except OSError:
        pass

def supervise_popen(command, timeout=10):
    process = Popen(command)
    Thread(target=delayed_kill, args=(process.pid,timeout),).start()

    process.wait()



##############################################################################
# LaTeX generation functions.
##############################################################################

def protect(string):
    r''' Protects all the "\" in a string by adding a second one before

    >>> protect(r'\foo \*')
    '\\\\foo \\\\*'
    '''
    return re.sub(r"\\", r"\\\\", string)


def safe_unlink(filename):
    """ Remove a file from the disk only if it exists, if not r=fails silently
    """
    if os.path.exists(filename):
        os.unlink(filename)

rxcountpages = re.compile(r"$\s*/Type\s*/Page[/\s]", re.MULTILINE|re.DOTALL)

def count_pages(filename):
    data = file(filename,"rb").read()
    return len(rxcountpages.findall(data))


def tex2pdf(filename, remove_tex=True, timeout=10, runs=2):
    """ Compiles a TeX file with pdfLaTeX (or LaTeX, if or dvi ps requested)
        and cleans up the mess afterwards
    """
    current_dir = os.getcwd()
    os.chdir(os.path.dirname(filename))
    print >> sys.stderr, "Compiling document to pdf"
    basename = os.path.splitext(os.path.basename(filename))[0]
    if os.path.exists(basename + '.pdf'):
        os.unlink(basename + '.pdf')
    for _ in range(runs):
        supervise_popen(("pdflatex",  "--interaction", "scrollmode",
                        os.path.basename(filename)), timeout=timeout)
    error_file = None
    errors =  file(os.path.abspath(basename + '.log')).readlines()[-1]
    if not os.path.exists(basename + '.pdf') or \
                                    "Fatal error" in errors:
        error_file = os.path.abspath(basename + '.log')
    if remove_tex:
        safe_unlink(filename+".tex")
        safe_unlink(filename+".log")
    safe_unlink(filename+".aux")
    safe_unlink(filename+".out")
    os.chdir(current_dir)
    return error_file


def rst2latex(rst_string, no_preamble=True, allow_latex=True):
    """ Calls docutils' engine to convert a rst string to a LaTeX file.
    """
    overrides = {'output_encoding': 'utf-8', 'initial_header_level': 3,
                 'no_doc_title': True, 'use_latex_citations': True, 
                 'use_latex_footnotes':True}
    if allow_latex:
        rst_string = u'''.. role:: math(raw)
                    :format: latex
                    \n\n''' + rst_string
    tex_string = docCore.publish_string(
                source=rst_string,
                writer_name='latex2e', 
                settings_overrides=overrides)
    if no_preamble:
        extract_document = \
            re.compile(r'.*\\begin\{document\}(.*)\\end\{document\}',
            re.DOTALL)
        matches = extract_document.match(tex_string)
        tex_string = matches.groups()[0]
    return tex_string


def get_latex_preamble():
    """ Retrieve the required preamble from docutils.
    """
    full_document = rst2latex('\n', no_preamble=False)
    preamble = re.split(r'\\begin\{document\}', full_document)[0]
    ## Remove the documentclass.
    preamble = r"""
                %s
                \makeatletter
                \newcommand{\class@name}{gael}
                \makeatother
                \usepackage{ltxgrid}
                %s
                """ % (
                    preamble.split('\n')[0],
                    '\n'.join(preamble.split('\n')[1:]),
                )
    return preamble


##############################################################################
# Functions to generate part of the booklet
##############################################################################
def addfile(outfile, texfilename):
    """ Includes the content of a tex file in our outfile.
    """
    include = codecs.open(texfilename, 'r')
    data = include.readlines()
    outfile.write(ur'\thispagestyle{empty}' + u'\n')
    outfile.writelines(data)


def preamble(outfile):
    outfile.write(r'''
    %s
    \usepackage{abstracts}
    \usepackage{ltxgrid}
    \usepackage{amssymb,latexsym,amsmath,amsthm}
    \usepackage{longtable}
    \geometry{left=.8cm, textwidth=17cm, bindingoffset=0.6cm,
                textheight=25.3cm, twoside}
    \usepackage{hyperref}
    \hypersetup{pdftitle={Proceedings of the 8th Annual Python in Science Conference}}
    \begin{document}

    '''.encode('utf-8') % get_latex_preamble())

    # XXX SciPy08 should not be hard coded, but to run out of the webapp

def hack_include_graphics(latex_text):
    """ Replaces all the \includegraphics call with call that impose the
        width to be 0.9\linewidth.
    """
    latex_text = re.sub(r'\\setlength\{\\rightmargin\}\{\\leftmargin\}',
                        r'\\setlength{\\leftmargin}{4ex}\\setlength{\\rightmargin}{0ex}',
                        latex_text)
    latex_text = re.sub(r'\\begin\{quote\}\n\\begin\{itemize\}',
                        r'\\begin{itemize}',
                        latex_text)
    latex_text = re.sub(r'\\end\{itemize\}\n\\end\{quote\}',
                        r'\\end{itemize}',
                        latex_text)
    latex_text = re.sub(r'\\includegraphics(\[.*\])?\{',
                        r'\includegraphics[width=\linewidth]{',
                        latex_text)
    latex_text = re.sub(r'\\href\{([^}]+)\}\{http://(([^{}]|(\{[^}]*\}))+)\}', 
                        r'''%
% Break penalties to have URL break easily:
\mathchardef\UrlBreakPenalty=0
\mathchardef\UrlBigBreakPenalty=0
%\hskip 0pt plus 2em
\href{\1}{\url{\1}}''',
                        latex_text)
    latex_text = re.sub(r'\\href\{([^}]+)\}\{https://(([^{}]|(\{[^}]*\}))+)\}', 
                        r'''%
% Break penalties to have URL break easily:
\mathchardef\UrlBreakPenalty=0
\mathchardef\UrlBigBreakPenalty=0
\linebreak
\href{\1}{\url{\1}}''',
                        latex_text)

    return latex_text


def render_abstract(outfile, abstract, start_page=None):
    """ Writes the LaTeX string corresponding to one abstract.
    """
    if start_page is not None:
        outfile.write(r"""
\setcounter{page}{%i}
""" % start_page)
    else:
        if hasattr(abstract, 'start_page'):
            start_page = abstract.start_page
        else:
            start_page = 1
    if not abstract.authors:
        author_list = abstract.owners
    else:
        author_list = abstract.authors
    authors = []
    print dir(author_list[0])
    for author in author_list:
        # If the author has no surname, he is not an author 
        if author.surname:
            if author.email_address:
                email = r'(\email{%s})' % author.email_address
            else:
                email = ''
            authors.append(ur'''\otherauthors{
                            %s %s
                            %s --
                            \address{%s, %s}
                            }''' % (author.first_names, author.surname,
                                    email,
                                    author.institution,
                                    author.city))
    if authors:
        authors = u'\n'.join(authors)
        authors += r'\addauthorstoc{%s}' % ', '.join(
                '%s. %s' % (author.first_names[0], author.surname)
                for author in author_list
                )
        author_cite_list = ['%s. %s' % (a.first_names[0], a.surname) 
                                for a in author_list]
        if len(author_cite_list) > 4:
            author_cite_list = author_cite_list[:3]
            author_cite_list.append('et al.')
        citation = ', '.join(author_cite_list) + \
        'in Proc. SciPy 2009, G. Varoquaux, S. van der Walt, J. Millman (Eds), '
        copyright = '\\copyright 2009, %s' % ( ', '.join(author_cite_list))
    else:
        authors = ''
        citation = 'Citation'
        copyright = 'Copyright'
    if hasattr(abstract, 'num_pages'):
        citation += 'pp. %i--%i' % (start_page, start_page +
                                        abstract.num_pages)
    else:
        citation += 'p. %i'% start_page
    if hasattr(abstract, 'number'):
        abstract.url = 'http://conference.scipy.org/proceedings/%s/paper_%i' \
        % (conf_name, abstract.number)
        url = r'\url{%s}' % abstract.url
    else:
        url = ''
    paper_text = abstract.paper_text
    if paper_text == '':
        paper_text = abstract.summary
    # XXX: It doesn't seem to be right to be doing this, but I get a
    # nasty UnicodeDecodeError on some rare abstracts, elsewhere.
    paper_text = codecs.utf_8_decode(hack_include_graphics(
                                rst2latex(paper_text)))[0]
    paper_abstract = abstract.paper_abstract
    if paper_abstract is None:
        paper_abstract = ''
    if not paper_abstract=='':
        paper_abstract = ur'\begin{abstract}%s\end{abstract}' % \
                    paper_abstract#.encode('utf-8')
    abstract_dict = {
            'text': paper_text.encode('utf-8'),
            'abstract': paper_abstract.encode('utf-8'),
            'authors': authors.encode('utf-8'),
            'title': abstract.title.encode('utf-8'),
            'citation': citation.encode('utf-8'),
            'copyright': copyright.encode('utf-8'),
            'url': url.encode('utf-8'),
        }
    outfile.write(codecs.utf_8_decode(ur'''
\phantomsection
\hypertarget{chapter}{} 
\vspace*{-2em}

\resetheadings{%(title)s}{%(citation)s}{%(url)s}{%(copyright)s}
\title{%(title)s}

\begin{minipage}{\linewidth}
%(authors)s
\end{minipage}

\noindent\rule{\linewidth}{0.2ex}
\vspace*{-0.5ex}
\twocolumngrid
%(abstract)s

\sloppy

%(text)s

\fussy
\onecolumngrid
\smallskip
\vfill
\filbreak
\clearpage

'''.encode('utf-8') % abstract_dict )[0])

def copy_files(dest=outfilename):
    """ Copy the required file from the source dir to the output dir.
    """
    dirname = os.path.dirname(dest)
    if dirname == '':
        dirname = '.'
    for filename in glob(sourcedir+os.sep+'*'):
        destfile = os.path.abspath(dirname + os.sep +
                                os.path.basename(filename))
        shutil.copy2(filename, destfile)


def mk_abstract_preview(abstract, outfilename, attach_dir, start_page=None):
    """ Generate a preview for an given paper.
    """
    copy_files()
    outdir = os.path.dirname(os.path.abspath(outfilename))
    for f in glob(os.path.join(attach_dir, '*')):
        if  os.path.isdir(f) and not os.path.exists(f):
            os.makedirs(f)
        else:
            if not outdir == os.path.dirname(os.path.abspath(f)):
                shutil.copy2(f, outdir)
    for f in glob(os.path.join(sourcedir, '*')):
        if  os.path.isdir(f):
            os.makedirs(f)
        else:
            destfile = os.path.abspath(os.path.join(outdir, f))
            shutil.copy2(f, outdir)

    outbasename = os.path.splitext(outfilename)[0]
    outfilename = outbasename + '.tex'

    outfile = codecs.open(outfilename, 'w', 'utf-8')
    preamble(outfile)
    render_abstract(outfile, abstract, start_page=start_page)
    outfile.write(ur'\end{document}' + u'\n')
    outfile.close()

    tex2pdf(outbasename, remove_tex=False)
    abstract.num_pages = count_pages(outbasename + '.pdf')

    # Generate the tex file again, now that we know the length.
    outfile = codecs.open(outfilename, 'w', 'utf-8')
    preamble(outfile)
    render_abstract(outfile, abstract, start_page=start_page)
    outfile.write(ur'\end{document}' + u'\n')
    outfile.close()

    return tex2pdf(os.path.splitext(outfilename)[0], remove_tex=False)


##############################################################################
# Code for using outside of the webapp.
##############################################################################

def mk_zipfile():
    """ Generates a zipfile with the required files to build an
        abstract.
    """
    from zipfile import ZipFile
    zipfilename = os.path.join(os.path.dirname(__file__), 
                            'mk_scipy_paper.zip')
    z = ZipFile(zipfilename, 'w')
    for filename in glob(os.path.join(sourcedir, '*')):
        if not os.path.isdir(filename):
            z.write(filename, arcname='source/' + os.path.basename(filename))
    z.write(__file__, arcname='mk_scipy_paper.py')
    return zipfilename

class Bunch(dict):
    def __init__(self, **kwargs):
        dict.__init__(self, **kwargs)
        self.__dict__ = self

    def __reprt(self):
        return repr(self.__dict__)

author_like = Bunch(
        first_names='XX', 
        surname='XXX',
        email_address='xxx@XXX',
        institution='XXX',
        address='XXX',
        country='XXX'
)


abstract_like = Bunch(
        paper_abstract='An abstract',
        authors=[author_like, ],
        title='',
    )

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="outfilename",
                    default="./paper.pdf",
                    help="output to FILE", metavar="FILE")
    parser.usage = """%prog [options] rst_file [data_file]
    Compiles a given rest file and information file to pdf for the SciPy
    proceedings.
    """
    
    (options, args) = parser.parse_args()
    if not len(args) in (1, 2):
        print "One or two arguments required: the input rest file and " \
                "the input data file"
        print ''
        parser.print_help()
        sys.exit(1)
    infile = args[0]
    if len(args)==1:
        data_file = 'data.py'
        if os.path.exists('data.py'):
            print "Using data file 'data.py'"
        else:
            print "Generating the data file and storing it in data.py"
            print "You will need to edit this file to add title, author " \
                "information, and abstract."
            abstract = abstract_like
            file('data.py', 'w').write(repr(abstract))
    elif len(args)==2:
        data_file = args[1]
    
    abstract = Bunch( **eval(file(data_file).read()))
    abstract.authors = [Bunch(**a) for a in abstract.authors]

    abstract['summary'] = u''
    abstract['paper_text'] = file(infile).read().decode('utf-8')

    outfilename = options.outfilename

    mk_abstract_preview(abstract, options.outfilename, 
                        os.path.dirname(options.outfilename))
    # Ugly, but I don't want to wait on the thread.
    sys.exit()