chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

@@ -0,0 +1,151 @@
// Package openaichataudio implements speech recognition served through the
// chat completions endpoint: one user message whose only content part is
// {"type": "input_audio", "input_audio": {"data": "data:<mime>;base64,..."}},
// answered by an assistant message whose content is the transcript.
//
// Only dedicated recognition models are addressed this way — Alibaba's
// qwen3-asr-flash and Xiaomi's mimo-v2.5-asr — so no instruction is sent: the
// model transcribes whatever it is given. A general audio-capable chat model
// would need a prompt and would answer about the audio rather than transcribe
// it, which is why this is its own protocol and not a chat request.
//
// https://help.aliyun.com/zh/model-studio/qwen-asr-api-reference
// https://mimo.mi.com/docs/en-US/quick-start/usage-guide/audio/Speech-Recognition
package openaichataudio
import (
"context"
"encoding/base64"
"fmt"
"path/filepath"
"strings"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.TranscriptionsSettings
Retry api.RetryPolicy
}
// Client talks chat-served speech recognition to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
const defaultPath = "/chat/completions"
func (c *Client) url() string {
if c.cfg.Endpoint.URL != "" {
return c.cfg.Endpoint.Resolve("")
}
path := defaultPath
if strings.HasSuffix(strings.TrimRight(c.cfg.Endpoint.BaseURL, "/"), path) {
path = ""
}
return c.cfg.Endpoint.Resolve(path)
}
// audioTypes maps the file extension onto the media type of the data URI.
// The two references show audio/wav and audio/mpeg; the rest are the
// registered types for the containers Alibaba lists. A fixed table rather
// than mime.TypeByExtension, which reads the host's tables and would make the
// request depend on the machine it runs on.
var audioTypes = map[string]string{
".wav": "audio/wav",
".mp3": "audio/mpeg",
".m4a": "audio/mp4",
".mp4": "audio/mp4",
".aac": "audio/aac",
".flac": "audio/flac",
".ogg": "audio/ogg",
".opus": "audio/opus",
".webm": "audio/webm",
".amr": "audio/amr",
}
// DataURI is the input_audio payload for one file. Both references show an
// audio media type in the URI, so a file whose extension names no audio
// container is refused rather than labelled application/octet-stream.
func DataURI(audio []byte, fileName string) (string, error) {
mediaType, ok := audioTypes[strings.ToLower(filepath.Ext(fileName))]
if !ok {
return "", fmt.Errorf("cannot tell the audio format of %q from its extension", fileName)
}
return "data:" + mediaType + ";base64," + base64.StdEncoding.EncodeToString(audio), nil
}
// BuildRequestBody is the golden-test entry point.
func (c *Client) BuildRequestBody(req api.TranscriptionRequest) (map[string]any, error) {
uri, err := DataURI(req.Audio, req.FileName)
if err != nil {
return nil, err
}
// The ceiling is on the whole string as sent — "encoded string size must
// not exceed 10 MB" — so the data: prefix counts too.
if limit := c.cfg.Settings.MaxEncodedBytes; limit > 0 && len(uri) > limit {
return nil, fmt.Errorf(
"the audio is %.1f MB and %.1f MB once base64-encoded; this model accepts at most %.1f MB encoded",
float64(len(req.Audio))/(1<<20), float64(len(uri))/(1<<20), float64(limit)/(1<<20))
}
body := map[string]any{
"model": c.cfg.Endpoint.Model,
"messages": []any{map[string]any{
"role": "user",
"content": []any{map[string]any{
"type": "input_audio",
"input_audio": map[string]any{"data": uri},
}},
}},
}
if req.Language != "" && c.cfg.Settings.LanguageParam == api.LanguageASROptions {
body["asr_options"] = map[string]any{"language": req.Language}
}
return body, nil
}
type response struct {
Choices []struct {
Message struct {
// Content is a pointer for the same reason as the multipart
// protocol's text: an absent transcript is an error, an empty one
// is silence.
Content *string `json:"content"`
} `json:"message"`
} `json:"choices"`
// Usage.Seconds is the audio length, which Alibaba reports.
Usage struct {
Seconds float64 `json:"seconds"`
} `json:"usage"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
// Transcribe sends one audio file.
func (c *Client) Transcribe(ctx context.Context, req api.TranscriptionRequest) (*api.Transcription, error) {
body, err := c.BuildRequestBody(req)
if err != nil {
return nil, err
}
var decoded response
err = c.cfg.Endpoint.PostJSONWithRetry(ctx, c.url(), body, &decoded, c.cfg.Retry, "transcription")
if err != nil {
return nil, err
}
if decoded.Error != nil && decoded.Error.Message != "" {
return nil, fmt.Errorf("transcription API error: %s", decoded.Error.Message)
}
if len(decoded.Choices) == 0 || decoded.Choices[0].Message.Content == nil {
return nil, fmt.Errorf("transcription reply carries no message content")
}
return &api.Transcription{
Text: strings.TrimSpace(*decoded.Choices[0].Message.Content),
Duration: decoded.Usage.Seconds,
}, nil
}
@@ -0,0 +1,161 @@
package openaichataudio
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// qwenASRResponse is the non-streaming response example from Alibaba's
// Qwen-ASR reference, copied from the page:
// https://help.aliyun.com/zh/model-studio/qwen-asr-api-reference
const qwenASRResponse = `{
"choices": [{
"finish_reason": "stop",
"index": 0,
"message": {
"annotations": [{"emotion": "neutral", "language": "zh", "type": "audio_info"}],
"content": "欢迎使用阿里云。",
"role": "assistant"
}
}],
"created": 1767683986,
"id": "chatcmpl-487abe5f-d4f2-9363-a877-xxxxxxx",
"model": "qwen3-asr-flash",
"object": "chat.completion",
"usage": {"completion_tokens": 12, "prompt_tokens": 42, "total_tokens": 54}
}`
// withSeconds is a reply carrying the usage.seconds that the reference's
// schema documents ("音频时长(秒)") but its example omits.
const withSeconds = `{"choices":[{"message":{"role":"assistant","content":"x"}}],"usage":{"seconds":3}}`
func newClient(url, model string) *Client {
return newClientWith(url, model, api.TranscriptionsSettings{})
}
func newClientWith(url, model string, settings api.TranscriptionsSettings) *Client {
return New(Config{
Endpoint: api.Endpoint{BaseURL: url, Model: model, Auth: api.BearerAuth("k")},
Settings: settings,
})
}
// The request is the one both references show: a single user message whose
// only part is the audio as a data URI, no instruction, no stream flag.
func TestRequestBodyMatchesTheReferences(t *testing.T) {
body, err := newClient("https://example.invalid/v1", "qwen3-asr-flash").
BuildRequestBody(api.TranscriptionRequest{Audio: []byte("ID3"), FileName: "clip.MP3"})
require.NoError(t, err)
assert.Equal(t, map[string]any{
"model": "qwen3-asr-flash",
"messages": []any{map[string]any{
"role": "user",
"content": []any{map[string]any{
"type": "input_audio",
"input_audio": map[string]any{"data": "data:audio/mpeg;base64,SUQz"},
}},
}},
}, body)
}
func TestDataURIMediaTypeFollowsTheExtension(t *testing.T) {
uri, err := DataURI([]byte("RIFF"), "a.wav")
require.NoError(t, err)
assert.Equal(t, "data:audio/wav;base64,UklGRg==", uri)
// No audio type can be named for it, and the references show one.
_, err = DataURI([]byte("x"), "noext")
assert.Error(t, err)
}
// Both references cap the string as sent, so the data: prefix counts. A file
// sized to exactly the encoded budget without the prefix goes over it.
func TestEncodedCeilingCountsTheWholeDataURI(t *testing.T) {
const limit = 1024
c := newClientWith("https://example.invalid", "m", api.TranscriptionsSettings{MaxEncodedBytes: limit})
audio := make([]byte, limit*3/4) // base64 of this is exactly limit bytes
_, err := c.BuildRequestBody(api.TranscriptionRequest{Audio: audio, FileName: "a.wav"})
require.Error(t, err)
prefix := len("data:audio/wav;base64,")
fits := make([]byte, (limit-prefix)/4*3)
_, err = c.BuildRequestBody(api.TranscriptionRequest{Audio: fits, FileName: "a.wav"})
require.NoError(t, err)
}
func TestLanguageGoesInASROptionsWhereDeclared(t *testing.T) {
req := api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav", Language: "zh"}
body, err := newClient("https://example.invalid", "m").BuildRequestBody(req)
require.NoError(t, err)
assert.NotContains(t, body, "asr_options", "undeclared, so not sent")
body, err = newClientWith("https://example.invalid", "m",
api.TranscriptionsSettings{LanguageParam: api.LanguageASROptions}).BuildRequestBody(req)
require.NoError(t, err)
assert.Equal(t, map[string]any{"language": "zh"}, body["asr_options"])
}
func TestDecodesTheDocumentedResponse(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var path string
var sent map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
_ = json.NewDecoder(r.Body).Decode(&sent)
_, _ = w.Write([]byte(qwenASRResponse))
}))
defer server.Close()
out, err := newClient(server.URL+"/compatible-mode/v1", "qwen3-asr-flash").
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("RIFF"), FileName: "a.wav"})
require.NoError(t, err)
assert.Equal(t, "/compatible-mode/v1/chat/completions", path)
assert.Equal(t, &api.Transcription{Text: "欢迎使用阿里云。"}, out)
}
// A reply with no assistant content is not silence.
func TestReplyWithoutContentIsAnError(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"choices":[]}`))
}))
defer server.Close()
_, err := newClient(server.URL, "m").
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav"})
assert.Error(t, err)
}
func TestDurationFromUsageSeconds(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(withSeconds))
}))
defer server.Close()
out, err := newClient(server.URL, "m").
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav"})
require.NoError(t, err)
assert.Equal(t, float64(3), out.Duration)
}
func TestEmptyContentIsSilence(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":""}}]}`))
}))
defer server.Close()
out, err := newClient(server.URL, "m").
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav"})
require.NoError(t, err)
assert.Equal(t, "", out.Text)
}