feat(anim): 多帧(动图)验证码流水线 + 统一任务入口
Build and Push / build (push) Successful in 6m38s

- captcha/pipeline.go:decode_frames(GIF/APNG)→ detect_frames(复用 YOLOX)→ track(IoU 贪心)→ mark_visited
- AnimalJump:动物跳点类验证码,输入动图 + 候选点,返回每个点是否被经过 + 该点的首个帧号 + 未经过点列表
- POST /api/task/run(type 分发,taskTypes 注册表作为新类型扩展点)
- POST /api/frames/detect(逐帧检测,给自定义时序流水线复用)
- GET /api/task/types
- 类型展示 +2 条(动图点选 / 逐帧检测)
- 试用页支持动图任务:动图上传 + 候选点文本 + radius/class_filter
This commit is contained in:
Cmake
2026-12-04 01:38:31 +08:00
parent 85b2844f73
commit 8e1d57df2a
5 changed files with 471 additions and 7 deletions
+270
View File
@@ -0,0 +1,270 @@
package captcha
import (
"bytes"
"fmt"
"image"
"image/gif"
"math"
"sort"
"anticaptcha/pkg/onnx"
)
// 多帧(动图)验证码流水线。
//
// 为什么单独一层:动图类验证码不是「一张图 → 一个答案」,而是
// 「N 帧 → 追踪 → 时序推理 → 答案」,跟单图分类/检测的调用约定完全不同。
// 这里把它拆成可复用的步骤,新类型只要换步骤组合与参数,不必再写 Go 代码:
//
// decode_frames → 动图拆帧(GIF / APNG / 多图数组)
// detect_frames → 每帧跑目标检测(复用 YOLOX)
// track → 按类别 + IoU 串成轨迹
// select_unvisited → 用轨迹去筛候选点,得到「没被经过的点」
//
// 「一个动物在多个点之间跳跃,点它没跳过的点」= decode → detect → track → select_unvisited。
// Point 一个坐标点
type Point struct {
X int `json:"x"`
Y int `json:"y"`
}
// CandidatePoint 候选点及其是否被经过
type CandidatePoint struct {
X int `json:"x"`
Y int `json:"y"`
Visited bool `json:"visited"`
FirstFrame int `json:"first_frame"` // 首次被经过的帧号,-1 表示没经过
Hits int `json:"hits"` // 被经过的帧数
}
// FrameObjects 单帧检测结果
type FrameObjects struct {
Frame int `json:"frame"`
Objects []ObjectHit `json:"objects"`
}
// Track 一条轨迹
type Track struct {
Class string `json:"class"`
Path []Point `json:"path"`
Frames []int `json:"frames"`
}
// AnimResult 动图任务的返回
type AnimResult struct {
Frames int `json:"frames"`
UsedFrames int `json:"used_frames"`
PerFrame []FrameObjects `json:"per_frame"`
Tracks []Track `json:"tracks"`
Candidates []CandidatePoint `json:"candidates"`
Click []Point `json:"click"`
Model string `json:"model"`
UnvisitedCnt int `json:"unvisited_count"`
}
// decodeFrames 把输入拆成多帧。GIF/APNG 走 image/gif,普通图当单帧。
// 视频(mp4/webm)需要 ffmpeg,这里不处理——调用方可以先自己抽帧后按多图送进来。
func decodeFrames(raw []byte) ([]image.Image, error) {
if g, err := gif.DecodeAll(bytes.NewReader(raw)); err == nil && len(g.Image) > 1 {
out := make([]image.Image, 0, len(g.Image))
for _, fr := range g.Image {
out = append(out, fr)
}
return out, nil
}
img, _, err := image.Decode(bytes.NewReader(raw))
if err != nil {
return nil, fmt.Errorf("既不是多帧动图也不是可解码图片: %v", err)
}
return []image.Image{img}, nil
}
// DetectFrames 每帧跑一次目标检测(step 控制抽帧间隔,动图帧多时用它降耗时)
func (h *Handler) DetectFrames(frames []image.Image, step int) ([]FrameObjects, error) {
if step <= 0 {
step = 1
}
if _, ok := onnx.GetSession("detection_object"); !ok {
return nil, fmt.Errorf("目标检测模型未加载(models/Detection_Object.onnx)")
}
out := make([]FrameObjects, 0, len(frames)/step+1)
for i := 0; i < len(frames); i += step {
dets, err := h.detectObjects(frames[i])
if err != nil {
return nil, err
}
fo := FrameObjects{Frame: i, Objects: make([]ObjectHit, 0, len(dets))}
for _, d := range dets {
fo.Objects = append(fo.Objects, ObjectHit{
Class: d.ClassName,
ClassID: d.ClassID,
Confidence: math.Round(d.Confidence*10000) / 10000,
Box: []int{int(d.X1), int(d.Y1), int(d.X2), int(d.Y2)},
})
}
out = append(out, fo)
}
return out, nil
}
// buildTracks 按类别 + IoU 把逐帧检测串成轨迹(贪心匹配,够用且无状态)
func buildTracks(perFrame []FrameObjects) []Track {
type live struct {
class string
box []int
path []Point
frames []int
}
var finished []Track
var actives []*live
for _, fo := range perFrame {
used := make([]bool, len(actives))
for _, ob := range fo.Objects {
bestIdx, bestIou := -1, 0.0
for i, a := range actives {
if used[i] || a.class != ob.Class {
continue
}
if v := iouBox(a.box, ob.Box); v > bestIou {
bestIou, bestIdx = v, i
}
}
center := Point{X: (ob.Box[0] + ob.Box[2]) / 2, Y: (ob.Box[1] + ob.Box[3]) / 2}
if bestIdx >= 0 && bestIou >= 0.2 {
a := actives[bestIdx]
a.box = ob.Box
a.path = append(a.path, center)
a.frames = append(a.frames, fo.Frame)
used[bestIdx] = true
} else {
actives = append(actives, &live{
class: ob.Class, box: ob.Box,
path: []Point{center}, frames: []int{fo.Frame},
})
used = append(used, true)
}
}
// 连续 N 帧没匹配上的轨迹归档
keep := actives[:0]
for i, a := range actives {
if i < len(used) && used[i] {
keep = append(keep, a)
} else {
finished = append(finished, Track{Class: a.class, Path: a.path, Frames: a.frames})
}
}
actives = keep
}
for _, a := range actives {
finished = append(finished, Track{Class: a.class, Path: a.path, Frames: a.frames})
}
sort.Slice(finished, func(i, j int) bool { return len(finished[i].Path) > len(finished[j].Path) })
return finished
}
func iouBox(a, b []int) float64 {
if len(a) < 4 || len(b) < 4 {
return 0
}
x1 := math.Max(float64(a[0]), float64(b[0]))
y1 := math.Max(float64(a[1]), float64(b[1]))
x2 := math.Min(float64(a[2]), float64(b[2]))
y2 := math.Min(float64(a[3]), float64(b[3]))
if x2 <= x1 || y2 <= y1 {
return 0
}
inter := (x2 - x1) * (y2 - y1)
areaA := float64((a[2] - a[0]) * (a[3] - a[1]))
areaB := float64((b[2] - b[0]) * (b[3] - b[1]))
if areaA+areaB-inter <= 0 {
return 0
}
return inter / (areaA + areaB - inter)
}
// markVisited 用轨迹去筛候选点:轨迹经过半径 radius 内的点算「已跳过」
func markVisited(candidates []Point, tracks []Track, radius float64, classFilter string) []CandidatePoint {
out := make([]CandidatePoint, len(candidates))
for i, c := range candidates {
out[i] = CandidatePoint{X: c.X, Y: c.Y, FirstFrame: -1}
}
r2 := radius * radius
for _, tr := range tracks {
if classFilter != "" && tr.Class != classFilter {
continue
}
for k, p := range tr.Path {
for i := range out {
dx := float64(p.X - out[i].X)
dy := float64(p.Y - out[i].Y)
if dx*dx+dy*dy <= r2 {
out[i].Visited = true
out[i].Hits++
if out[i].FirstFrame < 0 && k < len(tr.Frames) {
out[i].FirstFrame = tr.Frames[k]
}
}
}
}
}
return out
}
// DetectFramesRaw 拆帧 + 逐帧检测(给 /api/frames/detect 用,也方便调试自己的流水线)
func (h *Handler) DetectFramesRaw(raw []byte, step int) (*AnimResult, error) {
frames, err := decodeFrames(raw)
if err != nil {
return nil, err
}
perFrame, err := h.DetectFrames(frames, step)
if err != nil {
return nil, err
}
return &AnimResult{
Frames: len(frames),
UsedFrames: len(perFrame),
PerFrame: perFrame,
Model: "yolox-s-coco",
}, nil
}
// AnimalJump 动图点选:一个目标在多帧之间跳动,返回「没被经过的点」
//
// raw 动图原始字节(GIF/APNG)或单图
// candidates 页面上的候选点(可以先用 /api/detection/object 找圆点再传进来)
// radius 判定「经过」的半径,默认 40px
// classFilter 只统计某个类别的轨迹(如 "sports ball"、"bird"),空表示全部
func (h *Handler) AnimalJump(raw []byte, candidates []Point, radius float64, classFilter string, step int) (*AnimResult, error) {
frames, err := decodeFrames(raw)
if err != nil {
return nil, err
}
if radius <= 0 {
radius = 40
}
perFrame, err := h.DetectFrames(frames, step)
if err != nil {
return nil, err
}
tracks := buildTracks(perFrame)
marks := markVisited(candidates, tracks, radius, classFilter)
res := &AnimResult{
Frames: len(frames),
UsedFrames: len(perFrame),
PerFrame: perFrame,
Tracks: tracks,
Candidates: marks,
Model: "yolox-s-coco + iou-track",
}
for _, m := range marks {
if !m.Visited {
res.Click = append(res.Click, Point{X: m.X, Y: m.Y})
res.UnvisitedCnt++
}
}
return res, nil
}
+26
View File
@@ -181,6 +181,32 @@ var capabilityCatalog = []CapabilityDef{
},
Sample: "图标点选的候选图标品类判断、单物体识别",
},
{
Key: "animal_jump", Name: "动图点选(未经过的点)", Group: "点选", Endpoint: "/api/task/run",
Desc: "拆帧 → 每帧检测 → 串轨迹 → 筛候选点,返回「没被经过的点」(type=animal_jump)",
Inputs: []string{"gif_base64:动图(GIF/APNG)或单图", "candidates:[{x,y}] 候选点坐标", "可选 radius(默认40) / class_filter(只统计某个类别的轨迹) / step(抽帧间隔)"},
Output: "{ \"result\": { \"candidates\": [{\"x\":80,\"y\":80,\"visited\":true,\"hits\":3}], \"click\": [{\"x\":80,\"y\":250}], \"unvisited_count\": 1, \"tracks\": [...] } }",
ModelKey: "detection_object", Cost: 3,
Tips: []string{
"轨迹是 IoU 贪心匹配串起来的,物体跳动间隔太大就配不上(可调 radius)",
"class_filter 填 COCO 类名(bird / sports ball / cat)可过滤掉背景误检",
"step 抽帧能大幅降耗时:30 帧动图用 step=2 只跑 15 次检测",
"候选点可以先自己用 /api/detection/object 找圆点,再喂进来",
},
Sample: "「点它没跳过的那些点」类动图验证码",
},
{
Key: "frames_detect", Name: "逐帧检测", Group: "点选", Endpoint: "/api/frames/detect",
Desc: "把动图拆成帧、每帧跑目标检测,返回每帧的框;给自定义时序流水线复用",
Inputs: []string{"gif_base64:动图或单图", "可选 step:抽帧间隔"},
Output: "{ \"result\": { \"frames\": 12, \"used_frames\": 6, \"per_frame\": [{\"frame\":0,\"objects\":[...]}] } }",
ModelKey: "detection_object", Cost: 2,
Tips: []string{
"视频(mp4/webm)本接口不处理,需要 ffmpeg 先抽帧再按多图送",
"想自己写后处理(比如算位移矢量、判是否越线)就用它取数据",
},
Sample: "滑块轨迹分析、动图行为识别",
},
{
Key: "click_icon_order", Name: "图标点选顺序", Group: "点选", Endpoint: "/api/detection/icon/order",
Desc: "按提示图标的顺序,给出大图中对应的点击坐标序列",
+5 -1
View File
@@ -49,7 +49,11 @@ func (h *CaptchaHandler) RegisterRoutes(r *gin.RouterGroup, authRequired bool) {
auth.POST("/detection/text", h.DetectionText)
auth.POST("/detection/object", h.DetectionObject) // 目标检测(YOLOX COCO 80 类)
auth.POST("/detection/object/detail", h.DetectionObjectDetail) // 检测 + 逐框细分类
auth.POST("/classify/object", h.ClassifyObject) // 整图分类(ImageNet 1000 类)
// 多帧(动图)任务:统一入口 + 类型列表 + 逐帧检测
auth.GET("/task/types", h.TaskTypes)
auth.POST("/task/run", h.RunTask)
auth.POST("/frames/detect", h.DetectFrames)
auth.POST("/classify/object", h.ClassifyObject) // 整图分类(ImageNet 1000 类)
auth.POST("/detection/icon/order", h.DetectionIconOrder)
auth.POST("/detection/text/order", h.DetectionTextOrder)
+120
View File
@@ -0,0 +1,120 @@
package handler
import (
"encoding/base64"
"net/http"
"strings"
"anticaptcha/internal/captcha"
"anticaptcha/internal/model"
"github.com/gin-gonic/gin"
)
// 任务类型注册表:这是「新验证码类型」的扩展点。
// 加一种动图/多帧类验证码,只需要在 captcha 层加一个方法,再往这里注册一条,
// 前端和其他调用方都通过同一个 /api/task/run 入口调用,不用再加路由。
var taskTypes = map[string]string{
"animal_jump": "动图点选:目标在多帧之间跳动,返回没被经过的候选点",
}
type taskRequest struct {
Type string `json:"type"`
GIFBase64 string `json:"gif_base64"`
ImgBase64 string `json:"img_base64"`
Candidates []struct {
X int `json:"x"`
Y int `json:"y"`
} `json:"candidates"`
Radius float64 `json:"radius"`
ClassFilter string `json:"class_filter"`
Step int `json:"step"`
}
// TaskTypes GET /api/task/types —— 列出当前支持的多帧任务类型
func (h *CaptchaHandler) TaskTypes(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"types": taskTypes})
}
// RunTask POST /api/task/run —— 多帧(动图)任务的统一入口
func (h *CaptchaHandler) RunTask(c *gin.Context) {
var req taskRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "参数解析失败: " + err.Error()})
return
}
raw := req.GIFBase64
if raw == "" {
raw = req.ImgBase64
}
if raw == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少 gif_base64(也接受 img_base64)"})
return
}
data, err := decodeAnyBase64(raw)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "base64 解析失败: " + err.Error()})
return
}
switch req.Type {
case "animal_jump":
cands := make([]captcha.Point, 0, len(req.Candidates))
for _, p := range req.Candidates {
cands = append(cands, captcha.Point{X: p.X, Y: p.Y})
}
res, err := h.handler.AnimalJump(data, cands, req.Radius, req.ClassFilter, req.Step)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, model.CaptchaResult{Result: res})
default:
c.JSON(http.StatusBadRequest, gin.H{
"error": "未知任务类型: " + req.Type,
"types": taskTypes,
})
}
}
// DetectFrames POST /api/frames/detect —— 只做逐帧检测,供自定义流水线复用
func (h *CaptchaHandler) DetectFrames(c *gin.Context) {
var req taskRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "参数解析失败: " + err.Error()})
return
}
raw := req.GIFBase64
if raw == "" {
raw = req.ImgBase64
}
if raw == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少 gif_base64(也接受 img_base64)"})
return
}
data, err := decodeAnyBase64(raw)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "base64 解析失败: " + err.Error()})
return
}
res, err := h.handler.DetectFramesRaw(data, req.Step)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, model.CaptchaResult{Result: gin.H{
"frames": res.Frames,
"used_frames": res.UsedFrames,
"per_frame": res.PerFrame,
}})
}
func decodeAnyBase64(s string) ([]byte, error) {
if i := strings.Index(s, ","); i >= 0 {
s = s[i+1:]
}
if d, err := base64.StdEncoding.DecodeString(s); err == nil {
return d, nil
}
return base64.RawStdEncoding.DecodeString(s)
}
+50 -6
View File
@@ -25,6 +25,8 @@ const FIELDS: Record<string, FieldSpec> = {
detect_text: { a: 'img_base64', aLabel: '大图' },
detect_object: { a: 'img_base64', aLabel: '图片(含物体)' },
detect_object_detail: { a: 'img_base64', aLabel: '图片(含物体)' },
animal_jump: { a: 'gif_base64', aLabel: '动图(GIF)' },
frames_detect: { a: 'gif_base64', aLabel: '动图(GIF)' },
classify_object: { a: 'img_base64', aLabel: '图片 / 单个物品' },
slider_match: { a: 'target_base64', b: 'background_base64', aLabel: '缺口小图', bLabel: '背景大图' },
slider_comparison: { a: 'target_base64', b: 'background_base64', aLabel: '缺口图', bLabel: '完整背景' },
@@ -63,6 +65,9 @@ export default function PlaygroundPage({ token, role, onLogout }: Props) {
const [imgB, setImgB] = useState('')
const [speedRatio, setSpeedRatio] = useState('1')
const [checkPixel, setCheckPixel] = useState('10')
const [candidates, setCandidates] = useState('150,150\n355,150\n200,220\n500,400')
const [radius, setRadius] = useState('40')
const [classFilter, setClassFilter] = useState('')
const [busy, setBusy] = useState(false)
const [result, setResult] = useState<unknown>(null)
const [err, setErr] = useState('')
@@ -169,16 +174,32 @@ export default function PlaygroundPage({ token, role, onLogout }: Props) {
return
}
const body: Record<string, unknown> = {}
body[spec.a] = imgA
if (spec.b) body[spec.b] = imgB
if (capKey === 'double_rotate') {
body.speed_ratio = Number(speedRatio) || 1
body.check_pixel = Number(checkPixel) || 10
if (capKey === 'animal_jump' || capKey === 'frames_detect') {
body.gif_base64 = imgA
if (capKey === 'animal_jump') {
body.type = 'animal_jump'
body.candidates = candidates
.split(/[\n;]+/)
.map((line) => line.split(/[,,\s]+/).filter(Boolean))
.filter((p) => p.length >= 2)
.map((p) => ({ x: Number(p[0]), y: Number(p[1]) }))
body.radius = Number(radius) || 40
if (classFilter.trim()) body.class_filter = classFilter.trim()
}
body.step = 1
} else {
body[spec.a] = imgA
if (spec.b) body[spec.b] = imgB
if (capKey === 'double_rotate') {
body.speed_ratio = Number(speedRatio) || 1
body.check_pixel = Number(checkPixel) || 10
}
}
setBusy(true)
const t0 = performance.now()
try {
const res = await api<unknown>(cap.endpoint, { method: 'POST', body: JSON.stringify(body) })
const endpoint = capKey === 'animal_jump' ? '/api/task/run' : cap.endpoint
const res = await api<unknown>(endpoint, { method: 'POST', body: JSON.stringify(body) })
setMs(Math.round(performance.now() - t0))
setResult(res)
} catch (e) {
@@ -259,6 +280,29 @@ export default function PlaygroundPage({ token, role, onLogout }: Props) {
{imgB ? `已选「${spec.bLabel}」,点击更换` : `点击选择「${spec.bLabel}」`}
</div>
)}
{(capKey === 'animal_jump' || capKey === 'frames_detect') && (
<div className="ac-field">
<span>candidates(每行一个 x,y)</span>
<textarea
className="ac-textarea"
style={{ minHeight: 76 }}
value={candidates}
onChange={(e) => setCandidates(e.target.value)}
/>
</div>
)}
{capKey === 'animal_jump' && (
<div className="ac-row">
<div className="ac-field" style={{ flex: 1 }}>
<span>radius(判定经过的半径)</span>
<input className="ac-input" value={radius} onChange={(e) => setRadius(e.target.value)} />
</div>
<div className="ac-field" style={{ flex: 1 }}>
<span>class_filter(如 bird)</span>
<input className="ac-input" value={classFilter} onChange={(e) => setClassFilter(e.target.value)} />
</div>
</div>
)}
{capKey === 'double_rotate' && (
<div className="ac-row">
<div className="ac-field" style={{ flex: 1 }}>