diagnose

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: GPL-3.0 Imports: 13 Imported by: 0 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.

Documentation

Overview

Package diagnose inspects a dictionary the way a developer would: it picks a handful of representative records, reports what the container and the DOM actually contain, and measures how much semantic structure the current parser recovers from them.

It is a development and compatibility-analysis tool, not part of the lookup hot path. The one piece the running service shares with it is representative sampling, which also decides which profile a dictionary gets.

Index

Constants

View Source
const (
	WarnRichHTMLNoDefinitions = "rich-html-no-definitions"
	WarnHighFallbackRate      = "high-fallback-rate"
	WarnImplausibleSenseCount = "implausible-sense-count"
	WarnOversizedDefinition   = "oversized-definition"
	WarnDuplicateDefinitions  = "duplicate-definitions"
	WarnBilingualNoTranslate  = "bilingual-without-translations"
	WarnExamplesNoDefinitions = "examples-without-definitions"
	WarnHeadwordMismatch      = "headword-unlike-lookup-key"
	WarnUntypedSectionsOnly   = "content-only-in-untyped-sections"
)

Warning codes. They are deliberately phrased as observations rather than verdicts: every one of them has a legitimate explanation for some dictionary, and the only claim being made is that a human should look.

View Source
const GenericProfileID = "generic"

GenericProfileID is the label used when no profile applies.

Variables

View Source
var DetectionSampling = SampleOptions{Pool: 24, Keep: 5}

DetectionSampling is the budget used during rescan, where sampling only has to decide a profile. It is deliberately smaller than the diagnostic budget: every dictionary in the user's library pays for it at startup.

View Source
var DiagnosticSampling = SampleOptions{Pool: 64, Keep: 10}

DiagnosticSampling is the budget used by the diagnostic commands, which run on demand and can afford to look harder.

Functions

func ApplyProfileOverride

func ApplyProfileOverride(profile *parser.Profile, override string) (*parser.Profile, string)

ApplyProfileOverride implements the development-only parser override: "auto" or "" keeps automatic detection, "generic" disables profiles, and anything else names a profile to force. It returns the profile to use and the label to report it under.

Nothing persists it. The product always resolves a parser from the current MDX and the current rules, which is what lets a dictionary pick up future parser improvements without anyone re-recording a mapping.

func ScoreRecord

func ScoreRecord(raw []byte) int

ScoreRecord rates how much of a dictionary's recurring template one record exposes, from its markup alone.

Richer structure, more distinct class vocabulary, repeated sense-like siblings, cross-references and pronunciation references all mean a record shows more of what the parser will have to cope with. Length contributes but is capped, so one enormous encyclopedia article cannot outrank a properly structured entry.

Types

type Container

type Container struct {
	ID          string   `json:"id"`
	Title       string   `json:"title"`
	Health      string   `json:"health"`
	EntryCount  int64    `json:"entryCount"`
	Encoding    string   `json:"encoding,omitempty"`
	Version     string   `json:"version,omitempty"`
	CreatedAt   string   `json:"createdAt,omitempty"`
	MDDVolumes  int      `json:"mddVolumes"`
	Diagnostics []string `json:"diagnostics,omitempty"`
}

Container is what the MDX file itself says about the dictionary.

type CorpusReport

type CorpusReport struct {
	Root         string       `json:"root"`
	Total        int          `json:"total"`
	Healthy      int          `json:"healthy"`
	Unavailable  int          `json:"unavailable"`
	Dictionaries []Report     `json:"dictionaries"`
	Profiles     []Count      `json:"profileDistribution"`
	Families     []Family     `json:"families,omitempty"`
	Aggregate    CorpusTotals `json:"aggregate"`
}

CorpusReport is the batch result over a whole dictionary directory.

func Corpus

func Corpus(registry *mdict.Registry, opts Options, progress func(index, total int, title string)) CorpusReport

Corpus runs the diagnostics over every dictionary in a registry.

func (CorpusReport) Markdown

func (c CorpusReport) Markdown() string

Markdown renders the corpus report for a human reader.

It contains titles, IDs, counts, percentages, class names and warning codes, and no dictionary content whatsoever, so the output is safe to keep and to quote from.

type CorpusTotals

type CorpusTotals struct {
	Sampled int `json:"sampled"`
	// WithDefinitions and friends count dictionaries where at least one sample
	// produced that kind of structure.
	WithDefinitions  int `json:"withDefinitions"`
	WithPOS          int `json:"withPartOfSpeech"`
	WithExamples     int `json:"withExamples"`
	WithTranslations int `json:"withTranslations"`
	WithIPA          int `json:"withIPA"`
	WithPhrases      int `json:"withPhrases"`
	WithCrossRefs    int `json:"withCrossReferences"`
	// StrongStructure counts dictionaries where most samples produced senses.
	StrongStructure int `json:"strongStructure"`
	// HeavyFallback counts dictionaries where most samples produced none.
	HeavyFallback int `json:"heavyFallback"`
	// FullyUnparsed counts dictionaries where every sample fell back.
	FullyUnparsed int `json:"fullyUnparsed"`
	Flagged       int `json:"flagged"`
	// MeanStructuredRate and MeanFallbackRate average the per-dictionary rates,
	// so a 500 000-headword dictionary and a 400-headword one count the same.
	MeanStructuredRate float64 `json:"meanStructuredRate"`
	MeanFallbackRate   float64 `json:"meanFallbackRate"`
	// Warnings counts each conservative signal across the corpus.
	Warnings []Count `json:"warnings,omitempty"`
}

CorpusTotals are the numbers a parser change is judged by.

type Count

type Count struct {
	Name  string `json:"name"`
	Count int    `json:"count"`
}

Count is one name and how often it occurred across the samples.

type Coverage

type Coverage struct {
	Samples      int `json:"samples"`
	Headword     int `json:"headword"`
	PartOfSpeech int `json:"partOfSpeech"`
	Definitions  int `json:"definitions"`
	Translations int `json:"translations"`
	Examples     int `json:"examples"`
	IPA          int `json:"ipa"`
	Forms        int `json:"forms"`
	Phrases      int `json:"phrases"`
	CrossRefs    int `json:"crossReferences"`
	Sections     int `json:"sections"`
	// Fallback counts samples that produced no structure at all and were
	// emitted as one untyped section.
	Fallback int `json:"fallback"`
	// Structured is how many samples yielded at least one sense.
	Structured int `json:"structured"`
	// Empty is how many samples yielded nothing worth showing.
	Empty int `json:"empty"`

	StructuredRate float64 `json:"structuredRate"`
	FallbackRate   float64 `json:"fallbackRate"`
	// MedianSenses is the middle sense count across the samples.
	MedianSenses int `json:"medianSenses"`
}

Coverage counts how many representative samples yielded each kind of semantic structure.

These are coverage counts, not accuracy: nothing here has been compared against a human reading of the entry. A field being present says the parser produced something of that kind, not that what it produced is right.

type DOMSummary

type DOMSummary struct {
	Tags       []Count `json:"tags"`
	Classes    []Count `json:"classes"`
	Attributes []Count `json:"attributes"`
	// Signatures are the most common tag/class combinations, the closest thing
	// to "what this dictionary's entries are made of".
	Signatures []string `json:"signatures"`
	// ReferenceSchemes counts sound://, snd://, entry:// and similar links.
	ReferenceSchemes []Count `json:"referenceSchemes,omitempty"`
	MaxDepth         int     `json:"maxDepth"`
	MedianBytes      int     `json:"medianBytes"`
	// ClassVocabulary is the trimmed class list the family key is derived from.
	ClassVocabulary []string `json:"classVocabulary,omitempty"`
	// FamilyKey is a stable hash of that vocabulary. Two dictionaries sharing
	// it are built from the same template.
	FamilyKey string `json:"familyKey,omitempty"`
}

DOMSummary describes the markup conventions a dictionary uses.

Everything in it is structural — tag names, class names, attribute names, reference schemes and counts. No dictionary text is recorded, which is what makes a corpus report safe to keep and to talk about.

func SummarizeDOM

func SummarizeDOM(samples []Sample) DOMSummary

SummarizeDOM aggregates the markup conventions across a dictionary's samples.

type EvidenceStrength

type EvidenceStrength string

EvidenceStrength grades how well a profile's structural fingerprint fits.

const (
	// EvidenceStrong means one profile matched a majority of representative
	// samples and nothing else matched it equally well.
	EvidenceStrong EvidenceStrength = "strong"
	// EvidenceWeak means a profile matched, but only in a minority of samples.
	// A single coincidental match is exactly how a dictionary gets mislabelled,
	// so weak evidence resolves to generic.
	EvidenceWeak EvidenceStrength = "weak"
	// EvidenceConflicting means two profiles fit equally well.
	EvidenceConflicting EvidenceStrength = "conflicting"
	// EvidenceAbsent means no profile fingerprint matched at all.
	EvidenceAbsent EvidenceStrength = "absent"
)

type Family

type Family struct {
	Key string `json:"key"`
	// Members are dictionary IDs.
	Members []string `json:"members"`
	Titles  []string `json:"titles"`
	// SharedClasses is the class vocabulary they have in common, which is the
	// evidence for calling them one family.
	SharedClasses []string `json:"sharedClasses"`
	// Profiles is what those members currently parse with.
	Profiles []string `json:"profiles"`
}

Family is a group of dictionaries built from the same HTML template.

func Families

func Families(reports []Report) []Family

Families groups dictionaries whose class vocabularies substantially coincide. It is exported so tooling that already holds a set of reports can ask the question without re-running the whole corpus scan.

type Options

type Options struct {
	Sampling SampleOptions
	// ProfileOverride forces a parser choice for comparison runs: "" or "auto"
	// keeps automatic detection, "generic" disables profiles, anything else
	// names a profile ID. It is a debugging aid, not a stored configuration.
	ProfileOverride string
	// ResolveAudio reports whether a reference exists in the dictionary's MDD.
	// Nil means resource resolution is not being tested, which is the normal
	// case for an MDX-only corpus.
	ResolveAudio func(ref string) bool
}

Options configures one dictionary diagnostic.

type ProfileCandidate

type ProfileCandidate struct {
	ID string `json:"id"`
	// Matched is how many samples satisfied the full structural fingerprint.
	Matched int `json:"matched"`
	// Score is the summed fingerprint score, used only to break ties.
	Score int `json:"score"`
}

ProfileCandidate records how one profile scored against the samples.

type ProfileEvidence

type ProfileEvidence struct {
	// Selected is the profile ID that will actually be used, or "generic".
	Selected string           `json:"selected"`
	Strength EvidenceStrength `json:"strength"`
	Samples  int              `json:"samples"`
	// Override records a development-only parser override, so a report never
	// presents a forced choice as though the evidence had produced it.
	Override   string             `json:"override,omitempty"`
	Candidates []ProfileCandidate `json:"candidates,omitempty"`
}

ProfileEvidence is the conservative verdict on which profile applies.

func SelectProfile

func SelectProfile(title string, samples []Sample) (*parser.Profile, ProfileEvidence)

SelectProfile decides which profile a dictionary should be parsed with.

The rule this preserves is that a structural fingerprint, not a title and not an output-volume contest, decides. What changes is how many records get a vote: one coincidental sample can no longer carry a dictionary into the wrong profile, and two profiles that fit equally well resolve to generic rather than to whichever happened to be listed first.

type PronunciationEvidence

type PronunciationEvidence struct {
	// IPASamples is how many samples yielded a transcription.
	IPASamples int `json:"ipaSamples"`
	// AudioRefSamples is how many samples reference a recording in their markup.
	AudioRefSamples int `json:"audioRefSamples"`
	// RegionMarkers are the accent markers found around those references.
	RegionMarkers []string `json:"regionMarkers,omitempty"`
	// MDDVolumes is how many resource volumes accompany the MDX.
	MDDVolumes int `json:"mddVolumes"`
	// AudioResolved counts references that resolve to a real MDD asset. It is
	// only meaningful when MDDVolumes is non-zero.
	AudioResolved int `json:"audioResolved"`
}

PronunciationEvidence separates what the MDX claims from what the MDD can actually deliver.

A corpus of MDX files without their MDD volumes is the normal case for compatibility analysis. Reporting "no audio" for those would confuse a missing resource pack with a parser failure, so reference detection and resource resolution are counted apart and never combined into one verdict.

type Report

type Report struct {
	Container     Container             `json:"container"`
	Profile       ProfileEvidence       `json:"profile"`
	DOM           DOMSummary            `json:"dom"`
	Coverage      Coverage              `json:"coverage"`
	Pronunciation PronunciationEvidence `json:"pronunciation"`
	Warnings      []Warning             `json:"warnings,omitempty"`
	// SampleScores records the informativeness of the chosen samples, which is
	// how a "this dictionary has nothing to sample" case stays visible.
	SampleScores []int `json:"sampleScores,omitempty"`
}

Report is everything the diagnostics know about one dictionary.

func Inspect

func Inspect(dict *mdict.Dictionary, opts Options) Report

Inspect produces the full diagnostic for one dictionary.

type Sample

type Sample struct {
	// Key is the MDX key the record was reached through. It is retained for
	// local debugging only and is never written to a shareable report.
	Key string
	// HTML is the resolved record content.
	HTML []byte
	// Doc is the parsed document, shared by every consumer so a dictionary is
	// only parsed once per sample.
	Doc *html.Node
	// Score is the structural informativeness that got it selected.
	Score int
}

Sample is one record chosen to represent a dictionary's recurring template.

func Samples

func Samples(dict *mdict.Dictionary, opts SampleOptions) []Sample

Samples picks the structurally most informative records from a dictionary.

The selection is language-independent and deterministic: candidates are strided across the key index, scored from their markup alone, and the best are kept. No word list, script assumption or locale is involved anywhere.

type SampleOptions

type SampleOptions struct {
	// Pool is how many candidate keys are resolved and scored.
	Pool int
	// Keep is how many of them are retained as representative samples.
	Keep int
}

SampleOptions controls representative sampling.

type Warning

type Warning struct {
	Code   string `json:"code"`
	Detail string `json:"detail"`
}

Warning is a conservative signal that a dictionary is worth a human look. It is never proof that parsing is wrong.

Jump to

Keyboard shortcuts

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