Source

sws2tex / html2latex.py

Full commit
  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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
###############################################################################
#   Sage: Open Source Mathematical Software
#       Copyright (C) 2009-2010 Wilfried Huss <huss@finanz.math.tugraz.at>
#       Copyright (C) 2009-2010 Robert Marik <marik@mendelu.cz>
#  Distributed under the terms of the GNU General Public License (GPL),
#  version 2 or any later version.  The full text of the GPL is available at:
#                  http://www.gnu.org/licenses/
###############################################################################

r"""
Try to convert HTML code created by TinyMCE into proper LaTeX syntax.
Only a small subset of HTML tags is supported.
"""

import HTMLParser
import string
import re
import os

def download_file(url, localFile = None, directory = None):
    r"""
    Download a url from the Web, and copy it to the location
    specified by directory/localFile.

    If directory is None, use the current directory.
    If localFile is None, use the part of the url after the last '/'
    as the file name.
    """
    import urllib2

    print "Downloading file: ", url
    try:
        urlHandle = urllib2.urlopen(url)

        if localFile is None:
            localFile = url.split('/')[-1]

        if not directory is None:
            localFile = directory + '/' + localFile
        localHandle = open(localFile, 'w')

        localHandle.write(urlHandle.read())

        urlHandle.close()
        localHandle.close()
    except urllib2.HTTPError, error:
        print "Unable to download file: ", url
        print error.msg

def detect_math(text):
    r"""
        Replace TeX math delimiters $...$ and $$...$$ with the corresponding
        forms of jsmath:

        <span class="math">...</span>
        <div class="math">...</div>

    TESTS::

        sage: s = "$$x$$abs$inline math$defg$$display math x^2$$hijk$inline math$lmno$$\mathbf{A}$$"
        sage: detect_math(s)
        '\n<div class="math">\nx\n</div>\nabs<span class="math">inline math</span>defg\n<div class="math">\ndisplay math x^2\n</div>\nhijk<span class="math">inline math</span>lmno\n<div class="math">\n\\mathbf{A}\n</div>\n'
    """
    import itertools
    # find math inside $$...$$
    text_list = text.split('$$')

    text = []
    for tag, line in zip(itertools.cycle(['<div class="math">', '</div>']),text_list):
        text.append(line)
        text.append(tag)

    if text[-1] == '<div class="math">':
        text = text[:-1]

    text = string.join(text, '\n')

    # find math inside $...$
    text_list = text.split('$')

    text = []
    for tag, line in zip(itertools.cycle(['<span class="math">', '</span>']),text_list):
        text.append(line)
        text.append(tag)

    if text[-1] == '<span class="math">':
        text = text[:-1]

    text = string.join(text, '')
    return text

#htmlentitydefs.entitydefs
entities = {
    "eacute": "\\'{e}",
    "iacute": "\\'{\i}",
    "aacute": "\\'{a}",
    "uacute": "\\'{u}",
    "Uacute": "\\'{U}",
    "yacute": "\\'{y}",
    "scaron": "\\v{s}",
    "Scaron": "\\v{S}",
    "auml": '\\"{a}',
    "ouml": '\\"{o}',
    "uuml": '\\"{u}',
    "Auml": '\\"{A}',
    "Ouml": '\\"{O}',
    "Uuml": '\\"{U}',
    "szlig": '\\ss{}',
    "nbsp": "~",
    "lt": ("$<$", " < "),
    "gt": ("$>$", " > "),
    "amp": ("\\&", "&")
}

class Html2Latex(HTMLParser.HTMLParser):

    def __init__(self, options = None, cell_id = None, temp_dir = None):
        HTMLParser.HTMLParser.__init__(self)
        self.options = options
        self.cell_id = cell_id
        self.temp_dir = temp_dir
        self.in_math_mode = False
        self.latex = ['']                # latex code
        self.data = ''

        self.stack = []

    def add_data(self):
        self.latex[-1] += self.data
        self.data = ''

    def tag2string(self, tag, attrs, startendtag = False):
        if len(attrs) == 0:
            return "<%s>" % tag

        attr_string = []
        for (key, value) in attrs:
            attr_string.append('%s="%s"' % (key, value))

        tag_end = ">"
        if startendtag:
            tag_end = "/>"

        return "<%s " % tag + string.join(attr_string, ' ') + tag_end

    def parse_style(self, style_text):
        r"""
        Parsing html style to LaTeX equivalents. 

        The following syles are supported: color, background-color,
        text-align, font-family.
        """
        style = {}
        color = re.compile('color: #([0-9a-f]{6});')
        color_match = color.match(style_text)
        if color_match is not None:
            text_color = color_match.group(1).upper()
            style['color'] = text_color

        color = re.compile('background-color: #([0-9a-f]{6});')
        color_match = color.match(style_text)
        if color_match is not None:
            background_color = color_match.group(1).upper()
            style['background-color'] = background_color

        align = re.compile('text-align: (.*?);')
        align_match = align.match(style_text)
        if align_match is not None:
            alignment = align_match.group(1)
            style['align'] = alignment

        font_family = re.compile('font-family: (.*?);')
        font_match = font_family.match(style_text)
        if font_match is not None:
            fontstyle = font_match.group(1)
            style['font-family'] = fontstyle

        #print style

        return style

    def handle_starttag(self, tag, attrs):
        r"""
        Replace start of a html tag by LaTeX equivalent. 

        The following tags are recognized: span (see parse_style for
        styles which are recognized), div, p, ul, ol, li, a, em,
        strong, h1, h2, h3, h4, small, font (font tag is simply
        skipped)
        """
        #print self.tag2string(tag,attrs)
        #print tag
        #print attrs
        self.add_data()
        self.latex.append('')
        if tag == 'span':
            if dict(attrs).get('class') == 'math':
                self.in_math_mode = True
                self.latex[-1] += '$'

            style_text = dict(attrs).get('style')
            if style_text is not None:
                style = self.parse_style(style_text)
                if style.has_key('color'):
                    self.latex[-1] += '{\\color[HTML]{%s}' % style.get('color')

                if style.has_key('background-color'):
                    self.latex[-1] += '\\colorbox[HTML]{%s}{' % style.get('background-color')

                if style.has_key('font-family'):
                    if style['font-family'] == 'courier new,courier':
                        self.latex[-1] += '{\\ttfamily '
                    elif style['font-family'] == 'helvetica':
                        self.latex[-1] += '{\\sffamily '
                    elif style['font-family'] == 'arial,helvetica,sans-serif':
                        self.latex[-1] += '{\\sffamily '
                    else:
                        self.latex[-1] += '{'

            self.stack.append(attrs)

        elif tag == 'div' and dict(attrs).get('class') == 'math':
            self.in_math_mode = True
            self.latex[-1] += '$$'
        elif tag == 'p':
            style_text = dict(attrs).get('style')
            if style_text is not None:
                style = self.parse_style(style_text)
                if style.has_key('align'):
                    if style['align'] == "right":
                        self.latex[-1] += '\n\n{\\leftskip 0 pt plus 1 fill \\rightskip 0 pt\n '
                    elif style['align'] == "center":
                        self.latex[-1] += '\n\n{\\leftskip 0 pt plus 1 fill \\rightskip 0 pt plus 1 fill\n '
                    else:
                        self.latex[-1] += '\n\n{\n '                
            else:
                self.latex[-1] += '\n\n{\n '                
        elif tag == 'ul':
            self.latex[-1] += '\\begin{itemize}\n'
        elif tag == 'ol':
            self.latex[-1] += '\\begin{enumerate}\n'
        elif tag == 'li':
            self.latex[-1] += r'\item '
        elif tag == 'a':
            href = dict(attrs).get('href')
            name = dict(attrs).get('name')
            if href is not None and href[0] != '#': # Weblink
                self.latex[-1] += '\\href{%s}{' % href
            elif name is not None:
                self.latex[-1] += '\\label{%s}' % name

            self.stack.append(attrs)
        elif tag == 'em':
            self.latex[-1] += '{\\itshape '
        elif tag == 'strong':
            self.latex[-1] += '{\\bfseries '
        elif tag == 'h1':
            if dict(attrs).get('class') == 'star':
                self.latex[-1] += '\\section*{'
            else:
                self.latex[-1] += '\\section{'
        elif tag == 'h2':
            if dict(attrs).get('class') == 'star':
                self.latex[-1] += '\\subsection*{'
            else:
                self.latex[-1] += '\\subsection{'
        elif tag == 'h3':
            if dict(attrs).get('class') == 'star':
                self.latex[-1] += '\\subsubsection*{'
            else:
                self.latex[-1] += '\\subsubsection{'
        elif tag == 'h4':
            self.latex[-1] += '\\paragraph{'
        elif tag == 'small':
            self.latex[-1] += '{\\footnotesize '
        elif tag == 'font':
            pass
        elif tag == 'img':
            # dict(attrs).get('src') looks like cell://name.png
            self.latex[-1] += "\\includegraphics{sage_worksheet/cells/%s/%s}" % (self.cell_id,dict(attrs).get('src')[7:])
        elif tag == 'style':
            self.latex[-1] += r'\iffalse % style commented out '
        else:
            if self.options != None and not self.options.ignore_unknown_tags:
                self.latex[-1] += self.tag2string(tag, attrs)

    def handle_endtag(self, tag):
        r""" 
        Replace end of a html tag by LaTeX equivalent. See
        handle_starttag for list of supported tags.
        """
        #print "</%s>" % tag
        if tag == 'span':
            if self.in_math_mode == True:
                self.in_math_mode = False
                self.add_data()
                self.latex[-1] += '$'

            attrs = self.stack.pop()
            style_text = dict(attrs).get('style')
            if style_text is not None:
                style = self.parse_style(style_text)
                if style.has_key('color'):
                    self.add_data()
                    self.latex[-1] += '}' # close \textcolor

                if style.has_key('background-color'):
                    self.add_data()
                    self.latex[-1] += '}' # close \colorbox

                if style.has_key('font-family'):
                    self.add_data()
                    self.latex[-1] += '}' # close group
            try:
                self.add_data()  # to make test_3 below work
            except:
                pass


        elif tag == 'div' and self.in_math_mode == True:
            self.in_math_mode = False
            self.add_data()
            self.latex[-1] += '$$'
        elif tag == 'p':
            self.add_data()
            self.latex[-1] += '\par}\n\n'
        elif tag == 'ul':
            self.add_data()
            self.latex[-1] += '\\end{itemize}\n'
        elif tag == 'ol':
            self.add_data()
            self.latex[-1] += '\\end{enumerate}\n'
        elif tag == 'li':
            self.add_data()
        elif tag == 'a':
            attrs = self.stack.pop()
            href = dict(attrs).get('href')
            name = dict(attrs).get('name')
            if href is not None and href[0] != '#': # Weblink
                self.add_data()
                self.latex[-1] += '}'
            elif name is not None:
                self.add_data()
            elif href is not None and href[0] == '#': # internal link
                self.add_data()
                self.latex[-1] += ' (\\autoref{%s})' % href[1:]

            #self.handle_a()
        elif tag == 'em':
            self.add_data()
            self.latex[-1] += '}'
        elif tag == 'strong':
            self.add_data()
            self.latex[-1] += '}'
        elif tag == 'small':
            self.add_data()
            self.latex[-1] += '}'
        elif tag == 'h1' or tag == 'h2' or tag == 'h3' or tag == 'h4':
            self.add_data()
            self.latex[-1] += '}'
        elif tag == 'font':
            self.add_data()
        elif tag == 'style':
            self.add_data()
            self.latex[-1] += '\\fi \n'
        else:
            self.add_data()
            if self.options != None and not self.options.ignore_unknown_tags:
                self.latex[-1] += "</%s>" % tag

        self.data += self.latex.pop()

    def handle_startendtag(self, tag, attrs):
        r"""
        Replace tags which do not have open/close pair.
        
        Supported tags are p, br, hr, a, img.

        Tags <img .../> are inserted by TinyMCE.
        """
        self.add_data()
        self.latex.append('')

        if tag == 'p':
            self.latex[-1] += '\n\n'
        elif tag == 'br':
            self.latex[-1] += '\n\n'
        elif tag == 'hr':
            self.latex[-1] += '\n\n\\hrule\n\n'
        elif tag == 'a':
            exit(1)
            self.stack.append(attrs)
            self.handle_a()
        elif tag == 'img':
            # dict(attrs).get('src') looks like http://.... or file.png
            where_is=dict(attrs).get('src')[0:4]
            img_options = []
            if dict(attrs).get('width') is not None:
                img_options += ["width=%spx" % dict(attrs).get('width')]
            if dict(attrs).get('height') is not None:
                img_options += ["height=%spx" % dict(attrs).get('height')]
            img_options = ",".join(img_options)
            if where_is == 'http':
                url = dict(attrs).get('src')
                download_file(url, directory = self.temp_dir)

                file = dict(attrs).get('src').split('/')
                file = file[len(file)-1]
                self.latex[-1] += "\\includegraphics[%s]{%s}" % (img_options,file)
            else:
                self.latex[-1] += "\\includegraphics[%s]{sage_worksheet/data/%s}" % (img_options,dict(attrs).get('src'))
        else:
            self.add_data()
            if self.options != None and not self.options.ignore_unknown_tags:
                self.latex[-1] += self.tag2string(tag, attrs)

        self.data += self.latex.pop()

    def handle_a(self):
        #print "TEST: handle_a"
        attrs = dict(self.stack.pop())
        href = attrs.get('href')
        name = attrs.get('name')

        if href is not None:
            if href[0] == '#': # internal link
                self.add_data()
                self.latex[-1] += ' (\\autoref{%s})' % href[1:]
            else: # Weblink
                self.latex[-1] += '\\href{%s}{%s}' % (href, self.data)
                self.data = ''
        elif name is not None:
            self.latex[-1] += '\\label{%s}' % name
            self.add_data()

    def handle_data(self, data):
        #print "DATA: " + data
        if self.in_math_mode:
            self.data += data
        else:
            data = string.replace(data, "_", "\_")
            data = string.replace(data, "^", "\^{ }")
            self.data += data

        #print "-----------------------------------------------------"
        #print "SELF DATA: " + self.data
        #print "-----------------------------------------------------"

    def handle_entityref(self, name):
        #print name
        ref = entities.get(name)
        if ref is not None:
            if isinstance(ref, tuple):
                if self.in_math_mode:
                    self.data += ref[1]
                else:
                    self.data += ref[0]
            else:
                self.data += ref

    def parse_html(self, text, OutputCell = False, cell_id = None, temp_dir = None):
        r"""
        Parse html into LaTeX

            sage: A=Html2Latex()
            sage: A.parse_html(r"<p><span>We multiply the last row by $-1$ and add to the first row</span></p>")
            '\n\n{\n We multiply the last row by $-1$ and add to the first row\\par}\n\n'
        
            sage: A=Html2Latex()
            sage: A.parse_html(r'T_hi_s i^s $a^2_x$ Test_ $$x^2$$ <a href="nothing">HTML</a> string.$sin(x)$test')
            'T\\_hi\\_s i\\^{ }s $a^2_x$ Test\\_ \n$$\nx^2\n$$\n \\href{nothing}{HTML} string.$sin(x)$test'

            sage: A=Html2Latex()
            sage: A.parse_html(r'<p>Nested Tags: <a href="http://www.sagemath.org">This is <strong>all <em>inside a html $x^2$ link to the</em> sage</strong> website.</a> Outside of link.</p>')
            '\n\n{\n Nested Tags: \\href{http://www.sagemath.org}{This is {\\bfseries all {\\itshape inside a html $x^2$ link to the} sage} website.} Outside of link.\\par}\n\n'

        Paragraph alignment is recognized::
        
            sage: A=Html2Latex()
            sage: A.parse_html(r'<p style="text-align: right;">aligned paragraph</p>', OutputCell = False)
            '\n\n{\\leftskip 0 pt plus 1 fill \\rightskip 0 pt\n aligned paragraph\\par}\n\n'
            
        Pictures::

            sage: A=Html2Latex()
            sage: A.parse_html('<img src="cell://file.png"></img>', cell_id = 9)
            '\\includegraphics{sage_worksheet/cells/9/file.png}'

            sage: A=Html2Latex()
            sage: A.parse_html('<img src="file.png"/>')
            '\\includegraphics[]{sage_worksheet/data/file.png}'

        """
        text = detect_math(text)
        self.cell_id = cell_id
        self.temp_dir = temp_dir
        self.feed(text)        

        if OutputCell:
            return self.data
        else:
            return self.latex[0] + self.data

test_str = r"""

T_hi_s i^s $a^2_x$ Test_ $$x^2$$ <a href="nothing">HTML</a>
string.$sin(x)$test
"""

test_2 = r"""
<p>Nested Tags: <a href="http://www.sagemath.org">This is <strong>all <em>inside a html $x^2$ link to the</em> sage</strong> website.</a> Outside of link.</p>
"""


test_3 = r"""
<p><span>We multiply the last row by $-1$ and add to the first row</span></p>
"""

# Test program
if __name__ == '__main__':
    parser = Html2Latex()
    print parser.parse_html(test_3)