markdowntei.py 1.42 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'

    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}')
                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)