Skip to content

Commit

Permalink
✨ 支持查武器的图片版 (#500)
Browse files Browse the repository at this point in the history
  • Loading branch information
KimigaiiWuyi committed Apr 15, 2023
1 parent 43d241a commit 74fc7c9
Show file tree
Hide file tree
Showing 7 changed files with 129 additions and 47 deletions.
20 changes: 12 additions & 8 deletions GenshinUID/genshinuid_wikitext/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from gsuid_core.models import Event
from gsuid_core.segment import MessageSegment

from .get_weapons_pic import get_weapons_wiki_img
from ..genshinuid_config.gs_config import gsconfig
from .get_artifacts_pic import get_artifacts_wiki_img
from .get_wiki_text import (
Expand All @@ -24,17 +25,17 @@
sv_wiki_text = SV('原神WIKI文字版')


@sv_wiki_text.on_prefix(('原魔介绍', '原魔资料'))
@sv_wiki_text.on_prefix(('原魔介绍', '原魔资料', '查原魔'))
async def send_enemies(bot: Bot, ev: Event):
await bot.send(await enemies_wiki(ev.text))


@sv_wiki_text.on_prefix(('食物介绍', '食物资料'))
@sv_wiki_text.on_prefix(('食物介绍', '食物资料', '查食物'))
async def send_food(bot: Bot, ev: Event):
await bot.send(await foods_wiki(ev.text))


@sv_wiki_text.on_prefix(('圣遗物介绍', '圣遗物资料'))
@sv_wiki_text.on_prefix(('圣遗物介绍', '圣遗物资料', '查圣遗物'))
async def send_artifacts(bot: Bot, ev: Event):
if gsconfig.get_config('PicWiki').data:
im = await get_artifacts_wiki_img(ev.text)
Expand All @@ -43,18 +44,21 @@ async def send_artifacts(bot: Bot, ev: Event):
await bot.send(im)


@sv_wiki_text.on_prefix(('武器介绍', '武器资料'))
@sv_wiki_text.on_prefix(('武器介绍', '武器资料', '查武器'))
async def send_weapon(bot: Bot, ev: Event):
name = ''.join(re.findall('[\u4e00-\u9fa5]', ev.text))
level = re.findall(r'\d+', ev.text)
if len(level) == 1:
im = await weapon_stats_wiki(name, int(level[0]))
else:
im = await weapon_wiki(name)
if gsconfig.get_config('PicWiki').data:
im = await get_weapons_wiki_img(name)
else:
im = await weapon_wiki(name)
await bot.send(im)


@sv_wiki_text.on_prefix(('角色天赋'))
@sv_wiki_text.on_prefix(('角色天赋', '查天赋'))
async def send_talents(bot: Bot, ev: Event):
name = ''.join(re.findall('[\u4e00-\u9fa5]', ev.text))
num = re.findall(r'\d+', ev.text)
Expand All @@ -67,7 +71,7 @@ async def send_talents(bot: Bot, ev: Event):
await bot.send(im)


@sv_wiki_text.on_prefix(('角色介绍', '角色资料'))
@sv_wiki_text.on_prefix(('角色介绍', '角色资料', '查角色'))
async def send_char(bot: Bot, ev: Event):
name = ''.join(re.findall('[\u4e00-\u9fa5]', ev.text))
level = re.findall(r'\d+', ev.text)
Expand All @@ -90,7 +94,7 @@ async def send_weapon_cost(bot: Bot, ev: Event):
await bot.send(im)


@sv_wiki_text.on_prefix(('角色命座'))
@sv_wiki_text.on_prefix(('角色命座', '查命座'))
async def send_polar(bot: Bot, ev: Event):
m = ''.join(re.findall('[\u4e00-\u9fa5]', ev.text))
num_re = re.findall(r'\d+', ev.text)
Expand Down
132 changes: 95 additions & 37 deletions GenshinUID/genshinuid_wikitext/get_weapons_pic.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import math
from typing import List, Union
from typing import Dict, List, Union

import aiofiles
from PIL import Image, ImageDraw
Expand All @@ -8,12 +8,12 @@
from ..utils.colors import white_color
from ..utils.error_reply import get_error
from ..utils.get_assets import get_assets_from_ambr
from ..utils.image.convert import str_lenth, convert_img
from ..utils.image.convert import convert_img, get_str_size
from ..utils.resource.RESOURCE_PATH import WIKI_WEAPON_PATH
from ..gsuid_utils.api.minigg.models import Weapon, WeaponStats
from ..utils.image.image_tools import (
get_color_bg,
get_star_png,
get_simple_bg,
get_unknown_png,
)
from ..gsuid_utils.api.minigg.request import (
Expand All @@ -30,18 +30,25 @@
)


async def get_artifacts_wiki_img(name: str) -> Union[str, bytes]:
async def get_weapons_wiki_img(name: str) -> Union[str, bytes]:
data = await get_weapon_info(name)
stats = await get_weapon_stats(name, 90)
if isinstance(data, int):
return get_error(data)
elif isinstance(stats, int):
elif isinstance(data, List):
return get_error(-400)
else:
if int(data['rarity']) < 3:
stats = await get_weapon_stats(name, 70)
else:
stats = await get_weapon_stats(name, 90)

if isinstance(stats, int):
return get_error(stats)
elif isinstance(data, List) or isinstance(stats, List):
elif isinstance(stats, List):
return get_error(-400)
else:
art_name = data['name']
path = WIKI_WEAPON_PATH / f'{art_name}.jpg'
weapon_name = data['name']
path = WIKI_WEAPON_PATH / f'{weapon_name}.jpg'
if path.exists():
async with aiofiles.open(path, 'rb') as f:
return await f.read()
Expand All @@ -50,13 +57,29 @@ async def get_artifacts_wiki_img(name: str) -> Union[str, bytes]:


async def draw_weapons_wiki_img(data: Weapon, stats: WeaponStats):
gray_color = (175, 173, 176)
gray_color = (214, 214, 214)
img_test = Image.new('RGBA', (1, 1))
img_test_draw = ImageDraw.Draw(img_test)
effect = data['effect']
effect = await str_lenth(effect, 22, 540)
effect = effect.replace('/', '·')
rw_ef = []
for i in range(len(data['r1'])):
now = ''
for j in range(1, 6):
ef_val = data[f'r{j}'][i].replace('/', '·')
now += ef_val + ' / '
now = f'{now[:-2]}'
rw_ef.append(now)

if effect:
effect = effect.format(*rw_ef)
else:
effect = '无特效'

effect = get_str_size(effect, gs_font_22, 490)

_, _, _, y1 = img_test_draw.textbbox((0, 0), effect, gs_font_22)
w, h = 600, 1040 + y1
w, h = 600, 1110 + y1

star_pic = get_star_png(data['rarity'])
type_pic = Image.open(TEXT_PATH / f'{data["weapontype"]}.png')
Expand All @@ -66,7 +89,8 @@ async def draw_weapons_wiki_img(data: Weapon, stats: WeaponStats):
else:
gacha_pic = gacha_pic.resize((333, 666))

img = await get_color_bg(w, h, 'wiki_weapon_bg')
bg = Image.open(TEXT_PATH / 'wiki_weapon_bg.jpg')
img = await get_simple_bg(w, h, bg)
img_draw = ImageDraw.Draw(img)

img_draw.text((44, 59), data['name'], white_color, gs_font_44, 'lm')
Expand All @@ -89,48 +113,67 @@ async def draw_weapons_wiki_img(data: Weapon, stats: WeaponStats):
sp = (
'%.1f%%' % (stats['specialized'] * 100)
if data['substat'] != '元素精通'
else str(math.floor(stats['specialized']))
else str(math.ceil(stats['specialized']))
)
else:
sp = ''

atk = f'{data["baseatk"]} · {stats["attack"]}'
subval = f'{sub_val} · {sp}'
atk = f'{data["baseatk"]}/{math.ceil(stats["attack"])}'
subval = f'{sub_val}/{sp}'

img_draw.text((45, 779), atk, white_color, gs_font_36, 'lm')
img_draw.text((545, 779), subval, white_color, gs_font_36, 'rm')

effect_name = f'{data["effectname"]}・精炼5' if data['effectname'] else '无特效'
img_draw.text((46, 837), effect_name, white_color, gs_font_28, 'lm')
img_draw.text((46, 866), effect, gray_color, gs_font_28)
effect_name = f'{data["effectname"]}' if data['effectname'] else '无特效'
img_draw.text((46, 837), effect_name, (255, 206, 51), gs_font_28, 'lm')
img_draw.text((46, 866), effect, gray_color, gs_font_22)

# 计算材料
temp = {}
cost = data['costs']
for i in reversed(cost.values()):
temp: Dict[str, List[int]] = {}
name_temp: Dict[str, List[str]] = {}
cost_data = data['costs']
for i in reversed(cost_data.values()):
for j in i: # type:ignore
for name in temp.keys():
similarity = len(set(j['name']) & set(name))
if similarity >= len(j['name']) / 2:
continue
elif j['name'] == name:
temp[name] += j['count']
else:
temp[j['name']] = j['count']
for k in list(temp.keys()):
sim = len(set(j['name']) & set(k))
# 如果材料名称完全相同
if k == j['name']:
if k not in name_temp:
name_temp[k] = [k]
temp[k] = [j['count']]
else:
temp[k][0] += j['count']
break
# 如果两种材料的相似性超过50%
elif sim >= len(j['name']) / 2:
if j['name'] not in name_temp[k]:
name_temp[k].append(j['name'])
temp[k].append(j['count'])
else:
_i = name_temp[k].index(j['name'])
temp[k][_i] += j['count']
break
else:
name_temp[j['name']] = [j['count']]
temp[j['name']] = [j['count']]

if data['rarity'] == '5':
temp['精锻用魔矿'] = 907
temp['精锻用魔矿'] = [907]
elif data['rarity'] == '4':
temp['精锻用魔矿'] = 605
temp['精锻用魔矿'] = [605]
elif data['rarity'] == '3':
temp['精锻用魔矿'] = 399
temp['精锻用魔矿'] = [399]
elif data['rarity'] == '2':
temp['精锻用魔矿'] = 108
temp['精锻用魔矿'] = [108]
elif data['rarity'] == '1':
temp['精锻用魔矿'] = 72
temp['精锻用魔矿'] = [72]

wiki_cost_bg = Image.open(TEXT_PATH / 'wiki_weapon_cost.png')
wiki_cost_tag = Image.open(TEXT_PATH / 'cost_tag.png')
img.paste(wiki_cost_tag, (37, 890 + y1), wiki_cost_tag)
wiki_cost_draw = ImageDraw.Draw(wiki_cost_bg)

cost_pos = ''
for index, cost_name in enumerate(temp):
material = await get_others_info('materials', cost_name)
if isinstance(material, int):
Expand All @@ -142,11 +185,26 @@ async def draw_weapons_wiki_img(data: Weapon, stats: WeaponStats):
cost_pic = get_unknown_png()
else:
cost_pic = _cost_pic.resize((64, 64))

if not cost_pos and material['materialtype'] == '武器突破素材':
pos = material['dropdomain']
days = material['daysofweek']
cost_pos = f'{pos} - {"/".join(days)}'

t = 100 * index
wiki_cost_bg.paste(cost_pic, (67 + t, 46), cost_pic)
val = str(temp[cost_name])
val_list = [str(x) for x in temp[cost_name]]
val = '/'.join(val_list)
wiki_cost_draw.text((99 + t, 123), val, white_color, gs_font_18, 'mm')

img.paste(wiki_cost_bg, (0, 850 + y1), wiki_cost_bg)
img_draw.text((88, 918 + y1), cost_pos, white_color, gs_font_22, 'lm')
img.paste(wiki_cost_bg, (0, 920 + y1), wiki_cost_bg)

img = img.convert('RGB')
img.save(
WIKI_WEAPON_PATH / '{}.jpg'.format(data['name']),
format='JPEG',
quality=100,
subsampling=0,
)
return await convert_img(img)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions GenshinUID/gsuid_utils/api/minigg/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,3 +358,6 @@ class Material(TypedDict):
source: List[str]
images: MaterialImage
version: str
# 下面两个当且仅当materialtype是xx突破素材的情况才有
dropdomain: str
daysofweek: List[str]
3 changes: 2 additions & 1 deletion GenshinUID/utils/get_assets.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from io import BytesIO
from typing import Literal, Optional

import aiofiles
Expand Down Expand Up @@ -26,7 +27,7 @@ async def _get_assets(
content = await res.read()
async with aiofiles.open(path, 'wb') as f:
await f.write(content)
return Image.open(content)
return Image.open(BytesIO(content))
else:
return None

Expand Down
18 changes: 17 additions & 1 deletion GenshinUID/utils/image/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from typing import Union, overload

import aiofiles
from PIL import Image
from PIL import Image, ImageFont


@overload
Expand Down Expand Up @@ -83,6 +83,22 @@ async def str_lenth(r: str, size: int, limit: int = 540) -> str:
return result


def get_str_size(
r: str, font: ImageFont.FreeTypeFont, limit: int = 540
) -> str:
result = ''
line = ''
for i in r:
line += i
size, _ = font.getsize(line)
if size >= limit:
result += f'{line}\n'
line = ''
else:
result += line
return result


def get_height(content: str, size: int) -> int:
line_count = content.count('\n')
return (line_count + 1) * size

0 comments on commit 74fc7c9

Please sign in to comment.