feat(generation): persist summary outcomes without articles
Record generation outcomes and summaries for history while keeping article content transient. Refs #7 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
203
backend/internal/generation/generation.go
Normal file
203
backend/internal/generation/generation.go
Normal file
@ -0,0 +1,203 @@
|
||||
package generation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
type UserInput struct {
|
||||
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
|
||||
}
|
||||
type Ranker interface {
|
||||
Rank(context.Context, string, []models.UserAsset, []Candidate) ([]Candidate, error)
|
||||
}
|
||||
type Summarizer interface {
|
||||
Summarize(context.Context, string, []models.UserAsset, []Candidate) (string, error)
|
||||
}
|
||||
type UseCase interface {
|
||||
Generate(context.Context, string) (Result, error)
|
||||
}
|
||||
type Dependencies struct {
|
||||
Repository Repository
|
||||
Scrapers map[string]scraper.Scraper
|
||||
Ranker Ranker
|
||||
Summarizer Summarizer
|
||||
Clock func() time.Time
|
||||
}
|
||||
type useCase struct{ Dependencies }
|
||||
|
||||
func NewUseCase(d Dependencies) UseCase {
|
||||
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)
|
||||
}
|
||||
out := GenerationOutcome{ID: NewID(), Language: input.Language, RankingMode: input.RankingMode, GlobalLimit: input.GlobalLimit, CreatedAt: u.Clock(), SourceStats: []SourceStat{}}
|
||||
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 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", "")
|
||||
}
|
||||
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.Enabled {
|
||||
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.Type]
|
||||
var articles []scraper.Article
|
||||
if feed == nil {
|
||||
err = fmt.Errorf("unavailable")
|
||||
} else {
|
||||
articles, err = feed.Scrape(ctx, append([]string(nil), symbols...))
|
||||
}
|
||||
if err != nil {
|
||||
stat.Status = "failed"
|
||||
stat.FailureCode = "source_unavailable"
|
||||
partial = true
|
||||
} else {
|
||||
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", "", "")
|
||||
}
|
||||
ranked, err := u.Ranker.Rank(ctx, input.RankingMode, input.Assets, candidates)
|
||||
if err != nil {
|
||||
return finish("failed", "ranking_failed", "")
|
||||
}
|
||||
originals := map[string]Candidate{}
|
||||
for _, c := range candidates {
|
||||
originals[c.ID] = c
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
selected := []Candidate{}
|
||||
for _, c := range ranked {
|
||||
original, ok := originals[c.ID]
|
||||
if !ok || seen[c.ID] {
|
||||
return finish("failed", "ranking_invalid", "")
|
||||
}
|
||||
seen[c.ID] = true
|
||||
i := stats[original.SourceID]
|
||||
out.SourceStats[i].LayaSelected++
|
||||
out.LayaSelected++
|
||||
}
|
||||
for _, c := range ranked {
|
||||
c = originals[c.ID]
|
||||
i := stats[c.SourceID]
|
||||
if out.SourceStats[i].Selected >= out.SourceStats[i].ArticleLimit || len(selected) >= input.GlobalLimit {
|
||||
continue
|
||||
}
|
||||
selected = append(selected, c)
|
||||
out.SourceStats[i].Selected++
|
||||
}
|
||||
out.Selected = len(selected)
|
||||
if len(selected) == 0 {
|
||||
return finish("no_results", "", "")
|
||||
}
|
||||
content, err := u.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)
|
||||
}
|
||||
Reference in New Issue
Block a user