work on docs, tests and some fix

This commit is contained in:
2025-03-05 02:20:02 +03:00
parent 971258728c
commit 2bf2144815
25 changed files with 262 additions and 397 deletions
+2
View File
@@ -4,6 +4,8 @@ import re
def set_description_message_pattern(pattern: str) -> None:
first_check = re.match(r'.*command.*', pattern)
second_check = re.match(r'.*{description}.*', pattern)
if bool(first_check) and bool(second_check):
print('Success')
set_description_message_pattern('Invalid des{ommand}cription pattern')
@@ -1,75 +0,0 @@
import os
import shutil
import time
from zipfile import ZipFile
import requests
from ..local_data_func.get_script_release_tag import get_script_tag
from tqdm import tqdm
class UpdateScript:
GITHUB_REPO = "https://api.github.com/repos/koloideal/WordMath"
@staticmethod
def get_latest_release() -> dict:
response = requests.get(f"{UpdateScript.GITHUB_REPO}/releases/latest")
data = response.json()
return {'tag': data['tag_name'],
'url': data['zipball_url']}
@staticmethod
def download_new_release(zip_url):
response = requests.get(zip_url, stream=True)
response.raise_for_status()
total_size = int(response.headers.get("content-length", 0))
block_size = 1024
with tqdm(total=total_size, unit="B", unit_scale=True) as progress_bar:
with open('new_release.zip', "wb") as file:
for data in response.iter_content(block_size):
progress_bar.update(len(data))
file.write(data)
time.sleep(0.3)
with ZipFile('new_release.zip') as zip_file:
zip_file.extractall("new_release")
@staticmethod
def upgrade_script():
excluded_files = ['venv', '.venv', '.git', 'new_release']
for obj in os.listdir():
if obj not in excluded_files:
if os.path.isfile(obj):
os.remove(obj)
elif os.path.isdir(obj):
shutil.rmtree(obj)
new_release = os.listdir('new_release')
new_release_name = new_release[0] if new_release[0].startswith('koloideal-WordMath') else None
path = f'new_release/{new_release_name}'
all_files = os.listdir(path)
for file in all_files:
shutil.move(path + '/' + file, './' + file)
shutil.rmtree('new_release')
@staticmethod
def start_update() -> bool:
existing_release_tag: str = get_script_tag()
latest_release: dict = UpdateScript.get_latest_release()
latest_release_tag = latest_release['tag']
latest_release_url = latest_release['url']
if latest_release_tag != existing_release_tag:
#UpdateScript.download_new_release(latest_release_url)
#UpdateScript.upgrade_script()
return latest_release_tag
else:
return False
@@ -1,68 +0,0 @@
from numpy import ndarray
from word2number import w2n
from ..local_data_func.get_operator_synonyms import get_operator_synonyms
import numexpr
def word2num_math(string: str) -> ndarray | ZeroDivisionError | OverflowError:
operator_synonyms: dict[str, list[str]] = get_operator_synonyms()
def variables_to_operator(synonym):
for key in operator_synonyms.keys():
if synonym in operator_synonyms[key]:
return key
action = {
"plus": '+',
"minus": '-',
"divide": '/',
"multiply": '*',
"degree": '**',
}
result_string: str = ''
all_variables_of_operators: list[str] = [x for l in operator_synonyms.values() for x in l]
operators = {}
while True:
is_clear = True
number_of_operator = 1
for word in string.split():
try:
if word in all_variables_of_operators:
ope_index = string.index(word)
if ope_index in operators.keys():
is_clear = True
break
else:
raise ValueError
except ValueError:
continue
else:
is_clear = False
operators[number_of_operator] = variables_to_operator(word)
number_of_operator += 1
string = string.replace(word, "&&", 1)
if is_clear:
break
num_of_ope = 1
for number in string.split("&&"):
try:
int_num = w2n.word_to_num(number.strip())
except ValueError:
return ValueError("Invalid input expression")
if num_of_ope in operators.keys():
result_string += f'{int_num} {action[operators[num_of_ope]]} '
num_of_ope += 1
else:
result_string += f'{int_num}'
try:
result = numexpr.evaluate(result_string)
except ZeroDivisionError:
return ZeroDivisionError('Except divide by zero')
except OverflowError:
return OverflowError('Too big result')
else:
return result
@@ -1,20 +0,0 @@
from rich.console import Console
from ...business_logic.word2num_math import word2num_math
console = Console()
print_line_separator = lambda: console.print('\n[bold blue]--------------------------------------[/bold blue]\n')
def start_solving_command():
while True:
console.print(
"\n[italic]Enter a string expression or [bold italic green] Q [/bold italic green] for exit:[/italic]")
string_expression = input()
if string_expression.lower() == 'q':
break
else:
print_line_separator()
console.print(
f'[bold green]Answer:[/bold green] [bold blue]{word2num_math(string_expression)}[/bold blue]')
print_line_separator()
@@ -1,26 +0,0 @@
import requests
from rich.console import Console
from ...business_logic.script_updater import UpdateScript
console = Console()
print_line_separator = lambda: console.print('\n[bold green]--------------------------------------[/bold green]\n')
def upgrade_command():
try:
requests.get('https://ya.ru')
except requests.exceptions.ConnectionError:
console.print('[bold red]No internet connection[/bold red]')
else:
latest_tag = UpdateScript.start_update()
if latest_tag:
print_line_separator()
console.print(f"[bold yellow]The newest version ({latest_tag}) of the script has been successfully installed![/bold yellow]")
print_line_separator()
console.print("[bold yellow]Rerun the script for the changes to take effect[/bold yellow]")
print_line_separator()
exit(0)
else:
console.print('[bold red]You have the latest version installed[/bold red]')
+13 -21
View File
@@ -1,20 +1,24 @@
import re
from pprint import pprint
from rich.console import Console
from argenta.command.entity import Command
from argenta.command.params.flag.entity import Flag
from argenta.command.params.flag.flags_group.entity import FlagsGroup
from argenta.router import Router
from .handlers_implementation.help_command import help_command
work_router: Router = Router(title='Work nts:')
work_router.set_invalid_input_flag_handler(lambda flag: print(f'Invalid input flag: "{flag.get_string_entity()} {flag.get_value()}"'))
settings_router: Router = Router(title='Settings points:')
console = Console()
flagi = FlagsGroup(flags=[
flags = FlagsGroup(flags=[
Flag(flag_name='host',
flag_prefix='--',
possible_flag_values=re.compile(r'^192.168.\d{1,3}.\d{1,3}$')),
@@ -23,33 +27,21 @@ flagi = FlagsGroup(flags=[
])
@work_router.command(Command(command='0', description='Get Help'))
@work_router.command(Command(trigger='0', description='Get Help'))
def command_help():
print('Help command')
'''flags = args.get_flags()
for flag in flags:
print(f'name: "{flag.get_string_entity()}", value: "{flag.get_value()}"')'''
#help_command()
help_command()
@work_router.command(Command(command='P', description='Start Solving', flags=flagi))
def command_start_solving(argrrtrts: dict):
@work_router.command(Command(trigger='P', description='Start Solving', flags=flags))
def command_start_solving(args: dict):
print('Solving...')
pprint(argrrtrts)
pprint(args)
#start_solving_command()
@settings_router.command(Command(command='G', description='Update WordMath'))
@settings_router.command(Command(trigger='G', description='Update WordMath'))
def command_update():
print('uefi')
# upgrade_command()
def invalid_input_flag(flag: Flag):
print(f'Invalid inpuuuuuuuuuuuuuuuuuuuuuuuut flag: "{flag.get_string_entity()} {flag.get_value()}"')
work_router.set_invalid_input_flag_handler(invalid_input_flag)
print('Command update')
@@ -1,44 +0,0 @@
{
"minus": [
"without",
"lacking",
"deprived_of",
"bereft_of",
"destitute_of",
"minus"
],
"plus": [
"added_to",
"add",
"coupled_with",
"with_the_addition_of",
"plus"
],
"divide": [
"separate",
"part",
"split",
"divide",
"divide_by"
],
"multiply": [
"extend",
"expand",
"spread",
"build_up",
"accumulate",
"augment",
"multiply",
"times"
],
"degree": [
"stage",
"extent",
"grade",
"proportion",
"gradation",
"to_the_power_of",
"degree",
"to_the"
]
}
@@ -1,3 +0,0 @@
{
"tag": "v4.1.1"
}
@@ -1,8 +0,0 @@
import json
def get_operator_synonyms() -> dict[str, list[str]]:
with open("tests/mock_app/local_data/operator_synonyms.json", "r", encoding="utf-8") as file:
operator_synonyms: dict = json.load(file)
return operator_synonyms
@@ -1,8 +0,0 @@
import json
def get_script_tag() -> str:
with open("tests/mock_app/local_data/script_release_tag.json", "r", encoding="utf-8") as file:
script_release_tag: str = json.load(file)['tag']
return script_release_tag