Skip to content

Commit

Permalink
Merge pull request #747 from weiduhuo/feature-relic
Browse files Browse the repository at this point in the history
feat: 更新[遗器模块]新增队伍配装等相关功能,模块主体功能全部完成
  • Loading branch information
Night-stars-1 authored Nov 3, 2023
2 parents 5acfb85 + ac01374 commit d7ca2a1
Show file tree
Hide file tree
Showing 28 changed files with 3,660 additions and 305 deletions.
13 changes: 6 additions & 7 deletions Honkai_Star_Rail.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,14 +357,13 @@ def select():
sra.set_config(False)
elif option == None:
...
elif option == _('退出脚本'):
if questionary.select(_("请问要退出脚本吗?"), [_("退出"), _("返回主菜单")]).ask() == _("返回主菜单"):
select()
else:
if option:
is_loop = sra.main(option)
if is_loop:
select()
else:
if questionary.select(_("请问要退出脚本吗?"), [_("退出"), _("返回主菜单")]).ask() == _("返回主菜单"):
select()
is_loop = sra.main(option)
if is_loop:
select()
serial_map = args.get("--map") if args.get("--map") != "default" else "1-1_1" # 地图编号
select() if not serial_map else sra.main(start=serial_map)
sra.end()
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ pluggy
httpcore
pydantic
jsonschema
prompt-toolkit<=3.0.36,>=2.0
28 changes: 15 additions & 13 deletions utils/calculated.py
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,7 @@ def is_blackscreen(self, threshold = 30):
screenshot = cv.cvtColor(self.take_screenshot()[0], cv.COLOR_BGR2GRAY)
return cv.mean(screenshot)[0] < threshold

def ocr_pos(self, characters:str = None, points = (0,0,0,0)):
def ocr_pos(self, characters: Optional[str]=None, points = (0,0,0,0)):
"""
说明:
获取指定文字的坐标
Expand All @@ -625,7 +625,8 @@ def ocr_pos(self, characters:str = None, points = (0,0,0,0)):
pos = data[characters] if characters in data else None
return characters, pos

def ocr_pos_for_single_line(self, characters_list:list[str] = None, points = (0,0,0,0), number = False, debug = False, img_pk:tuple = None) -> Union[int, str]:
def ocr_pos_for_single_line(self, characters_list: Optional[List[str]]=None, points=(0,0,0,0), number=False, debug=False, img_pk: Optional[Tuple]=None
) -> Optional[Union[int, str]]:
"""
说明:
获取指定坐标的单行文字
Expand Down Expand Up @@ -661,7 +662,7 @@ def read_img(self, path, prefix='./picture/pc/'):
"""
return cv.imread(f'{prefix}{path}')

def part_ocr(self, points = (0,0,0,0), debug=False, left=False, number = False, img_pk:tuple = None, is_single_line = False, only_white=False
def part_ocr(self, points = (0,0,0,0), debug=False, left=False, number=False, img_pk: Optional[tuple]=None, is_single_line=False, only_white=False
) -> Union[str, dict[str, tuple[int, int]]]:
"""
说明:
Expand Down Expand Up @@ -992,7 +993,7 @@ def change_team(self):

class Array2dict:

def __init__(self, arr:np.ndarray, key_index:int = -1, value_index:int = None):
def __init__(self, arr: np.ndarray, key_index: int = -1, value_index: Optional[int]=None):
"""
说明:
将np数组转化为字典暂住内存,用于对数组短时间内的频繁查找
Expand All @@ -1008,32 +1009,33 @@ def __init__(self, arr:np.ndarray, key_index:int = -1, value_index:int = None):
self.data_dict = {row[key_index]: idx for idx, row in enumerate(arr)}
else:
self.data_dict = {row[key_index]: row[value_index] for row in arr}
log.debug(self.data_dict)
# log.debug(self.data_dict)

def __getitem__(self, key):
def __getitem__(self, key: Any) -> Any:
return self.data_dict[key]

def get_data_hash(data:Any, key_filter:list[str] = None) -> str:
def get_data_hash(data: Any, key_filter: Optional[List[str]]=None, speed_modified=False) -> str:
"""
说明:
求任意类型数据 (包括list和dict) 的哈希值
首先将数据规范化输出为str,再计算md5转16进制
参数:
:param data: 任意类型数据
:param key_filter: 键值过滤器
:param speed_modified: 是否对速度属性进行修饰 (忽略小数位数值)
"""
if not key_filter:
tmp_data = data
elif type(data) is dict:
tmp_data = dict(data).copy() # 注意dict'='为引用传递,此处需拷贝副本
[tmp_data.pop(key) if key in tmp_data else None for key in key_filter]
elif isinstance(data, dict):
tmp_data = {key: value for key, value in data.items() if key not in key_filter}
if speed_modified and _("速度") in tmp_data["subs_stats"]:
tmp_data["subs_stats"][_("速度")] = float(int(tmp_data["subs_stats"][_("速度")])) # 去除小数部分
else:
log.eror(_("不支持dict以外类型的类型使用键值过滤器"))
return None
raise ValueError(_("不支持dict以外类型的类型使用键值过滤器"))
# pprint默认sort_dicts=True,对键值进行排序,以确保字典类型的唯一性
return hashlib.md5(pprint.pformat(tmp_data).encode('utf-8')).hexdigest()

def str_just(text:str, width:int, left = True):
def str_just(text: str, width: int, left=True):
"""
说明:
封装str.rjust()&str.ljust(),以适应中文字符的实际宽度
Expand Down
25 changes: 7 additions & 18 deletions utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,31 +53,16 @@ def read_json_file(filename: str, path=False, schema:dict=None) -> dict:
try:
jsonschema.validate(data, schema)
except jsonschema.exceptions.ValidationError as e:
log.error(_(f"JSON 数据不符合格式规范: {e}"))
raise Exception(_(f"JSON 数据不符合格式规范: {e}"))
if path:
return data, file_path
else:
return data
else:
if filename in [RELIC_FILE_NAME, LOADOUT_FILE_NAME, TEAM_FILE_NAME]:
init_json_file(filename)
return read_json_file(filename, path)
if path:
return {}, filename
else:
return {}


def init_json_file(filename: str):
"""
说明:
初始化json文件为空字典
参数:
:param filename: 文件名称
"""
with open(filename, "wb") as f:
log.info(_(f"{filename} 文件初始化"))
f.write(orjson.dumps({}, option = orjson.OPT_PASSTHROUGH_DATETIME | orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_INDENT_2))


def modify_json_file(filename:str, key:str, value:Any) -> dict:
Expand All @@ -92,9 +77,9 @@ def modify_json_file(filename:str, key:str, value:Any) -> dict:
data: 修改后的json字典
"""
# 先读,再写
data, file_path = read_json_file(filename, path=True)
data = read_json_file(filename)
data[key] = value
return rewrite_json_file(file_path, data)
return rewrite_json_file(filename, data)


def rewrite_json_file(filename:str, data:dict) -> dict:
Expand All @@ -108,6 +93,8 @@ def rewrite_json_file(filename:str, data:dict) -> dict:
data: 修改后的json字典
"""
file_path = normalize_file_path(filename)
if file_path is None:
file_path = filename # 原文件不存在,则新建
try:
with open(file_path, "wb") as f:
f.write(orjson.dumps(data, option=orjson.OPT_PASSTHROUGH_DATETIME | orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_INDENT_2))
Expand Down Expand Up @@ -339,6 +326,8 @@ class SRAData(metaclass=SRADataMeta):
"""是否在遗器OCR时开启对副词条的数据验证"""
detail_for_relic: bool = True
"""是否在打印遗器信息时显示拓展信息"""
ndigits_for_relic: int = 2
"""在打印遗器信息时的小数精度"""


def __init__(self) -> None:
Expand Down
51 changes: 51 additions & 0 deletions utils/questionary/NOTICE
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
Tom Bocklisch
Copyright 2019 Tom Bocklisch

----

This product includes software from PyInquirer (https://github.com/CITGuru/PyInquirer),
under the MIT License.

Copyright 2018 Oyetoke Toby and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

----

This product includes software from whaaaaat (https://github.com/finklabs/whaaaaat),
under the MIT License.

Copyright 2016 Fink Labs GmbH and inquirerpy contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
114 changes: 114 additions & 0 deletions utils/questionary/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Questionary

[![Version](https://img.shields.io/pypi/v/questionary.svg)](https://pypi.org/project/questionary/)
[![License](https://img.shields.io/pypi/l/questionary.svg)](#)
[![Continuous Integration](https://github.com/tmbo/questionary/workflows/Continuous%20Integration/badge.svg)](#)
[![Coverage](https://coveralls.io/repos/github/tmbo/questionary/badge.svg?branch=master)](https://coveralls.io/github/tmbo/questionary?branch=master)
[![Supported Python Versions](https://img.shields.io/pypi/pyversions/questionary.svg)](https://pypi.python.org/pypi/questionary)
[![Documentation](https://readthedocs.org/projects/questionary/badge/?version=latest)](https://questionary.readthedocs.io/en/latest/?badge=latest)

✨ Questionary is a Python library for effortlessly building pretty command line interfaces ✨

* [Features](#features)
* [Installation](#installation)
* [Usage](#usage)
* [Documentation](#documentation)
* [Support](#support)


![Example](https://raw.githubusercontent.com/tmbo/questionary/master/docs/images/example.gif)

```python3
import questionary

questionary.text("What's your first name").ask()
questionary.password("What's your secret?").ask()
questionary.confirm("Are you amazed?").ask()

questionary.select(
"What do you want to do?",
choices=["Order a pizza", "Make a reservation", "Ask for opening hours"],
).ask()

questionary.rawselect(
"What do you want to do?",
choices=["Order a pizza", "Make a reservation", "Ask for opening hours"],
).ask()

questionary.checkbox(
"Select toppings", choices=["foo", "bar", "bazz"]
).ask()

questionary.path("Path to the projects version file").ask()
```

Used and supported by

[<img src="https://raw.githubusercontent.com/tmbo/questionary/master/docs/images/rasa-logo.svg" width="200">](https://github.com/RasaHQ/rasa)

## Features

Questionary supports the following input prompts:

* [Text](https://questionary.readthedocs.io/en/stable/pages/types.html#text)
* [Password](https://questionary.readthedocs.io/en/stable/pages/types.html#password)
* [File Path](https://questionary.readthedocs.io/en/stable/pages/types.html#file-path)
* [Confirmation](https://questionary.readthedocs.io/en/stable/pages/types.html#confirmation)
* [Select](https://questionary.readthedocs.io/en/stable/pages/types.html#select)
* [Raw select](https://questionary.readthedocs.io/en/stable/pages/types.html#raw-select)
* [Checkbox](https://questionary.readthedocs.io/en/stable/pages/types.html#checkbox)
* [Autocomplete](https://questionary.readthedocs.io/en/stable/pages/types.html#autocomplete)

There is also a helper to [print formatted text](https://questionary.readthedocs.io/en/stable/pages/types.html#printing-formatted-text)
for when you want to spice up your printed messages a bit.

## Installation

Use the package manager [pip](https://pip.pypa.io/en/stable/) to install Questionary:

```bash
$ pip install questionary
✨🎂✨
```

## Usage

```python
import questionary

questionary.select(
"What do you want to do?",
choices=[
'Order a pizza',
'Make a reservation',
'Ask for opening hours'
]).ask() # returns value of selection
```

That's all it takes to create a prompt! Have a [look at the documentation](https://questionary.readthedocs.io/)
for some more examples.

## Documentation

Documentation for Questionary is available [here](https://questionary.readthedocs.io/).

## Support

Please [open an issue](https://github.com/tmbo/questionary/issues/new)
with enough information for us to reproduce your problem.
A [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)
would be very helpful.

## Contributing

Contributions are very much welcomed and appreciated. Head over to the documentation on [how to contribute](https://questionary.readthedocs.io/en/stable/pages/contributors.html#steps-for-submitting-code).

## Authors and Acknowledgment

Questionary is written and maintained by Tom Bocklisch and Kian Cross.

It is based on the great work by [Oyetoke Toby](https://github.com/CITGuru/PyInquirer)
and [Mark Fink](https://github.com/finklabs/whaaaaat).

## License
Licensed under the [MIT License](https://github.com/tmbo/questionary/blob/master/LICENSE). Copyright 2021 Tom Bocklisch.
54 changes: 54 additions & 0 deletions utils/questionary/questionary/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# noinspection PyUnresolvedReferences
from prompt_toolkit.styles import Style
from prompt_toolkit.validation import ValidationError
from prompt_toolkit.validation import Validator

from .version import __version__
from .form import Form
from .form import FormField
from .form import form
from .prompt import prompt
from .prompt import unsafe_prompt

# import the shortcuts to create single question prompts
from .prompts.autocomplete import autocomplete
from .prompts.checkbox import checkbox
from .prompts.common import Choice
from .prompts.common import Separator
from .prompts.common import print_formatted_text as print
from .prompts.confirm import confirm
from .prompts.password import password
from .prompts.path import path
from .prompts.press_any_key_to_continue import press_any_key_to_continue
from .prompts.rawselect import rawselect
from .prompts.select import select
from .prompts.text import text
from .question import Question

__all__ = [
"__version__",
# question types
"autocomplete",
"checkbox",
"confirm",
"password",
"path",
"press_any_key_to_continue",
"rawselect",
"select",
"text",
# utility methods
"print",
"form",
"prompt",
"unsafe_prompt",
# commonly used classes
"Form",
"FormField",
"Question",
"Choice",
"Style",
"Separator",
"Validator",
"ValidationError",
]
Loading

0 comments on commit d7ca2a1

Please sign in to comment.