mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-29 11:36:36 +08:00
8824638efb
Backend
- service/transcoder.go: encoder selector (software / nvenc / qsv /
vaapi) with proper hwaccel + scale_* filters per encoder; configurable
bitrate/preset/height/segment-seconds via transcoder.* config; new
Active() snapshot + ActiveJob struct for the Tasks panel; unit-tested
via buildFFmpegArgs(...).
- service/thetvdb.go: TheTVDB v4 provider — login() caches the JWT for
24h, SearchSeries() returns Match struct.
- service/fanart.go: Fanart.tv provider — high-res movie artwork keyed
by TMDb id; used to upgrade poster/backdrop after a successful match.
- service/scraper.go: provider chain reworked — anime → Bangumi, tv →
TheTVDB, default → TMDb, with optional Fanart upgrade post-match.
- service/discover.go: TMDb /trending/movie/day + /movie/popular for
the Discover rail.
- service/ai.go: OpenAI-compatible client. SmartSearch() turns a free-
form query into a structured SearchIntent JSON; Recommend() emits a
short list of titles given the user's history. Disabled when
ai.api_key is empty.
- service/nfo.go: per-movie .nfo writer (Kodi/Jellyfin schema) +
library-scope batch exporter.
- service/media.go: SoftDelete / Restore / Purge / ListRecycleBin
helpers backed by gorm Unscoped().
- service/service.go: container wires Fanart, TheTVDB, Discover, AI,
NFO; everything still tears down cleanly via Close().
- config: new transcoder.* section (encoder, preset, video_bitrate,
max_rate, buf_size, max_height, segment_seconds) with sensible
defaults.
Handlers / routes
- new files: discover.go, recycle.go, nfo.go, ai.go, tasks.go.
- registers GET /tasks, /discover/{trending,popular},
/ai/{status,search,recommend}; admin-only GET /recycle and
DELETE/POST /media/:id (soft delete / restore / purge); admin-only
POST /media/:id/nfo and /libraries/:id/nfo.
Frontend
- new pages: DiscoverPage, TasksPage, RecycleBinPage; SearchPage gains
an optional AI smart-search toggle that calls /api/ai/search.
- MediaDetailPage gains admin actions for 导出 NFO and 移至回收站.
- new api/ helpers: ai.ts, discover.ts, recycle.ts, tasks.ts.
- App.tsx routes /discover, /tasks, /recycle (last two admin-only).
- Layout sidebar groups now include Discover + Tasks + Recycle Bin.
Docker / config
- Dockerfile: adds intel-media-driver / libva-utils / mesa-va-gallium
so QSV + VAAPI work out of the box on Intel iGPUs.
- docker-compose.yml: documents devices + group_add + nvidia runtime
overrides for hardware transcoding.
Verified: go build, go vet, go test (incl. new TestBuildFFmpegArgs across
software / nvenc / qsv / vaapi encoder profiles); tsc -b && vite build
emits 22 route chunks plus the deferred hls chunk; main bundle 248 KB /
83 KB gzipped.
167 lines
5.1 KiB
Go
167 lines
5.1 KiB
Go
// Package service — AI integration (OpenAI-compatible chat completions).
|
|
//
|
|
// AIService is a thin wrapper around any OpenAI-compatible REST endpoint
|
|
// (OpenAI, DeepSeek, Qwen, Ollama, …). Today we expose two operations:
|
|
//
|
|
// - SmartSearch: interpret a free-form Chinese / English query and
|
|
// return a normalised JSON intent the React UI can
|
|
// translate into filter params.
|
|
// - Recommend: given a list of recently-watched titles, generate
|
|
// a short list of "you might like…" recommendations.
|
|
//
|
|
// The service is disabled (every method returns nil) when ai.enabled is
|
|
// false or ai.api_key is empty.
|
|
package service
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"github.com/ShukeBta/MediaStationGo/internal/config"
|
|
)
|
|
|
|
// AIService talks to an OpenAI-compatible chat-completions endpoint.
|
|
type AIService struct {
|
|
cfg *config.Config
|
|
log *zap.Logger
|
|
client *http.Client
|
|
}
|
|
|
|
// NewAIService is the constructor.
|
|
func NewAIService(cfg *config.Config, log *zap.Logger) *AIService {
|
|
timeout := time.Duration(cfg.AI.Timeout) * time.Second
|
|
if timeout <= 0 {
|
|
timeout = 30 * time.Second
|
|
}
|
|
return &AIService{
|
|
cfg: cfg,
|
|
log: log,
|
|
client: &http.Client{Timeout: timeout},
|
|
}
|
|
}
|
|
|
|
// Enabled reports whether the AI integration is configured.
|
|
func (a *AIService) Enabled() bool {
|
|
return a.cfg.AI.Enabled && strings.TrimSpace(a.cfg.AI.APIKey) != ""
|
|
}
|
|
|
|
// SearchIntent is the structured output the smart search endpoint returns.
|
|
type SearchIntent struct {
|
|
Query string `json:"query"`
|
|
Year int `json:"year,omitempty"`
|
|
Genre string `json:"genre,omitempty"`
|
|
Type string `json:"type,omitempty"` // movie / tv / anime / music
|
|
Sort string `json:"sort,omitempty"` // recent / rating / random
|
|
Language string `json:"language,omitempty"`
|
|
}
|
|
|
|
// SmartSearch turns a natural-language query into a structured intent.
|
|
// Returns a best-effort intent on parse failure (raw query passes through).
|
|
func (a *AIService) SmartSearch(ctx context.Context, raw string) (*SearchIntent, error) {
|
|
if !a.Enabled() {
|
|
return &SearchIntent{Query: raw}, nil
|
|
}
|
|
const sys = "You are a media-library search assistant. Read the user's query and " +
|
|
"output a JSON object with the keys: query (string), year (int, optional), " +
|
|
"genre (string, optional), type (movie|tv|anime|music, optional), sort " +
|
|
"(recent|rating|random, optional), language (zh|en, optional). Respond with " +
|
|
"JSON only, no commentary."
|
|
out, err := a.complete(ctx, sys, raw)
|
|
if err != nil {
|
|
return &SearchIntent{Query: raw}, err
|
|
}
|
|
var intent SearchIntent
|
|
if err := json.Unmarshal([]byte(out), &intent); err != nil {
|
|
// Fallback: tolerate non-JSON output by treating the raw text as
|
|
// the cleaned query.
|
|
intent.Query = strings.TrimSpace(out)
|
|
}
|
|
if intent.Query == "" {
|
|
intent.Query = raw
|
|
}
|
|
return &intent, nil
|
|
}
|
|
|
|
// Recommend builds a short comma-separated list of titles given the user's
|
|
// history. The first call is intentionally best-effort: a future iteration
|
|
// may chain media DB lookups onto each suggestion.
|
|
func (a *AIService) Recommend(ctx context.Context, history []string, max int) ([]string, error) {
|
|
if !a.Enabled() || len(history) == 0 {
|
|
return nil, nil
|
|
}
|
|
if max <= 0 || max > 20 {
|
|
max = 8
|
|
}
|
|
sys := fmt.Sprintf("You are a film / TV recommendation assistant. Reply with %d "+
|
|
"comma-separated titles only, no commentary, in the same language as the input.", max)
|
|
usr := "I recently watched: " + strings.Join(history, "; ")
|
|
out, err := a.complete(ctx, sys, usr)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
parts := strings.Split(out, ",")
|
|
titles := make([]string, 0, len(parts))
|
|
for _, p := range parts {
|
|
p = strings.TrimSpace(p)
|
|
p = strings.Trim(p, "\"'`")
|
|
if p != "" {
|
|
titles = append(titles, p)
|
|
}
|
|
}
|
|
return titles, nil
|
|
}
|
|
|
|
// complete is the shared helper — POST /v1/chat/completions.
|
|
func (a *AIService) complete(ctx context.Context, system, user string) (string, error) {
|
|
payload := map[string]any{
|
|
"model": a.cfg.AI.Model,
|
|
"temperature": 0.2,
|
|
"messages": []map[string]string{
|
|
{"role": "system", "content": system},
|
|
{"role": "user", "content": user},
|
|
},
|
|
}
|
|
body, _ := json.Marshal(payload)
|
|
endpoint := strings.TrimRight(a.cfg.AI.APIBase, "/") + "/chat/completions"
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+a.cfg.AI.APIKey)
|
|
resp, err := a.client.Do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode >= 400 {
|
|
raw, _ := io.ReadAll(resp.Body)
|
|
return "", fmt.Errorf("ai %d: %s", resp.StatusCode, strings.TrimSpace(string(raw)))
|
|
}
|
|
|
|
type choice struct {
|
|
Message struct {
|
|
Content string `json:"content"`
|
|
} `json:"message"`
|
|
}
|
|
var out struct {
|
|
Choices []choice `json:"choices"`
|
|
}
|
|
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
|
return "", err
|
|
}
|
|
if len(out.Choices) == 0 {
|
|
return "", errors.New("ai: empty completion")
|
|
}
|
|
return strings.TrimSpace(out.Choices[0].Message.Content), nil
|
|
}
|