subtitlematch

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 7, 2026 License: GPL-3.0 Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

subs

Matches loose subtitle files to the videos they belong to, when the two names share almost nothing.

StudioHandleXXX_Mommy-and-Son-Nesting-Season+(transcribed+on+25-Jul-2024).srt
  → 2023-05-23_Some.Performer-stepMommy.and.stepSon.Nesting.Season_1080p.mp4

Names alone cannot resolve that. The matcher combines studio/JAV codes, normalised title tokens, and — decisively — the subtitle's own runtime against the scene duration.

// The package name is long; alias it and call sites stay readable.
import subs "github.com/Anastylosis/subtitlematch"

index := subs.NewIndex(scenes, subs.NewVocab(names))
m := index.Match(sub, 5)

It answers with a Verdict, not a boolean:

verdict meaning
Confirmed name and runtime agree, no rival comes close
Likely good evidence, weaker on one axis
Ambiguous too close to separate safely
Unmatched nothing credible in the library

Ambiguous is the point: a caller can decline to act rather than guess, because moving a subtitle onto the wrong video is worse than leaving it alone.

Scope

Nothing here touches a media manager, database or filesystem. The input is filenames, durations and subtitle contents; the output is a verdict per candidate pair. Callers supply the library listing and act on the result.

That is what lets a local-filesystem consumer and a fingerprint-database consumer share it unchanged.

Documentation

  • docs/usage.md — the API, and which fields carry more weight than they look
  • docs/design.md — why it decides the way it does, and the measurements behind each rule

License

GPL-3.0-only.

Documentation

Overview

Package subtitlematch matches loose subtitle files to the videos they belong to.

A subtitle not named after its video is invisible to a media manager, which attaches a caption only when the file sits beside the video as <stem>.srt or <stem>.<lang>.srt. Reconnecting the two is not string comparison — the names often share nothing — so the matcher combines studio/JAV codes, normalised title tokens, and the subtitle's own runtime against the scene duration. Runtime is the decisive signal.

Nothing here talks to a media manager, database or filesystem. The input is filenames, durations and subtitle contents; the output is a verdict per candidate pair. Callers supply the library listing and act on the result.

See docs/design.md for why it decides the way it does, and docs/usage.md for the API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Codes

func Codes(s string) map[string]bool

Codes extracts studio/JAV identifiers, normalised to ABC-123 with leading zeros removed so "venu00765" and "VENU-765" compare equal. These are the strongest single signal available when present.

func DetectLanguage

func DetectLanguage(r io.Reader) (lang string, confidence float64, ok bool)

DetectLanguage returns an ISO-639-1 code for a subtitle's text, plus a confidence margin over the runner-up. ok is false when no language could be determined with any confidence.

Script is checked first: CJK, Hangul and Cyrillic are unambiguous and do not need word statistics.

func F1

func F1(a, b map[string]bool) float64

F1 is the harmonic mean of precision and recall between two token sets. It is symmetric-ish and penalises both missing and extra words, which suits comparing a filename against a title where either may carry more detail.

func HMS

func HMS(d time.Duration) string

HMS renders a duration as H:MM:SS for reports.

func Overlap

func Overlap(a, b map[string]bool) int

Overlap counts tokens present in both sets.

func Runtime

func Runtime(r io.Reader) (d time.Duration, ok bool)

Runtime returns the timestamp of the last cue — an approximation of the video's length, and the signal that makes matching trustworthy (see docs/design.md).

The whole stream is scanned, not just the tail: cues are not always stored chronologically and a trailing credit line can carry an earlier timestamp. Returns ok=false when nothing parsable is found.

func RuntimeFit

func RuntimeFit(subRuntime, sceneDur time.Duration) (score float64, delta time.Duration)

RuntimeFit scores how well a subtitle runtime matches a scene duration.

A subtitle's final cue normally ends slightly BEFORE the video does, so the expected delta (sceneDur - subRuntime) is small and positive. A negative delta means the subtitle outlives the video, which is evidence against the pairing rather than for it.

Returns a score in [0,1] and the signed delta. A zero score means the runtimes are incompatible.

func StripNoise

func StripNoise(stem string) string

StripNoise removes scraper and transcoder junk from a filename stem.

func Tokens

func Tokens(s string) map[string]bool

Tokens reduces a name to its comparable words: noise stripped, punctuation flattened, stop words and creator handles dropped, synonyms folded.

Types

type Candidate

type Candidate struct {
	Scene SceneRef
	Score float64
	// Delta is sceneDuration - subtitleRuntime.
	Delta time.Duration
	// NameSim is the better of title/filename similarity, kept so a verdict
	// can require real name agreement and not a runtime-inflated score.
	NameSim float64
	// Reasons explains the score in human terms, for the report.
	Reasons []string
}

Candidate is one scored possibility for a subtitle.

type Index

type Index struct {
	// contains filtered or unexported fields
}

Index holds a preprocessed library for repeated matching.

func NewIndex

func NewIndex(scenes []SceneRef, vocab *Vocab) *Index

NewIndex preprocesses scenes for matching.

vocab may be nil, in which case every token counts as content — matching still works, it just loses the ability to tell "same creator" apart from "same scene".

func (*Index) Len

func (ix *Index) Len() int

Len reports how many scenes are indexed.

func (*Index) Match

func (ix *Index) Match(sub Subtitle, maxCandidates int) Match

Match scores a subtitle against the library and returns a verdict with up to maxCandidates ranked possibilities.

Scoring is additive across independent signals, so agreement between two weak signals can outweigh one strong-looking name match:

studio/JAV code    +60   (near-decisive when present)
exact stem match   +100  (the subtitle is already named after the video)
title similarity   +0..70 (token F1)
runtime agreement  +0..45, and a contradiction subtracts 30
matching date      +25

type Match

type Match struct {
	Subtitle   Subtitle
	Verdict    Verdict
	Candidates []Candidate
}

Match is the matcher's answer for a single subtitle.

func (Match) Best

func (m Match) Best() *Candidate

Best returns the winning candidate, or nil when there is none.

type SceneRef

type SceneRef struct {
	ID         string
	Title      string
	Date       string
	Studio     string
	Performers []string
	// Path of the scene's primary file, as Stash reports it.
	Path string
	// Basename stem of that file, without extension.
	Stem     string
	Duration time.Duration
	// HasCaption is true when the scene already carries a caption track in
	// this subtitle's language; used to avoid proposing a duplicate.
	HasCaption bool
	// contains filtered or unexported fields
}

SceneRef is the subset of a Stash scene the matcher needs.

type Subtitle

type Subtitle struct {
	// Path as reported by the backend that listed it.
	Path string
	// Stem is the basename without its extension.
	Stem string
	// Runtime is the last cue time; zero when unknown.
	Runtime time.Duration
	// Lang is the ISO-639-1 code detected from the file's text.
	Lang string
	// Size in bytes, used to break ties between duplicate transcripts.
	Size int64
	// Dirs are the folder names between the scan root and the file. They name
	// a creator when the filename does not, and count as creator evidence
	// only.
	Dirs []string
}

Subtitle is one loose subtitle file to place.

type Verdict

type Verdict string

Verdict expresses how much trust a match deserves.

const (
	// Confirmed: name and runtime agree, and no rival comes close.
	Confirmed Verdict = "CONFIRMED"
	// Likely: good evidence, but weaker on one axis.
	Likely Verdict = "LIKELY"
	// Ambiguous: several candidates are too close to separate safely.
	Ambiguous Verdict = "AMBIGUOUS"
	// Unmatched: nothing credible in the library.
	Unmatched Verdict = "UNMATCHED"
)

type Vocab

type Vocab struct {
	// contains filtered or unexported fields
}

Vocab names the creators in a library — performers and studios, plus aliases — so their handles can be told apart from title words.

It holds only squashed names (separators removed, as scrapers write them: "riverstone", "thehousenextdoor"), never individual words. Indexing every word of every alias sweeps up ordinary vocabulary and gutted title matching when measured; see docs/design.md.

func NewVocab

func NewVocab(names []string) *Vocab

NewVocab builds a vocabulary from performer and studio names (and aliases).

func (*Vocab) IsCreator

func (v *Vocab) IsCreator(tok string) bool

IsCreator reports whether a token names a creator. Scrapers bolt suffixes on ("riverstonexxx"), so a token also counts when it starts with a known handle; trailing digits are ignored for the same reason.

func (*Vocab) Len

func (v *Vocab) Len() int

Len reports how many distinct creator handles are known.

func (*Vocab) Split

func (v *Vocab) Split(toks map[string]bool) (content, creator map[string]bool)

Split partitions tokens into content and creator sets.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL