Selaa lähdekoodia

页面增加功能

AnlaAnla 5 päivää sitten
vanhempi
commit
bfc1a6a3d1
4 muutettua tiedostoa jossa 292 lisäystä ja 184 poistoa
  1. 1 1
      .idea/deployment.xml
  2. 33 17
      app/routers/search.py
  3. 4 1
      app/routers/upload.py
  4. 254 165
      app/static/index.html

+ 1 - 1
.idea/deployment.xml

@@ -26,7 +26,7 @@
       <paths name="显卡服务器@192.168.77.249">
         <serverdata>
           <mappings>
-            <mapping local="$PROJECT_DIR$" web="/" />
+            <mapping deploy="/ML/RemoteProject/PokemonCardSearch" local="$PROJECT_DIR$" web="/" />
           </mappings>
         </serverdata>
       </paths>

+ 33 - 17
app/routers/search.py

@@ -65,10 +65,9 @@ async def search_image(file: UploadFile = File(...), top_k: int = 5):
     return {"results": formatted_results}
 
 
-@router.post("/filter")
+@router.post("/state", summary="统计")
 async def filter_database(
         card_name: Optional[str] = None,
-        source_id: Optional[str] = None,
         limit: int = 20
 ):
     """数据库元数据过滤"""
@@ -76,24 +75,41 @@ async def filter_database(
     if card_name:
         # 模糊查询
         expr_list.append(f'card_name like "{card_name}%"')
-    if source_id:
-        expr_list.append(f'source_id == "{source_id}"')
 
     expr = " && ".join(expr_list) if expr_list else ""
 
-    # 如果没有条件,查询所有(慎用,有限制)
+    # 如果没有条件,查询所有
     if not expr:
         expr = "id > 0"
 
-    res = milvus_collection.query(
-        expr=expr,
-        output_fields=["id", "img_path", "card_name", "card_num", "lang"],
-        limit=limit
-    )
-
-    # 格式化路径
-    for item in res:
-        full_path = item.pop("img_path", "")
-        item["img_url"] = f"/static/images/{full_path.split('/')[-1]}" if full_path else ""
-
-    return {"count": len(res), "data": res}
+    try:
+        # 获取符合条件的总数量 (count(*))
+        count_res = milvus_collection.query(
+            expr=expr,
+            output_fields=["count(*)"]
+        )
+        # count_res 的格式通常是 [{'count(*)': 105}]
+        total_count = count_res[0]["count(*)"]
+
+        # 步骤 2: 获取实际数据 (带 limit)
+        res = milvus_collection.query(
+            expr=expr,
+            output_fields=["id", "img_path", "card_name", "card_num", "lang"],
+            limit=limit
+        )
+
+        # 格式化路径
+        for item in res:
+            full_path = item.pop("img_path", "")
+            item["img_url"] = f"/static/images/{full_path.split('/')[-1]}" if full_path else ""
+
+        return {
+            "total": total_count,
+            "limit": limit,
+            "returned_count": len(res),
+            "data": res
+        }
+
+    except Exception as e:
+        print(f"Query Error: {e}")
+        return {"error": str(e)}

+ 4 - 1
app/routers/upload.py

@@ -238,10 +238,13 @@ def process_zip_file(zip_path: str):
             os.remove(zip_path)
 
 
-@router.post("/batch")
+@router.post("/batch", summary="上传宝可梦数据压缩包")
 def upload_zip(file: UploadFile = File(...)):
     """
     上传 ZIP 存入向量库
+    大文件夹.zip
+        小文件夹必须遵循该格式: ('129873', {'us'}, 'Swadloon'), 2
+            图片...
     """
     if not file.filename.endswith(".zip"):
         raise HTTPException(status_code=400, detail="Only zip files are allowed.")

+ 254 - 165
app/static/index.html

@@ -6,12 +6,13 @@
     <title>Pokemon Card Search</title>
     <style>
         :root {
-            --primary-color: #4F46E5; /* 靛蓝色 */
+            --primary-color: #4F46E5;
             --primary-hover: #4338ca;
             --bg-color: #f3f4f6;
             --card-bg: #ffffff;
             --text-main: #1f2937;
             --text-sub: #6b7280;
+            --border-color: #e5e7eb;
         }
 
         * { box-sizing: border-box; margin: 0; padding: 0; }
@@ -38,19 +39,45 @@
             color: var(--text-main);
             margin-bottom: 0.5rem;
         }
-        header p { color: var(--text-sub); }
 
-        /* 搜索上传区域 */
-        .search-panel {
+        /* --- Tab 切换样式 --- */
+        .tabs {
+            display: flex;
+            justify-content: center;
+            margin-bottom: 1.5rem;
+            gap: 1rem;
+        }
+        .tab-btn {
+            background: transparent;
+            border: none;
+            padding: 0.75rem 1.5rem;
+            font-size: 1rem;
+            font-weight: 600;
+            color: var(--text-sub);
+            cursor: pointer;
+            border-bottom: 3px solid transparent;
+            transition: all 0.3s;
+        }
+        .tab-btn.active {
+            color: var(--primary-color);
+            border-bottom-color: var(--primary-color);
+        }
+
+        /* 搜索面板容器 */
+        .search-panel-container {
             background: var(--card-bg);
             padding: 2rem;
             border-radius: 16px;
             box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
             max-width: 600px;
-            margin: 0 auto 3rem auto;
-            text-align: center;
+            margin: 0 auto 2rem auto;
+            min-height: 300px; /* 防止切换时高度跳动太大 */
         }
 
+        .panel-content { display: none; }
+        .panel-content.active { display: block; animation: fadeIn 0.3s; }
+
+        /* --- 图片上传区域样式 (保持不变) --- */
         .upload-zone {
             border: 2px dashed #d1d5db;
             border-radius: 12px;
@@ -58,51 +85,52 @@
             margin-bottom: 1.5rem;
             cursor: pointer;
             transition: all 0.3s ease;
-            position: relative;
+            text-align: center;
             background-color: #fff;
         }
-
-        .upload-zone:hover {
+        .upload-zone:hover, .upload-zone.drag-active {
             border-color: var(--primary-color);
             background-color: #f9fafb;
         }
-
-        /* 拖拽激活时的样式 */
-        .upload-zone.drag-active {
-            border-color: var(--primary-color);
-            background-color: #eef2ff; /* 浅蓝色背景 */
-            transform: scale(1.02);
-        }
-
-        #preview-container {
-            display: none;
-            margin-top: 1rem;
-        }
-
         #preview-img {
             max-width: 100%;
-            max-height: 300px;
+            max-height: 200px;
             border-radius: 8px;
-            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
+            margin-top: 1rem;
+            display: none;
+            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
         }
 
-        input[type="file"] { display: none; }
-
-        .upload-label {
-            display: block;
-            color: var(--text-sub);
-            font-weight: 500;
-            pointer-events: none;
+        /* --- 文本搜索区域样式 (新增) --- */
+        .text-search-group {
+            display: flex;
+            flex-direction: column;
+            gap: 1rem;
+            margin-bottom: 1.5rem;
+            text-align: left;
+        }
+        .form-input {
+            width: 100%;
+            padding: 0.8rem 1rem;
+            border: 1px solid var(--border-color);
+            border-radius: 8px;
+            font-size: 1rem;
+            transition: border-color 0.2s;
+        }
+        .form-input:focus {
+            outline: none;
+            border-color: var(--primary-color);
+            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
         }
 
+        /* --- 公共控件样式 --- */
         .controls {
             display: flex;
             justify-content: center;
             align-items: center;
             gap: 1rem;
-            margin-bottom: 1rem;
+            margin-top: 1rem;
         }
-
         .search-btn {
             background-color: var(--primary-color);
             color: white;
@@ -116,25 +144,37 @@
             display: inline-flex;
             align-items: center;
         }
-
         .search-btn:hover { background-color: var(--primary-hover); }
         .search-btn:disabled { background-color: #9ca3af; cursor: not-allowed; }
 
-        .top-n-input {
+        .limit-input {
             padding: 0.75rem;
-            border: 1px solid #d1d5db;
+            border: 1px solid var(--border-color);
             border-radius: 8px;
             width: 80px;
             text-align: center;
         }
 
-        /* 结果展示区域 */
+        /* --- 结果统计栏 --- */
+        .stats-bar {
+            max-width: 1200px;
+            margin: 0 auto 1rem auto;
+            padding: 0.75rem 1.5rem;
+            background-color: #e0e7ff;
+            color: #3730a3;
+            border-radius: 8px;
+            font-weight: 500;
+            display: none; /* 默认隐藏 */
+            justify-content: space-between;
+            align-items: center;
+        }
+
+        /* --- 结果卡片样式 --- */
         .results-grid {
             display: grid;
             grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
             gap: 1.5rem;
         }
-
         .result-card {
             background: var(--card-bg);
             border-radius: 12px;
@@ -144,12 +184,10 @@
             display: flex;
             flex-direction: column;
         }
-
         .result-card:hover {
             transform: translateY(-5px);
             box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
         }
-
         .card-img-wrapper {
             width: 100%;
             height: 280px;
@@ -158,16 +196,14 @@
             align-items: center;
             justify-content: center;
             overflow: hidden;
+            position: relative;
         }
-
         .card-img-wrapper img {
             width: 100%;
             height: 100%;
             object-fit: contain;
         }
-
         .card-info { padding: 1rem; }
-
         .card-title {
             font-size: 1.1rem;
             font-weight: bold;
@@ -177,15 +213,18 @@
             overflow: hidden;
             text-overflow: ellipsis;
         }
-
         .card-meta {
             font-size: 0.875rem;
             color: var(--text-sub);
-            margin-bottom: 0.75rem;
             display: flex;
             justify-content: space-between;
+            margin-bottom: 0.5rem;
         }
 
+        /* 相似度条 (仅在图片搜索时显示) */
+        .similarity-wrapper { display: none; }
+        .show-score .similarity-wrapper { display: block; }
+
         .score-bar-bg {
             height: 6px;
             background-color: #e5e7eb;
@@ -193,14 +232,12 @@
             overflow: hidden;
             margin-top: 0.5rem;
         }
-
         .score-bar-fill {
             height: 100%;
             background-color: #10b981;
             width: 0%;
             transition: width 0.5s ease-out;
         }
-
         .score-text {
             font-size: 0.75rem;
             color: var(--text-sub);
@@ -208,6 +245,7 @@
             text-align: right;
         }
 
+        /* Spinner */
         .spinner {
             border: 3px solid rgba(255,255,255,0.3);
             border-radius: 50%;
@@ -218,213 +256,264 @@
             margin-right: 8px;
             display: none;
         }
-
-        @keyframes spin {
-            0% { transform: rotate(0deg); }
-            100% { transform: rotate(360deg); }
-        }
-
-        @media (max-width: 640px) {
-            header h1 { font-size: 1.8rem; }
-            .results-grid { grid-template-columns: 1fr 1fr; }
-            .card-img-wrapper { height: 200px; }
-        }
+        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
+        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
     </style>
 </head>
 <body>
 
     <div class="container">
         <header>
-            <h1>🔍 Pokemon Card Search</h1>
-            <p>Upload a card image to find similar matches</p>
+            <h1>Pokédex Search</h1>
+            <p>探索宝可梦卡片数据库</p>
         </header>
 
-        <div class="search-panel">
-            <!-- 上传区域:增加 id 和 ondrop 处理 -->
-            <div class="upload-zone" id="dropZone">
-                <div id="upload-placeholder">
-                    <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#9ca3af" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
-                        <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
-                        <circle cx="8.5" cy="8.5" r="1.5"></circle>
-                        <polyline points="21 15 16 10 5 21"></polyline>
-                    </svg>
-                    <span class="upload-label">点击或拖拽上传图片</span>
-                </div>
+        <!-- Tab 切换 -->
+        <div class="tabs">
+            <button class="tab-btn active" onclick="switchTab('img')">📷 以图搜图</button>
+            <button class="tab-btn" onclick="switchTab('text')">🔤 名称搜索</button>
+        </div>
 
-                <div id="preview-container">
-                    <img id="preview-img" src="" alt="Input Preview">
-                    <p style="margin-top:0.5rem; color:var(--text-sub); font-size:0.9rem;">点击可重新选择</p>
+        <div class="search-panel-container">
+
+            <!-- 面板 1: 图片搜索 -->
+            <div id="panel-img" class="panel-content active">
+                <div class="upload-zone" id="dropZone">
+                    <div id="upload-placeholder">
+                        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#9ca3af" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+                            <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
+                            <circle cx="8.5" cy="8.5" r="1.5"></circle>
+                            <polyline points="21 15 16 10 5 21"></polyline>
+                        </svg>
+                        <span style="display:block; margin-top:0.5rem; color:#6b7280;">点击或拖拽上传图片</span>
+                    </div>
+                    <img id="preview-img" src="" alt="Preview">
+                    <input type="file" id="imgInput" accept="image/*" style="display:none">
                 </div>
 
-                <!-- 隐藏的 input -->
-                <input type="file" id="imgInput" accept="image/*">
+                <div class="controls">
+                    <label>显示数量:</label>
+                    <input type="number" id="imgTopN" class="limit-input" value="5" min="1" max="20">
+                    <button class="search-btn" onclick="searchImage()" id="btnImgSearch">
+                        <div class="spinner"></div> 搜索相似
+                    </button>
+                </div>
             </div>
 
-            <div class="controls">
-                <div style="display:flex; align-items:center; gap:0.5rem;">
-                    <label for="topN" style="font-weight:500; color:var(--text-sub)">Top Results:</label>
-                    <input type="number" id="topN" class="top-n-input" value="5" min="1" max="20">
+            <!-- 面板 2: 文本搜索 (新功能) -->
+            <div id="panel-text" class="panel-content">
+                <div class="text-search-group">
+                    <label for="cardNameInput" style="font-weight:600; color:var(--text-main)">卡片名称 (模糊匹配):</label>
+                    <input type="text" id="cardNameInput" class="form-input" placeholder="例如: Pikachu, Charizard...">
+                </div>
+
+                <div class="controls">
+                    <label>最大返回:</label>
+                    <input type="number" id="textLimit" class="limit-input" value="20" min="1" max="100">
+                    <button class="search-btn" onclick="searchByMetadata()" id="btnTextSearch">
+                        <div class="spinner"></div> 查询数据
+                    </button>
                 </div>
-                <button class="search-btn" onclick="searchImage()" id="searchBtn">
-                    <div class="spinner" id="loadingSpinner"></div>
-                    Search
-                </button>
             </div>
+
         </div>
 
+        <!-- 统计信息栏 -->
+        <div id="statsBar" class="stats-bar">
+            <span id="statsText"></span>
+        </div>
+
+        <!-- 结果展示区域 -->
         <div id="resultsArea">
-            <h3 style="margin-bottom: 1rem; color: var(--text-sub); display:none;" id="resultTitle">Search Results</h3>
             <div class="results-grid" id="resultsGrid"></div>
         </div>
     </div>
 
     <script>
-        const imgInput = document.getElementById('imgInput');
+        // --- Tab 切换逻辑 ---
+        function switchTab(type) {
+            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
+            document.querySelectorAll('.panel-content').forEach(p => p.classList.remove('active'));
+
+            if (type === 'img') {
+                document.querySelector('.tab-btn:nth-child(1)').classList.add('active');
+                document.getElementById('panel-img').classList.add('active');
+            } else {
+                document.querySelector('.tab-btn:nth-child(2)').classList.add('active');
+                document.getElementById('panel-text').classList.add('active');
+                document.getElementById('cardNameInput').focus();
+            }
+            // 切换时清空结果,避免混淆
+            document.getElementById('resultsGrid').innerHTML = '';
+            document.getElementById('statsBar').style.display = 'none';
+        }
+
+        // --- 图片上传相关逻辑 (Drag & Drop) ---
         const dropZone = document.getElementById('dropZone');
-        const previewContainer = document.getElementById('preview-container');
+        const imgInput = document.getElementById('imgInput');
         const previewImg = document.getElementById('preview-img');
         const placeholder = document.getElementById('upload-placeholder');
 
-        // --- 核心改动:处理拖拽事件 ---
-
-        // 1. 阻止浏览器默认行为 (打开图片)
         ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
-            dropZone.addEventListener(eventName, preventDefaults, false);
+            dropZone.addEventListener(eventName, (e) => { e.preventDefault(); e.stopPropagation(); }, false);
         });
 
-        function preventDefaults(e) {
-            e.preventDefault();
-            e.stopPropagation();
-        }
-
-        // 2. 视觉反馈 (高亮)
         ['dragenter', 'dragover'].forEach(eventName => {
             dropZone.addEventListener(eventName, () => dropZone.classList.add('drag-active'), false);
         });
-
         ['dragleave', 'drop'].forEach(eventName => {
             dropZone.addEventListener(eventName, () => dropZone.classList.remove('drag-active'), false);
         });
 
-        // 3. 处理文件放置 (Drop)
-        dropZone.addEventListener('drop', handleDrop, false);
-
-        function handleDrop(e) {
-            const dt = e.dataTransfer;
-            const files = dt.files;
-
-            if (files && files.length > 0) {
-                // 将拖入的文件赋值给 input 元素,方便后续搜索逻辑使用
+        dropZone.addEventListener('drop', (e) => {
+            const files = e.dataTransfer.files;
+            if (files.length) {
                 imgInput.files = files;
                 updatePreview(files[0]);
             }
-        }
+        });
 
-        // 4. 处理点击上传 (Click)
         dropZone.addEventListener('click', () => imgInput.click());
-
-        // 5. 阻止 input 的点击事件冒泡 (防止触发 dropZone 的 click 导致死循环)
         imgInput.addEventListener('click', (e) => e.stopPropagation());
+        imgInput.onchange = () => { if (imgInput.files[0]) updatePreview(imgInput.files[0]); };
 
-        // 6. 监听 Input 变化 (点击选择文件后触发)
-        imgInput.onchange = (e) => {
-            if (imgInput.files && imgInput.files[0]) {
-                updatePreview(imgInput.files[0]);
-            }
-        };
-
-        // --- 统一的预览逻辑 ---
         function updatePreview(file) {
-            if (file) {
-                placeholder.style.display = 'none';
-                previewContainer.style.display = 'block';
-                previewImg.src = URL.createObjectURL(file);
-            }
+            placeholder.style.display = 'none';
+            previewImg.style.display = 'block';
+            previewImg.src = URL.createObjectURL(file);
         }
 
-        // --- 搜索逻辑 (保持不变) ---
+        // --- 功能 1: 图片搜索 (原有) ---
         async function searchImage() {
-            if (!imgInput.files[0]) {
-                alert("请先选择一张图片!");
-                return;
-            }
-
-            const btn = document.getElementById('searchBtn');
-            const spinner = document.getElementById('loadingSpinner');
-            const topN = document.getElementById('topN').value;
-            const grid = document.getElementById('resultsGrid');
-            const resultTitle = document.getElementById('resultTitle');
+            if (!imgInput.files[0]) return alert("请先上传图片!");
 
-            btn.disabled = true;
-            spinner.style.display = 'block';
-            grid.innerHTML = '';
-            resultTitle.style.display = 'none';
+            const btn = document.getElementById('btnImgSearch');
+            setLoading(btn, true);
 
             try {
                 const formData = new FormData();
                 formData.append('file', imgInput.files[0]);
+                const topN = document.getElementById('imgTopN').value;
 
                 const res = await fetch(`/api/search/image?top_k=${topN}`, {
                     method: 'POST',
                     body: formData
                 });
 
-                if (!res.ok) throw new Error("Server Error");
+                const data = await res.json();
+
+                // 图片搜索通常没有 total 统计,显示返回数量即可
+                showStats(`🔍 相似度匹配完成,显示前 ${data.results.length} 个结果`);
+                renderResults(data.results, true); // true 表示显示分数条
+
+            } catch (e) {
+                alert("搜索失败: " + e.message);
+            } finally {
+                setLoading(btn, false);
+            }
+        }
+
+        // --- 功能 2: 元数据搜索 (新增) ---
+        async function searchByMetadata() {
+            const name = document.getElementById('cardNameInput').value.trim();
+            const limit = document.getElementById('textLimit').value;
+            const btn = document.getElementById('btnTextSearch');
+
+            setLoading(btn, true);
+
+            try {
+                // 构建 URL Query Params
+                const params = new URLSearchParams({ limit: limit });
+                if (name) params.append('card_name', name);
+
+                // 注意:这里使用你提供的 POST 接口
+                const res = await fetch(`/api/search/state?${params.toString()}`, {
+                    method: 'POST',
+                    headers: { 'Accept': 'application/json' },
+                    body: '' // POST 请求体为空
+                });
+
+                if (!res.ok) throw new Error("API Request Failed");
 
                 const data = await res.json();
-                renderResults(data.results);
 
-            } catch (error) {
-                alert("搜索出错: " + error.message);
+                // 显示统计信息
+                if (data.total !== undefined) {
+                    showStats(`📊 数据库中符合条件的共有 <b>${data.total}</b> 条,当前展示前 <b>${data.returned_count}</b> 条`);
+                }
+
+                // 渲染结果 (false 表示不显示分数条)
+                renderResults(data.data || [], false);
+
+            } catch (e) {
+                console.error(e);
+                alert("查询出错: " + e.message);
             } finally {
-                btn.disabled = false;
-                spinner.style.display = 'none';
-                resultTitle.style.display = 'block';
+                setLoading(btn, false);
             }
         }
 
-        function renderResults(items) {
+        // --- 通用渲染函数 ---
+        function renderResults(items, showScore) {
             const grid = document.getElementById('resultsGrid');
+            grid.innerHTML = '';
 
             if (!items || items.length === 0) {
-                grid.innerHTML = '<p style="text-align:center; grid-column: 1/-1; color:#666;">未找到相似结果</p>';
+                grid.innerHTML = '<p style="grid-column:1/-1; text-align:center; color:#666; padding:2rem;">未找到相关数据</p>';
                 return;
             }
 
             items.forEach((item, index) => {
-                const percentage = (item.score * 100).toFixed(1);
+                // 处理相似度分数 (仅图片搜索有)
+                let scoreHtml = '';
+                if (showScore && item.score !== undefined) {
+                    const pct = (item.score * 100).toFixed(1);
+                    scoreHtml = `
+                        <div class="similarity-wrapper">
+                            <div class="score-bar-bg">
+                                <div class="score-bar-fill" style="width: ${pct}%"></div>
+                            </div>
+                            <div class="score-text">相似度: ${pct}%</div>
+                        </div>
+                    `;
+                }
+
                 const cardNumDisplay = (item.card_num && item.card_num !== -1) ? `#${item.card_num}` : '';
 
-                const cardHtml = `
-                    <div class="result-card" style="opacity: 0; animation: fadeIn 0.5s forwards ${index * 0.1}s">
+                const html = `
+                    <div class="result-card" style="opacity:0; animation:fadeIn 0.5s forwards ${index * 0.05}s">
                         <div class="card-img-wrapper">
-                            <img src="${item.img_url}" alt="${item.card_name}" onerror="this.src='https://via.placeholder.com/200?text=Image+Not+Found'">
+                            <img src="${item.img_url}" loading="lazy"
+                                 onerror="this.src='https://via.placeholder.com/200x280?text=No+Image'">
                         </div>
                         <div class="card-info">
                             <div class="card-title" title="${item.card_name}">${item.card_name}</div>
                             <div class="card-meta">
-                                <span>${item.lang.toUpperCase()}</span>
+                                <span style="background:#eee; padding:2px 6px; border-radius:4px; font-size:12px;">${item.lang ? item.lang.toUpperCase() : 'UNK'}</span>
                                 <span>${cardNumDisplay}</span>
                             </div>
-                            <div class="score-bar-bg">
-                                <div class="score-bar-fill" style="width: ${percentage}%"></div>
+                            <div class="result-card-class ${showScore ? 'show-score' : ''}">
+                                ${scoreHtml}
                             </div>
-                            <div class="score-text">Sim: ${percentage}%</div>
                         </div>
                     </div>
                 `;
-                grid.insertAdjacentHTML('beforeend', cardHtml);
+                grid.insertAdjacentHTML('beforeend', html);
             });
         }
 
-        const style = document.createElement('style');
-        style.innerHTML = `
-            @keyframes fadeIn {
-                from { opacity: 0; transform: translateY(10px); }
-                to { opacity: 1; transform: translateY(0); }
-            }
-        `;
-        document.head.appendChild(style);
+        // --- 辅助 UI 函数 ---
+        function setLoading(btn, isLoading) {
+            btn.disabled = isLoading;
+            btn.querySelector('.spinner').style.display = isLoading ? 'inline-block' : 'none';
+        }
+
+        function showStats(htmlContent) {
+            const bar = document.getElementById('statsBar');
+            const text = document.getElementById('statsText');
+            bar.style.display = 'flex';
+            text.innerHTML = htmlContent;
+        }
     </script>
 </body>
 </html>