nonebot-plugin-bugu 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nonebot_plugin_bugu/__init__.py +31 -0
- nonebot_plugin_bugu/api.py +282 -0
- nonebot_plugin_bugu/collection.py +166 -0
- nonebot_plugin_bugu/commands.py +234 -0
- nonebot_plugin_bugu/config.py +91 -0
- nonebot_plugin_bugu/draw.py +406 -0
- nonebot_plugin_bugu/features/__init__.py +0 -0
- nonebot_plugin_bugu/features/collection.py +247 -0
- nonebot_plugin_bugu/features/common.py +100 -0
- nonebot_plugin_bugu/features/flowers/__init__.py +0 -0
- nonebot_plugin_bugu/features/flowers/data.py +167 -0
- nonebot_plugin_bugu/features/flowers/render.py +300 -0
- nonebot_plugin_bugu/features/flowers/reply.py +123 -0
- nonebot_plugin_bugu/features/neighbors/__init__.py +0 -0
- nonebot_plugin_bugu/features/neighbors/data.py +143 -0
- nonebot_plugin_bugu/features/neighbors/render.py +225 -0
- nonebot_plugin_bugu/features/neighbors/reply.py +149 -0
- nonebot_plugin_bugu/features/recipes/__init__.py +0 -0
- nonebot_plugin_bugu/features/recipes/data.py +313 -0
- nonebot_plugin_bugu/features/recipes/render.py +371 -0
- nonebot_plugin_bugu/features/recipes/reply.py +219 -0
- nonebot_plugin_bugu/features/recipes/search.py +151 -0
- nonebot_plugin_bugu/features/starsea/__init__.py +0 -0
- nonebot_plugin_bugu/features/starsea/data.py +267 -0
- nonebot_plugin_bugu/features/starsea/render.py +579 -0
- nonebot_plugin_bugu/features/starsea/reply.py +356 -0
- nonebot_plugin_bugu/features/starsea/search.py +271 -0
- nonebot_plugin_bugu/fonts.py +152 -0
- nonebot_plugin_bugu/runtime.py +109 -0
- nonebot_plugin_bugu/values.py +87 -0
- nonebot_plugin_bugu-0.2.0.dist-info/METADATA +257 -0
- nonebot_plugin_bugu-0.2.0.dist-info/RECORD +35 -0
- nonebot_plugin_bugu-0.2.0.dist-info/WHEEL +4 -0
- nonebot_plugin_bugu-0.2.0.dist-info/entry_points.txt +3 -0
- nonebot_plugin_bugu-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""菜谱的文字回复与命令逻辑。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import random
|
|
6
|
+
from typing import Dict, List, Sequence, Set, Tuple
|
|
7
|
+
|
|
8
|
+
from ...collection import KIND_RECIPE
|
|
9
|
+
from ...values import grade_text
|
|
10
|
+
from ..common import Reply, ReplyEnv, render_card, usage
|
|
11
|
+
from .data import Recipe, RecipeBook
|
|
12
|
+
from .render import render_recipe_card
|
|
13
|
+
from .search import (
|
|
14
|
+
FILTER_LABELS,
|
|
15
|
+
RecipeHit,
|
|
16
|
+
filter_summary,
|
|
17
|
+
list_by_filter,
|
|
18
|
+
parse_query,
|
|
19
|
+
search,
|
|
20
|
+
split_sections,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
# ------------------------------------------------------------------ 文案
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def stats_text(book: RecipeBook) -> str:
|
|
27
|
+
lines = [f"菜谱 · 共 {book.count} 道", ""]
|
|
28
|
+
type_options = book.filters.get("type") or []
|
|
29
|
+
if type_options:
|
|
30
|
+
lines.append("按类型:" + "、".join(f"{o.value} {o.count}" for o in type_options))
|
|
31
|
+
kitchen_options = book.filters.get("kitchen") or []
|
|
32
|
+
if kitchen_options:
|
|
33
|
+
lines.append("按厨具:" + "、".join(f"{o.value} {o.count}" for o in kitchen_options))
|
|
34
|
+
lines.append("")
|
|
35
|
+
lines.append(usage(
|
|
36
|
+
"菜谱 <菜名 / 编号> —— 查看菜谱卡片",
|
|
37
|
+
"菜谱查 <食材 / 菜名 / 类型 / 厨具> —— 搜索与筛选",
|
|
38
|
+
"菜谱 随机 —— 随机看一道",
|
|
39
|
+
"例:菜谱 炒鲜蔬 / 菜谱 12 / 菜谱查 苹果 / 菜谱查 煮锅 苹果",
|
|
40
|
+
))
|
|
41
|
+
return "\n".join(lines)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def recipe_text(book: RecipeBook, recipe: Recipe) -> str:
|
|
45
|
+
head = [f"【{recipe.display_name}】#{recipe.number_text}" + (f" · {recipe.type}" if recipe.type else "")]
|
|
46
|
+
if recipe.level_text:
|
|
47
|
+
head[0] += f" · {recipe.level_text}"
|
|
48
|
+
|
|
49
|
+
meta = []
|
|
50
|
+
if recipe.quality:
|
|
51
|
+
meta.append(f"{grade_text(recipe.quality)}品质")
|
|
52
|
+
if recipe.strength is not None:
|
|
53
|
+
meta.append(f"力气 +{recipe.strength}")
|
|
54
|
+
if recipe.cuisine:
|
|
55
|
+
meta.append(recipe.cuisine)
|
|
56
|
+
if meta:
|
|
57
|
+
head.append(" · ".join(meta))
|
|
58
|
+
|
|
59
|
+
if recipe.ingredients:
|
|
60
|
+
names = []
|
|
61
|
+
for ingredient in recipe.ingredients:
|
|
62
|
+
label = ingredient.label
|
|
63
|
+
if ingredient.quality in {"A", "S"} and not ingredient.placeholder:
|
|
64
|
+
label = f"{grade_text(ingredient.quality)}品质{label}"
|
|
65
|
+
names.append(label)
|
|
66
|
+
head.append("食材:" + " × ".join(names))
|
|
67
|
+
if recipe.kitchen is not None:
|
|
68
|
+
head.append(f"厨具:{recipe.kitchen.name}")
|
|
69
|
+
if recipe.buff is not None:
|
|
70
|
+
effect = recipe.buff.label
|
|
71
|
+
if recipe.buff.effect_raw:
|
|
72
|
+
effect += f"({recipe.buff.effect_raw})"
|
|
73
|
+
head.append(f"效果:{effect}")
|
|
74
|
+
if recipe.food_tags:
|
|
75
|
+
head.append("标签:" + "、".join(recipe.food_tags))
|
|
76
|
+
if recipe.neighbor is not None:
|
|
77
|
+
head.append(f"友邻料理:{recipe.neighbor.name}")
|
|
78
|
+
if recipe.description:
|
|
79
|
+
head.append(f"描述:{recipe.description}")
|
|
80
|
+
for source in recipe.sources:
|
|
81
|
+
head.append(f"获取途径:{source}")
|
|
82
|
+
if recipe.incomplete_notice:
|
|
83
|
+
head.append(recipe.incomplete_notice)
|
|
84
|
+
return "\n".join(head)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _hit_line(hit: RecipeHit) -> str:
|
|
88
|
+
recipe = hit.recipe
|
|
89
|
+
parts = [f"#{recipe.number_text}", recipe.display_name]
|
|
90
|
+
if recipe.type:
|
|
91
|
+
parts.append(recipe.type)
|
|
92
|
+
if recipe.quality:
|
|
93
|
+
parts.append(recipe.quality)
|
|
94
|
+
if recipe.kitchen is not None and recipe.kitchen.specified:
|
|
95
|
+
parts.append(recipe.kitchen.name)
|
|
96
|
+
return " · ".join(parts)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def list_text(
|
|
100
|
+
book: RecipeBook,
|
|
101
|
+
hits: Sequence[RecipeHit],
|
|
102
|
+
query: str,
|
|
103
|
+
*,
|
|
104
|
+
limit: int = 12,
|
|
105
|
+
) -> str:
|
|
106
|
+
if not hits:
|
|
107
|
+
return f"没找到和「{query}」有关的菜谱。"
|
|
108
|
+
shown = list(hits[:limit])
|
|
109
|
+
parsed = parse_query(book, query)
|
|
110
|
+
title = "菜谱 · 搜索「" + query + "」"
|
|
111
|
+
if parsed.filters:
|
|
112
|
+
title += f"({filter_summary(parsed.filters)})"
|
|
113
|
+
lines = [title, f"命中 {len(hits)} 道" + (f",显示前 {len(shown)} 道" if len(hits) > len(shown) else "")]
|
|
114
|
+
|
|
115
|
+
by_ingredient, rest = split_sections(hits, query)
|
|
116
|
+
if len(parsed.keywords) == 1 and by_ingredient and rest:
|
|
117
|
+
lines.append("")
|
|
118
|
+
lines.append(f"可用「{parsed.keywords[0]}」烹饪:")
|
|
119
|
+
for hit in by_ingredient[:limit]:
|
|
120
|
+
lines.append(f"· {_hit_line(hit)}")
|
|
121
|
+
lines.append("")
|
|
122
|
+
lines.append(f"名称里有「{parsed.keywords[0]}」:")
|
|
123
|
+
for hit in rest[:limit]:
|
|
124
|
+
lines.append(f"· {_hit_line(hit)}")
|
|
125
|
+
else:
|
|
126
|
+
lines.append("")
|
|
127
|
+
for hit in shown:
|
|
128
|
+
lines.append(f"· {_hit_line(hit)}")
|
|
129
|
+
|
|
130
|
+
lines.append("")
|
|
131
|
+
lines.append(usage("菜谱 <菜名 / 编号> 查看详情"))
|
|
132
|
+
return "\n".join(lines)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def filter_text(book: RecipeBook, key: str, value: str, limit: int = 30) -> str:
|
|
136
|
+
recipes = list_by_filter(book, key, value)
|
|
137
|
+
label = FILTER_LABELS.get(key, key)
|
|
138
|
+
lines = [f"菜谱 · {label}「{value}」共 {len(recipes)} 道", ""]
|
|
139
|
+
for recipe in recipes[:limit]:
|
|
140
|
+
lines.append(f"· #{recipe.number_text} {recipe.display_name}")
|
|
141
|
+
if len(recipes) > limit:
|
|
142
|
+
lines.append(f"…… 还有 {len(recipes) - limit} 道")
|
|
143
|
+
lines.append("")
|
|
144
|
+
lines.append(usage("菜谱 <菜名> 查看详情"))
|
|
145
|
+
return "\n".join(lines)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ------------------------------------------------------------------ 出图
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
async def _recipe_reply(book: RecipeBook, recipe: Recipe, env: ReplyEnv) -> Reply:
|
|
152
|
+
png = None
|
|
153
|
+
if env.can_render:
|
|
154
|
+
urls = [recipe.dish, recipe.kitchen.icon if recipe.kitchen else ""]
|
|
155
|
+
urls.append(recipe.neighbor.icon if recipe.neighbor else "")
|
|
156
|
+
urls.extend(icon for ing in recipe.ingredients for icon in ing.icons)
|
|
157
|
+
images = await env.client.get_images(urls)
|
|
158
|
+
png = await render_card(
|
|
159
|
+
render_recipe_card,
|
|
160
|
+
book,
|
|
161
|
+
recipe,
|
|
162
|
+
images,
|
|
163
|
+
fonts=env.fonts,
|
|
164
|
+
unlocked=env.is_collected(KIND_RECIPE, recipe.number),
|
|
165
|
+
label="菜谱卡片",
|
|
166
|
+
)
|
|
167
|
+
return png if png is not None else recipe_text(book, recipe)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# ------------------------------------------------------------------ 命令
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
async def reply_recipes(arg: str, env: ReplyEnv) -> Reply:
|
|
174
|
+
book = await env.client.get_recipes()
|
|
175
|
+
arg = (arg or "").strip()
|
|
176
|
+
if not arg:
|
|
177
|
+
return stats_text(book)
|
|
178
|
+
if arg in {"随机", "随便", "来一个", "random"}:
|
|
179
|
+
return await _recipe_reply(book, random.choice(book.recipes), env)
|
|
180
|
+
|
|
181
|
+
exact = book.find_exact(arg)
|
|
182
|
+
if exact is not None:
|
|
183
|
+
return await _recipe_reply(book, exact, env)
|
|
184
|
+
|
|
185
|
+
# 只给筛选条件(例如「煮锅」)就直接列这个分类
|
|
186
|
+
parsed = parse_query(book, arg)
|
|
187
|
+
if parsed.filters and not parsed.keywords:
|
|
188
|
+
key, value = next(iter(parsed.filters.items()))
|
|
189
|
+
return filter_text(book, key, next(iter(value)))
|
|
190
|
+
|
|
191
|
+
hits, _ = search(book, arg)
|
|
192
|
+
if len(hits) == 1:
|
|
193
|
+
return await _recipe_reply(book, hits[0].recipe, env)
|
|
194
|
+
return list_text(book, hits, arg, limit=env.config.bugu_search_limit)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
async def reply_search(arg: str, env: ReplyEnv) -> Reply:
|
|
198
|
+
arg = (arg or "").strip()
|
|
199
|
+
if not arg:
|
|
200
|
+
return usage(
|
|
201
|
+
"菜谱查 <食材 / 菜名 / 类型 / 厨具 / 效果 / 特征>",
|
|
202
|
+
"例:菜谱查 苹果",
|
|
203
|
+
" :菜谱查 煮锅 苹果",
|
|
204
|
+
" :菜谱查 秘制",
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
book = await env.client.get_recipes()
|
|
208
|
+
hits, parsed = search(book, arg)
|
|
209
|
+
if len(hits) == 1:
|
|
210
|
+
return await _recipe_reply(book, hits[0].recipe, env)
|
|
211
|
+
if not hits and parsed.is_empty:
|
|
212
|
+
return f"没找到「{arg}」。试试菜名、编号、食材(苹果 / 海鲜),或者类型(简单 / 招牌 / 宴客 / 秘制)。"
|
|
213
|
+
return list_text(book, hits, arg, limit=env.config.bugu_search_limit)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def sections_for_query(book: RecipeBook, query: str) -> Tuple[List[Recipe], Dict[str, Set[str]]]:
|
|
217
|
+
"""调试 / 测试用:返回命中的菜谱与解析出的筛选条件。"""
|
|
218
|
+
hits, parsed = search(book, query)
|
|
219
|
+
return [hit.recipe for hit in hits], parsed.filters
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""菜谱搜索与筛选。
|
|
2
|
+
|
|
3
|
+
规则对齐站点搜索框 + 顶部筛选器:
|
|
4
|
+
|
|
5
|
+
* 搜索:食材(支持别名,水果→水果类)、菜名、编号;
|
|
6
|
+
* 筛选:菜品类型 / 厨具 / 特殊效果 / 菜品特征(同一筛选器内是「或」,不同筛选器之间是「与」);
|
|
7
|
+
* 一个查询里可以混着写:``/菜谱查 煮锅 苹果`` → 「用苹果做的煮锅菜谱」。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Dict, List, Optional, Sequence, Set, Tuple
|
|
14
|
+
|
|
15
|
+
from .data import Recipe, RecipeBook
|
|
16
|
+
|
|
17
|
+
FILTER_LABELS = {
|
|
18
|
+
"type": "菜品类型",
|
|
19
|
+
"kitchen": "厨具",
|
|
20
|
+
"buff": "特殊效果",
|
|
21
|
+
"foodTag": "菜品特征",
|
|
22
|
+
"quality": "品质",
|
|
23
|
+
"cuisine": "风味",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
# 「食材」以外的命中原因,用来分组展示
|
|
27
|
+
REASON_LABELS = {
|
|
28
|
+
"ingredient": "食材",
|
|
29
|
+
"name": "菜名",
|
|
30
|
+
"number": "编号",
|
|
31
|
+
"filter": "筛选",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class RecipeHit:
|
|
37
|
+
recipe: Recipe
|
|
38
|
+
reasons: List[str] = field(default_factory=list)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class ParsedQuery:
|
|
43
|
+
keywords: List[str] = field(default_factory=list)
|
|
44
|
+
filters: Dict[str, Set[str]] = field(default_factory=dict)
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def is_empty(self) -> bool:
|
|
48
|
+
return not self.keywords and not self.filters
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def parse_query(book: RecipeBook, text: str) -> ParsedQuery:
|
|
52
|
+
"""把一句话拆成「关键词 + 筛选条件」。"""
|
|
53
|
+
parsed = ParsedQuery()
|
|
54
|
+
for token in (text or "").split():
|
|
55
|
+
token = token.strip()
|
|
56
|
+
if not token:
|
|
57
|
+
continue
|
|
58
|
+
found = book.filter_value(token)
|
|
59
|
+
if found is not None:
|
|
60
|
+
key, value = found
|
|
61
|
+
parsed.filters.setdefault(key, set()).add(value)
|
|
62
|
+
else:
|
|
63
|
+
parsed.keywords.append(token)
|
|
64
|
+
return parsed
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def matches_filters(recipe: Recipe, filters: Dict[str, Set[str]]) -> bool:
|
|
68
|
+
"""不同筛选器之间是「与」,同一个筛选器的多个值之间是「或」。"""
|
|
69
|
+
if not filters:
|
|
70
|
+
return True
|
|
71
|
+
kitchen_name = recipe.kitchen.name if recipe.kitchen and recipe.kitchen.specified else None
|
|
72
|
+
checks = {
|
|
73
|
+
"type": lambda values: recipe.type in values,
|
|
74
|
+
"kitchen": lambda values: kitchen_name in values,
|
|
75
|
+
"buff": lambda values: recipe.buff is not None and recipe.buff.name in values,
|
|
76
|
+
"foodTag": lambda values: any(tag in values for tag in recipe.food_tags),
|
|
77
|
+
"quality": lambda values: recipe.quality in values,
|
|
78
|
+
"cuisine": lambda values: recipe.cuisine in values,
|
|
79
|
+
}
|
|
80
|
+
for key, values in filters.items():
|
|
81
|
+
if not values:
|
|
82
|
+
continue
|
|
83
|
+
check = checks.get(key)
|
|
84
|
+
if check is not None and not check(values):
|
|
85
|
+
return False
|
|
86
|
+
return True
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _match_reason(book: RecipeBook, recipe: Recipe, keyword: str) -> Optional[str]:
|
|
90
|
+
folded = keyword.casefold()
|
|
91
|
+
alias = book.aliases.get(keyword, keyword)
|
|
92
|
+
if alias and alias in recipe.ingredient_tokens:
|
|
93
|
+
return "ingredient"
|
|
94
|
+
if folded and folded in recipe.search_name.casefold():
|
|
95
|
+
return "name"
|
|
96
|
+
if keyword.isdigit() and int(keyword) == recipe.number:
|
|
97
|
+
return "number"
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def search(
|
|
102
|
+
book: RecipeBook,
|
|
103
|
+
query: str,
|
|
104
|
+
*,
|
|
105
|
+
limit: Optional[int] = None,
|
|
106
|
+
) -> Tuple[List[RecipeHit], ParsedQuery]:
|
|
107
|
+
"""按关键词 + 筛选条件搜索,返回命中的菜谱(按编号排序)。"""
|
|
108
|
+
parsed = parse_query(book, query)
|
|
109
|
+
if parsed.is_empty:
|
|
110
|
+
return [], parsed
|
|
111
|
+
|
|
112
|
+
pool = [recipe for recipe in book.recipes if matches_filters(recipe, parsed.filters)]
|
|
113
|
+
hits: List[RecipeHit] = []
|
|
114
|
+
for recipe in pool:
|
|
115
|
+
reasons: List[str] = []
|
|
116
|
+
matched = True
|
|
117
|
+
for keyword in parsed.keywords:
|
|
118
|
+
reason = _match_reason(book, recipe, keyword)
|
|
119
|
+
if reason is None:
|
|
120
|
+
matched = False
|
|
121
|
+
break
|
|
122
|
+
reasons.append(reason)
|
|
123
|
+
if not matched:
|
|
124
|
+
continue
|
|
125
|
+
hits.append(RecipeHit(recipe=recipe, reasons=reasons or ["filter"]))
|
|
126
|
+
|
|
127
|
+
hits.sort(key=lambda hit: hit.recipe.number)
|
|
128
|
+
if limit is not None and limit > 0:
|
|
129
|
+
return hits[:limit], parsed
|
|
130
|
+
return hits, parsed
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def list_by_filter(book: RecipeBook, key: str, value: str) -> List[Recipe]:
|
|
134
|
+
return [recipe for recipe in book.recipes if matches_filters(recipe, {key: {value}})]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def split_sections(
|
|
138
|
+
hits: Sequence[RecipeHit], query: str
|
|
139
|
+
) -> Tuple[List[RecipeHit], List[RecipeHit]]:
|
|
140
|
+
"""单个关键词时按站点习惯分成「可用它烹饪」和「名字里有它」两组。"""
|
|
141
|
+
by_ingredient = [hit for hit in hits if "ingredient" in hit.reasons]
|
|
142
|
+
rest = [hit for hit in hits if hit not in by_ingredient]
|
|
143
|
+
return by_ingredient, rest
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def filter_summary(filters: Dict[str, Set[str]]) -> str:
|
|
147
|
+
parts = []
|
|
148
|
+
for key, values in filters.items():
|
|
149
|
+
label = FILTER_LABELS.get(key, key)
|
|
150
|
+
parts.append(f"{label}:{'/'.join(sorted(values))}")
|
|
151
|
+
return " · ".join(parts)
|
|
File without changes
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""星海地图的数据模型。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, Dict, Iterator, List, Optional, Tuple
|
|
7
|
+
|
|
8
|
+
from ...values import (
|
|
9
|
+
absolute_url,
|
|
10
|
+
as_float,
|
|
11
|
+
as_int,
|
|
12
|
+
as_int_list,
|
|
13
|
+
as_str,
|
|
14
|
+
as_str_list,
|
|
15
|
+
grade_text,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Species:
|
|
21
|
+
"""一个可采集物(昆虫 / 鱼 / 树木 / 鲜花 / 矿产 / 创想卡 / 种子……)。"""
|
|
22
|
+
|
|
23
|
+
id: int
|
|
24
|
+
name: str
|
|
25
|
+
kind: str
|
|
26
|
+
kind_name: str
|
|
27
|
+
display_name: str
|
|
28
|
+
grade: str
|
|
29
|
+
islet_specialty: bool
|
|
30
|
+
detail: str
|
|
31
|
+
icon: str
|
|
32
|
+
has_icon: bool
|
|
33
|
+
sort: int
|
|
34
|
+
kind_note: str = ""
|
|
35
|
+
flower_family: str = ""
|
|
36
|
+
flower_color: str = ""
|
|
37
|
+
flower_state: Optional[int] = None
|
|
38
|
+
flower_state_name: str = ""
|
|
39
|
+
flower_state_note: str = ""
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def label(self) -> str:
|
|
43
|
+
return self.display_name or self.name
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def grade_label(self) -> str:
|
|
47
|
+
return grade_text(self.grade)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class SeaType:
|
|
52
|
+
code: str
|
|
53
|
+
name: str
|
|
54
|
+
special: bool
|
|
55
|
+
icon: str
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class Encounter:
|
|
60
|
+
name: str
|
|
61
|
+
avatar: str
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class SeaPoint:
|
|
66
|
+
"""星海上的一个点位(采集点 / 传送点 / 星门)。"""
|
|
67
|
+
|
|
68
|
+
name: str
|
|
69
|
+
type: str
|
|
70
|
+
type_name: str
|
|
71
|
+
type_icon: str
|
|
72
|
+
special: bool
|
|
73
|
+
x: float
|
|
74
|
+
y: float
|
|
75
|
+
species_ids: List[int] = field(default_factory=list)
|
|
76
|
+
creatures: List[str] = field(default_factory=list)
|
|
77
|
+
trees: List[str] = field(default_factory=list)
|
|
78
|
+
flowers: List[str] = field(default_factory=list)
|
|
79
|
+
specialty: Optional[str] = None
|
|
80
|
+
header: str = ""
|
|
81
|
+
note: str = ""
|
|
82
|
+
hide_flower_state: bool = False
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def is_station(self) -> bool:
|
|
86
|
+
return self.type == "Station"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass
|
|
90
|
+
class SeaMap:
|
|
91
|
+
code: str
|
|
92
|
+
name: str
|
|
93
|
+
note: str
|
|
94
|
+
image: str
|
|
95
|
+
thumb: str
|
|
96
|
+
offset_x: int
|
|
97
|
+
offset_y: int
|
|
98
|
+
points: List[SeaPoint] = field(default_factory=list)
|
|
99
|
+
encounters: List[Encounter] = field(default_factory=list)
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def display_name(self) -> str:
|
|
103
|
+
return self.name or self.code
|
|
104
|
+
|
|
105
|
+
def ordered_points(self) -> List[SeaPoint]:
|
|
106
|
+
"""点位编号顺序:先按纵向分带(每 7%),带内从左到右。"""
|
|
107
|
+
return sorted(self.points, key=lambda p: (round(p.y / 7), p.x))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class StarSeaData:
|
|
112
|
+
maps: List[SeaMap]
|
|
113
|
+
species: Dict[int, Species]
|
|
114
|
+
types: List[SeaType] = field(default_factory=list)
|
|
115
|
+
assets: Dict[str, str] = field(default_factory=dict)
|
|
116
|
+
fetched_at: float = 0.0
|
|
117
|
+
|
|
118
|
+
def species_of(self, point: SeaPoint) -> List[Species]:
|
|
119
|
+
out: List[Species] = []
|
|
120
|
+
for sid in point.species_ids:
|
|
121
|
+
sp = self.species.get(sid)
|
|
122
|
+
if sp is not None:
|
|
123
|
+
out.append(sp)
|
|
124
|
+
return out
|
|
125
|
+
|
|
126
|
+
def groups_of(self, point: SeaPoint) -> List[Tuple[str, List[Species]]]:
|
|
127
|
+
"""按大类分组,保持首次出现的顺序。"""
|
|
128
|
+
groups: List[Tuple[str, List[Species]]] = []
|
|
129
|
+
index: Dict[str, List[Species]] = {}
|
|
130
|
+
for sp in self.species_of(point):
|
|
131
|
+
bucket = index.get(sp.kind)
|
|
132
|
+
if bucket is None:
|
|
133
|
+
bucket = []
|
|
134
|
+
index[sp.kind] = bucket
|
|
135
|
+
groups.append((sp.kind_name or sp.kind, bucket))
|
|
136
|
+
bucket.append(sp)
|
|
137
|
+
return groups
|
|
138
|
+
|
|
139
|
+
def find_map(self, code: str) -> Optional[SeaMap]:
|
|
140
|
+
wanted = (code or "").strip().casefold()
|
|
141
|
+
for sea_map in self.maps:
|
|
142
|
+
if sea_map.code.casefold() == wanted:
|
|
143
|
+
return sea_map
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
def iter_points(self) -> Iterator[Tuple[SeaMap, SeaPoint]]:
|
|
147
|
+
for sea_map in self.maps:
|
|
148
|
+
for point in sea_map.points:
|
|
149
|
+
yield sea_map, point
|
|
150
|
+
|
|
151
|
+
def points_with_species(self, species_id: int) -> List[Tuple[SeaMap, SeaPoint]]:
|
|
152
|
+
return [(m, p) for m, p in self.iter_points() if species_id in p.species_ids]
|
|
153
|
+
|
|
154
|
+
@property
|
|
155
|
+
def species_count(self) -> int:
|
|
156
|
+
return len(self.species)
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def point_count(self) -> int:
|
|
160
|
+
return sum(len(m.points) for m in self.maps)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def parse_species(raw: Dict[str, Any], base: str) -> Species:
|
|
164
|
+
return Species(
|
|
165
|
+
id=as_int(raw.get("id")),
|
|
166
|
+
name=as_str(raw.get("name")),
|
|
167
|
+
kind=as_str(raw.get("kind")),
|
|
168
|
+
kind_name=as_str(raw.get("kindName")) or as_str(raw.get("kind")),
|
|
169
|
+
display_name=as_str(raw.get("displayName")) or as_str(raw.get("name")),
|
|
170
|
+
grade=as_str(raw.get("grade")).upper(),
|
|
171
|
+
islet_specialty=bool(raw.get("isletSpecialty")),
|
|
172
|
+
detail=as_str(raw.get("detail")),
|
|
173
|
+
icon=absolute_url(base, as_str(raw.get("icon"))),
|
|
174
|
+
has_icon=bool(raw.get("hasIcon", True)),
|
|
175
|
+
sort=as_int(raw.get("sort")),
|
|
176
|
+
kind_note=as_str(raw.get("kindNote")),
|
|
177
|
+
flower_family=as_str(raw.get("flowerFamily")),
|
|
178
|
+
flower_color=as_str(raw.get("flowerColor")),
|
|
179
|
+
flower_state=None if raw.get("flowerState") is None else as_int(raw.get("flowerState"), -1),
|
|
180
|
+
flower_state_name=as_str(raw.get("flowerStateName")),
|
|
181
|
+
flower_state_note=as_str(raw.get("flowerStateNote")),
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def parse_point(raw: Dict[str, Any], base: str) -> SeaPoint:
|
|
186
|
+
return SeaPoint(
|
|
187
|
+
name=as_str(raw.get("name")),
|
|
188
|
+
type=as_str(raw.get("type")),
|
|
189
|
+
type_name=as_str(raw.get("typeName")),
|
|
190
|
+
type_icon=absolute_url(base, as_str(raw.get("typeIcon"))),
|
|
191
|
+
special=bool(raw.get("special")),
|
|
192
|
+
x=as_float(raw.get("x")),
|
|
193
|
+
y=as_float(raw.get("y")),
|
|
194
|
+
species_ids=as_int_list(raw.get("speciesIds")),
|
|
195
|
+
creatures=as_str_list(raw.get("creatures")),
|
|
196
|
+
trees=as_str_list(raw.get("trees")),
|
|
197
|
+
flowers=as_str_list(raw.get("flowers")),
|
|
198
|
+
specialty=as_str(raw.get("specialty")) or None,
|
|
199
|
+
header=absolute_url(base, as_str(raw.get("header"))),
|
|
200
|
+
note=as_str(raw.get("note")),
|
|
201
|
+
hide_flower_state=bool(raw.get("hideFlowerState")),
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def parse_map(raw: Dict[str, Any], base: str) -> SeaMap:
|
|
206
|
+
encounters = [
|
|
207
|
+
Encounter(
|
|
208
|
+
name=as_str(item.get("name")),
|
|
209
|
+
avatar=absolute_url(base, as_str(item.get("avatar"))),
|
|
210
|
+
)
|
|
211
|
+
for item in raw.get("encounters") or []
|
|
212
|
+
if isinstance(item, dict)
|
|
213
|
+
]
|
|
214
|
+
return SeaMap(
|
|
215
|
+
code=as_str(raw.get("code")),
|
|
216
|
+
name=as_str(raw.get("name")),
|
|
217
|
+
note=as_str(raw.get("note")),
|
|
218
|
+
image=absolute_url(base, as_str(raw.get("image"))),
|
|
219
|
+
thumb=absolute_url(base, as_str(raw.get("thumb"))),
|
|
220
|
+
offset_x=as_int(raw.get("offsetX")),
|
|
221
|
+
offset_y=as_int(raw.get("offsetY")),
|
|
222
|
+
points=[parse_point(p, base) for p in raw.get("points") or [] if isinstance(p, dict)],
|
|
223
|
+
encounters=encounters,
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def parse_starsea(payload: Dict[str, Any], base: str) -> StarSeaData:
|
|
228
|
+
"""解析 ``/api/starsea``;结构不对时抛 ``ValueError``(由 api 层转成友好提示)。"""
|
|
229
|
+
if not isinstance(payload, dict):
|
|
230
|
+
raise ValueError("接口返回的不是 JSON 对象")
|
|
231
|
+
if not payload.get("ready", True):
|
|
232
|
+
raise ValueError("站点上的星海地图还没建好数据")
|
|
233
|
+
|
|
234
|
+
raw_maps = payload.get("maps")
|
|
235
|
+
if not isinstance(raw_maps, list) or not raw_maps:
|
|
236
|
+
raise ValueError("接口没有返回任何地图")
|
|
237
|
+
|
|
238
|
+
species: Dict[int, Species] = {}
|
|
239
|
+
for item in payload.get("species") or []:
|
|
240
|
+
if not isinstance(item, dict):
|
|
241
|
+
continue
|
|
242
|
+
sp = parse_species(item, base)
|
|
243
|
+
species[sp.id] = sp
|
|
244
|
+
|
|
245
|
+
types = [
|
|
246
|
+
SeaType(
|
|
247
|
+
code=as_str(item.get("code")),
|
|
248
|
+
name=as_str(item.get("name")),
|
|
249
|
+
special=bool(item.get("special")),
|
|
250
|
+
icon=absolute_url(base, as_str(item.get("icon"))),
|
|
251
|
+
)
|
|
252
|
+
for item in payload.get("types") or []
|
|
253
|
+
if isinstance(item, dict)
|
|
254
|
+
]
|
|
255
|
+
|
|
256
|
+
assets = {
|
|
257
|
+
as_str(key): absolute_url(base, as_str(value))
|
|
258
|
+
for key, value in (payload.get("assets") or {}).items()
|
|
259
|
+
if isinstance(value, str)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return StarSeaData(
|
|
263
|
+
maps=[parse_map(m, base) for m in raw_maps if isinstance(m, dict)],
|
|
264
|
+
species=species,
|
|
265
|
+
types=types,
|
|
266
|
+
assets=assets,
|
|
267
|
+
)
|