Fix for dc:creator and dc:date tag – make it as described in OPF 2.0.1 spec.
[librarian.git] / librarian / fb2.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 import os.path
7 from copy import deepcopy
8 from lxml import etree
9
10 from librarian import functions, OutputFile
11 from .epub import replace_by_verse
12
13
14 functions.reg_substitute_entities()
15 functions.reg_person_name()
16
17
18 def sectionify(tree):
19     """Finds section headers and adds a tree of _section tags."""
20     sections = ['naglowek_czesc',
21             'naglowek_akt', 'naglowek_rozdzial', 'naglowek_scena',
22             'naglowek_podrozdzial']
23     section_level = dict((v,k) for (k,v) in enumerate(sections))
24
25     # We can assume there are just subelements an no text at section level.
26     for level, section_name in reversed(list(enumerate(sections))):
27         for header in tree.findall('//' + section_name):
28             section = header.makeelement("_section")
29             header.addprevious(section)
30             section.append(header)
31             sibling = section.getnext()
32             while (sibling is not None and
33                     section_level.get(sibling.tag, 1000) > level):
34                 section.append(sibling)
35                 sibling = section.getnext()
36
37
38 def transform(wldoc, verbose=False,
39               cover=None, flags=None):
40     """ produces a FB2 file
41
42     cover: a cover.Cover object or True for default
43     flags: less-advertising, working-copy
44     """
45
46     document = deepcopy(wldoc)
47     del wldoc
48
49     if flags:
50         for flag in flags:
51             document.edoc.getroot().set(flag, 'yes')
52
53     style_filename = os.path.join(os.path.dirname(__file__), 'fb2/fb2.xslt')
54     style = etree.parse(style_filename)
55
56     replace_by_verse(document.edoc)
57     sectionify(document.edoc)
58
59     result = document.transform(style)
60
61     return OutputFile.from_string(unicode(result).encode('utf-8'))
62
63 # vim:et