243 lines
7.6 KiB
Go
243 lines
7.6 KiB
Go
package generation
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/tradarr/backend/internal/models"
|
|
"github.com/tradarr/backend/internal/scraper"
|
|
)
|
|
|
|
type UserInput struct {
|
|
SummaryModelID *string
|
|
Language, RankingMode string
|
|
GlobalLimit int
|
|
Assets []models.UserAsset
|
|
Sources []models.Source
|
|
}
|
|
type Candidate struct {
|
|
ID, SourceID string
|
|
Article scraper.Article
|
|
}
|
|
type SourceStat struct {
|
|
SourceID string `json:"source_id"`
|
|
SourceType string `json:"source_type"`
|
|
Status string `json:"status"`
|
|
Candidates int `json:"candidates"`
|
|
LayaSelected int `json:"laya_selected"`
|
|
Selected int `json:"selected"`
|
|
ArticleLimit int `json:"article_limit"`
|
|
ContentFallbacks int `json:"content_fallbacks"`
|
|
FailureCode string `json:"failure_code,omitempty"`
|
|
}
|
|
type GenerationOutcome struct {
|
|
ID string `json:"id"`
|
|
Status string `json:"status"`
|
|
Language string `json:"language"`
|
|
RankingMode string `json:"ranking_mode"`
|
|
TotalCandidates int `json:"total_candidates"`
|
|
ContentFallbacks int `json:"content_fallbacks"`
|
|
LayaSelected int `json:"laya_selected"`
|
|
Selected int `json:"selected"`
|
|
GlobalLimit int `json:"global_limit"`
|
|
SourceStats []SourceStat `json:"source_stats"`
|
|
FailureCode string `json:"failure_code,omitempty"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
type Result struct {
|
|
Summary *models.Summary `json:"summary"`
|
|
Outcome GenerationOutcome `json:"outcome"`
|
|
}
|
|
type GenerationRecord = Result
|
|
type Repository interface {
|
|
LoadUserInput(context.Context, string) (UserInput, error)
|
|
SaveGeneration(context.Context, string, GenerationRecord) error
|
|
}
|
|
|
|
// LayaRanker is a dedicated engine port, never a generic provider role.
|
|
type LayaRanker interface {
|
|
Rank(context.Context, string, []models.UserAsset, []Candidate) ([]Candidate, error)
|
|
}
|
|
type Ranker = LayaRanker
|
|
|
|
type Summarizer interface {
|
|
Summarize(context.Context, string, []models.UserAsset, []Candidate) (string, error)
|
|
}
|
|
type ResolvedSummary struct {
|
|
Summarizer Summarizer
|
|
CatalogID, ProviderID, Provider, Model string
|
|
}
|
|
type SummaryResolver interface {
|
|
Resolve(context.Context, string, *string) (ResolvedSummary, error)
|
|
}
|
|
|
|
type UseCase interface {
|
|
Generate(context.Context, string) (Result, error)
|
|
}
|
|
type Dependencies struct {
|
|
Decider MentionDecider
|
|
Names MentionNameResolver
|
|
Repository Repository
|
|
SummaryResolver SummaryResolver
|
|
LayaRanker LayaRanker
|
|
Scrapers map[string]scraper.Scraper
|
|
Ranker Ranker
|
|
Summarizer Summarizer
|
|
Clock func() time.Time
|
|
}
|
|
type useCase struct{ Dependencies }
|
|
|
|
func NewUseCase(d Dependencies) UseCase {
|
|
if d.LayaRanker != nil {
|
|
d.Ranker = d.LayaRanker
|
|
}
|
|
if d.Decider == nil {
|
|
d.Decider, _ = d.Ranker.(MentionDecider)
|
|
}
|
|
if d.Clock == nil {
|
|
d.Clock = time.Now
|
|
}
|
|
return &useCase{d}
|
|
}
|
|
func NewID() string {
|
|
var b [16]byte
|
|
if _, err := rand.Read(b[:]); err != nil {
|
|
panic(err)
|
|
}
|
|
b[6] = (b[6] & 15) | 64
|
|
b[8] = (b[8] & 63) | 128
|
|
return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:])
|
|
}
|
|
func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
|
input, err := u.Repository.LoadUserInput(ctx, userID)
|
|
if err != nil {
|
|
return Result{}, fmt.Errorf("load generation input: %w", err)
|
|
}
|
|
id := models.GenerationJobID(ctx)
|
|
if id == "" {
|
|
id = NewID()
|
|
}
|
|
out := GenerationOutcome{ID: id, Language: input.Language, RankingMode: input.RankingMode, GlobalLimit: input.GlobalLimit, CreatedAt: u.Clock(), SourceStats: []SourceStat{}}
|
|
resolved := ResolvedSummary{Summarizer: u.Summarizer}
|
|
finish := func(status, code, content string) (Result, error) {
|
|
out.Status = status
|
|
out.FailureCode = code
|
|
result := Result{Outcome: out}
|
|
if content != "" {
|
|
result.Summary = &models.Summary{ID: NewID(), UserID: userID, Content: content, GeneratedAt: out.CreatedAt}
|
|
if resolved.CatalogID != "" {
|
|
result.Summary.SummaryModelID = &resolved.CatalogID
|
|
result.Summary.AIProviderID = &resolved.ProviderID
|
|
result.Summary.ProviderName = &resolved.Provider
|
|
result.Summary.ModelName = &resolved.Model
|
|
}
|
|
}
|
|
if err := u.Repository.SaveGeneration(ctx, userID, result); err != nil {
|
|
return Result{}, fmt.Errorf("save generation: %w", err)
|
|
}
|
|
return result, nil
|
|
}
|
|
if (input.Language != "fr" && input.Language != "en") || (input.RankingMode != "title" && input.RankingMode != "title_content") || input.GlobalLimit <= 0 {
|
|
return finish("failed", "invalid_preferences", "")
|
|
}
|
|
// Explicit Summarizer is a test/injected port. Production always resolves
|
|
// the selected catalogue ID before touching any source or Laya.
|
|
if u.SummaryResolver != nil {
|
|
resolved, err = u.SummaryResolver.Resolve(ctx, userID, input.SummaryModelID)
|
|
if err != nil {
|
|
return finish("failed", "summary_model_unavailable", "")
|
|
}
|
|
}
|
|
if resolved.Summarizer == nil {
|
|
return finish("failed", "summary_model_unavailable", "")
|
|
}
|
|
if u.Decider == nil {
|
|
return finish("failed", "laya_unavailable", "")
|
|
}
|
|
symbols := []string{}
|
|
for _, a := range input.Assets {
|
|
symbols = append(symbols, a.Symbol)
|
|
}
|
|
candidates := []Candidate{}
|
|
stats := map[string]int{}
|
|
partial := false
|
|
for _, source := range input.Sources {
|
|
if !source.Operational() {
|
|
continue
|
|
}
|
|
stat := SourceStat{SourceID: source.ID, SourceType: source.Type, ArticleLimit: source.ArticleLimit, Status: "ok"}
|
|
if stat.ArticleLimit <= 0 {
|
|
stat.ArticleLimit = 20
|
|
}
|
|
feed := u.Scrapers[*source.SourceKey]
|
|
var articles []scraper.Article
|
|
if feed == nil {
|
|
err = fmt.Errorf("unavailable")
|
|
} else {
|
|
sourceSymbols := symbols
|
|
if *source.SourceKey == models.SourceYahooFinance {
|
|
sourceSymbols = yahooSymbols(input.Assets)
|
|
}
|
|
articles, err = feed.Scrape(ctx, append([]string(nil), sourceSymbols...))
|
|
}
|
|
if err != nil {
|
|
stat.Status = "failed"
|
|
stat.FailureCode = "source_unavailable"
|
|
partial = true
|
|
} else {
|
|
articles = recentArticles(articles)
|
|
if len(articles) > stat.ArticleLimit {
|
|
articles = articles[:stat.ArticleLimit]
|
|
}
|
|
for _, article := range articles {
|
|
stat.Candidates++
|
|
out.TotalCandidates++
|
|
if input.RankingMode == "title_content" && (strings.TrimSpace(article.Content) == "" || strings.TrimSpace(article.Content) == strings.TrimSpace(article.Title)) {
|
|
stat.ContentFallbacks++
|
|
out.ContentFallbacks++
|
|
article.Content = ""
|
|
}
|
|
if input.RankingMode == "title" {
|
|
article.Content = ""
|
|
}
|
|
candidates = append(candidates, Candidate{ID: NewID(), SourceID: source.ID, Article: article})
|
|
}
|
|
}
|
|
stats[source.ID] = len(out.SourceStats)
|
|
out.SourceStats = append(out.SourceStats, stat)
|
|
}
|
|
if len(candidates) == 0 {
|
|
if partial {
|
|
return finish("failed", "sources_unavailable", "")
|
|
}
|
|
return finish("no_results", "", "")
|
|
}
|
|
selected, layaAccepted, err := u.selectThreePass(ctx, input, candidates)
|
|
if err != nil {
|
|
return finish("failed", err.Error(), "")
|
|
}
|
|
for source, n := range layaAccepted {
|
|
out.SourceStats[stats[source]].LayaSelected = n
|
|
out.LayaSelected += n
|
|
}
|
|
for _, c := range selected {
|
|
out.SourceStats[stats[c.SourceID]].Selected++
|
|
}
|
|
|
|
out.Selected = len(selected)
|
|
if len(selected) == 0 {
|
|
return finish("no_results", "", "")
|
|
}
|
|
content, err := resolved.Summarizer.Summarize(ctx, input.Language, input.Assets, selected)
|
|
if err != nil || strings.TrimSpace(content) == "" {
|
|
return finish("failed", "summary_failed", "")
|
|
}
|
|
if partial {
|
|
return finish("partial", "source_unavailable", content)
|
|
}
|
|
return finish("succeeded", "", content)
|
|
}
|