Spaces:
Sleeping
Sleeping
jslmmfboom-coder commited on
Commit ·
e5ad646
1
Parent(s): e3c4e52
Add demo scene button, thread config, user expansion
Browse files- app.py +175 -0
- index.html +93 -0
- module/config.py +3 -0
- module/demo_images.py +135 -0
app.py
CHANGED
|
@@ -36,6 +36,7 @@ from module.qdrant_manager import (
|
|
| 36 |
)
|
| 37 |
from module.qdrant_manager import qdrant_search_similar, pt_id
|
| 38 |
from module.text_classifier import classify_scene
|
|
|
|
| 39 |
|
| 40 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 41 |
FRONTEND_PATH = os.path.join(BASE_DIR, 'index.html')
|
|
@@ -105,6 +106,9 @@ async def lifespan(app):
|
|
| 105 |
total_startup = time.perf_counter() - startup_t0
|
| 106 |
print(f'[启动] 总启动时间: {total_startup:.1f}s')
|
| 107 |
|
|
|
|
|
|
|
|
|
|
| 108 |
yield
|
| 109 |
|
| 110 |
session_data['shutdown_stats'] = _snapshot()
|
|
@@ -684,6 +688,177 @@ async def status():
|
|
| 684 |
}
|
| 685 |
|
| 686 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 687 |
if __name__ == "__main__":
|
| 688 |
import uvicorn
|
| 689 |
port = int(os.environ.get("PORT", 7860))
|
|
|
|
| 36 |
)
|
| 37 |
from module.qdrant_manager import qdrant_search_similar, pt_id
|
| 38 |
from module.text_classifier import classify_scene
|
| 39 |
+
from module.demo_images import ensure_demo_images
|
| 40 |
|
| 41 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 42 |
FRONTEND_PATH = os.path.join(BASE_DIR, 'index.html')
|
|
|
|
| 106 |
total_startup = time.perf_counter() - startup_t0
|
| 107 |
print(f'[启动] 总启动时间: {total_startup:.1f}s')
|
| 108 |
|
| 109 |
+
# 生成示例场景图片(用于 /api/demo 端点)
|
| 110 |
+
ensure_demo_images(BASE_DIR)
|
| 111 |
+
|
| 112 |
yield
|
| 113 |
|
| 114 |
session_data['shutdown_stats'] = _snapshot()
|
|
|
|
| 688 |
}
|
| 689 |
|
| 690 |
|
| 691 |
+
@app.post("/api/demo")
|
| 692 |
+
async def demo(scene_type: str = Form("auto")):
|
| 693 |
+
"""示例场景检测:自动读取 test_imgs 中的示例图片执行检测
|
| 694 |
+
|
| 695 |
+
Args:
|
| 696 |
+
scene_type: 'text' / 'complex' / 'auto'(auto 表示自动选择)
|
| 697 |
+
"""
|
| 698 |
+
import shutil
|
| 699 |
+
demo_map = ensure_demo_images(BASE_DIR)
|
| 700 |
+
if not demo_map:
|
| 701 |
+
return JSONResponse({"error": "示例图片生成失败"}, status_code=500)
|
| 702 |
+
|
| 703 |
+
# 选择场景类型
|
| 704 |
+
if scene_type == 'auto':
|
| 705 |
+
scene_type = 'text'
|
| 706 |
+
if scene_type not in demo_map:
|
| 707 |
+
return JSONResponse({"error": f"不支持的场景类型: {scene_type}"}, status_code=400)
|
| 708 |
+
|
| 709 |
+
img_paths = demo_map[scene_type]
|
| 710 |
+
if len(img_paths) < 2:
|
| 711 |
+
return JSONResponse({"error": "示例图片不足"}, status_code=500)
|
| 712 |
+
|
| 713 |
+
# 复制到临时目录执行检测(不污染任何用户的历史数据)
|
| 714 |
+
import tempfile
|
| 715 |
+
tmp_dir = tempfile.mkdtemp(prefix='demo_')
|
| 716 |
+
tmp_imgs = []
|
| 717 |
+
for i, p in enumerate(img_paths[:2]):
|
| 718 |
+
dst = os.path.join(tmp_dir, f"demo_{i}.jpg")
|
| 719 |
+
shutil.copy(p, dst)
|
| 720 |
+
tmp_imgs.append(dst)
|
| 721 |
+
|
| 722 |
+
try:
|
| 723 |
+
loop = asyncio.get_event_loop()
|
| 724 |
+
result = await loop.run_in_executor(
|
| 725 |
+
executor,
|
| 726 |
+
_run_demo_pipeline,
|
| 727 |
+
tmp_imgs, scene_type
|
| 728 |
+
)
|
| 729 |
+
return result
|
| 730 |
+
except Exception as e:
|
| 731 |
+
import traceback
|
| 732 |
+
traceback.print_exc()
|
| 733 |
+
return JSONResponse({"error": f"示例检测失败: {str(e)}"}, status_code=500)
|
| 734 |
+
finally:
|
| 735 |
+
# 清理临时目录
|
| 736 |
+
try:
|
| 737 |
+
shutil.rmtree(tmp_dir, ignore_errors=True)
|
| 738 |
+
except Exception:
|
| 739 |
+
pass
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
def _run_demo_pipeline(img_paths, expected_scene):
|
| 743 |
+
"""执行示例检测流程(不涉及用户历史数据,纯两张图比对)"""
|
| 744 |
+
import cv2
|
| 745 |
+
import numpy as np
|
| 746 |
+
|
| 747 |
+
path1, path2 = img_paths[0], img_paths[1]
|
| 748 |
+
|
| 749 |
+
# 场景分类(用第一张图)
|
| 750 |
+
ocr_result = None
|
| 751 |
+
full_text = ''
|
| 752 |
+
try:
|
| 753 |
+
scene_type, detail = classify_scene(path1, ocr_engine)
|
| 754 |
+
ocr_result = detail.get('ocr_result')
|
| 755 |
+
full_text = detail.get('full_text', '')
|
| 756 |
+
except Exception as e:
|
| 757 |
+
scene_type = expected_scene
|
| 758 |
+
print(f"[demo] 场景分类失败: {e}")
|
| 759 |
+
|
| 760 |
+
is_same = False
|
| 761 |
+
similarity = 0.0
|
| 762 |
+
log_entry = {
|
| 763 |
+
'query_path': path1,
|
| 764 |
+
'history_path': path2,
|
| 765 |
+
'scene_type': scene_type,
|
| 766 |
+
'is_same_scene': False,
|
| 767 |
+
'query_image': os.path.basename(path1),
|
| 768 |
+
'history_image': os.path.basename(path2),
|
| 769 |
+
'query_text': full_text,
|
| 770 |
+
}
|
| 771 |
+
visualization_data = []
|
| 772 |
+
|
| 773 |
+
if scene_type == 'text':
|
| 774 |
+
# 文本场景:OCR + BGE 比对
|
| 775 |
+
from module.text_matcher import compute_text_similarity
|
| 776 |
+
try:
|
| 777 |
+
# OCR 第二张图
|
| 778 |
+
scene2, detail2 = classify_scene(path2, ocr_engine)
|
| 779 |
+
text2 = detail2.get('full_text', '')
|
| 780 |
+
log_entry['history_text'] = text2
|
| 781 |
+
|
| 782 |
+
# BGE 编码比对
|
| 783 |
+
text_sim = compute_text_similarity(full_text, text2, bge_tokenizer, bge_model)
|
| 784 |
+
similarity = text_sim
|
| 785 |
+
is_same = text_sim >= 0.85
|
| 786 |
+
log_entry['text_similarity'] = text_sim
|
| 787 |
+
log_entry['is_same_scene'] = is_same
|
| 788 |
+
except Exception as e:
|
| 789 |
+
print(f"[demo] 文本场景比对失败: {e}")
|
| 790 |
+
|
| 791 |
+
else:
|
| 792 |
+
# 复杂场景:DINOv2 比对
|
| 793 |
+
try:
|
| 794 |
+
if dinov2_extractor is not None:
|
| 795 |
+
dino_sim = dinov2_extractor.compute_similarity(path1, path2)
|
| 796 |
+
similarity = dino_sim if dino_sim else 0.0
|
| 797 |
+
is_same = similarity >= 0.5
|
| 798 |
+
log_entry['dinov2_similarity'] = round(similarity, 4)
|
| 799 |
+
log_entry['is_same_scene'] = is_same
|
| 800 |
+
|
| 801 |
+
# 计算 patch 匹配(用于可视化)
|
| 802 |
+
if is_same:
|
| 803 |
+
patch_info = dinov2_extractor.compute_patch_matches(path1, path2, top_k=50)
|
| 804 |
+
log_entry['patch_match_info'] = patch_info
|
| 805 |
+
except Exception as e:
|
| 806 |
+
print(f"[demo] 复杂场景比对失败: {e}")
|
| 807 |
+
|
| 808 |
+
# 构建可视化(两张图都还在,直接构建)
|
| 809 |
+
_image_cache = {}
|
| 810 |
+
for p in [path1, path2]:
|
| 811 |
+
try:
|
| 812 |
+
data = np.fromfile(p, dtype=np.uint8)
|
| 813 |
+
img = cv2.imdecode(data, cv2.IMREAD_COLOR)
|
| 814 |
+
if img is not None:
|
| 815 |
+
_image_cache[p] = img
|
| 816 |
+
except Exception:
|
| 817 |
+
pass
|
| 818 |
+
|
| 819 |
+
try:
|
| 820 |
+
if scene_type == 'text':
|
| 821 |
+
vis = _build_text_vis_from_cache(log_entry, _image_cache)
|
| 822 |
+
if vis:
|
| 823 |
+
visualization_data.append(vis)
|
| 824 |
+
else:
|
| 825 |
+
vis = _build_complex_vis_from_cache(log_entry, _image_cache)
|
| 826 |
+
if vis:
|
| 827 |
+
visualization_data.append(vis)
|
| 828 |
+
except Exception as e:
|
| 829 |
+
print(f"[demo] 可视化生成失败: {e}")
|
| 830 |
+
|
| 831 |
+
# 将原图也转为 base64 返回(前端无需再请求 /api/image)
|
| 832 |
+
def _img_to_b64(path):
|
| 833 |
+
try:
|
| 834 |
+
data = np.fromfile(path, dtype=np.uint8)
|
| 835 |
+
img = cv2.imdecode(data, cv2.IMREAD_COLOR)
|
| 836 |
+
if img is None:
|
| 837 |
+
return None
|
| 838 |
+
_, buf = cv2.imencode('.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 85])
|
| 839 |
+
return f'data:image/jpeg;base64,{base64.b64encode(buf).decode("utf-8")}'
|
| 840 |
+
except Exception:
|
| 841 |
+
return None
|
| 842 |
+
|
| 843 |
+
return {
|
| 844 |
+
"scene_type": scene_type,
|
| 845 |
+
"is_same_scene": is_same,
|
| 846 |
+
"similarity": round(similarity, 4),
|
| 847 |
+
"query_image": os.path.basename(path1),
|
| 848 |
+
"history_image": os.path.basename(path2),
|
| 849 |
+
"query_image_b64": _img_to_b64(path1),
|
| 850 |
+
"history_image_b64": _img_to_b64(path2),
|
| 851 |
+
"visualizations": visualization_data,
|
| 852 |
+
"evaluation_logs": [{
|
| 853 |
+
"query_image": os.path.basename(path1),
|
| 854 |
+
"history_image": os.path.basename(path2),
|
| 855 |
+
"scene_type": scene_type,
|
| 856 |
+
"is_same_scene": is_same,
|
| 857 |
+
"similarity": round(similarity, 4),
|
| 858 |
+
}],
|
| 859 |
+
}
|
| 860 |
+
|
| 861 |
+
|
| 862 |
if __name__ == "__main__":
|
| 863 |
import uvicorn
|
| 864 |
port = int(os.environ.get("PORT", 7860))
|
index.html
CHANGED
|
@@ -99,6 +99,13 @@ tr.row-fail td{color:#721c24}
|
|
| 99 |
<input type="text" id="usernameInput" placeholder="请输入用户名" maxlength="50">
|
| 100 |
<div id="loginError" class="error-msg"></div>
|
| 101 |
<button class="btn btn-primary" style="width:100%;margin-top:8px" onclick="doLogin()">确认登录</button>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
</div>
|
| 103 |
</div>
|
| 104 |
|
|
@@ -114,6 +121,8 @@ tr.row-fail td{color:#721c24}
|
|
| 114 |
<span>📁 历史图片: <b id="dispCount">0</b> 张</span>
|
| 115 |
</div>
|
| 116 |
<div class="status-actions">
|
|
|
|
|
|
|
| 117 |
<button class="btn btn-success btn-sm" onclick="openHistory()">📁 历史图片</button>
|
| 118 |
<button class="btn btn-info btn-sm" onclick="switchUser()">🔄 更换用户</button>
|
| 119 |
</div>
|
|
@@ -432,6 +441,90 @@ function hideLoading() {
|
|
| 432 |
document.getElementById('historyPanel').addEventListener('click', function(e) {
|
| 433 |
if (e.target === this) closeHistory();
|
| 434 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 435 |
</script>
|
| 436 |
</body>
|
| 437 |
</html>
|
|
|
|
| 99 |
<input type="text" id="usernameInput" placeholder="请输入用户名" maxlength="50">
|
| 100 |
<div id="loginError" class="error-msg"></div>
|
| 101 |
<button class="btn btn-primary" style="width:100%;margin-top:8px" onclick="doLogin()">确认登录</button>
|
| 102 |
+
<div style="margin-top:16px;border-top:1px solid #eee;padding-top:14px">
|
| 103 |
+
<p style="font-size:12px;color:#999;margin-bottom:8px">无需登录,一键体验示例场景:</p>
|
| 104 |
+
<div style="display:flex;gap:8px">
|
| 105 |
+
<button class="btn btn-warning" style="flex:1" onclick="runDemo('text')">📄 文本场景示例</button>
|
| 106 |
+
<button class="btn btn-warning" style="flex:1" onclick="runDemo('complex')">🏞️ 复杂场景示例</button>
|
| 107 |
+
</div>
|
| 108 |
+
</div>
|
| 109 |
</div>
|
| 110 |
</div>
|
| 111 |
|
|
|
|
| 121 |
<span>📁 历史图片: <b id="dispCount">0</b> 张</span>
|
| 122 |
</div>
|
| 123 |
<div class="status-actions">
|
| 124 |
+
<button class="btn btn-warning btn-sm" onclick="runDemo('text')">📄 文本示例</button>
|
| 125 |
+
<button class="btn btn-warning btn-sm" onclick="runDemo('complex')">🏞️ 复杂示例</button>
|
| 126 |
<button class="btn btn-success btn-sm" onclick="openHistory()">📁 历史图片</button>
|
| 127 |
<button class="btn btn-info btn-sm" onclick="switchUser()">🔄 更换用户</button>
|
| 128 |
</div>
|
|
|
|
| 441 |
document.getElementById('historyPanel').addEventListener('click', function(e) {
|
| 442 |
if (e.target === this) closeHistory();
|
| 443 |
});
|
| 444 |
+
|
| 445 |
+
// ========== 示例场景演示 ==========
|
| 446 |
+
async function runDemo(sceneType) {
|
| 447 |
+
showLoading('正在运行示例场景检测,请稍候...');
|
| 448 |
+
// 清空之前的结果
|
| 449 |
+
const resultArea = document.getElementById('resultArea');
|
| 450 |
+
if (resultArea) resultArea.innerHTML = '';
|
| 451 |
+
|
| 452 |
+
try {
|
| 453 |
+
const fd = new FormData();
|
| 454 |
+
fd.append('scene_type', sceneType);
|
| 455 |
+
const res = await fetch('/api/demo', { method: 'POST', body: fd });
|
| 456 |
+
const data = await res.json();
|
| 457 |
+
if (data.error) {
|
| 458 |
+
alert('示例检测失败: ' + data.error);
|
| 459 |
+
hideLoading();
|
| 460 |
+
return;
|
| 461 |
+
}
|
| 462 |
+
renderDemoResult(data, sceneType);
|
| 463 |
+
} catch (e) {
|
| 464 |
+
alert('网络错误: ' + e.message);
|
| 465 |
+
} finally {
|
| 466 |
+
hideLoading();
|
| 467 |
+
}
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
+
function renderDemoResult(data, sceneType) {
|
| 471 |
+
// 如果在登录页,切到主页视图展示结果
|
| 472 |
+
document.getElementById('loginView').classList.add('hidden');
|
| 473 |
+
const mainView = document.getElementById('mainView');
|
| 474 |
+
mainView.classList.remove('hidden');
|
| 475 |
+
document.getElementById('dispUser').textContent = '示例演示';
|
| 476 |
+
document.getElementById('dispCount').textContent = '0';
|
| 477 |
+
|
| 478 |
+
const resultArea = document.getElementById('resultArea');
|
| 479 |
+
const isSame = data.is_same_scene;
|
| 480 |
+
const sceneLabel = data.scene_type === 'text' ? '文本场景' : '复杂场景';
|
| 481 |
+
const simPercent = (data.similarity * 100).toFixed(1);
|
| 482 |
+
|
| 483 |
+
let html = '';
|
| 484 |
+
html += `<div class="card"><h3>🎯 示例场景检测结果(${sceneLabel})</h3>`;
|
| 485 |
+
html += `<div style="margin:12px 0;padding:16px;border-radius:8px;background:${isSame ? '#d4edda' : '#f8d7da'};border:2px solid ${isSame ? '#28a745' : '#dc3545'};text-align:center">`;
|
| 486 |
+
html += `<h2 style="color:${isSame ? '#155724' : '#721c24'};font-size:20px;margin-bottom:4px">${isSame ? '✅ 同一场景' : '❌ 不同场景'}</h2>`;
|
| 487 |
+
html += `<p style="color:${isSame ? '#155724' : '#721c24'};font-size:14px">相似度: ${simPercent}% | 场景类型: ${sceneLabel}</p>`;
|
| 488 |
+
html += `</div>`;
|
| 489 |
+
|
| 490 |
+
// 图片对比
|
| 491 |
+
html += `<div style="display:flex;gap:12px;margin:12px 0">`;
|
| 492 |
+
html += `<div style="flex:1;text-align:center"><p style="font-size:12px;color:#666;margin-bottom:4px">Query 图</p>${data.query_image_b64 ? `<img src="${data.query_image_b64}" style="max-width:100%;border-radius:6px;border:1px solid #eee">` : '<span style="color:#999">无</span>'}</div>`;
|
| 493 |
+
html += `<div style="flex:1;text-align:center"><p style="font-size:12px;color:#666;margin-bottom:4px">History 图</p>${data.history_image_b64 ? `<img src="${data.history_image_b64}" style="max-width:100%;border-radius:6px;border:1px solid #eee">` : '<span style="color:#999">无</span>'}</div>`;
|
| 494 |
+
html += `</div>`;
|
| 495 |
+
|
| 496 |
+
// 可视化
|
| 497 |
+
if (data.visualizations && data.visualizations.length > 0) {
|
| 498 |
+
for (const vis of data.visualizations) {
|
| 499 |
+
const visType = vis.scene_type === 'text' ? '文本场景' : '复杂场景';
|
| 500 |
+
html += `<div style="margin-top:12px">`;
|
| 501 |
+
html += `<div class="vis-toggle" onclick="this.nextElementSibling.classList.toggle('collapsed');this.nextElementSibling.classList.toggle('expanded')"><span>▶</span> 🖼️ 点击查看可视化证据(${visType})</div>`;
|
| 502 |
+
html += `<div class="vis-content collapsed">`;
|
| 503 |
+
html += `<img src="${vis.image_base64}" style="width:100%;border-radius:6px;border:1px solid #eee">`;
|
| 504 |
+
if (vis.scene_type === 'complex') {
|
| 505 |
+
html += `<div class="vis-stats">`;
|
| 506 |
+
html += `<span>DINOv2 相似度: <b>${(vis.dinov2_similarity * 100).toFixed(1)}%</b></span>`;
|
| 507 |
+
html += `<span>Patch 匹配数: <b>${vis.patch_match_count}</b></span>`;
|
| 508 |
+
html += `<span>平均相似度: <b>${(vis.avg_patch_similarity * 100).toFixed(1)}%</b></span>`;
|
| 509 |
+
html += `</div>`;
|
| 510 |
+
} else {
|
| 511 |
+
html += `<div class="vis-stats">`;
|
| 512 |
+
html += `<span>BGE 语义相似度: <b>${(vis.text_similarity * 100).toFixed(1)}%</b></span>`;
|
| 513 |
+
html += `<span>共同关键词: <b>${vis.common_keyword_count}</b> 个</span>`;
|
| 514 |
+
if (vis.common_keywords && vis.common_keywords.length > 0) {
|
| 515 |
+
html += `<div style="margin-top:4px;font-size:12px;color:#666">关键词: ${vis.common_keywords.join('、')}</div>`;
|
| 516 |
+
}
|
| 517 |
+
html += `</div>`;
|
| 518 |
+
}
|
| 519 |
+
html += `</div></div>`;
|
| 520 |
+
}
|
| 521 |
+
}
|
| 522 |
+
|
| 523 |
+
html += `<div style="margin-top:16px;text-align:center;font-size:12px;color:#999">这是示例演示结果。如需检测您自己的图片,请先登录。</div>`;
|
| 524 |
+
html += `</div>`;
|
| 525 |
+
|
| 526 |
+
resultArea.innerHTML = html;
|
| 527 |
+
}
|
| 528 |
</script>
|
| 529 |
</body>
|
| 530 |
</html>
|
module/config.py
CHANGED
|
@@ -9,6 +9,9 @@ DEVICE = "cpu"
|
|
| 9 |
USE_HALF = False
|
| 10 |
IMAGE_SIZE = 512
|
| 11 |
|
|
|
|
|
|
|
|
|
|
| 12 |
# MASt3R 已禁用(CPU 部署,耗时过长)
|
| 13 |
MAST3R_ROOT = None
|
| 14 |
LOCAL_WEIGHTS = None
|
|
|
|
| 9 |
USE_HALF = False
|
| 10 |
IMAGE_SIZE = 512
|
| 11 |
|
| 12 |
+
# 匹配 HF Spaces 免费 2vCPU 配置,显式设置线程数避免过度并发开销
|
| 13 |
+
torch.set_num_threads(2)
|
| 14 |
+
|
| 15 |
# MASt3R 已禁用(CPU 部署,耗时过长)
|
| 16 |
MAST3R_ROOT = None
|
| 17 |
LOCAL_WEIGHTS = None
|
module/demo_images.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""示例场景图片生成 — 在启动时自动生成演示用图片
|
| 2 |
+
|
| 3 |
+
生成两组示例:
|
| 4 |
+
- 文本场景:模拟合同文档(白底 + 文字行 + 标题),两张内容相同但亮度/偏移不同
|
| 5 |
+
- 复杂场景:模拟实景照片(彩色渐变 + 几何形状),两张构图相似但有差异
|
| 6 |
+
"""
|
| 7 |
+
import os
|
| 8 |
+
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _get_font(size):
|
| 12 |
+
try:
|
| 13 |
+
return ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", size)
|
| 14 |
+
except Exception:
|
| 15 |
+
try:
|
| 16 |
+
return ImageFont.truetype("DejaVuSans.ttf", size)
|
| 17 |
+
except Exception:
|
| 18 |
+
return ImageFont.load_default()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _generate_text_scene(path1, path2):
|
| 22 |
+
"""生成文本场景示例:模拟合同文档
|
| 23 |
+
|
| 24 |
+
两张图内容相同,但图2做了亮度调整和水平偏移,模拟不同角度拍摄
|
| 25 |
+
"""
|
| 26 |
+
w, h = 600, 800
|
| 27 |
+
|
| 28 |
+
for path, brightness, offset_x in [(path1, 0, 0), (path2, 30, 5)]:
|
| 29 |
+
img = Image.new('RGB', (w, h), (255, 255, 255))
|
| 30 |
+
draw = ImageDraw.Draw(img)
|
| 31 |
+
|
| 32 |
+
# 标题区域
|
| 33 |
+
draw.rectangle([50 + offset_x, 40, 550 + offset_x, 80], fill=(30, 30, 30))
|
| 34 |
+
# 正文行
|
| 35 |
+
for i in range(25):
|
| 36 |
+
y = 120 + i * 25
|
| 37 |
+
x_start = 50 + offset_x
|
| 38 |
+
x_end = 550 - (i % 5) * 20 + offset_x
|
| 39 |
+
draw.rectangle([x_start, y, x_end, y + 12], fill=(60, 60, 60))
|
| 40 |
+
|
| 41 |
+
# 模拟印章(红色圆形)
|
| 42 |
+
draw.ellipse([400 + offset_x, 650, 500 + offset_x, 750],
|
| 43 |
+
outline=(180, 30, 30), width=3)
|
| 44 |
+
draw.text((420 + offset_x, 680), "SEAL", fill=(180, 30, 30),
|
| 45 |
+
font=_get_font(20))
|
| 46 |
+
|
| 47 |
+
# 亮度调整
|
| 48 |
+
if brightness > 0:
|
| 49 |
+
import numpy as np
|
| 50 |
+
arr = np.array(img).astype(int) + brightness
|
| 51 |
+
arr = np.clip(arr, 0, 255).astype('uint8')
|
| 52 |
+
img = Image.fromarray(arr)
|
| 53 |
+
|
| 54 |
+
img.save(path, 'JPEG', quality=85)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _generate_complex_scene(path1, path2):
|
| 58 |
+
"""生成复杂场景示例:模拟实景照片
|
| 59 |
+
|
| 60 |
+
两张图构图相似(同一场景不同角度),使用彩色渐变和几何形状
|
| 61 |
+
"""
|
| 62 |
+
w, h = 600, 450
|
| 63 |
+
|
| 64 |
+
for path, shift_x, color_shift in [(path1, 0, 0), (path2, 15, 20)]:
|
| 65 |
+
img = Image.new('RGB', (w, h))
|
| 66 |
+
draw = ImageDraw.Draw(img)
|
| 67 |
+
|
| 68 |
+
# 天空渐变
|
| 69 |
+
for y in range(h // 2):
|
| 70 |
+
r = int(100 + y * 0.3 + color_shift)
|
| 71 |
+
g = int(150 + y * 0.2)
|
| 72 |
+
b = int(200 + y * 0.15)
|
| 73 |
+
draw.line([(0, y), (w, y)], fill=(min(r, 255), min(g, 255), min(b, 255)))
|
| 74 |
+
|
| 75 |
+
# 地面渐变
|
| 76 |
+
for y in range(h // 2, h):
|
| 77 |
+
r = int(80 + (y - h // 2) * 0.3)
|
| 78 |
+
g = int(120 + (y - h // 2) * 0.2)
|
| 79 |
+
b = int(60 + (y - h // 2) * 0.1)
|
| 80 |
+
draw.line([(0, y), (w, y)], fill=(min(r, 255), min(g, 255), min(b, 255)))
|
| 81 |
+
|
| 82 |
+
# 太阳
|
| 83 |
+
sun_x = 450 + shift_x
|
| 84 |
+
draw.ellipse([sun_x - 40, 50, sun_x + 40, 130],
|
| 85 |
+
fill=(255, 220, 100))
|
| 86 |
+
|
| 87 |
+
# 山脉
|
| 88 |
+
draw.polygon([(0, 225), (150 + shift_x, 150), (300 + shift_x, 200),
|
| 89 |
+
(450 + shift_x, 160), (600, 220), (600, 225)],
|
| 90 |
+
fill=(80, 100, 80))
|
| 91 |
+
|
| 92 |
+
# 建筑
|
| 93 |
+
draw.rectangle([100 + shift_x, 250, 200 + shift_x, 400],
|
| 94 |
+
fill=(120, 100, 90))
|
| 95 |
+
draw.rectangle([250 + shift_x, 280, 350 + shift_x, 400],
|
| 96 |
+
fill=(100, 110, 100))
|
| 97 |
+
draw.rectangle([400 + shift_x, 260, 480 + shift_x, 400],
|
| 98 |
+
fill=(90, 80, 100))
|
| 99 |
+
|
| 100 |
+
# 轻微模糊模拟不同焦距
|
| 101 |
+
if shift_x > 0:
|
| 102 |
+
img = img.filter(ImageFilter.GaussianBlur(radius=0.8))
|
| 103 |
+
|
| 104 |
+
img.save(path, 'JPEG', quality=85)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def ensure_demo_images(base_dir):
|
| 108 |
+
"""确保示例图片存在,不存在则生成
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
base_dir: 项目根目录
|
| 112 |
+
Returns:
|
| 113 |
+
dict: {'text': [path1, path2], 'complex': [path1, path2]}
|
| 114 |
+
"""
|
| 115 |
+
demo_dir = os.path.join(base_dir, 'test_imgs')
|
| 116 |
+
os.makedirs(demo_dir, exist_ok=True)
|
| 117 |
+
|
| 118 |
+
text1 = os.path.join(demo_dir, 'demo_text_1.jpg')
|
| 119 |
+
text2 = os.path.join(demo_dir, 'demo_text_2.jpg')
|
| 120 |
+
complex1 = os.path.join(demo_dir, 'demo_complex_1.jpg')
|
| 121 |
+
complex2 = os.path.join(demo_dir, 'demo_complex_2.jpg')
|
| 122 |
+
|
| 123 |
+
if not os.path.exists(text1):
|
| 124 |
+
try:
|
| 125 |
+
_generate_text_scene(text1, text2)
|
| 126 |
+
_generate_complex_scene(complex1, complex2)
|
| 127 |
+
print("[示例] 已生成演示图片")
|
| 128 |
+
except Exception as e:
|
| 129 |
+
print(f"[示例] 生成失败: {e}")
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
return {
|
| 133 |
+
'text': [text1, text2],
|
| 134 |
+
'complex': [complex1, complex2],
|
| 135 |
+
}
|