P1-3 镜牢饰品选择按体系关键词排序
- 包住 Mirror.acquire_ego_gift(type=1):上游取到卡片列表时整屏 OCR 一次,
按坐标把文字归到卡上,命中当前体系关键词行数多的排前面;排序稳定,
白棉花、已持有、体系图标仍由上游原逻辑处理,调用结束还原 find_element
- OCR 读引擎逐行结果,不用会合并同名文本的 {文本: 坐标},也不用 my_crop
- 关键词表 lc_mcp/data/gift_keywords.json,匹配前做与选队相同的归一(含震颐/沉论误读)
- LCP_GIFT_KEYWORDS=0 关闭(与上游完全一致),=<路径> 换表;表读不了记 [ERROR] 不装
- 单测执行上游真实 acquire_ego_gift,覆盖两张/三张卡、选一/选二、已持有、白棉花、误读
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,310 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""镜牢饰品选择按体系关键词排序(BACKLOG P1-3)。
|
||||||
|
|
||||||
|
2026-11-14 核对: acquire_ego_gift() 两张卡时只排白棉花和已持有然后拿第一张, 不看 team_system。
|
||||||
|
补丁在上游挑选前按卡面 OCR 的体系关键词给卡排序; 端到端用例执行上游真实的 acquire_ego_gift。
|
||||||
|
"""
|
||||||
|
import ast
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import types
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(REPO))
|
||||||
|
from lc_mcp import aalc_patches as ap # noqa: E402
|
||||||
|
|
||||||
|
AALC = REPO / 'vendor' / 'aalc'
|
||||||
|
MIRROR = AALC / 'tasks' / 'mirror' / 'mirror.py'
|
||||||
|
SCALE = 720 / 1440
|
||||||
|
|
||||||
|
|
||||||
|
def line_at(card, row):
|
||||||
|
"""卡面第 row 行文字的位置(在上游判断范围内)。"""
|
||||||
|
return card[0] + 100 * SCALE * 2, card[1] + 40 * row
|
||||||
|
|
||||||
|
|
||||||
|
class GiftCardHitsTest(unittest.TestCase):
|
||||||
|
|
||||||
|
CARDS = [(300, 300), (600, 300), (900, 300)]
|
||||||
|
|
||||||
|
def hits(self, lines, keywords=('流血', '出血', 'bleed')):
|
||||||
|
return ap.gift_card_hits(self.CARDS, lines, keywords, SCALE)
|
||||||
|
|
||||||
|
def test_lines_are_assigned_to_the_card_they_sit_on(self):
|
||||||
|
lines = [('施加3层流血', *line_at(self.CARDS[1], 0)),
|
||||||
|
('出血时伤害提高', *line_at(self.CARDS[1], 1)),
|
||||||
|
('烧伤', *line_at(self.CARDS[0], 0)),
|
||||||
|
('选择EGO饰品', 600, 40)] # 标题不在任何卡上
|
||||||
|
self.assertEqual(self.hits(lines), [[], ['流血', '出血'], []])
|
||||||
|
|
||||||
|
def test_english_is_case_insensitive_and_spaces_are_ignored(self):
|
||||||
|
lines = [('Inflict BLEED', *line_at(self.CARDS[2], 0)), ('流 血', *line_at(self.CARDS[0], 0))]
|
||||||
|
self.assertEqual(self.hits(lines), [['流血'], [], ['bleed']])
|
||||||
|
|
||||||
|
def test_known_ocr_misreads_still_hit(self):
|
||||||
|
lines = [('施加震颐', *line_at(self.CARDS[0], 0)), ('沉论层数', *line_at(self.CARDS[1], 0))]
|
||||||
|
self.assertEqual(ap.gift_card_hits(self.CARDS, lines, ('震颤',), SCALE), [['震颤'], [], []])
|
||||||
|
self.assertEqual(ap.gift_card_hits(self.CARDS, lines, ('沉沦',), SCALE), [[], ['沉沦'], []])
|
||||||
|
|
||||||
|
def test_overlapping_ranges_go_to_the_nearest_card(self):
|
||||||
|
cards = [(300, 300), (450, 300)] # 两张卡的范围在 x=425..525 重叠
|
||||||
|
lines = [('流血', 440, 300), ('流血', 500, 300)]
|
||||||
|
self.assertEqual(ap.gift_card_hits(cards, lines, ('流血',), SCALE), [['流血'], ['流血']])
|
||||||
|
|
||||||
|
def test_rank_is_stable(self):
|
||||||
|
cards = ['a', 'b', 'c']
|
||||||
|
self.assertEqual(ap.rank_gift_cards(cards, [[], ['x'], []]), ['b', 'a', 'c'])
|
||||||
|
self.assertEqual(ap.rank_gift_cards(cards, [[], [], []]), cards)
|
||||||
|
self.assertEqual(ap.rank_gift_cards(cards, [['x'], ['x', 'y'], ['x']]), ['b', 'a', 'c'])
|
||||||
|
|
||||||
|
|
||||||
|
class KeywordTableTest(unittest.TestCase):
|
||||||
|
|
||||||
|
def test_shipped_table_covers_every_upstream_system(self):
|
||||||
|
table = ap.load_gift_keywords()
|
||||||
|
source = AALC / 'tasks' / '__init__.py'
|
||||||
|
if source.is_file():
|
||||||
|
tree = ast.parse(source.read_text(encoding='utf-8'))
|
||||||
|
node = next(n for n in tree.body if isinstance(n, ast.Assign)
|
||||||
|
and getattr(n.targets[0], 'id', None) == 'all_systems')
|
||||||
|
self.assertEqual(set(table), set(ast.literal_eval(node.value).values()))
|
||||||
|
for system, words in table.items():
|
||||||
|
self.assertTrue(words, system)
|
||||||
|
|
||||||
|
def test_bad_files_raise_value_error(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
path = os.path.join(tmp, 'k.json')
|
||||||
|
for content in ('[]', '{"bleed": "流血"}', '{"bleed": [1]}', '{'):
|
||||||
|
with self.subTest(content=content):
|
||||||
|
with open(path, 'w', encoding='utf-8') as f:
|
||||||
|
f.write(content)
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
ap.load_gift_keywords(path)
|
||||||
|
|
||||||
|
def test_notes_are_ignored(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
path = os.path.join(tmp, 'k.json')
|
||||||
|
with open(path, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump({'_说明': ['x'], 'bleed': ['流血', ' ']}, f, ensure_ascii=False)
|
||||||
|
self.assertEqual(ap.load_gift_keywords(path), {'bleed': ('流血',)})
|
||||||
|
|
||||||
|
|
||||||
|
class GiftScreen:
|
||||||
|
"""饰品选择界面: 每张卡 {'pos', 'lines'}; 系统图标模板永远匹配不上(本机现状)。"""
|
||||||
|
|
||||||
|
def __init__(self, cards, pick='0/1'):
|
||||||
|
self.cards = cards
|
||||||
|
self.pick = pick
|
||||||
|
self.clicks = []
|
||||||
|
self.ocr_runs = 0
|
||||||
|
self.model = None
|
||||||
|
self.screenshot = object()
|
||||||
|
|
||||||
|
def lines(self):
|
||||||
|
return [(text, *line_at(card['pos'], row))
|
||||||
|
for card in self.cards for row, text in enumerate(card['lines'])]
|
||||||
|
|
||||||
|
def take_screenshot(self):
|
||||||
|
return self.screenshot
|
||||||
|
|
||||||
|
def mouse_to_blank(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def click_element(self, target, **kwargs):
|
||||||
|
return target.endswith('acquire_ego_gift_select_assets.png')
|
||||||
|
|
||||||
|
def find_element(self, target, find_type='image', threshold=0.8, my_crop=None, **kwargs):
|
||||||
|
if target == ap.GIFT_CARD and find_type == 'image_with_multiple_targets':
|
||||||
|
return [card['pos'] for card in self.cards]
|
||||||
|
return False
|
||||||
|
|
||||||
|
def find_language_text(self, zh_text, en_text, my_crop=None, **kwargs):
|
||||||
|
words = [zh_text] if isinstance(zh_text, str) else zh_text
|
||||||
|
x1, y1, x2, y2 = my_crop
|
||||||
|
for text, x, y in self.lines():
|
||||||
|
if x1 <= x <= x2 and y1 <= y <= y2 and any(w in text for w in words):
|
||||||
|
return [x, y]
|
||||||
|
return False
|
||||||
|
|
||||||
|
def find_text_element(self, targets, my_crop=None, **kwargs):
|
||||||
|
return self.pick in targets
|
||||||
|
|
||||||
|
def mouse_click(self, x, y):
|
||||||
|
self.clicks.append((x, y))
|
||||||
|
|
||||||
|
def run(self, image):
|
||||||
|
self.ocr_runs += 1
|
||||||
|
lines = self.lines()
|
||||||
|
return SimpleNamespace(txts=tuple(t for t, _, _ in lines),
|
||||||
|
boxes=[[[x - 10, y - 5], [x + 10, y - 5], [x + 10, y + 5], [x - 10, y + 5]]
|
||||||
|
for _, x, y in lines])
|
||||||
|
|
||||||
|
|
||||||
|
def card(x, *lines):
|
||||||
|
return {'pos': (x, 300), 'lines': list(lines)}
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(MIRROR.is_file(), 'vendor/aalc 子模块未检出')
|
||||||
|
class UpstreamAcquireEgoGiftTest(unittest.TestCase):
|
||||||
|
"""执行上游真实的 Mirror.acquire_ego_gift, 看最后点了哪张卡。"""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.lines = []
|
||||||
|
tree = ast.parse(MIRROR.read_text(encoding='utf-8'))
|
||||||
|
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Mirror')
|
||||||
|
self.fn_node = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == 'acquire_ego_gift')
|
||||||
|
|
||||||
|
def choose(self, cards, system='bleed', patched=True, pick='0/1', env=None):
|
||||||
|
screen = GiftScreen(cards, pick=pick)
|
||||||
|
cfg = SimpleNamespace(set_win_size=720, not_skip_whitegossypium=False, mouse_action_interval=0)
|
||||||
|
ns = dict(cfg=cfg, auto=screen, sleep=lambda *a: None, time=SimpleNamespace(sleep=lambda *a: None),
|
||||||
|
retry=lambda: True, log=mock.Mock(),
|
||||||
|
ImageUtils=SimpleNamespace(get_bbox=lambda image: None, load_image=lambda path: None),
|
||||||
|
all_systems={0: 'burn', 1: 'bleed'})
|
||||||
|
exec(compile(ast.Module(body=[self.fn_node], type_ignores=[]), str(MIRROR), 'exec'), ns)
|
||||||
|
mirror_cls = type('Mirror', (), {'acquire_ego_gift': ns['acquire_ego_gift']})
|
||||||
|
mirror_mod = types.ModuleType('tasks.mirror.mirror')
|
||||||
|
mirror_mod.Mirror = mirror_cls
|
||||||
|
package = types.ModuleType('tasks.mirror')
|
||||||
|
package.mirror = mirror_mod
|
||||||
|
modules = {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package, 'tasks.mirror.mirror': mirror_mod,
|
||||||
|
'module': types.ModuleType('module'),
|
||||||
|
'module.automation': SimpleNamespace(auto=screen),
|
||||||
|
'module.config': SimpleNamespace(cfg=cfg),
|
||||||
|
'module.ocr': SimpleNamespace(ocr=screen)}
|
||||||
|
with mock.patch.dict(sys.modules, modules):
|
||||||
|
if patched:
|
||||||
|
self.assertIsNotNone(ap.install_gift_preference(log=self.lines.append, env=env or {}))
|
||||||
|
mirror = mirror_cls()
|
||||||
|
mirror.system, mirror.second_system = system, False
|
||||||
|
mirror.acquire_ego_gift()
|
||||||
|
self.assertNotIn('find_element', vars(screen), 'find_element 必须还原')
|
||||||
|
return [next(i for i, c in enumerate(cards) if c['pos'] == pos) for pos in screen.clicks], screen
|
||||||
|
|
||||||
|
@property
|
||||||
|
def log(self):
|
||||||
|
return '\n'.join(self.lines)
|
||||||
|
|
||||||
|
def test_two_cards_prefers_the_system_keyword(self):
|
||||||
|
cards = [card(300, '烧伤层数+1'), card(600, '施加2层流血')]
|
||||||
|
self.assertEqual(self.choose(cards, patched=False)[0], [0])
|
||||||
|
self.assertEqual(self.choose(cards)[0], [1])
|
||||||
|
self.assertIn('第1张=0 第2张=1(流血); 命中体系关键词, 先看第2张', self.log)
|
||||||
|
|
||||||
|
def test_owned_keyword_card_still_loses_to_an_unowned_one(self):
|
||||||
|
cards = [card(300, '烧伤层数+1'), card(600, '施加2层流血', '已持有')]
|
||||||
|
self.assertEqual(self.choose(cards)[0], [0])
|
||||||
|
|
||||||
|
def test_all_owned_falls_back_to_keyword_order(self):
|
||||||
|
cards = [card(300, '烧伤', '已持有'), card(600, '流血', '已持有')]
|
||||||
|
self.assertEqual(self.choose(cards)[0], [1])
|
||||||
|
|
||||||
|
def test_white_gossypium_is_still_skipped(self):
|
||||||
|
cards = [card(300, '烧伤层数+1'), card(600, '白棉花', '流血')]
|
||||||
|
self.assertEqual(self.choose(cards)[0], [0])
|
||||||
|
|
||||||
|
def test_all_white_gossypium_behaves_like_upstream(self):
|
||||||
|
cards = [card(300, '白棉花'), card(600, '白棉花', '流血')]
|
||||||
|
self.assertEqual(self.choose(cards)[0], self.choose(cards, patched=False)[0])
|
||||||
|
|
||||||
|
def test_three_cards_pick_one(self):
|
||||||
|
cards = [card(300, '烧伤'), card(600, '震颤'), card(900, '流血伤害提高', '出血')]
|
||||||
|
self.assertEqual(self.choose(cards, patched=False)[0], [0])
|
||||||
|
self.assertEqual(self.choose(cards)[0], [2])
|
||||||
|
|
||||||
|
def test_three_cards_pick_two(self):
|
||||||
|
cards = [card(300, '烧伤'), card(600, '流血'), card(900, '流血', '出血')]
|
||||||
|
self.assertEqual(self.choose(cards, pick='0/2')[0], [2, 1])
|
||||||
|
|
||||||
|
def test_misread_keyword_for_tremor(self):
|
||||||
|
cards = [card(300, '流血'), card(600, '施加震颐')]
|
||||||
|
self.assertEqual(self.choose(cards, system='tremor')[0], [1])
|
||||||
|
|
||||||
|
def test_no_hits_keeps_upstream_choice(self):
|
||||||
|
cards = [card(300, '烧伤'), card(600, '充能')]
|
||||||
|
self.assertEqual(self.choose(cards)[0], [0])
|
||||||
|
self.assertIn('未命中体系关键词, 保持原顺序', self.log)
|
||||||
|
|
||||||
|
def test_duplicate_lines_on_two_cards_both_count(self):
|
||||||
|
# {文本: 坐标} 会把两张卡上的同一句合并成一条; 补丁直接读 OCR 引擎的逐行结果
|
||||||
|
cards = [card(300, '流血'), card(600, '流血', '出血')]
|
||||||
|
self.assertEqual(self.choose(cards)[0], [1])
|
||||||
|
self.assertIn('第1张=1(流血) 第2张=2(流血/出血)', self.log)
|
||||||
|
|
||||||
|
def test_unknown_system_skips_ocr(self):
|
||||||
|
cards = [card(300, '烧伤'), card(600, '流血')]
|
||||||
|
chosen, screen = self.choose(cards, system='unknown')
|
||||||
|
self.assertEqual((chosen, screen.ocr_runs), ([0], 0))
|
||||||
|
|
||||||
|
|
||||||
|
class InstallGiftPreferenceTest(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.lines = []
|
||||||
|
self.original = mock.Mock(return_value='done')
|
||||||
|
self.mirror_cls = type('Mirror', (), {'acquire_ego_gift': self.original})
|
||||||
|
mirror_mod = types.ModuleType('tasks.mirror.mirror')
|
||||||
|
mirror_mod.Mirror = self.mirror_cls
|
||||||
|
package = types.ModuleType('tasks.mirror')
|
||||||
|
package.mirror = mirror_mod
|
||||||
|
self.auto = SimpleNamespace(find_element=mock.Mock(return_value=[(300, 300), (600, 300)]))
|
||||||
|
modules = {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package, 'tasks.mirror.mirror': mirror_mod,
|
||||||
|
'module': types.ModuleType('module'),
|
||||||
|
'module.automation': SimpleNamespace(auto=self.auto),
|
||||||
|
'module.config': SimpleNamespace(cfg=SimpleNamespace(set_win_size=720))}
|
||||||
|
patcher = mock.patch.dict(sys.modules, modules)
|
||||||
|
patcher.start()
|
||||||
|
self.addCleanup(patcher.stop)
|
||||||
|
|
||||||
|
def install(self, env=None):
|
||||||
|
return ap.install_gift_preference(log=self.lines.append, env=env or {})
|
||||||
|
|
||||||
|
def test_env_zero_leaves_upstream_untouched(self):
|
||||||
|
self.assertIsNone(self.install({ap.GIFT_KEYWORDS_ENV: '0'}))
|
||||||
|
self.assertIs(self.mirror_cls.acquire_ego_gift, self.original)
|
||||||
|
|
||||||
|
def test_unreadable_table_is_an_error_and_not_installed(self):
|
||||||
|
self.assertIsNone(self.install({ap.GIFT_KEYWORDS_ENV: '/nonexistent/k.json'}))
|
||||||
|
self.assertIs(self.mirror_cls.acquire_ego_gift, self.original)
|
||||||
|
self.assertTrue(self.lines[0].startswith('[ERROR] [lc_mcp] 饰品体系优先补丁跳过'))
|
||||||
|
|
||||||
|
def test_refuse_screen_passes_through(self):
|
||||||
|
self.install()
|
||||||
|
mirror = self.mirror_cls()
|
||||||
|
mirror.system = 'bleed'
|
||||||
|
self.assertEqual(mirror.acquire_ego_gift(type=2), 'done')
|
||||||
|
self.original.assert_called_once_with(mirror, type=2)
|
||||||
|
|
||||||
|
def test_find_element_is_restored_after_an_exception(self):
|
||||||
|
real = self.auto.find_element
|
||||||
|
self.original.side_effect = RuntimeError('boom')
|
||||||
|
self.install()
|
||||||
|
mirror = self.mirror_cls()
|
||||||
|
mirror.system = 'bleed'
|
||||||
|
with self.assertRaises(RuntimeError):
|
||||||
|
mirror.acquire_ego_gift()
|
||||||
|
self.assertIs(self.auto.find_element, real)
|
||||||
|
|
||||||
|
def test_ranking_error_keeps_upstream_order(self):
|
||||||
|
cards = [(300, 300), (600, 300)]
|
||||||
|
|
||||||
|
def original(mirror):
|
||||||
|
return self.auto.find_element(ap.GIFT_CARD, find_type='image_with_multiple_targets')
|
||||||
|
|
||||||
|
self.mirror_cls.acquire_ego_gift = original
|
||||||
|
self.install()
|
||||||
|
mirror = self.mirror_cls()
|
||||||
|
mirror.system = 'bleed'
|
||||||
|
with mock.patch.object(ap, '_ocr_lines', side_effect=RuntimeError('ocr down')):
|
||||||
|
self.assertEqual(mirror.acquire_ego_gift(), cards)
|
||||||
|
self.assertIn('关键词排序出错(RuntimeError: ocr down)', '\n'.join(self.lines))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
Reference in New Issue
Block a user