|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +# tools/translator.py |
| 5 | + |
| 6 | +from csv import DictReader, DictWriter |
| 7 | +from json import dumps |
| 8 | +from os import listdir, mkdir |
| 9 | +from os.path import abspath, dirname, realpath |
| 10 | +from shutil import rmtree |
| 11 | +from time import sleep |
| 12 | +from traceback import format_exc |
| 13 | + |
| 14 | +from core.colors import Colors |
| 15 | +from core.config import Config |
| 16 | +from core.icons import Icons |
| 17 | +from core.tool import Tool |
| 18 | + |
| 19 | +class Translator(Tool): |
| 20 | + """ Say hello to the user |
| 21 | + """ |
| 22 | + |
| 23 | + command = (("translator", "tr"), "(tr)anslator") |
| 24 | + name = "Translator" |
| 25 | + path = __file__ |
| 26 | + version = "1.0" |
| 27 | + |
| 28 | + def __init__(self, args: list[str]): |
| 29 | + super().__init__() |
| 30 | + |
| 31 | + self.__cfg = Config() |
| 32 | + self.__path = str(abspath(f"{dirname(abspath(__file__))}/../{self.name}")) |
| 33 | + self.__setup() |
| 34 | + |
| 35 | + self._args = [ |
| 36 | + (("-c", "--create", "<project>"), "Create a blank project in workspace"), |
| 37 | + (("-d", "--delete", "<project>"), "Delete a project from workspace"), |
| 38 | + (("-t", "--translate", "<project>"), "Run a translation process by project"), |
| 39 | + ] + self._args[:] |
| 40 | + |
| 41 | + self._execs = [ |
| 42 | + lambda x:self._create(x), |
| 43 | + lambda x:self._delete(x), |
| 44 | + lambda x:self._translate(x) |
| 45 | + ] + self._execs[:] |
| 46 | + |
| 47 | + self._run(args) |
| 48 | + |
| 49 | + def __checkExistProject(self, distroName: str) -> bool: |
| 50 | + __distros = listdir(self.__path) |
| 51 | + |
| 52 | + if(distroName in __distros): |
| 53 | + return(True) |
| 54 | + |
| 55 | + print(f"{Icons.warn}Project doesn't exist on workspace") |
| 56 | + return(False) |
| 57 | + |
| 58 | + def __setup(self) -> None: |
| 59 | + try: |
| 60 | + mkdir(self.__path) |
| 61 | + print(f"{Icons.info}Create path workspace for {self.name} tool at {self.__path}") |
| 62 | + |
| 63 | + except(FileExistsError): |
| 64 | + print(f"{Icons.info}Using {self.__path} for {self.name} workspace") |
| 65 | + |
| 66 | + except(PermissionError): |
| 67 | + print(f"{Icons.warn}Permission denied: Unable to create '{self.__path}'.") |
| 68 | + |
| 69 | + except(Exception) as e: |
| 70 | + print(f"{Icons.err}An error occurred: {e}") |
| 71 | + |
| 72 | + def _create(self, args: list[str]) -> None: |
| 73 | + try: |
| 74 | + if(self.__checkExistProject(args[0])): |
| 75 | + raise(FileExistsError(f'Project "{args[0]}" already exist in {self.__path}')) |
| 76 | + |
| 77 | + __projectPath = abspath(f"{self.__path}/{args[0]}") |
| 78 | + |
| 79 | + mkdir(__projectPath) |
| 80 | + |
| 81 | + with open(abspath(f"{__projectPath}/{args[0]}.csv"), "w", encoding=self.__cfg.getEncoding(), newline='') as csvFile: |
| 82 | + __header = [ "label", "en", "fr" ] |
| 83 | + __writer = DictWriter(csvFile, __header) |
| 84 | + __rows = list[dict[str, str]]([ |
| 85 | + { "label": "HELLO_WORLD", "en": "Hello World", "fr": "Bonjour Monde" } |
| 86 | + ]) |
| 87 | + |
| 88 | + if(not csvFile.tell()): |
| 89 | + __writer.writeheader() |
| 90 | + |
| 91 | + __writer.writerows(__rows) |
| 92 | + |
| 93 | + print(f'"{args[0]}" was created in {self.__path}') |
| 94 | + |
| 95 | + except(IndexError): |
| 96 | + print(f"{Icons.warn}No schedule name was specified !") |
| 97 | + |
| 98 | + except(FileExistsError) as e: |
| 99 | + print(f"{Icons.warn}{e}") |
| 100 | + |
| 101 | + except(Exception) as e: |
| 102 | + print(f"{Icons.err}{e}") |
| 103 | + |
| 104 | + def _delete(self, args: list[str]) -> None: |
| 105 | + if(self.__checkExistProject(args[0])): |
| 106 | + rmtree(abspath(f"{self.__path}/{args[0]}")) |
| 107 | + print(f'"{args[0]}" was deleted from {self.__path}') |
| 108 | + |
| 109 | + def _translate(self, args: list[str]) -> None: |
| 110 | + __projectPath = abspath(f"{self.__path}/{args[0]}") |
| 111 | + __datas = list[str]([]) |
| 112 | + __regions = dict({}) |
| 113 | + |
| 114 | + with open(f"{__projectPath}/{args[0]}.csv", 'r', newline='') as file: |
| 115 | + print(f"{Icons.play}Reading CSV file and load translation ...") |
| 116 | + lines = DictReader(file, delimiter=',') |
| 117 | + |
| 118 | + for line in lines: |
| 119 | + __datas.append(line) |
| 120 | + |
| 121 | + print(f"{Icons.play}Wrapping data in new format ...") |
| 122 | + for field in lines.fieldnames: |
| 123 | + if(field != 'label'): |
| 124 | + __regions[field] = dict({}) |
| 125 | + |
| 126 | + try: |
| 127 | + print(f'{Icons.play}PROCESSING "{field}" [ {Colors.yellow}...{Colors.end} ]', end="\r") |
| 128 | + |
| 129 | + for data in __datas: |
| 130 | + __regions[field].update({ data["label"]: data[field] }) |
| 131 | + |
| 132 | + sleep(.05) |
| 133 | + |
| 134 | + except(Exception): |
| 135 | + print(f'{Icons.warn}PROCESSING "{field}" [ {Colors.red}FAILED{Colors.end} ]') |
| 136 | + print(f"{Icons.warn}{format_exc()}") |
| 137 | + |
| 138 | + print(f"{Icons.play}Writing new regions json files ...") |
| 139 | + |
| 140 | + for key in __regions: |
| 141 | + __regionPath = abspath(f"{__projectPath}/{key}.json") |
| 142 | + |
| 143 | + try: |
| 144 | + print(f'{Icons.play}WRITTING "{__regionPath}" [ {Colors.yellow}...{Colors.end} ]', end="\r") |
| 145 | + |
| 146 | + with open(__regionPath, 'w') as regionFile: |
| 147 | + string = str(dumps(__regions[key], indent=2, sort_keys=True)) |
| 148 | + regionFile.write(string) |
| 149 | + |
| 150 | + sleep(.05) |
| 151 | + print(f'{Icons.info}WRITTING "{__regionPath}" [ {Colors.green}OK{Colors.end} ] ') |
| 152 | + |
| 153 | + except(Exception): |
| 154 | + print(f'{Icons.warn}WRITTING "{__regionPath}" [ {Colors.red}FAILED{Colors.end} ]') |
| 155 | + print(f"{Icons.warn}{format_exc()}") |
| 156 | + |
| 157 | + print(f"{Icons.info}Translations created with success !") |
0 commit comments