""" Gradio web interface for Noita spell icon recognition. Usage: python app.py # Then open http://localhost:17860 """ import json import os from pathlib import Path import gradio as gr import numpy as np from PIL import Image, ImageDraw from inference import SpellClassifier from wand_cropper import extract_spell_icons_with_debug RAW_ICONS_DIR = Path("data/raw_icons") MANIFEST_PATH = Path("data/icon_manifest.json") SPELL_ID_MAP_PATH = Path("data/spell_id_map.json") DEFAULT_EMPTY_THRESHOLD = 0.45 WAND2_TEMPLATE = ( "{{{{Wand2\n" "| wandCard = Yes\n" "| castDelay = 0.17\n" "| rechargeTime = 0.33\n" "| manaMax = 100000.00\n" "| manaCharge = 100000.00\n" "| capacity = {capacity}\n" "| spread = 0\n" "| speed = 1.00\n" "| spells = {spells}\n" "}}}}" ) def find_wiki_icon(spell_name: str, manifest: dict) -> str | None: """Find the wiki icon file for a given spell name.""" for filename, info in manifest.items(): if info["spell_name_en"].lower() == spell_name.lower(): icon_path = RAW_ICONS_DIR / filename if icon_path.exists(): return str(icon_path) return None def draw_debug_boxes(image: Image.Image, boxes: list[tuple[int, int, int, int]]) -> Image.Image: preview = image.convert("RGB").copy() draw = ImageDraw.Draw(preview) for i, (left, top, right, bottom) in enumerate(boxes, start=1): draw.rectangle((left, top, right, bottom), outline=(255, 80, 80), width=2) draw.text((left + 2, max(0, top - 14)), str(i), fill=(255, 220, 80)) return preview def _build_scale_list(min_scale: float, max_scale: float, step: float) -> list[float]: if step <= 0: return [1.0] min_scale = max(0.4, min_scale) max_scale = max(min_scale, max_scale) scales = [] value = min_scale while value <= max_scale + 1e-6: scales.append(round(value, 3)) value += step if 1.0 not in scales: scales.append(1.0) return sorted(set(scales)) def _refine_crop_candidates( image: Image.Image, box: tuple[int, int, int, int], shift_px: int, scales: list[float], ) -> list[Image.Image]: left, top, right, bottom = box width = max(1, right - left) height = max(1, bottom - top) cx = (left + right) / 2.0 cy = (top + bottom) / 2.0 shifts = [0] if shift_px > 0: shifts = [0, -shift_px, shift_px] img_w, img_h = image.size crops: list[Image.Image] = [] for scale in scales: w = max(2, int(round(width * scale))) h = max(2, int(round(height * scale))) half_w = w / 2.0 half_h = h / 2.0 for dx in shifts: for dy in shifts: l = int(round(cx + dx - half_w)) t = int(round(cy + dy - half_h)) r = l + w b = t + h l = max(0, l) t = max(0, t) r = min(img_w, r) b = min(img_h, b) if r - l < 2 or b - t < 2: continue crops.append(image.crop((l, t, r, b))) return crops def _ensure_numpy(image): if image is None: return None if isinstance(image, np.ndarray): return image if isinstance(image, Image.Image): return np.array(image) return None def _ensure_pil(image) -> Image.Image | None: if image is None: return None if isinstance(image, Image.Image): return image if isinstance(image, np.ndarray): return Image.fromarray(image) return None def _render_split_lines(image: Image.Image, line_positions: list[int]) -> Image.Image: preview = image.convert("RGB").copy() draw = ImageDraw.Draw(preview) width, height = preview.size for y in sorted(set(line_positions)): if 0 < y < height: draw.line((0, y, width, y), fill=(255, 80, 80), width=3) return preview def _extract_base_image(editor_data) -> Image.Image | None: if isinstance(editor_data, dict): bg = editor_data.get("background") if bg is not None: if isinstance(bg, Image.Image): return bg if isinstance(bg, np.ndarray): return Image.fromarray(bg) composite = editor_data.get("composite") if composite is not None: if isinstance(composite, Image.Image): return composite if isinstance(composite, np.ndarray): return Image.fromarray(composite) if isinstance(editor_data, Image.Image): return editor_data if isinstance(editor_data, np.ndarray): return Image.fromarray(editor_data) return None def _extract_drawn_mask(editor_data) -> np.ndarray | None: if isinstance(editor_data, dict): layers = editor_data.get("layers") if isinstance(layers, list) and layers: layer_np = _ensure_numpy(layers[-1]) if layer_np is not None: if layer_np.ndim == 3 and layer_np.shape[-1] == 4: return layer_np[..., 3] > 8 if layer_np.ndim == 3: return layer_np.mean(axis=2) > 8 if isinstance(layers, np.ndarray): layer_np = layers if layer_np.ndim == 3 and layer_np.shape[-1] == 4: return layer_np[..., 3] > 8 if layer_np.ndim == 3: return layer_np.mean(axis=2) > 8 composite = editor_data.get("composite") background = editor_data.get("background") comp_np = _ensure_numpy(composite) bg_np = _ensure_numpy(background) if comp_np is not None and bg_np is not None and comp_np.shape == bg_np.shape: diff = np.mean(np.abs(comp_np.astype(np.float32) - bg_np.astype(np.float32)), axis=2) return diff > 8 return None def _extract_line_positions(editor_data, min_width_ratio: float = 0.1) -> list[int]: mask = _extract_drawn_mask(editor_data) if mask is None: return [] height, width = mask.shape[:2] row_counts = mask.sum(axis=1) threshold = max(10, int(width * min_width_ratio)) active = row_counts >= threshold positions = [] start = None for i, flag in enumerate(active): if flag and start is None: start = i elif not flag and start is not None: if i - start >= 2: positions.append(int((start + i) / 2)) start = None if start is not None and height - start >= 2: positions.append(int((start + height) / 2)) return positions def _split_image_by_lines(image: Image.Image, line_positions: list[int], min_height: int = 24) -> list[Image.Image]: width, height = image.size lines = sorted({p for p in line_positions if 0 < p < height}) bounds = [0] + lines + [height] segments: list[Image.Image] = [] for top, bottom in zip(bounds[:-1], bounds[1:]): if bottom - top < min_height: continue segments.append(image.crop((0, top, width, bottom))) return segments def create_app(): """Build and return the Gradio app.""" classifier = SpellClassifier() with open(MANIFEST_PATH, "r", encoding="utf-8") as f: manifest = json.load(f) spell_id_map = {} if SPELL_ID_MAP_PATH.exists(): with open(SPELL_ID_MAP_PATH, "r", encoding="utf-8") as f: spell_id_map = json.load(f) def predict_single(image, center_crop_ratio=1.0): if image is None: return "请上传一张图片", None pil_image = Image.fromarray(image) if not isinstance(image, Image.Image) else image results = classifier.classify(pil_image, top_k=5, center_crop_ratio=center_crop_ratio) lines = ["| 排名 | 法术名称 | 置信度 |", "|:---:|:---|:---:|"] for i, (name, conf) in enumerate(results): bar = "█" * int(conf * 20) lines.append(f"| {i+1} | **{name}** | {conf*100:.1f}% {bar} |") result_text = "\n".join(lines) top_name = results[0][0] icon_path = find_wiki_icon(top_name, manifest) return result_text, icon_path def _analyze_wand_image( pil_image: Image.Image, layout_mode, expected_rows, crop_scale, center_crop_ratio, empty_threshold, low_conf_policy, enable_refine, refine_shift_px, refine_scale_min, refine_scale_max, refine_scale_step, segment_title: str | None = None, ): crops, debug = extract_spell_icons_with_debug( pil_image, layout_mode=layout_mode, expected_rows=expected_rows, crop_scale=crop_scale, ) if not crops: return None, "未能找到任何法术格子。请检查截图内容。" use_refine = bool(enable_refine and layout_mode == "10_per_row") if use_refine: scales = _build_scale_list(refine_scale_min, refine_scale_max, refine_scale_step) refined_crops = [] refined_results = [] for box, base_crop in zip(debug.crop_boxes, crops): candidates = _refine_crop_candidates(pil_image, box, refine_shift_px, scales) if not candidates: candidates = [base_crop] candidate_results = classifier.classify_batch( candidates, top_k=3, center_crop_ratio=center_crop_ratio, ) best_idx = max( range(len(candidate_results)), key=lambda idx: candidate_results[idx][0][1], ) refined_crops.append(candidates[best_idx]) refined_results.append(candidate_results[best_idx]) crops = refined_crops batch_results = refined_results else: batch_results = classifier.classify_batch(crops, top_k=3, center_crop_ratio=center_crop_ratio) md_lines = [f"### 成功提取 {len(crops)} 个候选法术格子", ""] md_lines.append("| 序号 | Top-1 | Top-2 | Top-3 |") md_lines.append("|:---:|:---|:---|:---|") gallery_images = [] low_conf_count = 0 empty_slots = 0 spell_ids: list[str] = [] unknown_names: list[str] = [] ignored_slots = 0 for i, (crop, top_k_res) in enumerate(zip(crops, batch_results), start=1): best_name, best_conf = top_k_res[0] if best_conf < 0.55: low_conf_count += 1 row = [f"**{name}** ({conf*100:.1f}%)" for name, conf in top_k_res] while len(row) < 3: row.append("-") md_lines.append(f"| {i} | {row[0]} | {row[1]} | {row[2]} |") gallery_images.append((crop, f"{i}. {best_name} ({best_conf*100:.1f}%)")) if best_conf < empty_threshold: if low_conf_policy == "empty": spell_ids.append("") empty_slots += 1 elif low_conf_policy == "unknown": spell_ids.append("") unknown_names.append(f"{best_name}(低置信度)") else: ignored_slots += 1 else: spell_id = spell_id_map.get(best_name) if not spell_id: unknown_names.append(best_name) spell_ids.append("") else: spell_ids.append(spell_id) md_lines.append("") md_lines.append(f"- 检测到行数: {len(debug.row_bounds)}") md_lines.append(f"- 检测到列候选数: {len(debug.column_bounds)}") md_lines.append(f"- 低置信度格子数(<55%): {low_conf_count}") md_lines.append(f"- 低置信度判为空的格子数(<{empty_threshold:.2f}): {empty_slots}") if ignored_slots: md_lines.append(f"- 已忽略低置信度格子数: {ignored_slots}") if unknown_names: md_lines.append("- 未找到映射的法术: " + "、".join(sorted(set(unknown_names)))) md_lines.append("- 如果有法术被完全跳过,请先看右侧红框调试图:若红框数量就少了,说明是切割问题;若红框齐全但识别错了,说明主要是模型问题。") if segment_title: md_lines.insert(0, f"#### {segment_title}") debug_image = draw_debug_boxes(pil_image, debug.crop_boxes) return { "md_lines": md_lines, "gallery_images": gallery_images, "debug_image": debug_image, "spell_ids": spell_ids, }, None def predict_wand( image, layout_mode, expected_rows, crop_scale, center_crop_ratio, empty_threshold, low_conf_policy, enable_refine, refine_shift_px, refine_scale_min, refine_scale_max, refine_scale_step, ): if image is None: return "请上传一张法杖截图", [], None, "" pil_image = Image.fromarray(image) if not isinstance(image, Image.Image) else image result, err = _analyze_wand_image( pil_image, layout_mode, expected_rows, crop_scale, center_crop_ratio, empty_threshold, low_conf_policy, enable_refine, refine_shift_px, refine_scale_min, refine_scale_max, refine_scale_step, ) if err: return err, [], None, "" spells_text = ",".join(result["spell_ids"]) wand_code = WAND2_TEMPLATE.format(capacity=len(result["spell_ids"]), spells=spells_text) return "\n".join(result["md_lines"]), result["gallery_images"], result["debug_image"], wand_code def build_manual_segments(base_image, line_positions): base_pil = _ensure_pil(base_image) if base_pil is None: return [], [], "请先上传图片并点击添加横线。", gr.update(maximum=1, value=1) line_positions = line_positions or [] segments = _split_image_by_lines(base_pil, line_positions) if not segments: segments = [base_pil] segments_np = [_ensure_numpy(seg) for seg in segments if _ensure_numpy(seg) is not None] preview = [(seg, f"分段 {i+1}") for i, seg in enumerate(segments_np)] info = f"检测到 {len(line_positions)} 条横线,已分成 {len(segments_np)} 段。" return segments_np, preview, info, gr.update(maximum=max(1, len(segments_np)), value=1) def predict_segments_all( segments, layout_mode, expected_rows, crop_scale, center_crop_ratio, empty_threshold, low_conf_policy, enable_refine, refine_shift_px, refine_scale_min, refine_scale_max, refine_scale_step, ): if not segments: return "请先生成分段预览。", [], [], "" md_lines = [f"### 手动分段解析:共 {len(segments)} 段", ""] all_gallery = [] debug_gallery = [] all_spell_ids: list[str] = [] for idx, seg in enumerate(segments, start=1): seg_pil = _ensure_pil(seg) if seg_pil is None: md_lines.append(f"#### 分段 {idx}\n- 无法读取该分段图像。\n") continue result, err = _analyze_wand_image( seg_pil, layout_mode, expected_rows, crop_scale, center_crop_ratio, empty_threshold, low_conf_policy, enable_refine, refine_shift_px, refine_scale_min, refine_scale_max, refine_scale_step, segment_title=f"分段 {idx}", ) if err: md_lines.append(f"#### 分段 {idx}\n- {err}\n") continue md_lines.extend(result["md_lines"]) md_lines.append("") all_gallery.extend( [(img, f"{idx}-{label}") for img, label in result["gallery_images"]] ) debug_gallery.append((result["debug_image"], f"分段 {idx} 调试")) all_spell_ids.extend(result["spell_ids"]) wand_code = WAND2_TEMPLATE.format(capacity=len(all_spell_ids), spells=",".join(all_spell_ids)) return "\n".join(md_lines), all_gallery, debug_gallery, wand_code def predict_segment_one( segments, segment_index, layout_mode, expected_rows, crop_scale, center_crop_ratio, empty_threshold, low_conf_policy, enable_refine, refine_shift_px, refine_scale_min, refine_scale_max, refine_scale_step, ): if not segments: return "请先生成分段预览。", [], [], "" if not segment_index: segment_index = 1 idx = int(segment_index) if idx < 1 or idx > len(segments): return "分段序号超出范围。", [], [], "" seg = segments[idx - 1] seg_pil = _ensure_pil(seg) if seg_pil is None: return "无法读取该分段图像。", [], [], "" result, err = _analyze_wand_image( seg_pil, layout_mode, expected_rows, crop_scale, center_crop_ratio, empty_threshold, low_conf_policy, enable_refine, refine_shift_px, refine_scale_min, refine_scale_max, refine_scale_step, segment_title=f"分段 {idx}", ) if err: return err, [], [], "" wand_code = WAND2_TEMPLATE.format( capacity=len(result["spell_ids"]), spells=",".join(result["spell_ids"]), ) return "\n".join(result["md_lines"]), result["gallery_images"], [(result["debug_image"], f"分段 {idx} 调试")], wand_code def reset_manual_lines(image): base_pil = _ensure_pil(image) if base_pil is None: return None, [], None, "请先上传图片。" preview = _render_split_lines(base_pil, []) return base_pil, [], preview, "已载入图片,单击添加横线。" def add_manual_line(base_image, line_positions, evt: gr.SelectData): base_pil = _ensure_pil(base_image) if base_pil is None: return None, line_positions, "请先上传图片。" if evt is None or evt.index is None: return _render_split_lines(base_pil, line_positions), line_positions, "未获取到点击位置。" x, y = evt.index line_positions = sorted(set((line_positions or []) + [int(y)])) preview = _render_split_lines(base_pil, line_positions) return preview, line_positions, f"已添加 {len(line_positions)} 条横线。" def remove_last_line(base_image, line_positions): base_pil = _ensure_pil(base_image) if base_pil is None: return None, line_positions, "请先上传图片。" if not line_positions: return _render_split_lines(base_pil, []), [], "当前没有横线。" line_positions = sorted(line_positions)[:-1] preview = _render_split_lines(base_pil, line_positions) return preview, line_positions, f"已删除,剩余 {len(line_positions)} 条横线。" def clear_lines(base_image): base_pil = _ensure_pil(base_image) if base_pil is None: return None, [], "请先上传图片。" preview = _render_split_lines(base_pil, []) return preview, [], "已清空横线。" with gr.Blocks( title="Noita 法术图标识别器", ) as app: gr.Markdown( "# 🔮 Noita 法术图标识别器\n" "上传截图,CNN 将自动识别法术。\n" "这版额外提供了**切割调试红框图**,方便判断到底是分割漏了,还是模型认错了。" ) manual_segments_state = gr.State([]) manual_line_state = gr.State([]) manual_base_state = gr.State(None) with gr.Tabs(): with gr.TabItem("整张法杖解析 (自动切割)"): with gr.Row(): with gr.Column(scale=1): input_image_wand = gr.Image(label="上传整段法杖 UI 截图", type="pil", height=220) layout_mode = gr.Radio( choices=[("自动检测 (Auto)", "auto"), ("原版10法术/行 (10 per row)", "10_per_row")], value="auto", label="排版模式", info="如果截图中带有很多空法术且确定是原版10格一行的排版,请开启此模式。" ) expected_rows = gr.Slider( label="强制指定行数 (0为自动)", minimum=0, maximum=50, value=0, step=1, info="默认根据截图比例猜测行数。若截图边缘留白过多导致按正方形推算不对,才需要手动填入确实的行数。" ) crop_scale = gr.Slider( label="切片缩放倍率 (推荐 1.1)", minimum=0.5, maximum=2.0, value=1.1, step=0.05, info="控制切片红框的大小。如果包含边框太多,请调低此值。" ) center_crop_ratio = gr.Slider( label="中心过滤比例 (推荐 0.8)", minimum=0.4, maximum=1.0, value=0.8, step=0.05, info="在发给模型前,进一步从红框中心裁剪。0.8表示只取中心80%区域,能完美过滤槽位边框。" ) empty_threshold = gr.Slider( label="低置信度判空阈值", minimum=0.1, maximum=0.9, value=DEFAULT_EMPTY_THRESHOLD, step=0.01, ) low_conf_policy = gr.Radio( choices=[("判为空槽", "empty"), ("保留为未知", "unknown"), ("忽略该格", "ignore")], value="empty", label="低置信度处理方式", info="仅影响低于阈值的格子。忽略将从最终 Wand2 列表中移除该格。", ) enable_refine = gr.Checkbox( label="启用二次纠偏(仅10格模式)", value=True, info="在裁剪框附近进行平移/缩放尝试,选择置信度最高的结果。", ) refine_shift_px = gr.Slider( label="纠偏平移像素", minimum=0, maximum=12, value=6, step=1, ) refine_scale_min = gr.Slider( label="纠偏最小缩放", minimum=0.7, maximum=1.0, value=0.85, step=0.05, ) refine_scale_max = gr.Slider( label="纠偏最大缩放", minimum=1.0, maximum=1.4, value=1.1, step=0.05, ) refine_scale_step = gr.Slider( label="缩放步进", minimum=0.05, maximum=0.2, value=0.05, step=0.05, ) predict_btn_wand = gr.Button("✨ 一键解析法杖", variant="primary", size="lg") result_md_wand = gr.Markdown(label="解析结果") wand_code_box = gr.Textbox( label="可粘贴的 Wand2 代码", lines=8, elem_id="wand_code_box", ) copy_wand_code = gr.Button("📋 复制代码") with gr.Column(scale=1): result_gallery_wand = gr.Gallery( label="切割出的法术", show_label=True, elem_id="gallery", columns=[4], rows=[2], object_fit="contain", height="auto", ) debug_preview = gr.Image(label="切割调试图(红框)", type="pil", height=260) gr.Markdown("---") gr.Markdown("## 手动分段(单击添加横线)") with gr.Row(): with gr.Column(scale=1): manual_image = gr.Image( label="上传图片后单击添加横线", type="pil", height=700, interactive=True, ) remove_last_line_btn = gr.Button("↩️ 删除最后一条横线", variant="secondary") clear_lines_btn = gr.Button("🧹 清空横线", variant="secondary") build_segments_btn = gr.Button("✂️ 生成分段预览", variant="secondary") segment_info = gr.Markdown("请上传图片后,单击图片添加横线(从上到下分段)。") segment_index = gr.Slider( label="选择分段序号", minimum=1, maximum=1, value=1, step=1, ) parse_segment_btn = gr.Button("🔍 解析选中分段", variant="secondary") parse_all_btn = gr.Button("✨ 一键解析全部分段", variant="primary") result_md_manual = gr.Markdown(label="分段解析结果") wand_code_box_manual = gr.Textbox( label="可粘贴的 Wand2 代码(单段或全部)", lines=8, ) copy_wand_code_manual = gr.Button("📋 复制代码") with gr.Column(scale=1): segment_gallery = gr.Gallery( label="分段预览", show_label=True, columns=[2], rows=[2], object_fit="contain", height="auto", ) debug_gallery_manual = gr.Gallery( label="分段切割调试图", show_label=True, columns=[2], rows=[2], object_fit="contain", height="auto", ) result_gallery_manual = gr.Gallery( label="识别出的法术(分段)", show_label=True, columns=[4], rows=[2], object_fit="contain", height="auto", ) with gr.TabItem("单张法术识别"): with gr.Row(): with gr.Column(scale=1): input_image_single = gr.Image(label="上传单个法术图标", type="pil", height=300) center_crop_single = gr.Slider( label="中心裁剪比例", minimum=0.5, maximum=1.0, value=0.8, step=0.05, info="识别前只取图片中心区域,避开边框干扰。" ) predict_btn_single = gr.Button("🔍 识别单图", variant="primary", size="lg") with gr.Column(scale=1): result_md_single = gr.Markdown(label="识别结果") matched_icon_single = gr.Image(label="匹配的 Wiki 图标", type="filepath", height=200) example_dir = RAW_ICONS_DIR if example_dir.exists(): example_files = sorted(example_dir.glob("*.png"))[:12] if example_files: gr.Examples( examples=[[str(f)] for f in example_files], inputs=[input_image_single], label="示例单图标(来自 Wiki)", ) predict_btn_single.click( fn=predict_single, inputs=[input_image_single, center_crop_single], outputs=[result_md_single, matched_icon_single], ) predict_btn_wand.click( fn=predict_wand, inputs=[ input_image_wand, layout_mode, expected_rows, crop_scale, center_crop_ratio, empty_threshold, low_conf_policy, enable_refine, refine_shift_px, refine_scale_min, refine_scale_max, refine_scale_step, ], outputs=[result_md_wand, result_gallery_wand, debug_preview, wand_code_box], ) manual_image.upload( fn=reset_manual_lines, inputs=[manual_image], outputs=[manual_base_state, manual_line_state, manual_image, segment_info], ) manual_image.select( fn=add_manual_line, inputs=[manual_base_state, manual_line_state], outputs=[manual_image, manual_line_state, segment_info], ) remove_last_line_btn.click( fn=remove_last_line, inputs=[manual_base_state, manual_line_state], outputs=[manual_image, manual_line_state, segment_info], ) clear_lines_btn.click( fn=clear_lines, inputs=[manual_base_state], outputs=[manual_image, manual_line_state, segment_info], ) build_segments_btn.click( fn=build_manual_segments, inputs=[manual_base_state, manual_line_state], outputs=[manual_segments_state, segment_gallery, segment_info, segment_index], ) parse_all_btn.click( fn=predict_segments_all, inputs=[ manual_segments_state, layout_mode, expected_rows, crop_scale, center_crop_ratio, empty_threshold, low_conf_policy, enable_refine, refine_shift_px, refine_scale_min, refine_scale_max, refine_scale_step, ], outputs=[result_md_manual, result_gallery_manual, debug_gallery_manual, wand_code_box_manual], ) parse_segment_btn.click( fn=predict_segment_one, inputs=[ manual_segments_state, segment_index, layout_mode, expected_rows, crop_scale, center_crop_ratio, empty_threshold, low_conf_policy, enable_refine, refine_shift_px, refine_scale_min, refine_scale_max, refine_scale_step, ], outputs=[result_md_manual, result_gallery_manual, debug_gallery_manual, wand_code_box_manual], ) def _copy_hint(text): return text copy_wand_code.click( fn=_copy_hint, inputs=[wand_code_box], outputs=[wand_code_box], js="(text) => { navigator.clipboard.writeText(text); return text; }", ) copy_wand_code_manual.click( fn=_copy_hint, inputs=[wand_code_box_manual], outputs=[wand_code_box_manual], js="(text) => { navigator.clipboard.writeText(text); return text; }", ) return app if __name__ == "__main__": app = create_app() launch_kwargs = dict(theme=gr.themes.Soft(primary_hue="purple", secondary_hue="blue")) if os.getenv("SPACE_ID"): app.launch(**launch_kwargs) else: app.launch(server_name="0.0.0.0", server_port=17860, **launch_kwargs)