Skip to content

Commit 598cad6

Browse files
authored
Merge pull request #11 from Tracks12/feature/translate
Feature/translate
2 parents 605ad29 + 2f1a923 commit 598cad6

File tree

8 files changed

+194
-5
lines changed

8 files changed

+194
-5
lines changed

.gitignore

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
1-
.vscode/
1+
# Config
2+
.vscode
23

3-
__pycache__/
4+
# Builds
5+
/build
6+
/dist
7+
__pycache__
48
*.pyc
59

10+
# Packages
611
/libs/wslbuilder
712
/Shell/
13+
/Translator/
814
/WSLBuilder/
915
*.vhdx

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ To use the tool manager, you need to open a terminal prompt and run the python s
5959
> [!Important]
6060
> Some tools present in the registry have dependencies contained in the [`libs/`](libs/) folder in the form of a `*.rar` file, you must unzip them by typing the command `$ python setup.py`
6161
62+
[Summary](#summary)
63+
6264
### III.1 Command Prompt
6365

6466
Usage: `$ python main.py <argument>`
@@ -170,6 +172,7 @@ class Hello(Tool):
170172
| Tool | Version | Description |
171173
| -------------------------------- | ------- | ------------------------------------------ |
172174
| [Shell](docs/Shell.md) | v1.0 | Prompt interface with custom schedules |
175+
| [Translator](docs/Translator.md) | v0.1a | Translation tool manager |
173176
| [WSLBuilder](docs/WSLBuilder.md) | v1.1 | Managing Docker images compatible with WSL |
174177

175178
[Summary](#summary)

docs/Translator.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# **Translator**
2+
3+
[Back to index](../README.md)
4+
5+
## Summary
6+
7+
- [**Translator**](#translator)
8+
- [Summary](#summary)
9+
- [I. Preview](#i-preview)
10+
11+
## I. Preview
12+
13+
[Summary](#summary)
14+
15+
[Back to index](../README.md)

tools/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,13 @@
1515

1616
from tools.matrix import Matrix
1717
from tools.shell import Shell
18+
from tools.translator import Translator
1819
from tools.wslbuilder import WslBuilder
1920

2021
TOOLS: tuple[Tool] = (
2122
Matrix,
2223
Shell,
24+
Translator,
2325
WslBuilder,
2426
)
2527
""" Tools registry """

tools/matrix.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4+
# tools/matrix.py
5+
46
from os import system as shell
57
from random import randrange
68
from time import sleep

tools/shell.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4+
# tools/shell.py
5+
46
from json import dump, load
57
from os import listdir, mkdir, remove, system as shell
68
from os.path import abspath, dirname
@@ -119,10 +121,10 @@ def _listSchedule(self) -> None:
119121
print(f"\n{_}")
120122

121123
def _newSchedule(self, args: list[str]) -> None:
122-
__scheduleName = re.sub(SCHEDULENAME_REGEX, "-", args[0])
123-
__schedules = list[str]([])
124-
125124
try:
125+
__scheduleName = re.sub(SCHEDULENAME_REGEX, "-", args[0])
126+
__schedules = list[str]([])
127+
126128
if(self.__checkExistSchedule(__scheduleName)):
127129
raise(FileExistsError(f'Schedule "{args[0]}" already exist in {self.__schedulesPath}'))
128130

tools/translator.py

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
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 !")

tools/wslbuilder.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
1313
"""
1414

15+
# tools/wslbuilder.py
16+
1517
from os import listdir, mkdir, remove, rmdir, system as shell
1618
from os.path import abspath, dirname, getsize, isdir
1719

0 commit comments

Comments
 (0)