From 67831ca4e5420cc4299db5d4ad3f94555c6e88cd Mon Sep 17 00:00:00 2001 From: KevinNitroG Date: Sat, 26 Aug 2023 18:15:33 +0700 Subject: [PATCH] 1.3 --- dictionaryList.py | 18 +++------ docs/README.md | 3 +- docs/version_history.md | 14 +++++++ main.py | 9 +++-- src/compulsoryFunctions.py | 43 +++++++++------------- src/constants.py | 2 +- src/optional_functions/confirmCharacter.py | 6 +-- src/optional_functions/convert.py | 1 + src/optional_functions/createDictFile.py | 12 +++--- src/optional_functions/laTeX.py | 37 ++++++++++--------- src/optional_functions/sortDict.py | 2 +- src/utils.py | 8 +++- 12 files changed, 85 insertions(+), 70 deletions(-) diff --git a/dictionaryList.py b/dictionaryList.py index 210e32e..2d14a55 100644 --- a/dictionaryList.py +++ b/dictionaryList.py @@ -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' } ] diff --git a/docs/README.md b/docs/README.md index 918005b..a420efc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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/) @@ -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`
Lưu ý tuỳ chọn trong file này đều là in hoa diff --git a/docs/version_history.md b/docs/version_history.md index 9706662..f14063d 100644 --- a/docs/version_history.md +++ b/docs/version_history.md @@ -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) diff --git a/main.py b/main.py index b1a7c35..7d6eda0 100644 --- a/main.py +++ b/main.py @@ -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 * @@ -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 diff --git a/src/compulsoryFunctions.py b/src/compulsoryFunctions.py index 2f7ec40..53ea46b 100644 --- a/src/compulsoryFunctions.py +++ b/src/compulsoryFunctions.py @@ -1,8 +1,9 @@ -import fnmatch import zipfile import os import re +from pathlib import Path + from .utils import exit_program, switch_pwd, delete_dir from .pr import * @@ -10,7 +11,6 @@ # SHORT VARS EXPLANATION # yd = your_dict -# adzf = all_dict_zip_files # lold = list_of_line_dict # cf = current_format # wd = working_dict @@ -18,29 +18,29 @@ # 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') @@ -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.*)').replace('\\{long\\}', '(?P.*)') 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]) @@ -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")) @@ -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) diff --git a/src/constants.py b/src/constants.py index 7b94b84..63b2fe1 100644 --- a/src/constants.py +++ b/src/constants.py @@ -8,7 +8,7 @@ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝ """ maintainer = "KevinNitro" -version = '1.2' +version = '1.3' # # ANSI ESCAPE SEQUENCES # BLACK = "\033[0;30m" diff --git a/src/optional_functions/confirmCharacter.py b/src/optional_functions/confirmCharacter.py index ee98dc0..f53b942 100644 --- a/src/optional_functions/confirmCharacter.py +++ b/src/optional_functions/confirmCharacter.py @@ -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)] @@ -18,7 +18,7 @@ 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 @@ -26,7 +26,7 @@ def add_confirm_character(wd, cc): @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'): diff --git a/src/optional_functions/convert.py b/src/optional_functions/convert.py index 261c50e..9ddc762 100644 --- a/src/optional_functions/convert.py +++ b/src/optional_functions/convert.py @@ -1,4 +1,5 @@ def convert(wd, sd): + """Covert dictionary""" # wd = working_dict # sd = selected_dict wd[0] = sd['first_line'] diff --git a/src/optional_functions/createDictFile.py b/src/optional_functions/createDictFile.py index e80da6b..f38b17a 100644 --- a/src/optional_functions/createDictFile.py +++ b/src/optional_functions/createDictFile.py @@ -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 @@ -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( diff --git a/src/optional_functions/laTeX.py b/src/optional_functions/laTeX.py index 5723d58..330d6cd 100644 --- a/src/optional_functions/laTeX.py +++ b/src/optional_functions/laTeX.py @@ -1,13 +1,13 @@ import os +from urllib.request import urlopen +from json import loads import requests -from json import loads from ..constants import latex_format as lf from ..constants import latex_api, latex_cdn_link, latex_raw_github_link from ..pr import prGreen, prYellow, prRed, prPurple -from urllib.request import urlopen from ..utils import switch_pwd, decorator from ..compulsoryFunctions import split_dict @@ -19,23 +19,24 @@ # a_lf = ask_latex_function def should_download_latex(): + """Check either should download LaTeX dictionary or not""" print(prYellow("Check status đến LaTeX repo...")) - reponse = requests.get(latex_api) + reponse = requests.get(latex_api, timeout=5) if not reponse.ok: print(prRed("Không thể kết nối đến LaTeX repo")) return False print(prYellow("Fetch sha của LaTeX dict hiện có trên Github...")) - with urlopen(latex_api) as f: - fetched_sha = loads(f.read())['sha'] + with urlopen(latex_api) as file: + fetched_sha = loads(file.read())['sha'] try: - with open('LaTeX-sha.txt') as f: - current_sha = f.read() + with open('LaTeX-sha.txt', 'r', encoding='utf-8') as file: + current_sha = file.read() except: current_sha = '' if fetched_sha != current_sha: print(prYellow("Có bản LaTeX khác hiện có, đang tải bản LaTeX mới...")) - with open('LaTeX-sha.txt', 'w') as f: - f.write(fetched_sha) + with open('LaTeX-sha.txt', 'w', encoding='utf-8') as file: + file.write(fetched_sha) return True if not os.path.exists('LaTeX.txt'): return True @@ -44,25 +45,26 @@ def should_download_latex(): def download_latex(): + """Download LaTeX dictionary""" try: print(prYellow("Đang tải qua link Raw Github...")) - with urlopen(latex_raw_github_link) as f: - latex_dict = f.read().decode('utf-8') + with urlopen(latex_raw_github_link) as file: + latex_dict = file.read().decode('utf-8') except: print(prRed("Oops Raw Github link không phản hồi :v")) print(prYellow("Đang tải qua link CDN...")) - with urlopen(latex_cdn_link) as f: - latex_dict = f.read().decode('utf-8') + with urlopen(latex_cdn_link) as file: + latex_dict = file.read().decode('utf-8') print(prGreen("Done")) - with open('LaTeX.txt', 'w', encoding='utf-8') as f: - f.write(latex_dict) + with open('LaTeX.txt', 'w', encoding='utf-8') as file: + file.write(latex_dict) print(prGreen("Đã tạo file LaTeX dict trong folder LaTeX với tên:" + prPurple('LaTeX.txt'))) @decorator def remove_latex(wd): - '''Xoá LaTeX''' + """Xoá LaTeX""" md = [wd[0]] for i in range(1, len(wd)): if wd[i][0][0] not in lf: @@ -72,7 +74,7 @@ def remove_latex(wd): @decorator def add_latex(wd): - '''Thêm LaTeX''' + """Thêm LaTeX""" switch_pwd('./LaTeX') if should_download_latex(): download_latex() @@ -89,6 +91,7 @@ def add_latex(wd): def latex_function(wd, a_lf): + """LaTeX function""" if a_lf in ('R', 'U'): wd = remove_latex(wd) if a_lf in ('A', 'U'): diff --git a/src/optional_functions/sortDict.py b/src/optional_functions/sortDict.py index 9f9460f..0249eb4 100644 --- a/src/optional_functions/sortDict.py +++ b/src/optional_functions/sortDict.py @@ -10,7 +10,7 @@ @decorator def sort_dict(wd, sdt): - '''Sort dictionary''' + """Sort dictionary""" print(prYellow("Sort Dictionary theo kiểu " + prBlue(sdt))) md = [wd[0]] md += sorted(wd[1:], key=lambda x: x[sdt - 1]) diff --git a/src/utils.py b/src/utils.py index 270e01d..bda3923 100644 --- a/src/utils.py +++ b/src/utils.py @@ -1,11 +1,12 @@ import os import shutil +import sys from .pr import * -import sys def clear_screen(): + """Clear running screen""" if os.name == 'nt': # for Windows os.system('cls') else: # for Linux and Mac @@ -13,12 +14,14 @@ def clear_screen(): def wait_for_pressed_key(): + """Wait for user keyboard input""" print() os.system('pause') clear_screen() def exit_program(msg="Unkown", exit_code=0): + """Exit program""" print(prBold(prLightBlue("KẾT THÚC".center(40, '-'))), end='\n\n') if exit_code == 0: print(prCyan(msg)) @@ -39,6 +42,7 @@ def exit_program(msg="Unkown", exit_code=0): def switch_pwd(pwd): + """Switch present working directory""" try: os.chdir(pwd) except FileNotFoundError: @@ -49,6 +53,7 @@ def switch_pwd(pwd): def delete_dir(d): + """Delete directory""" try: shutil.rmtree(d) print(prYellow("Đã xoá folder: " + prPurple(d))) @@ -57,6 +62,7 @@ def delete_dir(d): def decorator(f): + """Log?""" def wrapper(*args, **kwargs): print(prLightBlue("WORKING:\t"), prLightPurple(f.__doc__)) result = f(*args, **kwargs)