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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""南+验证码手动标注 Web 服务。
|
| 3 |
+
显示验证码大图,输入数字回车保存并跳下一张。标签存 JSON。
|
| 4 |
+
用法: label_server.py <图片目录> <标签文件> [端口] [host]
|
| 5 |
+
"""
|
| 6 |
+
import glob
|
| 7 |
+
import io
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import sys
|
| 11 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 12 |
+
from urllib.parse import urlparse
|
| 13 |
+
|
| 14 |
+
from PIL import Image
|
| 15 |
+
|
| 16 |
+
IMG_DIR = os.path.abspath(sys.argv[1])
|
| 17 |
+
LABEL_FILE = sys.argv[2]
|
| 18 |
+
PORT = int(sys.argv[3]) if len(sys.argv) > 3 else 8000
|
| 19 |
+
HOST = sys.argv[4] if len(sys.argv) > 4 else "0.0.0.0"
|
| 20 |
+
|
| 21 |
+
_upscale_cache = {}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def load_labels():
|
| 25 |
+
if os.path.exists(LABEL_FILE):
|
| 26 |
+
return json.load(open(LABEL_FILE, encoding="utf-8"))
|
| 27 |
+
return {}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def save_labels(labels):
|
| 31 |
+
json.dump(labels, open(LABEL_FILE, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def all_images():
|
| 35 |
+
return sorted(os.path.basename(f) for f in glob.glob(os.path.join(IMG_DIR, "*.png")))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def upscaled_bytes(name):
|
| 39 |
+
if name in _upscale_cache:
|
| 40 |
+
return _upscale_cache[name]
|
| 41 |
+
p = os.path.join(IMG_DIR, name)
|
| 42 |
+
if not os.path.exists(p):
|
| 43 |
+
return None
|
| 44 |
+
im = Image.open(p).convert("RGB")
|
| 45 |
+
im = im.resize((im.width * 3, im.height * 3), Image.LANCZOS)
|
| 46 |
+
buf = io.BytesIO()
|
| 47 |
+
im.save(buf, "PNG")
|
| 48 |
+
_upscale_cache[name] = buf.getvalue()
|
| 49 |
+
return _upscale_cache[name]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
PAGE = """<!DOCTYPE html>
|
| 53 |
+
<html lang="zh">
|
| 54 |
+
<head>
|
| 55 |
+
<meta charset="utf-8">
|
| 56 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0">
|
| 57 |
+
<title>南+ 验证码标注</title>
|
| 58 |
+
<style>
|
| 59 |
+
*{box-sizing:border-box}
|
| 60 |
+
body{font-family:-apple-system,Segoe UI,sans-serif;background:#0f1115;color:#eee;margin:0;padding:10px 8px 20px;text-align:center;-webkit-tap-highlight-color:transparent;overflow-y:auto}
|
| 61 |
+
h1{font-size:17px;margin:0}
|
| 62 |
+
.progress{color:#7a8698;font-size:13px;margin:3px 0}
|
| 63 |
+
.img-area{display:flex;align-items:center;justify-content:center;margin:4px 0}
|
| 64 |
+
.img-area img{display:block;max-width:96vw;max-height:42vh;background:#fff;padding:5px;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,.5);object-fit:contain}
|
| 65 |
+
.name{color:#4a5260;font-size:11px;margin:2px 0}
|
| 66 |
+
input{font-size:30px;letter-spacing:10px;width:88%;max-width:280px;text-align:center;background:#1a1d24;border:2px solid #3a3f4a;border-radius:10px;color:#fff;padding:16px 6px;margin:10px 0;-webkit-appearance:none}
|
| 67 |
+
input:focus{outline:none;border-color:#4f8cff;box-shadow:0 0 0 3px rgba(79,140,255,.3)}
|
| 68 |
+
.btns{display:flex;justify-content:center;gap:12px;margin:8px 0}
|
| 69 |
+
button{font-size:16px;padding:12px 24px;background:#2a2f3a;color:#eee;border:none;border-radius:8px;cursor:pointer;min-width:76px}
|
| 70 |
+
button:active{background:#4f8cff;color:#fff;transform:scale(.96)}
|
| 71 |
+
.hint{color:#4a5260;font-size:11px}
|
| 72 |
+
.history{max-height:25vh;overflow-y:auto;text-align:left;margin:8px auto;padding:6px;background:#191c24;border-radius:8px;width:92%;max-width:360px}
|
| 73 |
+
.history .item{font-size:11px;color:#8892a0;padding:2px 4px;border-bottom:1px solid #222;display:flex;gap:8px}
|
| 74 |
+
.history .item span{color:#4f8cff;font-weight:600;font-size:13px}
|
| 75 |
+
.history .empty{color:#4a5260;font-size:11px;text-align:center;padding:6px}
|
| 76 |
+
@media (max-width:480px){
|
| 77 |
+
input{font-size:26px;padding:14px 4px;letter-spacing:6px}
|
| 78 |
+
button{padding:12px 18px;font-size:15px}
|
| 79 |
+
.img-area img{max-height:38vh}
|
| 80 |
+
}
|
| 81 |
+
</style>
|
| 82 |
+
</head>
|
| 83 |
+
<body>
|
| 84 |
+
<h1>南+ 验证码标注</h1>
|
| 85 |
+
<div class="progress" id="prog">加载中...</div>
|
| 86 |
+
<div class="img-area"><img id="capimg" src="" alt="captcha"></div>
|
| 87 |
+
<div class="name" id="name"></div>
|
| 88 |
+
<input id="inp" maxlength="4" autocomplete="off" placeholder="数字" inputmode="numeric" autocapitalize="off">
|
| 89 |
+
<div class="btns">
|
| 90 |
+
<button onclick="skip()">跳过</button>
|
| 91 |
+
<button onclick="back()">上一张</button>
|
| 92 |
+
</div>
|
| 93 |
+
<div class="hint" id="hint"></div>
|
| 94 |
+
<div class="history" id="history"><div class="empty">还没有标注记录</div></div>
|
| 95 |
+
<script>
|
| 96 |
+
let images=[], idx=0, labeledSet=new Set();
|
| 97 |
+
let history=[]; // [{name, code}]
|
| 98 |
+
async function load(){
|
| 99 |
+
const d=await(await fetch('/api/images')).json();
|
| 100 |
+
images=d.images; idx=0;
|
| 101 |
+
document.getElementById('prog').textContent='已标 '+d.labeled+' / '+d.total;
|
| 102 |
+
show();
|
| 103 |
+
}
|
| 104 |
+
function show(){
|
| 105 |
+
if(idx>=images.length){
|
| 106 |
+
document.body.innerHTML='<h2 style="padding:40px">全部完成!</h2>';
|
| 107 |
+
return;
|
| 108 |
+
}
|
| 109 |
+
const name=images[idx];
|
| 110 |
+
document.getElementById('capimg').src='/img/'+name;
|
| 111 |
+
document.getElementById('name').textContent=name+(labeledSet.has(name)?' (已标)':'');
|
| 112 |
+
document.getElementById('hint').textContent=idx+' / '+(labeledSet.size+images.length-idx);
|
| 113 |
+
const inp=document.getElementById('inp'); inp.value=''; inp.focus();
|
| 114 |
+
window.scrollTo(0,0);
|
| 115 |
+
renderHistory();
|
| 116 |
+
}
|
| 117 |
+
function renderHistory(){
|
| 118 |
+
const h=document.getElementById('history');
|
| 119 |
+
if(history.length===0){h.innerHTML='<div class="empty">���没有标注记录</div>'; return;}
|
| 120 |
+
h.innerHTML=history.slice(-20).reverse().map(r=>'<div class="item"><span>✓</span> '+r.name+' → <span>'+r.code+'</span></div>').join('');
|
| 121 |
+
}
|
| 122 |
+
async function submit(){
|
| 123 |
+
const name=images[idx]; const v=document.getElementById('inp').value.trim();
|
| 124 |
+
if(!v) return;
|
| 125 |
+
await fetch('/api/label',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name,label:v})});
|
| 126 |
+
labeledSet.add(name); history.push({name,code:v});
|
| 127 |
+
idx++; refresh();
|
| 128 |
+
}
|
| 129 |
+
function skip(){ if(idx<images.length){idx++; refresh();} }
|
| 130 |
+
function back(){
|
| 131 |
+
if(idx>0){ idx--;
|
| 132 |
+
// 回退时从 history 移除最后一条(如果是刚提交的)
|
| 133 |
+
if(history.length>0 && history[history.length-1].name===images[idx]) history.pop();
|
| 134 |
+
show();
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
async function refresh(){
|
| 138 |
+
const d=await(await fetch('/api/stats')).json();
|
| 139 |
+
document.getElementById('prog').textContent='已标 '+d.labeled+' / '+d.total;
|
| 140 |
+
show();
|
| 141 |
+
}
|
| 142 |
+
document.getElementById('inp').addEventListener('keydown',e=>{ if(e.key==='Enter'){e.preventDefault();submit();} });
|
| 143 |
+
document.addEventListener('keydown',e=>{
|
| 144 |
+
const v=document.getElementById('inp').value;
|
| 145 |
+
if(e.key==='s'&&v==='') skip();
|
| 146 |
+
if(e.key==='b'&&v==='') back();
|
| 147 |
+
});
|
| 148 |
+
load();
|
| 149 |
+
</script>
|
| 150 |
+
</body></html>
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class Handler(BaseHTTPRequestHandler):
|
| 155 |
+
labels = load_labels()
|
| 156 |
+
|
| 157 |
+
def _send(self, code, body, ctype):
|
| 158 |
+
self.send_response(code)
|
| 159 |
+
self.send_header("Content-Type", ctype)
|
| 160 |
+
self.send_header("Content-Length", str(len(body)))
|
| 161 |
+
self.send_header("Cache-Control", "no-store")
|
| 162 |
+
self.end_headers()
|
| 163 |
+
self.wfile.write(body)
|
| 164 |
+
|
| 165 |
+
def _json(self, obj):
|
| 166 |
+
self._send(200, json.dumps(obj).encode(), "application/json")
|
| 167 |
+
|
| 168 |
+
def do_GET(self):
|
| 169 |
+
u = urlparse(self.path)
|
| 170 |
+
if u.path == "/":
|
| 171 |
+
self._send(200, PAGE.encode(), "text/html; charset=utf-8")
|
| 172 |
+
elif u.path == "/api/images":
|
| 173 |
+
total = all_images()
|
| 174 |
+
labeled = set(Handler.labels.keys())
|
| 175 |
+
self._json({"images": [n for n in total if n not in labeled], "total": len(total), "labeled": len(labeled)})
|
| 176 |
+
elif u.path == "/api/stats":
|
| 177 |
+
self._json({"labeled": len(Handler.labels), "total": len(all_images())})
|
| 178 |
+
elif u.path.startswith("/img/"):
|
| 179 |
+
name = os.path.basename(u.path[len("/img/"):])
|
| 180 |
+
data = upscaled_bytes(name)
|
| 181 |
+
if data is None:
|
| 182 |
+
self._send(404, b"not found", "text/plain")
|
| 183 |
+
else:
|
| 184 |
+
self._send(200, data, "image/png")
|
| 185 |
+
else:
|
| 186 |
+
self._send(404, b"not found", "text/plain")
|
| 187 |
+
|
| 188 |
+
def do_POST(self):
|
| 189 |
+
u = urlparse(self.path)
|
| 190 |
+
if u.path == "/api/label":
|
| 191 |
+
length = int(self.headers.get("Content-Length", 0))
|
| 192 |
+
try:
|
| 193 |
+
data = json.loads(self.rfile.read(length))
|
| 194 |
+
except Exception:
|
| 195 |
+
data = {}
|
| 196 |
+
name, label = data.get("name", ""), str(data.get("label", "")).strip()
|
| 197 |
+
if name and label:
|
| 198 |
+
Handler.labels[name] = {"label": label, "votes": [label], "count": 1, "agreed": True}
|
| 199 |
+
save_labels(Handler.labels)
|
| 200 |
+
self._json({"ok": True, "labeled": len(Handler.labels)})
|
| 201 |
+
else:
|
| 202 |
+
self._send(404, b"not found", "text/plain")
|
| 203 |
+
|
| 204 |
+
def log_message(self, fmt, *args):
|
| 205 |
+
pass
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def main():
|
| 209 |
+
os.makedirs(IMG_DIR, exist_ok=True)
|
| 210 |
+
srv = ThreadingHTTPServer((HOST, PORT), Handler)
|
| 211 |
+
print(f"标注服务已启动: http://{HOST}:{PORT} 图片目录={IMG_DIR} 标签文件={LABEL_FILE}", flush=True)
|
| 212 |
+
print(f"待标图片数: {len(all_images())} 已标: {len(Handler.labels)}", flush=True)
|
| 213 |
+
srv.serve_forever()
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
if __name__ == "__main__":
|
| 217 |
+
main()
|