pytex/default_formatters/dictionary_formatter.py

88 lines
3.3 KiB
Python

import datetime
from pathlib import Path
from typing import Dict, Optional, List
from datetime import *
import csv
from PyTeX.formatter import Formatter
from PyTeX.utils import ensure_file_integrity
class DictionaryFormatter(Formatter):
def __init__(self, kind: str, author: str, header: Optional[List[str]]):
self.header = header
self.kind = kind.lower()
self.author = author
author_parts = self.author.lower().replace('ß', 'ss').split(' ')
self.author_acronym = author_parts[0][0] + author_parts[-1]
self.dictname = r'translator-{kind}-dictionary'.format(
kind=self.kind
)
self.name_lowercase = self.dictname + '-{language}'
self.file_name = self.name_lowercase + '.dict'
self.date = datetime.now().strftime('%Y/%m/%d')
self.year = int(datetime.now().strftime('%Y'))
self.replace_dict: Dict = {}
self.arg_replace_dict: Dict = {}
self.source_file_name = "not specified"
super().__init__()
def expected_file_name(self):
return self.file_name
def format_file(
self,
input_path: Path,
output_dir: Path = None,
relative_name: Optional[str] = None,
last_build_info: Optional[List[Dict]] = None
) -> List[str]:
self.source_file_name = str(input_path.name)
written_files = []
if self.header:
lines = '%' * 80 + '\n' \
+ '\n'.join(map(lambda line: '% ' + line, self.header)) \
+ '\n' + '%' * 80 + '\n\n'
else:
lines = []
if output_dir is None:
output_dir = input_path.parent
output_dir.mkdir(parents=True, exist_ok=True)
with open(input_path, newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
langs = next(spamreader)
translations = {}
for lang in langs[1:]:
translations[lang] = {}
for line in spamreader:
for n in range(1, len(line)):
translations[langs[n]][line[0]] = line[n]
for lang in langs[1:]:
lang_lines = lines
lang_lines += r'\ProvidesDictionary{{{dictname}}}{{{lang}}}'.format(
dictname=self.dictname,
lang=lang
)
lang_lines += '\n'
lang_lines += '\n'
for key in translations[lang].keys():
if translations[lang][key].strip() != '':
lang_lines += r'\providetranslation{{{key}}}{{{translation}}}'.format(
key=key.strip(),
translation=translations[lang][key].strip()
)
lang_lines += '\n'
ensure_file_integrity(
output_dir / self.file_name.format(language=lang),
str(Path(relative_name).parent / self.file_name.format(language=lang)),
last_build_info
)
(output_dir / self.file_name.format(language=lang)).write_text(''.join(lang_lines))
written_files.append(self.file_name.format(language=lang))
return written_files
def make_default_macros(self):
pass