genshin-wiki/scripts/avatar.py

473 lines
16 KiB
Python
Raw Permalink Normal View History

2023-08-21 11:27:53 +00:00
from functools import lru_cache
2023-05-02 03:10:53 +00:00
from itertools import chain
2023-05-02 10:20:27 +00:00
from typing import TypeVar
2023-04-29 14:59:16 +00:00
2023-05-02 14:21:08 +00:00
import ujson as json
from aiofiles import open as async_open
from humps import pascalize
2023-08-21 12:53:35 +00:00
from logging import getLogger
2023-05-02 14:21:08 +00:00
2023-05-02 10:20:27 +00:00
from model.avatar import (
AddProp,
2023-05-02 10:20:27 +00:00
AlternateSprint,
2023-05-02 14:21:08 +00:00
Avatar,
2023-05-02 10:20:27 +00:00
AvatarAttribute,
AvatarBirth,
2023-05-02 14:21:08 +00:00
AvatarConstellation,
2023-05-02 10:20:27 +00:00
AvatarInfo,
AvatarPromote,
AvatarStories,
2023-05-02 12:43:01 +00:00
AvatarTalents,
CombatTalent,
2023-05-02 10:20:27 +00:00
ElementalBurst,
ElementalSkill,
2023-05-02 12:43:01 +00:00
FirstAscensionPassive,
FourthAscensionPassive,
MiscellaneousPassive,
2023-05-02 10:20:27 +00:00
NormalAttack,
2023-05-02 12:43:01 +00:00
PassiveTalent,
2023-05-02 10:20:27 +00:00
Seuyu,
Story,
Talent,
TalentAttribute,
2023-05-02 12:43:01 +00:00
UtilityPassive,
2023-05-02 10:20:27 +00:00
)
from model.enums import Association, AvatarQuality, Element, PropType, WeaponType
2023-05-02 10:20:27 +00:00
from model.other import ItemCount
2023-05-02 03:10:53 +00:00
from utils.const import PROJECT_ROOT
2023-05-02 14:21:08 +00:00
from utils.funcs import remove_rich_tag
2023-04-29 14:59:16 +00:00
from utils.manager import ResourceManager
2023-05-02 03:10:53 +00:00
from utils.typedefs import Lang
2023-05-02 10:20:27 +00:00
try:
import regex as re
except ImportError:
import re
2023-08-21 12:53:35 +00:00
logger = getLogger("scripts.avatar")
2023-05-02 12:43:01 +00:00
TalentType = TypeVar("TalentType", bound=Talent)
2023-05-02 10:20:27 +00:00
2023-05-02 03:10:53 +00:00
OUT_DIR = PROJECT_ROOT.joinpath("out")
2023-08-21 12:53:35 +00:00
OUT_DIR.mkdir(parents=True, exist_ok=True)
2023-05-02 03:10:53 +00:00
prop_type_map = {
"Hp": PropType.HP,
"RockAddHurt": PropType.Geo,
"ElecAddHurt": PropType.Electro,
"FireAddHurt": PropType.Pyro,
"WaterAddHurt": PropType.Hydro,
"IceAddHurt": PropType.Cryo,
"WindAddHurt": PropType.Anemo,
"GrassAddHurt": PropType.Dendro,
}
2023-04-29 14:59:16 +00:00
def get_skill_attributes(
proud_skill_group_id: int,
) -> tuple[list[TalentAttribute], list[str]]:
2023-05-02 14:21:08 +00:00
proud_skill_datas = sorted(
filter(
lambda x: x["proudSkillGroupId"] == proud_skill_group_id,
proud_skill_json_data,
),
key=lambda x: x["level"],
)
result: list[TalentAttribute] = []
param_descriptions: list[str] = []
2023-05-02 14:21:08 +00:00
for proud_skill_data in proud_skill_datas:
param_descriptions = list(
filter(
lambda x: x is not None,
map(
lambda x: manager.get_text(x),
proud_skill_data["paramDescList"],
),
)
)
param_num = len(param_descriptions)
for param_description in param_descriptions:
param_num = max(
param_num,
*map(int, re.findall(r"param(\d*)\:", param_description)),
)
result.append(
TalentAttribute(
level=proud_skill_data["level"],
params=proud_skill_data["paramList"][:param_num],
2023-05-02 14:21:08 +00:00
break_level=proud_skill_data.get("breakLevel", 0),
coin=proud_skill_data.get("coinCost", 0),
cost_items=list(
map(
lambda x: ItemCount(item_id=x["id"], count=x["count"]),
filter(lambda x: x, proud_skill_data["costItems"]),
)
),
)
)
return result, param_descriptions
2023-05-02 14:21:08 +00:00
def parse_skill(skill_id: int, skill_cls: type[CombatTalent]) -> CombatTalent:
skill_data = next(filter(lambda x: x["id"] == skill_id, skill_json_data))
_name = manager.get_text(skill_data["nameTextMapHash"])
_description = manager.get_text(skill_data["descTextMapHash"])
icon = skill_data["skillIcon"]
cooldown = (
skill_data.get("cdTime", 0) if "cooldown" in skill_cls.__fields__ else None
)
attributes, param_descriptions = get_skill_attributes(
skill_data["proudSkillGroupId"]
)
2023-05-02 14:21:08 +00:00
return skill_cls(
**{
i[0]: i[1]
for i in zip(
[
"name",
"description",
"icon",
"cooldown",
"attributes",
"param_descriptions",
],
[_name, _description, icon, cooldown, attributes, param_descriptions],
2023-05-02 14:21:08 +00:00
)
if i is not None
}
)
def parse_passive_talent(
talent_data: dict, talent_cls: type[PassiveTalent]
) -> PassiveTalent:
group_id = talent_data["proudSkillGroupId"]
_promote_level = talent_data.get("needAvatarPromoteLevel", 0)
skill_data = next(
filter(lambda x: x["proudSkillGroupId"] == group_id, proud_skill_json_data)
)
param_descriptions = list(
filter(
lambda x: x is not None,
map(
lambda x: manager.get_text(x),
skill_data["paramDescList"],
),
)
)
_description = manager.get_text(skill_data["descTextMapHash"])
_param_list = skill_data["paramList"][
: len(re.findall(r"(\d+(?:\.)?\d+)", remove_rich_tag(_description) or ""))
]
return talent_cls(
name=manager.get_text(skill_data["nameTextMapHash"]) or "",
description=_description or "",
icon=skill_data["icon"],
promote_level=_promote_level,
param_descriptions=param_descriptions,
2023-05-02 14:21:08 +00:00
attribute=TalentAttribute(
params=_param_list,
2023-05-02 14:21:08 +00:00
break_level=skill_data.get("breakLevel", 0),
),
)
2023-08-21 11:27:53 +00:00
@lru_cache
def get_element_data() -> dict[Element, set[int]]:
_manager = ResourceManager("chs")
_avatar_json_data = _manager.fetch("AvatarExcelConfigData")
_fetter_info_json_data = manager.fetch("FetterInfoExcelConfigData")
text_map = {
"": Element.Pyro,
"": Element.Hydro,
"": Element.Anemo,
"": Element.Electro,
"": Element.Dendro,
"": Element.Cryo,
"": Element.Geo,
"": Element.Null,
}
result = {k: set() for k in text_map.values()}
for data in _avatar_json_data:
_id = data["id"]
if (
info_data := next(
chain(
filter(lambda x: x["avatarId"] == _id, _fetter_info_json_data),
[None],
)
)
) is None:
continue
if (
vision := _manager.get_text(
text_id := info_data["avatarVisionBeforTextMapHash"]
)
) is not None:
result[text_map[vision]] = set(list(result[text_map[vision]]) + [text_id])
return result
2023-05-02 14:21:08 +00:00
# noinspection PyShadowingBuiltins,SpellCheckingInspection,PyGlobalUndefined
2023-04-29 14:59:16 +00:00
async def parse_avatar_data(lang: Lang):
2023-05-02 14:21:08 +00:00
global out_path, manager
global avatar_json_data, fetter_info_json_data, story_json_data, promote_json_data
global skill_depot_json_data, skill_json_data, proud_skill_json_data, talent_json_data
2023-05-02 03:10:53 +00:00
out_path = OUT_DIR.joinpath(f"{lang}")
out_path.mkdir(exist_ok=True, parents=True)
manager = ResourceManager(lang=lang)
avatar_json_data = manager.fetch("AvatarExcelConfigData")
fetter_info_json_data = manager.fetch("FetterInfoExcelConfigData")
story_json_data = manager.fetch("FetterStoryExcelConfigData")
2023-05-02 10:20:27 +00:00
promote_json_data = manager.fetch("AvatarPromoteExcelConfigData")
skill_depot_json_data = manager.fetch("AvatarSkillDepotExcelConfigData")
skill_json_data = manager.fetch("AvatarSkillExcelConfigData")
proud_skill_json_data = manager.fetch("ProudSkillExcelConfigData")
2023-05-02 14:21:08 +00:00
talent_json_data = manager.fetch("AvatarTalentExcelConfigData")
2023-05-02 03:10:53 +00:00
2023-08-21 11:27:53 +00:00
element_data = get_element_data()
2023-05-02 03:10:53 +00:00
avatar_list = []
for data in avatar_json_data:
id = data["id"]
if (
info_data := next(
chain(
2023-05-02 14:21:08 +00:00
filter(lambda x: x["avatarId"] == id, fetter_info_json_data), [None]
2023-05-02 03:10:53 +00:00
)
)
) is None:
continue
name = manager.get_text(data["nameTextMapHash"])
2023-05-02 14:21:08 +00:00
element = next(
filter(
2023-08-21 11:27:53 +00:00
lambda x: info_data["avatarVisionBeforTextMapHash"] in x[1],
element_data.items(),
2023-05-02 14:21:08 +00:00
)
2023-08-21 11:27:53 +00:00
)[0]
2023-05-02 14:21:08 +00:00
quality = AvatarQuality(
data["qualityType"].removeprefix("QUALITY_").replace("ORANGE_SP", "SPECIAL")
)
2023-05-02 03:10:53 +00:00
weapon_type = next(
2023-05-02 14:21:08 +00:00
filter(
lambda x: x in data["weaponType"].replace("POLE", "POLEARM"),
WeaponType.__members__.values(),
)
2023-05-02 03:10:53 +00:00
)
2023-05-02 10:20:27 +00:00
# 角色信息
2023-05-02 03:10:53 +00:00
title = manager.get_text(info_data["avatarTitleTextMapHash"])
2023-05-02 14:21:08 +00:00
birth = (
AvatarBirth(
month=info_data["infoBirthMonth"], day=info_data["infoBirthDay"]
)
if id not in [10000005, 10000007]
else None
2023-05-02 03:10:53 +00:00
)
occupation = manager.get_text(info_data["avatarNativeTextMapHash"])
vision = manager.get_text(info_data["avatarVisionBeforTextMapHash"])
constellation = manager.get_text(
info_data["avatarConstellationBeforTextMapHash"]
)
description = manager.get_text(info_data["avatarDetailTextMapHash"])
association = Association(
info_data["avatarAssocType"].removeprefix("ASSOC_TYPE_")
)
seuyu = Seuyu(
cn=manager.get_text(info_data["cvChineseTextMapHash"]),
jp=manager.get_text(info_data["cvJapaneseTextMapHash"]),
en=manager.get_text(info_data["cvEnglishTextMapHash"]),
kr=manager.get_text(info_data["cvKoreanTextMapHash"]),
)
2023-05-02 14:21:08 +00:00
story_datas = sorted(
2023-05-02 03:10:53 +00:00
filter(lambda x: x["avatarId"] == id, story_json_data),
key=lambda x: x["fetterId"],
)
2023-05-02 14:21:08 +00:00
stories = []
for story_data in sorted(
filter(lambda x: x["avatarId"] == id, story_datas),
key=lambda x: x["fetterId"],
):
tips = list(
filter(
lambda x: x is not None,
map(lambda x: manager.get_text(x), story_data["tips"]),
2023-05-02 03:10:53 +00:00
)
2023-05-02 14:21:08 +00:00
)
story = Story(
title=manager.get_text(story_data["storyTitleTextMapHash"]),
content=manager.get_text(story_data["storyContextTextMapHash"]),
tips=tips,
)
stories.append(story)
avatar_stories = AvatarStories(
**{i[0]: i[1] for i in zip(AvatarStories.__fields__, stories)}
2023-05-02 03:10:53 +00:00
)
information = AvatarInfo(
title=title,
birth=birth,
occupation=occupation,
vision=vision,
constellation=constellation,
description=description,
association=association,
seuyu=seuyu,
2023-05-02 14:21:08 +00:00
stories=avatar_stories,
2023-05-02 03:10:53 +00:00
)
2023-05-02 10:20:27 +00:00
# 角色基础属性
2023-05-02 14:21:08 +00:00
attributes = AvatarAttribute(
2023-05-02 10:20:27 +00:00
HP=data["hpBase"],
Attack=data["attackBase"],
Defense=data["defenseBase"],
Critical=data["critical"],
CriticalHurt=data["criticalHurt"],
2023-05-02 10:20:27 +00:00
ChargeEfficiency=data["chargeEfficiency"],
)
# 天赋
skill_depot_data = next(
filter(lambda x: x["id"] == data["skillDepotId"], skill_depot_json_data)
)
skill_ids = list(filter(lambda x: x != 0, skill_depot_data["skills"]))
# 普通攻击
normal_attack = parse_skill(skill_ids[0], NormalAttack)
# 冲刺技能
2023-05-02 12:43:01 +00:00
alternate_sprint = (
parse_skill(skill_ids[2], AlternateSprint) if len(skill_ids) == 3 else None
)
if id not in [10000005, 10000007]:
# 元素战技
elemental_skill = parse_skill(skill_ids[1], ElementalSkill)
# 元素爆发
burst_skill = parse_skill(skill_depot_data["energySkill"], ElementalBurst)
# 第一次突破被动天赋
first_passive = parse_passive_talent(
2023-05-02 14:21:08 +00:00
skill_depot_data["inherentProudSkillOpens"][0], FirstAscensionPassive
)
# 第四次突破被动天赋
fourth_passive = parse_passive_talent(
2023-05-02 14:21:08 +00:00
skill_depot_data["inherentProudSkillOpens"][1], FourthAscensionPassive
)
# 实用固有天赋
utility_passive = parse_passive_talent(
2023-05-02 14:21:08 +00:00
skill_depot_data["inherentProudSkillOpens"][2], UtilityPassive
)
else:
elemental_skill = (
burst_skill
) = first_passive = fourth_passive = utility_passive = None
# 杂项固有天赋
2023-05-02 14:21:08 +00:00
if skill_depot_data["inherentProudSkillOpens"][3]:
2023-05-02 12:43:01 +00:00
miscellaneous_passive = parse_passive_talent(
skill_depot_data["inherentProudSkillOpens"][3], MiscellaneousPassive
)
else:
miscellaneous_passive = None
# noinspection PyTypeChecker
avatar_talents = AvatarTalents(
normal_attack=normal_attack,
elemental_skill=elemental_skill,
elemental_burst=burst_skill,
alternate_sprint=alternate_sprint,
first_ascension_passive=first_passive,
fourth_ascension_passive=fourth_passive,
utility_passive=utility_passive,
miscellaneous_passive=miscellaneous_passive,
)
2023-05-02 10:20:27 +00:00
# 角色突破数据
promote_id = data["avatarPromoteId"]
promote_datas = sorted(
filter(lambda x: x["avatarPromoteId"] == promote_id, promote_json_data),
key=lambda x: x.get("promoteLevel", 0),
)
promotes = []
for promote_data in promote_datas:
items = []
for item_data in promote_data["costItems"]:
2023-05-02 14:21:08 +00:00
if item_data and id not in [10000005, 10000007]:
2023-05-02 10:20:27 +00:00
items.append(
ItemCount(item_id=item_data["id"], count=item_data["count"])
)
add_props = []
for add_prop_data in promote_data["addProps"]:
_string = pascalize(
add_prop_data["propType"]
.removeprefix("FIGHT_PROP_")
.removeprefix("BASE_")
.lower()
).replace("Hp", "HP")
prop_type_string = {
**prop_type_map,
**PropType.__members__,
**{v: v for k, v in PropType.__members__.items()},
}[_string]
prop_type = PropType(prop_type_string)
add_props.append(
AddProp(
type=prop_type,
value=add_prop_data.get(
"value", attributes.dict().get(prop_type, 0)
),
)
)
2023-05-02 10:20:27 +00:00
promotes.append(
AvatarPromote(
promote_level=promote_data.get("promoteLevel", 0),
max_level=promote_data["unlockMaxLevel"],
add_props=add_props,
2023-05-02 10:20:27 +00:00
coin=promote_data.get("scoinCost", 0),
cost_items=items,
)
)
2023-05-02 14:21:08 +00:00
# 角色命座信息
constellations: list[AvatarConstellation] = []
for constellation_id in filter(lambda x: x != 0, skill_depot_data["talents"]):
constellation_data = next(
filter(lambda x: x["talentId"] == constellation_id, talent_json_data)
)
constellation_description = manager.get_text(
constellation_data["descTextMapHash"]
)
# noinspection PyTypeChecker
constellations.append(
AvatarConstellation(
name=manager.get_text(constellation_data["nameTextMapHash"]),
description=constellation_description,
icon=constellation_data["icon"],
param_list=list(
filter(lambda x: x != 0.0, constellation_data["paramList"])
),
)
)
avatar = Avatar(
id=id,
name=name,
element=element,
quality=quality,
weapon_type=weapon_type,
information=information,
attributes=attributes,
talents=avatar_talents,
promotes=promotes,
constellations=constellations,
)
avatar_list.append(avatar)
2023-08-21 12:53:35 +00:00
logger.info(f"成功爬取了 {name} 的数据")
2023-05-02 14:21:08 +00:00
async with async_open(out_path / "avatar.json", encoding="utf-8", mode="w") as file:
await file.write(
json.dumps(
[i.dict(exclude_none=True) for i in avatar_list],
2023-05-02 14:21:08 +00:00
ensure_ascii=False,
encode_html_chars=False,
indent=4,
),
)
return out_path, avatar_list