Skip to content
This repository has been archived by the owner on Apr 9, 2024. It is now read-only.

Commit

Permalink
1.3
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinNitroG committed Aug 26, 2023
1 parent 76acab1 commit 67831ca
Show file tree
Hide file tree
Showing 12 changed files with 85 additions and 70 deletions.
18 changes: 6 additions & 12 deletions dictionaryList.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,47 +7,41 @@
'specific_name': 'r', # specific name to easier to call in script, anything you like, you can leave it to ''
'format': '{sort}#raw#{long}', # the format of the key and value to replace
'first_line': r'#raw#', # the first line in the macro file
'macro': 'raw_macro.txt', # macro file name
'dictionary_zip_file': '' # if the app require zip dictionary like Gboard
'macro': 'raw_macro.txt' # macro file name
},
{
'name': 'Gboard - All languages',
'specific_name': 'g',
'format': '{sort}\t{long}\t',
'first_line': r'# Gboard Dictionary version:1',
'macro': 'dictionary.txt',
'dictionary_zip_file': 'PersonalDictionary-*.zip'
'macro': 'dictionary.txt'
},
{
'name': 'Gboard - Vietnamese',
'specific_name': 'g',
'format': '{sort}\t{long}\tvi',
'first_line': r'# Gboard Dictionary version:1',
'macro': 'dictionary.txt',
'dictionary_zip_file': 'PersonalDictionary-*.zip'
'macro': 'dictionary.txt'
},
{
'name': 'OpenKey',
'specific_name': 'o',
'format': '{sort}:{long}',
'first_line': r';Compatible OpenKey Macro Data file for UniKey*** version=1 ***',
'macro': 'OpenKeyMacro.txt',
'dictionary_zip_file': ''
'macro': 'OpenKeyMacro.txt'
},
{
'name': 'EVKey',
'specific_name': 'e',
'format': '{sort}||{long}',
'first_line': r'<<Đây là dòng làm dấu Unicode, không được sửa hoặc xoá dòng này>>',
'macro': 'evkmacro.txt',
'dictionary_zip_file': ''
'macro': 'evkmacro.txt'
},
{
'name': 'UniKey',
'specific_name': 'u',
'format': '{sort}:{long}',
'first_line': r';DO NOT DELETE THIS LINE*** version=1 ***',
'macro': 'ukmacro.txt',
'dictionary_zip_file': ''
'macro': 'ukmacro.txt'
}
]
3 changes: 2 additions & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
### 🐣 CƠ BẢN

1. Cài đặt [Python](https://www.python.org/downloads/)
2. [Tải repo](https://github.com/KevinNitroG/Dict-Tool/archive/refs/heads/main.zip), giải nén, vào folder repo
2. [Tải soure code về](https://github.com/KevinNitroG/Dict-Tool/releases/latest), giải nén, vào folder repo
3. Mở terminal chạy `pip install -r requirements.txt`
4. Chuẩn bị dictionary:
- **Cách 1:** Paste file dictionary vào folder [Dictionary In](../Dictionary%20In/)
Expand All @@ -58,6 +58,7 @@
### 🦾 NÂNG CAO

- Có thể tải [latest source code](https://github.com/KevinNitroG/Dict-Tool/archive/refs/heads/main.zip) về _(Bản beta kiểu vậy)_
- Có thể thay đổi một vài biến trong file [`userConstants.py`](../userConstants.py) và thêm các dictionary khác ở file [`dictionaryList.py`](../dictionaryList.py)
- Có thể tuỳ chọn option sẵn để skip qua bước script hỏi chọn options [userOptions.py](../userOptions.py)
> Hãy **rename** file [userOptions.py.sample](../userOptions.py.sample) thành `userOptions.py`<br>Lưu ý tuỳ chọn trong file này đều là in hoa
Expand Down
14 changes: 14 additions & 0 deletions docs/version_history.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
# 🧓 VERSION HISTORY

# 1.3

- **Beauty:**

- Pep8 format,... by deepsource bot
- Doc for function: Change to Eng, double quotes
- README.md change the download source code to latest release site

- **Code changes:**
- Delete unused function _(Dict type for ... sort?)_
- Add request get timeout = 5 second for get LaTeX api
- Remove 'dictionary_zip_file' in [dictList](../dictionaryList.py)
- Input dict: all kind of files :v

# 1.2

- Bruh rename [DictTools.py](../DictTool.py) to [main.py](../main.py)
Expand Down
9 changes: 5 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from src import *
from src import clear_screen, wait_for_pressed_key, switch_pwd, exit_program
from src import prBanner, prTitle, prGreen, prBlue, prLightPurple
from src import read_current_dict, detect_current_dict_type, create_re_compile_pattern, split_dict, select_dict_type, join_working_dict
from src import latex_function, confirm_character_function, sort_dict, convert, create_converted_dictionary_as_file

from dictionaryList import *
from userConstants import *
Expand All @@ -20,10 +23,8 @@ def main():
prTitle("PREPARE")
print(prLightPurple("Reading your dictionary...\n"))
switch_pwd(input_dict_folder)
all_dict_zip_file = [dict['dictionary_zip_file']
for dict in dictionary_list if dict['dictionary_zip_file']]
# read your dict file
working_dict = read_current_dict(your_dictionary, all_dict_zip_file)
working_dict = read_current_dict(your_dictionary)
# detect your dict file
current_dict = detect_current_dict_type(working_dict, dictionary_list)
# create re_compile_pattern for current dict
Expand Down
43 changes: 18 additions & 25 deletions src/compulsoryFunctions.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,46 @@
import fnmatch
import zipfile
import os
import re

from pathlib import Path

from .utils import exit_program, switch_pwd, delete_dir
from .pr import *


# SHORT VARS EXPLANATION

# yd = your_dict
# adzf = all_dict_zip_files
# lold = list_of_line_dict
# cf = current_format
# wd = working_dict
# rc_p = current_dict['re_compile_pattern']
# dl = dict_list


def read_current_dict(yd, adzf):
'''Đọc dictionary'''
def read_current_dict(yd):
"""Read current dictionary"""
yd = yd.strip().strip("\n")
list_dir = []
if yd != '':
lold = yd.splitlines()
else:
delete_dir('./Extracted Dict')
list_dir = [f for f in os.listdir() if (f.endswith(
'.txt') or True for zip_file_name in adzf if fnmatch.fnmatch(f, zip_file_name))]
all_items = Path('./')
list_dir = [item.name for item in all_items.iterdir() if (item.name not in ['Paste your dictionary into this folder'])
and item.is_file()]
if list_dir == []:
exit_program(
"Không tìm thấy bất kì file macro có sẵn trong thư mục hiện tại", 1)
# List out the list of file with number
print(prLightPurple("Chọn file macro:\n"))
for i, file in enumerate(list_dir, start=1):
print("{}. {}".format(str(i).rjust(5), file))
print(f"{str(i).rjust(5)}. {file}")
_ = int(input("\nNhập số thứ tự file bạn muốn chọn: "))
print()
selected_file_name = list_dir[_-1]
# If selection is a dictionary zip file
if selected_file_name.endswith('.zip'):
with zipfile.ZipFile(selected_file_name, 'r') as zip_ref:
delete_dir('./Extracted Dict')
switch_pwd('./Extracted Dict')
zip_ref.extractall("./")
os.rename(zip_ref.namelist()[0], 'extracted_dictionary.txt')
Expand All @@ -54,22 +54,14 @@ def read_current_dict(yd, adzf):


def create_re_compile_pattern(cf):
'''Tạo re.compile pattern'''
"""Create re.compile pattern"""
cf = re.escape(cf).replace(
'\\{sort\\}', '(?P<sort>.*)').replace('\\{long\\}', '(?P<long>.*)')
return cf


# Detech which type is the dict, {sort} before {long} or vice versa
# def specify_format_type(cf):
# # cf = current_format
# if cf.index('{sort}') < cf.index('{long}'):
# return 1
# return 2


def split_dict(wd, rc_p):
'''Tách dictionary thành list'''
"""Split dictionary into list"""
pattern = re.compile(rc_p)
for i in range(1, len(wd)):
match = re.search(pattern, wd[i])
Expand All @@ -78,21 +70,21 @@ def split_dict(wd, rc_p):


def select_dict_type(dl):
'''Chọn loại dictionary'''
"""Select dictionary type"""
for i, dict_type in enumerate(dl, start=1):
print("{}. {}".format(str(i).rjust(5), dict_type["name"]))
print(f"{str(i).rjust(5)}. {dict_type['name']}")
print()
_ = input("Chọn thứ tự: ")
return dl[int(_)-1]


def detect_current_dict_type(wd, dl):
'''Tự động nhận diện loại dictionary'''
"""Detect current dictionary"""
first_line = wd[0][:-1]
for dict_type in dl:
if first_line in dict_type["first_line"]:
if first_line in dict_type['first_line']:
_ = input(
"Dictionary hiện tại là {}? [Y/n]: ".format(dict_type["name"])).upper()
f"Dictionary hiện tại là {dict_type['name'].upper()}? [Y/n]: ")
if _ in ('Y', ''):
return dict_type
print(prLightPurple("\nChọn loại dictionary bộ gõ hiện tại\n"))
Expand All @@ -104,8 +96,9 @@ def detect_current_dict_type(wd, dl):
print(prLightPurple("\nChọn loại dictionary bộ gõ hiện tại\n"))
return select_dict_type(dl)
exit_program("Kết thúc chương trình")
return ''


def join_working_dict(wd):
'''Gộp list dictionary hoàn chỉnh'''
"""Join final dictionary"""
return '\n'.join(wd)
2 changes: 1 addition & 1 deletion src/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝
"""
maintainer = "KevinNitro"
version = '1.2'
version = '1.3'

# # ANSI ESCAPE SEQUENCES
# BLACK = "\033[0;30m"
Expand Down
6 changes: 3 additions & 3 deletions src/optional_functions/confirmCharacter.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@


def remove_confirm_character(wd, cc):
'''Xoá confirm character'''
"""Delete confirm character"""
for i in range(1, len(wd)):
if wd[i][0].endswith(cc):
wd[i][0] = wd[i][0][:-len(cc)]
Expand All @@ -18,15 +18,15 @@ def remove_confirm_character(wd, cc):


def add_confirm_character(wd, cc):
'''Thêm confirm character'''
"""Thêm confirm character"""
for i in range(1, len(wd)):
wd[i] = [wd[i][0] + cc, wd[i][1]]
return wd


@decorator
def confirm_character_function(wd, a_ccf, cc):
'''Confirm character'''
"""Confirm character"""
if a_ccf in ('R', 'U'):
wd = remove_confirm_character(wd, cc)
if a_ccf in ('A', 'U'):
Expand Down
1 change: 1 addition & 0 deletions src/optional_functions/convert.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
def convert(wd, sd):
"""Covert dictionary"""
# wd = working_dict
# sd = selected_dict
wd[0] = sd['first_line']
Expand Down
12 changes: 7 additions & 5 deletions src/optional_functions/createDictFile.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@


def dictionary_compress(sd):
"""Compress dictionary"""
import zipfile
compress, ext = os.path.splitext(sd['dictionary_zip_file'].rstrip('-*'))
compress = compress + '-Generated' + ext
Expand All @@ -20,18 +21,19 @@ def dictionary_compress(sd):


def evkey_special_create_file(content, evkey_macro):
"""Special method to create EVKey macro file"""
content = content[69:]
from ..constants import EVKey_macro_first_line_binary as first_line
with open(evkey_macro, 'wb') as f:
f.write(first_line)
with open(evkey_macro, 'a', encoding='utf-8') as f:
f.write(content)
with open(evkey_macro, 'wb') as file:
file.write(first_line)
with open(evkey_macro, 'a', encoding='utf-8') as file:
file.write(content)
print(prGreen("File macro đã được tạo ^^. Tên file: ") + prPurple(evkey_macro))


@decorator
def create_converted_dictionary_as_file(fd, sd):
'''Tạo file dictionary'''
"""Create dictionary file"""
_ = 'Y'
if os.path.exists(sd['macro']):
_ = input(
Expand Down
Loading

0 comments on commit 67831ca

Please sign in to comment.