-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdropitemseditor.py
540 lines (463 loc) · 18.4 KB
/
dropitemseditor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
"""
解析結果を編集して投稿しやすい形に整えるモジュール
web, CLI の両方から参照される想定。
"""
import copy
import dataclasses
from itertools import zip_longest
from logging import getLogger
from typing import List, Dict
import cv2
import numpy as np
import img2str
from img2str import (
ID_UNDROPPED,
ID_NO_POSESSION,
ID_STANDARD_ITEM_MIN,
ID_STANDARD_ITEM_MAX,
ID_GEM_MIN,
ID_SECRET_GEM_MAX,
ID_PIECE_MIN,
ID_MONUMENT_MAX,
ID_EXP_MIN,
ID_EXP_MAX,
)
logger = getLogger(__name__)
class DropItemsEditorError(Exception):
pass
class ScrollPositionError(DropItemsEditorError):
pass
def make_diff(itemlist1, itemlist2, owned=None):
tmplist = []
for before, after in zip(itemlist1, itemlist2):
diff = copy.deepcopy(after)
diff_b = copy.deepcopy(before)
if before["id"] == ID_UNDROPPED and after["id"] == ID_UNDROPPED:
diff["dropnum"] = "NaN"
tmplist.append(diff)
elif before["id"] == ID_NO_POSESSION or after["id"] == ID_NO_POSESSION:
continue
elif before["id"] == ID_UNDROPPED and after["id"] > 0:
diff["dropnum"] = "NaN"
if owned is not None:
owned_dic = {item["id"]: item["dropnum"] for item in owned}
if after["id"] in owned_dic.keys():
diff["dropnum"] = after["dropnum"] - owned_dic[after["id"]]
tmplist.append(diff)
elif before["id"] > 0 and after["id"] == ID_NO_POSESSION:
# 画像の認識順が周回前後逆の時のエラー対策
diff_b["dropnum"] = "NaN"
tmplist.append(before)
elif str(before["dropnum"]).isdigit() and str(after["dropnum"]).isdigit():
diff["dropnum"] = after["dropnum"] - before["dropnum"]
tmplist.append(diff)
else:
diff["dropnum"] = "NaN"
tmplist.append(diff)
return tmplist
def out_name(id, dropitems):
d = dropitems.item_name[id]
logger.debug('out_name before: %s', d)
if d[-1] == '_':
d = d[:-1]
if id in dropitems.item_shortname.keys():
d = dropitems.item_shortname[id]
if d[-1].isdigit():
d = d + '_'
logger.debug('out_name after: %s', d)
return d
@dataclasses.dataclass
class ParsedDropsDiff:
"""
DropsDiff を
- 礼装 craft_essence
- 素材 materials
- スキル石 gems
- ピースモニュメント pieces
- 種火 wisdoms
- 非恒常アイテム non_standards
に分解したもの。
"""
questname: str
craft_essence: List[Dict[str, int]]
materials: List[Dict[str, int]]
gems: List[Dict[str, int]]
pieces: List[Dict[str, int]]
wisdoms: List[Dict[str, str]]
non_standards: List[Dict[str, int]]
def as_json_data(self) -> List[Dict[str, str]]:
"""
Web 出力に最適化された JSON like なデータを返す。
つまり辞書のリスト。
素材のデータのみで、クエスト名は含まない。
出力例:
[
{ "id": 1, "material": "爪", "report": 10, "item_id": ... },
{ "id": 2, "material": "羽根", "report": 25, "item_id": ... },
{ "id": 3, "material": "!弓モニュ", "report": 3, "item_id": ... }
]
"""
categories = [
self.craft_essence,
self.materials,
self.gems,
self.pieces,
self.wisdoms,
self.non_standards,
]
data = []
index = 0
# 開始時のみ素材名先頭に "!" をつけない
first_row = True
for cat in categories:
# カテゴリごとに改行するため素材名先頭に "!" をつける
category_head = True
for item in cat:
name = item["name"]
count = item["dropnum"]
if first_row:
item_name = name
first_row = False
category_head = False
elif category_head:
# Web 上で報告フォーマットを編集するときの改行表現
# (FGO 周回カウンタサイト互換)
item_name = f'!{name}'
category_head = False
else:
item_name = name
d = {
'id': index,
'material': item_name,
'report': str(count),
'item_id': item["item_id"],
}
data.append(d)
index += 1
return data
def as_syukai_counter(self, url):
"""
周回カウンタ報告形式の文字列を返す
"""
def format(item_list):
return '-'.join(['{}{}'.format(item["name"], item["dropnum"]) for item in item_list])
def add_line(item_list, lines):
line = format(item_list)
if line:
lines.append(line)
lines = []
add_line(self.craft_essence, lines)
add_line(self.materials, lines)
add_line(self.gems, lines)
add_line(self.pieces, lines)
add_line(self.wisdoms, lines)
add_line(self.non_standards, lines)
questname = self.questname
if not questname:
questname = '(クエスト名)'
body = '\n'.join(lines)
if url != "":
url = '\n' + url
return f"""
【{questname}】000周
{body}
#FGO周回カウンタ http://aoshirobo.net/fatego/rc/{url}
""".lstrip()
class DropsDiff:
def __init__(self, item_list, questname, questdrops):
"""
item_list: make_diff() で求めたドロップ差分情報の辞書のリスト
questname: get_questinfo() で求めたフリークエスト名
questdrops: get_questinfo() で求めたフリークエストのドロップリスト
"""
self.item_list = item_list
self.questname = questname
self.questdrops = questdrops
self.is_freequest = self.questname is not None and len(self.questname) > 0
def validate_dropitems(self):
for item in self.item_list:
if item["name"] not in self.questdrops:
return False
return True
def parse(self, dropitems):
"""
素材、スキル石、モニュピ、種火に分解した結果を返す。
"""
craft_essence = []
non_standards = []
materials = []
gems = []
pieces = []
wisdoms = []
for i, item in enumerate(self.item_list):
if item["id"] == ID_UNDROPPED:
if len(self.questdrops) > 0:
item_id = [k for k, v in dropitems.item_name.items() if v == self.questdrops[i]][0]
if dropitems.item_type[item_id] == "Craft Essence":
craft_essence.append({"name": out_name(item_id, dropitems), "dropnum": 0, "item_id": item_id})
elif dropitems.item_type[item["id"]] == "Craft Essence":
craft_essence.append({"name": out_name(item["id"], dropitems), "dropnum": item["dropnum"], "item_id": item["id"]})
elif ID_STANDARD_ITEM_MIN <= item["id"] <= ID_STANDARD_ITEM_MAX:
materials.append({"name": out_name(item["id"], dropitems), "dropnum": item["dropnum"], "item_id": item["id"]})
elif ID_GEM_MIN <= item["id"] <= ID_SECRET_GEM_MAX:
gems.append({"name": out_name(item["id"], dropitems), "dropnum": item["dropnum"], "item_id": item["id"]})
elif ID_PIECE_MIN <= item["id"] <= ID_MONUMENT_MAX:
pieces.append({"name": out_name(item["id"], dropitems), "dropnum": item["dropnum"], "item_id": item["id"]})
elif ID_EXP_MIN <= item["id"] <= ID_EXP_MAX:
raise ValueError('item_dict should not have wisdoms')
else:
non_standards.append({"name": out_name(item["id"], dropitems), "dropnum": item["dropnum"], "item_id": item["id"]})
if self.is_freequest:
for questdrop in self.questdrops:
if questdrop in dropitems.exp_list:
# 種火はスクリーンショットから個数計算できないため常に
# NaN (N/A の意味。FGO周回カウンタ互換) を設定する
wisdoms.append({"name": questdrop, "dropnum": 'NaN', "item_id": None})
return ParsedDropsDiff(
self.questname,
craft_essence,
materials,
gems,
pieces,
wisdoms,
non_standards,
)
def get_questinfo(sc1, sc2):
sc1qname = sc1.quest_output
sc2qname = sc2.quest_output
logger.debug('sc1 quest: %s %s', sc1qname, getattr(sc1, 'droplist', None))
logger.debug('sc2 quest: %s %s', sc2qname, getattr(sc2, 'droplist', None))
if not sc1qname and not sc2qname:
return '', ''
if (sc1qname and sc2qname) and sc1qname != sc2qname:
return '', ''
if sc2qname:
return sc2qname, getattr(sc2, 'droplist', [])
else:
return sc1qname, getattr(sc1, 'droplist', [])
def get_questnames(sc1, sc2):
sc1qnames = sc1.quest_list
sc2qnames = sc2.quest_list
logger.debug('sc1 quests: %s', sc1qnames)
logger.debug('sc2 quests: %s', sc2qnames)
if (len(sc1qnames) > 0 and len(sc2qnames) > 0) and sc1qnames != sc2qnames:
return [""]
if len(sc2qnames) > 0:
return sc2qnames
elif len(sc1qnames) > 0:
return sc1qnames
else:
return [""]
class OwnedItem(img2str.Item):
def __init__(self, img_rgb, dropitems, debug=False):
self.dropitems = dropitems
self.background = img2str.classify_background(img_rgb, self.dropitems)
self.id = self.classify_standard_item(img_rgb, debug=False)
class OwnedNumber(img2str.Item):
def __init__(self, img_gray, svm, debug=False):
pts9 = [[112, 44, 140, 85],
[140, 44, 168, 85],
[168, 44, 196, 85],
[207, 44, 235, 85],
[235, 44, 263, 85],
[263, 44, 291, 85],
[302, 44, 330, 85],
[330, 44, 358, 85],
[358, 44, 386, 85]]
self.svm = svm
num = self.read_item(img_gray, pts9)
if num == "":
num = -1
else:
num = int(num)
self.num = num
def calc_pts(img_rgb):
height, width = img_rgb.shape[:2]
hsvLower = np.array([50, 0, 0]) # 抽出する色の下限(HSV)
hsvUpper = np.array([200, 60, 255]) # 抽出する色の上限(HSV)
hsv = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2HSV) # 画像をHSVに変換
hsv_mask = cv2.inRange(hsv, hsvLower, hsvUpper) # HSVからマスクを作成
contours = cv2.findContours(hsv_mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[0]
item_pts_l = []
item_pts_r = []
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 10000:
ret = cv2.boundingRect(cnt)
pts = [ret[0], ret[1], ret[0] + ret[2], ret[1] + ret[3]]
if 4.1 < ret[2] / ret[3] < 4.4:
if ret[0] + ret[2] / 2 < width / 2:
item_pts_l.append(pts)
else:
item_pts_r.append(pts)
item_pts_l.sort(key=lambda x: x[1])
item_pts_r.sort(key=lambda x: x[1])
item_pts = []
for left, right in zip_longest(item_pts_l, item_pts_r):
if left is not None:
item_pts.append(left)
if right is not None:
item_pts.append(right)
if len(item_pts) < 6:
logger.warning("正しい所持アイテムのスクショではありません")
return []
# リスト中央のやつの面積と比較して明らかに面積がおかしいものは除外する
center = int(len(item_pts) / 2)
teacher_area = (item_pts[center][2] - item_pts[center][0]) * (item_pts[center][3] - item_pts[center][1])
new_item_pts = []
for pts in item_pts:
area = (pts[2] - pts[0]) * (pts[3] - pts[1])
if teacher_area * 0.9 < area < teacher_area * 1.1:
new_item_pts.append(pts)
return new_item_pts
def read_owned_ss(owned_files, dropitems, svm, miss_item):
"""
owned_files の要素は file object であること。
file-like object だと imread() に失敗するので注意。
"""
owned_images = [img2str.imread(f) for f in owned_files]
return read_owned_objects(owned_images, dropitems, svm, miss_item)
def read_owned_objects(owned_images, dropitems, svm, miss_item):
"""
owned_images の要素は np.array であること。
file であれば先に imread() して np.array 形式にしておく。
"""
TRAINING_IMG_WIDTH = 1152
ownitems = []
remain_items = [item["id"] for item in miss_item]
for img_rgb in owned_images:
if len(remain_items) == 0:
break
item_pts = calc_pts(img_rgb)
logger.debug("item_pts: %s", item_pts)
if item_pts == []:
return (-1, [])
width_g = max([pts[2] for pts in item_pts]) - min([pts[0] for pts in item_pts])
wscale = (1.0 * width_g) / TRAINING_IMG_WIDTH
resizeScale = 1 / wscale
if resizeScale > 1:
game_screen = cv2.resize(img_rgb, (0, 0), fx=resizeScale, fy=resizeScale, interpolation=cv2.INTER_CUBIC)
else:
game_screen = cv2.resize(img_rgb, (0, 0), fx=resizeScale, fy=resizeScale, interpolation=cv2.INTER_AREA)
item_pts = calc_pts(game_screen)
offset_x = 506 - item_pts[0][0]
offset_y = 451 - item_pts[0][1]
g_height, g_width = game_screen.shape[:2]
pts = [[294 - offset_x, 369 - offset_y, 481 - offset_x, 572 - offset_y],
[1004 - offset_x, 369 - offset_y, 1191 - offset_x, 572 - offset_y],
[294 - offset_x, 599 - offset_y, 481 - offset_x, 802 - offset_y],
[1004 - offset_x, 599 - offset_y, 1191 - offset_x, 802 - offset_y],
[294 - offset_x, 829 - offset_y, 481 - offset_x, 1032 - offset_y],
[1004 - offset_x, 829 - offset_y, 1191 - offset_x, 1032 - offset_y],
[294 - offset_x, 1059 - offset_y, 481 - offset_x, 1262 - offset_y],
[1004 - offset_x, 1059 - offset_y, 1191 - offset_x, 1262 - offset_y],
]
item_ids = []
# miss_item が全て見つかったらループを抜ける
for i, pt in enumerate(pts):
if pt[2] > g_width or pt[3] > g_height:
break
item = OwnedItem(game_screen[pt[1]: pt[3], pt[0]: pt[2]], dropitems)
item_ids.append(item.id)
if item.id in remain_items:
remain_items.remove(item.id)
if len(remain_items) == 0:
break
logger.debug("item_ids: %s", item_ids)
item_nums = []
img_gray = cv2.cvtColor(game_screen, cv2.COLOR_BGR2GRAY)
for j, pt in enumerate(item_pts):
numitem = OwnedNumber(img_gray[pt[1]: pt[3], pt[0]: pt[2]], svm)
item_nums.append(numitem.num)
if i == j:
break
logger.debug("item_num: %s", item_nums)
for id, num in zip(item_ids, item_nums):
ownitem = {}
if id == "":
continue
ownitem["id"] = id
ownitem["name"] = dropitems.item_name[id]
ownitem["dropnum"] = num
if num >= 0:
ownitems.append(ownitem)
ownitems = sorted(ownitems, key=lambda x: x['id'])
code = 0
prev_id = -1
output_items = []
for item in ownitems:
if item["id"] == prev_id:
code = -1
break
output_items.append(item)
prev_id = item["id"]
return code, output_items
def make_owned_diff(itemlist1, itemlist2, owned_list):
owned_diff = []
set1 = {item["id"] for item in itemlist1}
set2 = {item["id"] for item in itemlist2}
s_diffs = set2 - set1
for s_diff in s_diffs:
for owned in owned_list:
if s_diff == owned["id"]:
owned_diff.append(owned)
return owned_diff
def merge_list(upper, bottom):
"""
上下スクロールのアイテムリストを結合する
"""
detect_flag = False
for i in range(len(bottom.itemlist)):
if bottom.itemlist[i]["id"] < 0:
continue
else:
b_candidate = i
break
logger.debug('b_candidate: %s', b_candidate)
for j in range(len(upper.itemlist)):
if upper.itemlist[j] == bottom.itemlist[b_candidate]:
break
logger.debug('u_candidate: %s', j)
if j == len(upper.itemlist) -1:
lower_start = 0
else:
lower_start = 12 - (j - b_candidate)
return upper.itemlist + bottom.itemlist[lower_start:]
def merge_sc(sc_list):
"""
list内のスクロール上下を決め、内容をマージする
"""
if len(sc_list) == 1:
return sc_list[0].itemlist
for i in range(len(sc_list[0].itemlist)):
if sc_list[0].itemlist[i]["id"] <= 0 or sc_list[1].itemlist[i]["id"] <= 0:
continue
if sc_list[0].itemlist[i]["dropPriority"] > sc_list[1].itemlist[i]["dropPriority"]:
logger.debug('use sc_list[0] → sc_list[1] on item %s', i)
return merge_list(sc_list[0], sc_list[1])
else:
return merge_list(sc_list[1], sc_list[0])
def detect_upper(sc_list):
"""
list内のスクロール上下を決め上のオブジェクトを返す
"""
if len(sc_list) == 1:
return sc_list[0]
for i in range(len(sc_list[0].itemlist)):
if sc_list[0].itemlist[i]["id"] <= 0 or sc_list[1].itemlist[i]["id"] <= 0:
continue
if sc_list[0].itemlist[i]["dropPriority"] == sc_list[1].itemlist[i]["dropPriority"]:
logger.critical("Same Scroll Position Image Detected")
raise ScrollPositionError("Same Scroll Position Image Detected")
elif sc_list[0].itemlist[i]["dropPriority"] > sc_list[1].itemlist[i]["dropPriority"]:
return sc_list[0]
else:
return sc_list[1]
def detect_missing_item(sc_after, sc_before):
miss_item = []
for after, before in zip(sc_after, sc_before):
if after["id"] == before["id"]:
continue
elif after["id"] != ID_UNDROPPED and after["id"] != ID_NO_POSESSION:
miss_item.append(after)
return miss_item