* docs(markers): design + implementation plans for multi-source markers & TheIntroDB contribution * fix(markers): TheIntroDB read-path correctness (TVDB, real confidence, best candidate) Honor TVDB ids in /media lookups (previously dropped — anime/TheTVDB-first libraries got no markers), decode and use the real per-segment confidence and submission_count instead of a hardcoded 0.9, and pick the most-submitted / highest-confidence candidate when several are returned. Adds httptest coverage for the introdb client and provider. Phase 1 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(markers): multi-source dispatch, per-provider config, per-segment provenance Add marker_provider_config (per-provider fetch enable/priority + contribute gates, contribution off by default) and a cached ProviderConfigStore. Add Registry.FetchMerged: query all fetch-enabled providers concurrently and keep the best candidate per segment (submission_count, then confidence, then fetch priority), stamping each winning marker with its provider/algorithm. Thread per-segment provenance through MarkerUpdatePayload and scanner.MarkerUpdate (additive SegmentProvenance overrides) so a merged result writes correct per-segment provider/confidence/algorithm; the legacy shared columns keep a summary. The lazy-playback path now uses FetchMerged. With only TheIntroDB enabled, behavior is unchanged. Phase 2 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(markers): TheIntroDB submission client, contribution audit, service engine Add a markers.Submitter capability and implement it on the introdb provider (POST /v3/submit, GET /v3/user/stats; key required, usage-limit aware, applies the null start/end conventions). Add the marker_contributions audit table and a value-hash-keyed ContributionStore for idempotency. Add ContributionService: resolves enabled submitter providers, gates eligibility (never re-submit online-sourced markers; auto runs require contribute_auto_local + scanner-intro above the per-provider confidence threshold), checks idempotency, submits, and records. Wired in main.go; no trigger yet (admin API and task follow). Phase 3 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(api): admin marker editing, contribution, and provider config endpoints Add the RequireAdmin marker API: GET/PUT /admin/files/{id}/markers (read with provenance; manual upsert where a segment object sets and null clears), DELETE .../markers/{segment}, POST .../contribute and GET .../contributions, plus GET/PUT /admin/markers/providers[/{provider}] and a .../validate key-check returning user stats. Manual writes go through the priority-gated UpsertMarkers (source=manual) and notify live sessions; a new FileRepository.ClearMarkers nulls a segment's columns. Validation mirrors the contribution rules. Phase 4 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(markers): daily auto-contribution task for local intro markers Add ContributeMarkersTask (daily 04:00, after local detection): when a provider has contribute_enabled + contribute_auto_local, page through episode files with a scanner intro marker at/above the provider's confidence threshold (new ContributionStore.CandidateLocalIntroFiles keyset query) and run them through ContributionService with Auto=true. No-op when no provider opts in; idempotent and resumable across runs. Phase 5 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(intromarkers): refine chromaprint starts with dialogue cues * feat(markers): finish marker management backend * feat(web): add marker editing UI * feat(markers): use plugin marker providers * fix(markers): address PR review feedback * feat(player): show marker labels on seek hover * fix(markers): type nullable marker mutation params * feat(markers): audit marker edits and add permission --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
206 lines
4.9 KiB
Go
206 lines
4.9 KiB
Go
package intromarkers
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"math"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
"unicode"
|
|
|
|
"github.com/Silo-Server/silo-server/internal/lang"
|
|
"github.com/Silo-Server/silo-server/internal/models"
|
|
"github.com/Silo-Server/silo-server/internal/subtitles"
|
|
)
|
|
|
|
type chromaprintStartRefiner interface {
|
|
RefineChromaprintStart(ctx context.Context, candidate Candidate, segment Segment) (Segment, bool, error)
|
|
}
|
|
|
|
type DialogueBoundaryRefiner struct {
|
|
config Config
|
|
readFile func(string) ([]byte, error)
|
|
}
|
|
|
|
var htmlTagPattern = regexp.MustCompile(`<[^>]+>`)
|
|
|
|
func NewDialogueBoundaryRefiner(config Config) *DialogueBoundaryRefiner {
|
|
return &DialogueBoundaryRefiner{
|
|
config: config.normalized(),
|
|
readFile: os.ReadFile,
|
|
}
|
|
}
|
|
|
|
func (r *DialogueBoundaryRefiner) RefineChromaprintStart(ctx context.Context, candidate Candidate, segment Segment) (Segment, bool, error) {
|
|
cfg := r.config.normalized()
|
|
if !cfg.DialogueRefinementEnabled || segment.End <= segment.Start || segment.Algorithm != ChromaprintAlgorithm {
|
|
return segment, false, nil
|
|
}
|
|
if err := ctx.Err(); err != nil {
|
|
return segment, false, err
|
|
}
|
|
subtitle, ok := selectDialogueSubtitle(candidate)
|
|
if !ok {
|
|
return segment, false, nil
|
|
}
|
|
readFile := r.readFile
|
|
if readFile == nil {
|
|
readFile = os.ReadFile
|
|
}
|
|
data, err := readFile(subtitle.Path)
|
|
if err != nil {
|
|
return segment, false, fmt.Errorf("read dialogue subtitle %q for file %d: %w", subtitle.Path, candidate.FileID, err)
|
|
}
|
|
cues, err := subtitles.ParseCues(data)
|
|
if err != nil {
|
|
return segment, false, fmt.Errorf("parse dialogue subtitle %q for file %d: %w", subtitle.Path, candidate.FileID, err)
|
|
}
|
|
refinedStart, ok := dialogueRefinedStart(cues, segment, cfg)
|
|
if !ok {
|
|
return segment, false, nil
|
|
}
|
|
refined := segment
|
|
refined.Start = refinedStart
|
|
refined.Algorithm = ChromaprintDialogueAlgorithm
|
|
return refined, true, nil
|
|
}
|
|
|
|
func selectDialogueSubtitle(candidate Candidate) (models.ExternalSubtitle, bool) {
|
|
audioLanguage := lang.Canonical(candidate.AudioLanguage)
|
|
bestScore := -1
|
|
var best models.ExternalSubtitle
|
|
for _, subtitle := range candidate.ExternalSubtitles {
|
|
if strings.TrimSpace(subtitle.Path) == "" ||
|
|
!isDialogueSubtitleFormat(subtitle.Format) ||
|
|
subtitle.Forced ||
|
|
subtitle.HearingImpaired {
|
|
continue
|
|
}
|
|
score := 0
|
|
subtitleLanguage := lang.Canonical(subtitle.Language)
|
|
if audioLanguage != "" && subtitleLanguage == audioLanguage {
|
|
score += 100
|
|
} else if audioLanguage == "" && subtitleLanguage == "en" {
|
|
score += 20
|
|
}
|
|
if subtitle.Default {
|
|
score += 10
|
|
}
|
|
if subtitleLanguage != "" {
|
|
score += 1
|
|
}
|
|
if score > bestScore {
|
|
bestScore = score
|
|
best = subtitle
|
|
}
|
|
}
|
|
if bestScore < 0 {
|
|
return models.ExternalSubtitle{}, false
|
|
}
|
|
return best, true
|
|
}
|
|
|
|
func isDialogueSubtitleFormat(format string) bool {
|
|
switch strings.ToLower(strings.TrimSpace(format)) {
|
|
case "srt", "subrip", "vtt", "webvtt":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func dialogueRefinedStart(cues []subtitles.SubtitleCue, segment Segment, cfg Config) (float64, bool) {
|
|
if segment.End <= segment.Start {
|
|
return 0, false
|
|
}
|
|
windowEnd := math.Min(segment.Start+cfg.DialogueRefinementWindowSeconds, segment.End)
|
|
if windowEnd <= segment.Start {
|
|
return 0, false
|
|
}
|
|
|
|
lastDialogueEnd := segment.Start
|
|
for _, cue := range cues {
|
|
if !cueLooksLikeDialogue(cue) {
|
|
continue
|
|
}
|
|
start := cue.Start.Seconds()
|
|
end := cue.End.Seconds()
|
|
if end <= segment.Start {
|
|
continue
|
|
}
|
|
if start > windowEnd {
|
|
break
|
|
}
|
|
if end > lastDialogueEnd {
|
|
lastDialogueEnd = end
|
|
}
|
|
}
|
|
|
|
if lastDialogueEnd <= segment.Start {
|
|
return 0, false
|
|
}
|
|
if lastDialogueEnd-segment.Start > cfg.DialogueRefinementMaxShiftSeconds {
|
|
return 0, false
|
|
}
|
|
if segment.End-lastDialogueEnd < cfg.DialogueRefinementMinimumRemainingSeconds {
|
|
return 0, false
|
|
}
|
|
return lastDialogueEnd, true
|
|
}
|
|
|
|
func cueLooksLikeDialogue(cue subtitles.SubtitleCue) bool {
|
|
for _, line := range cue.Lines {
|
|
if lineLooksLikeDialogue(line) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func lineLooksLikeDialogue(line string) bool {
|
|
cleaned := strings.TrimSpace(stripSubtitleDialogueMarkup(line))
|
|
if cleaned == "" || strings.Contains(cleaned, "♪") {
|
|
return false
|
|
}
|
|
lower := strings.ToLower(cleaned)
|
|
if isBracketedCue(lower, "[", "]") ||
|
|
isBracketedCue(lower, "(", ")") ||
|
|
isBracketedCue(lower, "{", "}") {
|
|
return false
|
|
}
|
|
for _, r := range cleaned {
|
|
if unicode.IsLetter(r) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func stripSubtitleDialogueMarkup(line string) string {
|
|
line = stripSubtitleASSTags(line)
|
|
line = htmlTagPattern.ReplaceAllString(line, "")
|
|
return strings.TrimSpace(line)
|
|
}
|
|
|
|
func isBracketedCue(line, open, close string) bool {
|
|
return strings.HasPrefix(line, open) && strings.HasSuffix(line, close)
|
|
}
|
|
|
|
func stripSubtitleASSTags(line string) string {
|
|
var b strings.Builder
|
|
b.Grow(len(line))
|
|
inTag := false
|
|
for _, r := range line {
|
|
switch {
|
|
case r == '{':
|
|
inTag = true
|
|
case r == '}':
|
|
inTag = false
|
|
case !inTag:
|
|
b.WriteRune(r)
|
|
}
|
|
}
|
|
return b.String()
|
|
}
|