markdowntei.py 1.94 KB
'Markdown to TEI converter'

import re
import metadata
from tei import Tei, Utterance
from splitter import split_sessions


class MarkdownTei:
    'Converter from Markdown to TEI'

    def __init__(self):
        self.who = 'komentarz'
        self.committees = {}

    def convert(self, filename, output):
        'Convert file to TEI'
        self.who = 'komentarz'
        data = list(filter(None, [self._utterance(par)
                                  for par in self._read(filename)]))
        sessions = split_sessions(data)
        if len(sessions) > 1:
            for index, session in enumerate(sessions):
                filemeta = metadata.metadata(
                    session[0:10], f'{filename}:{index+1}')
                # self._autofill_metadata(filemeta)
                metadata.validate(filemeta)
                tei = Tei(session, filemeta)
                tei.save(output)
        else:
            filemeta = metadata.metadata(data[0:10], filename)
            metadata.validate(filemeta)
            tei = Tei(sessions[0], filemeta)
            tei.save(output)

    @ staticmethod
    def _read(filename):
        return filter(None, [par.strip() for par in open(filename)])

    def _utterance(self, par):
        match = re.match(r'\*\((.*)\)\*', par)
        if match:
            return Utterance(who='komentarz', u=match.group(1))
        match = re.match(r'\*\*(.*):\*\*', par)
        if match:
            self.who = match.group(1)
            return None
        return Utterance(who=self.who, u=par)

    def _autofill_metadata(self, filemeta):
        if '??' not in filemeta['sessionNo']:
            return
        if '??' in filemeta['abbreviation']:
            return
        name = filemeta['type']
        if name not in self.committees:
            self.committees[name] = 0
        self.committees[name] += 1
        filemeta['sessionNo'] = str(self.committees[name])
        print(f'Set {filemeta["type"]} to {self.committees[name]}')