aboutsummaryrefslogtreecommitdiff
path: root/mammoth/__init__.py
blob: 195e8182732a516f718be22e63e78c81e2d9a1ca (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
from .results import Result
from . import docx, documents


def convert_to_html(fileobj):
    document = docx.read(fileobj).value
    html = _convert_element_to_html(document)
    return Result(html, [])


def _convert_element_to_html(element):
    return _converters[type(element)](element)
    

_converters = {}


def converter(element_type):
    def add(func):
        _converters[element_type] = func
        
    return add


@converter(documents.Document)
def convert_document(document):
    return _convert_elements_to_html(document.children)


@converter(documents.Paragraph)
def convert_paragraph(paragraph):
    return "<p>{0}</p>".format(_convert_elements_to_html(paragraph.children))


@converter(documents.Run)
def convert_run(run):
    return _convert_elements_to_html(run.children)


@converter(documents.Text)
def convert_text(text):
    return text.value


def _convert_elements_to_html(elements):
    return "".join(map(_convert_element_to_html, elements))