feat(ocr): 新增本地 OCR sidecar

This commit is contained in:
yml
2026-11-17 17:26:59 +08:00
parent a6eb6c95b9
commit 90addb80d5
166 changed files with 72858 additions and 34 deletions
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"hash/crc32"
@@ -238,3 +239,77 @@ func TestCollectPaddleOCRJSONLTextSupportsPPOCRv6(t *testing.T) {
t.Fatalf("candidates = %v, want 火爆出租-778群 as first candidate", candidates)
}
}
func TestParseLocalOCRGroupNamesSupportsShortNumericAndChineseNames(t *testing.T) {
cases := []struct {
name string
title string
}{
{name: "纯数字", title: "111"},
{name: "中英数字", title: "小语对接h870"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
lines := []localOCRLine{
{Text: "C", Score: 0.76, Y1: 73, Y2: 73, Y3: 87, Y4: 87},
{Text: tc.title, Score: 0.95, Y1: 117, Y2: 117, Y3: 134, Y4: 134},
{Text: "使用微信或企业微信扫码加入", Score: 0.96, Y1: 163, Y2: 163, Y3: 177, Y4: 177},
{Text: "该二维码7天内(11月24日前)有效", Score: 0.99, Y1: 487, Y2: 487, Y3: 498, Y4: 498},
}
rawText, candidates := parseLocalOCRGroupNames(lines)
if len(candidates) == 0 || candidates[0] != tc.title {
t.Fatalf("candidates = %v, want %q; raw=%q", candidates, tc.title, rawText)
}
})
}
}
func TestRecognizeQrCodeGroupNameUsesLocalOCRService(t *testing.T) {
var gotContentType string
var gotPPMHeader string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotContentType = r.Header.Get("Content-Type")
body := new(bytes.Buffer)
_, _ = body.ReadFrom(r.Body)
if len(body.Bytes()) >= 2 {
gotPPMHeader = string(body.Bytes()[:2])
}
_ = json.NewEncoder(w).Encode(localOCRResponse{
OK: true,
Result: []localOCRLine{
{Text: "111", Score: 0.999996, Y1: 117, Y2: 117, Y3: 134, Y4: 134},
{Text: "使用微信或企业微信扫码加入", Score: 0.95, Y1: 163, Y2: 163, Y3: 177, Y4: 177},
},
})
}))
defer server.Close()
repo := NewRepository(nil, nil, nil,
WithOCRServiceURL(server.URL),
withOCRHTTPClient(server.Client()),
withOCRGate(newOCRRequestGate(1, 0)),
withOCRSleep(func(context.Context, time.Duration) error { return nil }),
)
imageData := testOCRPNG(t)
result, err := repo.RecognizeQrCodeGroupName(t.Context(), "group.png", "image/png", bytes.NewReader(imageData))
if err != nil {
t.Fatal(err)
}
if result.GroupName != "111" || !strings.Contains(result.RawText, "使用微信") {
t.Fatalf("result = %+v", result)
}
if gotContentType != "image/x-portable-pixmap" || gotPPMHeader != "P6" {
t.Fatalf("content-type=%q ppm-header=%q", gotContentType, gotPPMHeader)
}
}
func testOCRPNG(t *testing.T) []byte {
t.Helper()
source := image.NewRGBA(image.Rect(0, 0, 64, 96))
draw.Draw(source, source.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
var buffer bytes.Buffer
if err := png.Encode(&buffer, source); err != nil {
t.Fatal(err)
}
return buffer.Bytes()
}