1 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
4 from collections import Counter
10 from .parser import parser
11 from . import dcparser, DCNS, RDFNS, DirDocProvider
12 from .functions import lang_code_3to2
16 def __init__(self, filename=None, url=None, provider=None):
17 source = filename or urllib.request.urlopen(url)
18 tree = etree.parse(source, parser=parser)
20 tree.getroot().document = self
24 self.base_meta = dcparser.BookInfo({}, {
25 DCNS('language'): ["pol"],
26 }, validate_required=False)
28 self.provider = provider if provider is not None else DirDocProvider('.')
30 self.tree.getroot().validate()
34 # Allow metadata of the master element as document meta.
35 #master = self.tree.getroot()[-1]
36 return self.tree.getroot().meta
40 # Change slash-verses into real verses.
41 for _e, elem in etree.iterwalk(self.tree, ('start',), 'strofa'):
46 for part_uri in self.meta.parts or []:
47 with self.provider.by_slug(part_uri.slug) as f:
49 yield type(self)(filename=f, provider=self.provider)
50 except Exception as e:
54 def build(self, builder, base_url=None, **kwargs):
55 return builder(base_url=base_url).build(self, **kwargs)
58 persons = set(self.meta.editors
59 + self.meta.technical_editors)
60 for child in self.children:
61 persons.update(child.editors())
67 return self.tree.findall('.//ref')
69 def get_statistics(self):
70 def count_text(text, counter, in_fn=False, stanza=False):
72 text = re.sub(r'\s+', ' ', text)
74 chars = len(text) if text.strip() else 0
75 words = len(text.split()) if text.strip() else 0
77 counter['chars_with_fn'] += chars
78 counter['words_with_fn'] += words
80 counter['chars'] += chars
81 counter['words'] += words
83 counter['chars_out_verse_with_fn'] += chars
85 counter['chars_out_verse'] += chars
87 def count(elem, counter, in_fn=False, stanza=False):
88 if elem.tag in (RDFNS('RDF'), 'nota_red', 'abstrakt', 'uwaga', 'ekstra'):
90 if not in_fn and elem.tag in ('pa', 'pe', 'pr', 'pt', 'motyw'):
92 if elem.tag == 'strofa':
94 #verses = len(elem.findall('.//br')) + 1
95 verses = list(elem.get_verses())
96 counter['verses_with_fn'] += len(verses)
98 counter['verses'] += len(verses)
102 count(child, counter, in_fn=in_fn, stanza=True)
104 count_text(elem.text, counter, in_fn=in_fn, stanza=stanza)
106 count(child, counter, in_fn=in_fn, stanza=stanza)
107 count_text(child.tail, counter, in_fn=in_fn, stanza=stanza)
116 count(self.tree.getroot(), data['self'])
117 for k, v in data['self'].items():
120 for part in self.children:
121 if isinstance(part, Exception):
122 data['parts'].append((None, {'error': part}))
124 data['parts'].append((part, part.get_statistics()))
125 for k, v in data['parts'][-1][1]['total'].items():
126 data['total'][k] = data['total'].get(k, 0) + v