Skip to content

converter

This file contains classes to convert files to the Giella xml format.

Converter

Take care of data common to all Converter classes.

Source code in corpustools/converter.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
class Converter:
    """Take care of data common to all Converter classes."""

    def __init__(
        self,
        filename: CorpusPath,
        lazy_conversion: bool = False,
        write_intermediate: bool = False,
    ):
        """Initialise the Converter class.

        Args:
            filename: the path to the file that should be converted
            write_intermediate: whether intermediate versions of the
                 converted document should be written (used for debugging purposes).
        """
        codecs.register_error("mixed", self.mixed_decoder)
        self.names = filename
        self.lazy_conversion = lazy_conversion
        self.write_intermediate = write_intermediate
        try:
            self.metadata = self.names.metadata
        except xslsetter.XsltError as error:
            raise util.ConversionError(error) from error

        self.metadata.set_lang_genre_xsl()
        with util.ignored(OSError):
            os.makedirs(self.tmpdir)

    @property
    def dependencies(self):
        """Return files that converted files depend on."""
        return [self.names.orig, self.names.xsl]

    @property
    def standard(self):
        """Return a boolean indicating if the file is convertable."""
        return self.metadata.get_variable("conversion_status") == "standard"

    @property
    def ocr(self):
        """Return a boolean indicating if the file is convertable."""
        return self.metadata.get_variable("conversion_status") == "ocr"

    @property
    def goldstandard(self):
        """Return a boolean indicating if the file is a gold standard doc."""
        return self.metadata.get_variable("conversion_status").startswith("correct")

    @staticmethod
    def get_dtd_location():
        """Return the path to the corpus dtd file."""
        return os.path.join(HERE, "dtd/corpus.dtd")

    def validate_complete(self, complete: etree.Element):
        """Validate the complete document."""
        dtd = etree.DTD(Converter.get_dtd_location())

        if not dtd.validate(complete):
            self.names.log.write_text(
                f"Error at: {str(util.lineno())}"
                + "\n".join(str(entry) for entry in dtd.error_log)
                + "\n".join(util.print_element(complete, 0, 4))
            )

            raise util.ConversionError(
                "{}: Not valid XML. More info in the log file: {}".format(
                    type(self).__name__, self.names.log
                )
            )

    def to_giella(self, path: Path) -> etree.Element:
        """Convert a document to the giella xml format.

        Args:
            path: path to the document

        Returns:
            The converted document as an lxml Element.
        """
        chooser: dict[str, Callable] = {
            ".doc": htmlcontentconverter.convert2intermediate,
            ".docx": htmlcontentconverter.convert2intermediate,
            ".epub": htmlcontentconverter.convert2intermediate,
            ".html": htmlcontentconverter.convert2intermediate,
            ".odt": htmlcontentconverter.convert2intermediate,
            ".pdf": htmlcontentconverter.convert2intermediate,
            ".rtf": htmlcontentconverter.convert2intermediate,
            ".svg": svgconverter.convert2intermediate,
            ".txt": plaintextconverter.convert2intermediate,
            ".tex": htmlcontentconverter.convert2intermediate,
            ".writenow": htmlcontentconverter.convert2intermediate,
            ".usx": usxconverter.convert2intermediate,
            ".correct.txt": error_annotated_converter.convert2intermediate,
        }

        str_path = path.absolute().as_posix()
        if "avvir_xml" in str_path:
            return avvirconverter.convert2intermediate(path)
        elif str_path.endswith("bible.xml"):
            return biblexmlconverter.convert2intermediate(path)
        elif "udhr_" in str_path and path.suffix == ".xml":
            return htmlcontentconverter.convert2intermediate(path)
        elif (
            self.metadata.get_variable("conversion_status") == "ocr"
            and path.suffix == ".pdf"
        ):
            return ocrconverter.to_xml(
                path,
                language=("sme_gt" if "corpus-sme" in str_path else "nor"),
            )  # hardcoded until further notice
        elif path.name.endswith(".correct.txt"):
            return error_annotated_converter.convert2intermediate(path)
        else:
            return chooser[path.suffix](path)

    def transform_to_complete(self):
        """Combine the intermediate xml document with its medatata."""
        try:
            intermediate = self.to_giella(self.names.orig)
        except KeyError as error:
            raise util.ConversionError(
                "{} can not convert files of this format {}:".format(
                    self.names.orig, str(error)
                )
            ) from error
        try:
            self.fix_document(intermediate)
        except etree.XMLSyntaxError as error:
            with open(self.names.log, "w") as logfile:
                logfile.write(f"Error at: {str(util.lineno())}")

            raise util.ConversionError(
                f"Syntax error in: {self.names}\nError {str(error)}"
            ) from error

        try:
            xsl_maker = xslmaker.XslMaker(self.metadata.tree)
            complete = xsl_maker.transformer(intermediate)

            return complete.getroot()
        except etree.XSLTApplyError:
            with open(self.names.log, "w") as logfile:
                logfile.write(f"Error at: {str(util.lineno())}")

            raise util.ConversionError(
                f"Check the syntax in: {self.names.xsl}"
            ) from None
        except etree.XSLTParseError as error:
            with open(self.names.log, "w") as logfile:
                logfile.write(f"Error at: {str(util.lineno())}")

            raise util.ConversionError(
                f"XSLTParseError in: {self.names.xsl}\nError {str(error)}"
            ) from error

    def fix_document(self, complete):
        """Fix a misc. issues found in converted document."""
        fixer = documentfixer.DocumentFixer(complete)

        fixer.fix_newstags()
        fixer.soft_hyphen_to_hyph_tag()
        self.metadata.set_variable("wordcount", fixer.calculate_wordcount())

        if not self.goldstandard:
            fixer.detect_quotes()

        # The above line adds text to hyph, fix that
        for hyph in complete.iter("hyph"):
            hyph.text = None

        if self.metadata.get_variable("mainlang") in [
            "sma",
            "sme",
            "smj",
            "smn",
            "sms",
            "nob",
            "fin",
            "swe",
            "nno",
            "dan",
            "fkv",
            "sju",
            "sje",
            "mhr",
            "mrj",
            "mns",
        ]:
            try:
                fixer.fix_body_encoding(self.metadata.get_variable("mainlang"))
            except UserWarning as error:
                util.print_frame(error)
                util.print_frame(self.names.orig)

    mixed_to_unicode = {
        "e4": "ä",
        "85": "…",  # u'\u2026' ... character.
        "96": "–",  # u'\u2013' en-dash
        "97": "—",  # u'\u2014' em-dash
        "91": "‘",  # u'\u2018' left single quote
        "92": "’",  # u'\u2019' right single quote
        "93": "“",  # u'\u201C' left double quote
        "94": "”",  # u'\u201D' right double quote
        "95": "•",  # u'\u2022' bullet
    }

    def mixed_decoder(self, decode_error):
        """Convert text to unicode."""
        badstring = decode_error.object[decode_error.start : decode_error.end]
        badhex = badstring.encode("hex")
        repl = self.mixed_to_unicode.get(badhex, "\ufffd")
        if repl == "\ufffd":  # � unicode REPLACEMENT CHARACTER
            LOGGER.warn("Skipped bad byte \\x%s, seen in %s", badhex, self.names.orig)
        return repl, (decode_error.start + len(repl))

    def fix_parallels(self, complete):
        for parallel in complete.xpath(".//parallel_text"):
            if not parallel.get("location"):
                parallel.getparent().remove(parallel)

    def make_complete(self, language_guesser):
        """Make a complete Giella xml file.

        Combine the intermediate Giella xml file and the metadata into
        a complete Giella xml file.
        Fix the character encoding
        Detect the languages in the xml file
        """
        complete = self.transform_to_complete()
        self.validate_complete(complete)
        self.fix_parallels(complete)
        lang_detector = languagedetector.LanguageDetector(complete, language_guesser)
        lang_detector.detect_language()

        # Add whitespace to separate header, body and paragraphs
        # and make it easier to see where the diffs are
        complete.find("header").tail = "\n"
        complete.find("body").text = "\n"
        for para in complete.iter("p"):
            para.tail = "\n"

        return complete

    @staticmethod
    def has_content(complete):
        """Find out if the xml document has any content.

        Args:
            complete (lxml.etree.Element): a etree element containing
                the converted document.

        Returns:
            (int): The length of the content in complete.
        """
        xml_printer = ccat.XMLPrinter(all_paragraphs=True, hyph_replacement=None)
        xml_printer.etree = etree.ElementTree(complete)

        return len(xml_printer.process_file().getvalue())

    def write_complete(self, languageguesser):
        """Write the complete converted document to disk.

        Args:
            languageguesser (text.Classifier): a text.Classifier
        """
        if not self.lazy_conversion or (
            self.lazy_conversion
            and newer_group(self.dependencies, self.names.converted)
        ):
            with util.ignored(OSError):
                os.makedirs(os.path.dirname(self.names.converted))

            if self.ocr or self.standard or self.goldstandard:
                complete = self.make_complete(languageguesser)

                if self.has_content(complete):
                    with open(self.names.converted, "w") as converted:
                        print(
                            unicodedata.normalize(
                                "NFC", etree.tostring(complete, encoding="unicode")
                            ),
                            file=converted,
                        )
                else:
                    LOGGER.error("%s has no text", self.names.orig)

    @property
    def tmpdir(self):
        """Return the directory where temporary files should be placed."""
        return self.names.converted_corpus_dir / "tmp"

dependencies property

Return files that converted files depend on.

goldstandard property

Return a boolean indicating if the file is a gold standard doc.

ocr property

Return a boolean indicating if the file is convertable.

standard property

Return a boolean indicating if the file is convertable.

tmpdir property

Return the directory where temporary files should be placed.

__init__(filename, lazy_conversion=False, write_intermediate=False)

Initialise the Converter class.

Parameters:

Name Type Description Default
filename CorpusPath

the path to the file that should be converted

required
write_intermediate bool

whether intermediate versions of the converted document should be written (used for debugging purposes).

False
Source code in corpustools/converter.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def __init__(
    self,
    filename: CorpusPath,
    lazy_conversion: bool = False,
    write_intermediate: bool = False,
):
    """Initialise the Converter class.

    Args:
        filename: the path to the file that should be converted
        write_intermediate: whether intermediate versions of the
             converted document should be written (used for debugging purposes).
    """
    codecs.register_error("mixed", self.mixed_decoder)
    self.names = filename
    self.lazy_conversion = lazy_conversion
    self.write_intermediate = write_intermediate
    try:
        self.metadata = self.names.metadata
    except xslsetter.XsltError as error:
        raise util.ConversionError(error) from error

    self.metadata.set_lang_genre_xsl()
    with util.ignored(OSError):
        os.makedirs(self.tmpdir)

fix_document(complete)

Fix a misc. issues found in converted document.

Source code in corpustools/converter.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def fix_document(self, complete):
    """Fix a misc. issues found in converted document."""
    fixer = documentfixer.DocumentFixer(complete)

    fixer.fix_newstags()
    fixer.soft_hyphen_to_hyph_tag()
    self.metadata.set_variable("wordcount", fixer.calculate_wordcount())

    if not self.goldstandard:
        fixer.detect_quotes()

    # The above line adds text to hyph, fix that
    for hyph in complete.iter("hyph"):
        hyph.text = None

    if self.metadata.get_variable("mainlang") in [
        "sma",
        "sme",
        "smj",
        "smn",
        "sms",
        "nob",
        "fin",
        "swe",
        "nno",
        "dan",
        "fkv",
        "sju",
        "sje",
        "mhr",
        "mrj",
        "mns",
    ]:
        try:
            fixer.fix_body_encoding(self.metadata.get_variable("mainlang"))
        except UserWarning as error:
            util.print_frame(error)
            util.print_frame(self.names.orig)

get_dtd_location() staticmethod

Return the path to the corpus dtd file.

Source code in corpustools/converter.py
113
114
115
116
@staticmethod
def get_dtd_location():
    """Return the path to the corpus dtd file."""
    return os.path.join(HERE, "dtd/corpus.dtd")

has_content(complete) staticmethod

Find out if the xml document has any content.

Parameters:

Name Type Description Default
complete Element

a etree element containing the converted document.

required

Returns:

Type Description
int

The length of the content in complete.

Source code in corpustools/converter.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
@staticmethod
def has_content(complete):
    """Find out if the xml document has any content.

    Args:
        complete (lxml.etree.Element): a etree element containing
            the converted document.

    Returns:
        (int): The length of the content in complete.
    """
    xml_printer = ccat.XMLPrinter(all_paragraphs=True, hyph_replacement=None)
    xml_printer.etree = etree.ElementTree(complete)

    return len(xml_printer.process_file().getvalue())

make_complete(language_guesser)

Make a complete Giella xml file.

Combine the intermediate Giella xml file and the metadata into a complete Giella xml file. Fix the character encoding Detect the languages in the xml file

Source code in corpustools/converter.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
def make_complete(self, language_guesser):
    """Make a complete Giella xml file.

    Combine the intermediate Giella xml file and the metadata into
    a complete Giella xml file.
    Fix the character encoding
    Detect the languages in the xml file
    """
    complete = self.transform_to_complete()
    self.validate_complete(complete)
    self.fix_parallels(complete)
    lang_detector = languagedetector.LanguageDetector(complete, language_guesser)
    lang_detector.detect_language()

    # Add whitespace to separate header, body and paragraphs
    # and make it easier to see where the diffs are
    complete.find("header").tail = "\n"
    complete.find("body").text = "\n"
    for para in complete.iter("p"):
        para.tail = "\n"

    return complete

mixed_decoder(decode_error)

Convert text to unicode.

Source code in corpustools/converter.py
271
272
273
274
275
276
277
278
def mixed_decoder(self, decode_error):
    """Convert text to unicode."""
    badstring = decode_error.object[decode_error.start : decode_error.end]
    badhex = badstring.encode("hex")
    repl = self.mixed_to_unicode.get(badhex, "\ufffd")
    if repl == "\ufffd":  # � unicode REPLACEMENT CHARACTER
        LOGGER.warn("Skipped bad byte \\x%s, seen in %s", badhex, self.names.orig)
    return repl, (decode_error.start + len(repl))

to_giella(path)

Convert a document to the giella xml format.

Parameters:

Name Type Description Default
path Path

path to the document

required

Returns:

Type Description
Element

The converted document as an lxml Element.

Source code in corpustools/converter.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def to_giella(self, path: Path) -> etree.Element:
    """Convert a document to the giella xml format.

    Args:
        path: path to the document

    Returns:
        The converted document as an lxml Element.
    """
    chooser: dict[str, Callable] = {
        ".doc": htmlcontentconverter.convert2intermediate,
        ".docx": htmlcontentconverter.convert2intermediate,
        ".epub": htmlcontentconverter.convert2intermediate,
        ".html": htmlcontentconverter.convert2intermediate,
        ".odt": htmlcontentconverter.convert2intermediate,
        ".pdf": htmlcontentconverter.convert2intermediate,
        ".rtf": htmlcontentconverter.convert2intermediate,
        ".svg": svgconverter.convert2intermediate,
        ".txt": plaintextconverter.convert2intermediate,
        ".tex": htmlcontentconverter.convert2intermediate,
        ".writenow": htmlcontentconverter.convert2intermediate,
        ".usx": usxconverter.convert2intermediate,
        ".correct.txt": error_annotated_converter.convert2intermediate,
    }

    str_path = path.absolute().as_posix()
    if "avvir_xml" in str_path:
        return avvirconverter.convert2intermediate(path)
    elif str_path.endswith("bible.xml"):
        return biblexmlconverter.convert2intermediate(path)
    elif "udhr_" in str_path and path.suffix == ".xml":
        return htmlcontentconverter.convert2intermediate(path)
    elif (
        self.metadata.get_variable("conversion_status") == "ocr"
        and path.suffix == ".pdf"
    ):
        return ocrconverter.to_xml(
            path,
            language=("sme_gt" if "corpus-sme" in str_path else "nor"),
        )  # hardcoded until further notice
    elif path.name.endswith(".correct.txt"):
        return error_annotated_converter.convert2intermediate(path)
    else:
        return chooser[path.suffix](path)

transform_to_complete()

Combine the intermediate xml document with its medatata.

Source code in corpustools/converter.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def transform_to_complete(self):
    """Combine the intermediate xml document with its medatata."""
    try:
        intermediate = self.to_giella(self.names.orig)
    except KeyError as error:
        raise util.ConversionError(
            "{} can not convert files of this format {}:".format(
                self.names.orig, str(error)
            )
        ) from error
    try:
        self.fix_document(intermediate)
    except etree.XMLSyntaxError as error:
        with open(self.names.log, "w") as logfile:
            logfile.write(f"Error at: {str(util.lineno())}")

        raise util.ConversionError(
            f"Syntax error in: {self.names}\nError {str(error)}"
        ) from error

    try:
        xsl_maker = xslmaker.XslMaker(self.metadata.tree)
        complete = xsl_maker.transformer(intermediate)

        return complete.getroot()
    except etree.XSLTApplyError:
        with open(self.names.log, "w") as logfile:
            logfile.write(f"Error at: {str(util.lineno())}")

        raise util.ConversionError(
            f"Check the syntax in: {self.names.xsl}"
        ) from None
    except etree.XSLTParseError as error:
        with open(self.names.log, "w") as logfile:
            logfile.write(f"Error at: {str(util.lineno())}")

        raise util.ConversionError(
            f"XSLTParseError in: {self.names.xsl}\nError {str(error)}"
        ) from error

validate_complete(complete)

Validate the complete document.

Source code in corpustools/converter.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def validate_complete(self, complete: etree.Element):
    """Validate the complete document."""
    dtd = etree.DTD(Converter.get_dtd_location())

    if not dtd.validate(complete):
        self.names.log.write_text(
            f"Error at: {str(util.lineno())}"
            + "\n".join(str(entry) for entry in dtd.error_log)
            + "\n".join(util.print_element(complete, 0, 4))
        )

        raise util.ConversionError(
            "{}: Not valid XML. More info in the log file: {}".format(
                type(self).__name__, self.names.log
            )
        )

write_complete(languageguesser)

Write the complete converted document to disk.

Parameters:

Name Type Description Default
languageguesser Classifier

a text.Classifier

required
Source code in corpustools/converter.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
def write_complete(self, languageguesser):
    """Write the complete converted document to disk.

    Args:
        languageguesser (text.Classifier): a text.Classifier
    """
    if not self.lazy_conversion or (
        self.lazy_conversion
        and newer_group(self.dependencies, self.names.converted)
    ):
        with util.ignored(OSError):
            os.makedirs(os.path.dirname(self.names.converted))

        if self.ocr or self.standard or self.goldstandard:
            complete = self.make_complete(languageguesser)

            if self.has_content(complete):
                with open(self.names.converted, "w") as converted:
                    print(
                        unicodedata.normalize(
                            "NFC", etree.tostring(complete, encoding="unicode")
                        ),
                        file=converted,
                    )
            else:
                LOGGER.error("%s has no text", self.names.orig)