parser

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: GPL-3.0 Imports: 12 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 parser turns heterogeneous dictionary HTML into the Entry IR.

Index

Constants

View Source
const FallbackSectionTitle = "Entry"

FallbackSectionTitle labels the untyped section the generic parser emits when no structure could be recovered. Diagnostics identify a fallback parse by this title rather than by guessing from sense counts.

Variables

This section is empty.

Functions

func Ancestors

func Ancestors(node *html.Node) []*html.Node

Ancestors returns the node's ancestor chain, nearest first.

func Attr

func Attr(node *html.Node, name string) string

Attr returns an attribute value, or "" when absent.

func AttrOK

func AttrOK(node *html.Node, name string) (string, bool)

AttrOK returns an attribute value and whether it was present.

func CanonicalForm

func CanonicalForm(raw string) string

CanonicalForm normalizes an inflection label, returning "" when unrecognised.

func CanonicalPOS

func CanonicalPOS(raw string) string

CanonicalPOS normalizes a part-of-speech label. It returns "" when the text is not recognisably a part of speech, so callers can fall back rather than inventing a category.

func CanonicalPOSVocabulary added in v1.1.0

func CanonicalPOSVocabulary() []string

CanonicalPOSVocabulary returns every canonical label this parser can emit. Presentation adapters use it in exhaustive tests so adding a parser POS cannot silently leave a user surface with an unreviewed long label.

func ClassSet

func ClassSet(node *html.Node) map[string]struct{}

ClassSet returns the node's class attribute as a set.

func CleanIPA

func CleanIPA(raw string) string

CleanIPA strips the surrounding slashes and brackets.

func DescriptorText

func DescriptorText(node *html.Node) string

DescriptorText gathers the class names, ids, titles and hrefs on and around a node. Region detection uses it to decide whether an audio link is British or American without depending on any single dictionary's conventions.

func DetectRegion

func DetectRegion(descriptors ...string) entryir.Region

DetectRegion classifies a pronunciation from all the evidence around it: class names, ids, titles, hrefs, resource filenames and neighbouring text.

It returns RegionOther when the evidence is absent or contradictory. Guessing would put an American clip behind a UK flag, which is worse than showing no region at all.

func HeadwordMatchesKey added in v1.1.0

func HeadwordMatchesKey(headword, key string) bool

HeadwordMatchesKey reports whether a parsed headword plausibly names the same entry as the key it was looked up under.

The comparison is deliberately loose. Hyphenation dots, letter case, diacritics rendered as separate spans and a trailing homograph number are all normal differences between the two; a completely different string is not.

func IsKnownLabel

func IsKnownLabel(raw string) bool

IsKnownLabel reports whether text reads as a dictionary usage label.

func LooksLikeIPA

func LooksLikeIPA(raw string) bool

LooksLikeIPA reports whether text is plausibly a phonetic transcription.

func Normalize

func Normalize(text string) string

Normalize collapses whitespace and trims a string.

func Parse

func Parse(raw []byte, opts Options) (*entryir.Entry, error)

Parse converts raw entry HTML into the Entry IR.

func ParseSenseNumber

func ParseSenseNumber(raw string) string

ParseSenseNumber extracts a sense number from a label, or "" if it is prose.

func Query

func Query(root *html.Node, sel Selector) *html.Node

Query returns the first descendant matching the selector.

func QueryAll

func QueryAll(root *html.Node, sel Selector) []*html.Node

QueryAll returns every descendant matching the selector, in document order. Matches are not nested: once a node matches, its subtree is not searched for further matches of the same selector, which is what "the sense blocks" or "the example blocks" always means in practice.

func QueryAllNested

func QueryAllNested(root *html.Node, sel Selector) []*html.Node

QueryAllNested behaves like QueryAll but also descends into matches, which is needed where subsenses share their parent's class.

func RemoveMatching

func RemoveMatching(root *html.Node, sel Selector) int

RemoveMatching detaches every node matching the selector from the tree. Profiles use it to drop chrome — fold buttons, speaker icons, "show all" widgets — before any text extraction happens.

func ScopedVisibleText added in v1.1.0

func ScopedVisibleText(raw []byte, profile *Profile) string

ScopedVisibleText is the visible text a profile actually puts in scope.

It is the fair denominator for asking how much of a record a parse accounted for. A profile's `root` narrows a record that holds several regional editions of one entry to the edition being presented, and its `ignore` list names fold buttons and speaker icons as chrome. Neither is content the parser failed to keep, so neither belongs in the total it is measured against. With no profile this is exactly VisibleText.

func Text

func Text(node *html.Node, opts TextOptions) string

Text extracts the visible text of a subtree.

func VisibleText added in v1.1.0

func VisibleText(raw []byte) string

VisibleText is the normalized text a reader would see in a raw record.

It exists for diagnostics that need a denominator: how much of the record did the parse account for? Producing it here rather than in the caller keeps one definition of "visible" — scripts, styles and document head removed, inline-hidden nodes skipped — shared with what the parser itself reads.

func Walk

func Walk(root *html.Node, visit func(*html.Node) bool)

Walk visits every element node in document order. Returning false from the visitor skips the node's subtree.

Types

type AudioResolver

type AudioResolver interface {
	ResolveAudio(ref string) *entryir.Audio
}

AudioResolver turns a resource reference found in entry HTML into a playable asset, or nil when the user's MDD does not contain it.

Returning nil is the whole point: a pronunciation with no backing MDD file is reported without audio rather than being filled in from any other source.

type AudioResolverFunc

type AudioResolverFunc func(ref string) *entryir.Audio

AudioResolverFunc adapts a function to AudioResolver.

func (AudioResolverFunc) ResolveAudio

func (f AudioResolverFunc) ResolveAudio(ref string) *entryir.Audio

ResolveAudio implements AudioResolver.

type FormRule

type FormRule struct {
	// Container bounds the inflection table.
	Container []string `json:"container"`
	// Label selects the form name, Word the form itself. When Label is unset
	// every word found is reported under Name.
	Label []string `json:"label,omitempty"`
	Word  []string `json:"word,omitempty"`
	Name  string   `json:"name,omitempty"`
}

FormRule extracts inflected forms.

type ImageResolver added in v1.1.0

type ImageResolver interface {
	ResolveImage(ref, alt string) *entryir.Image
}

ImageResolver turns an inline image reference into a dictionary-bound MDD resource. Missing MDD assets and non-dictionary URLs resolve to nil.

type ImageResolverFunc added in v1.1.0

type ImageResolverFunc func(ref, alt string) *entryir.Image

ImageResolverFunc adapts a function to ImageResolver.

func (ImageResolverFunc) ResolveImage added in v1.1.0

func (f ImageResolverFunc) ResolveImage(ref, alt string) *entryir.Image

ResolveImage implements ImageResolver.

type Options

type Options struct {
	// Headword is the key that was looked up, used when the entry does not
	// state its own headword.
	Headword string
	// Profile is the matched dictionary profile, or nil for generic parsing.
	Profile *Profile
	// Audio resolves pronunciation references. May be nil.
	Audio AudioResolver
	// Image resolves inline illustrations in free-form prose. May be nil.
	Image ImageResolver
	// MaxExamplesPerSense caps example output. Some dictionaries ship twenty
	// corpus sentences per sense, which is unreadable in a popup.
	MaxExamplesPerSense int
	// Debug records rule provenance and confidence notes on the entry.
	Debug bool
}

Options configures one parse.

type Profile

type Profile struct {
	ID   string `json:"id"`
	Name string `json:"name"`

	// Match decides whether this profile applies to a dictionary.
	Match ProfileMatch `json:"match"`

	// Root narrows parsing to the first matching node. Dictionaries that ship
	// several regional editions of the same entry in one record use this to
	// keep one of them instead of reporting every sense twice.
	Root []string `json:"root,omitempty"`

	// Ignore removes chrome — fold buttons, speaker icons, scripts — before
	// anything else runs.
	Ignore []string `json:"ignore,omitempty"`

	// Headword locates the entry's own headword.
	Headword []string `json:"headword,omitempty"`

	// Translation marks nodes holding a translation of the neighbouring
	// English text, which must be lifted out rather than concatenated into it.
	Translation []string `json:"translation,omitempty"`

	// Pronunciation rules are evaluated in order.
	Pronunciation []PronunciationRule `json:"pronunciation,omitempty"`

	// PartBlock delimits one part-of-speech section. When unset the whole entry
	// is treated as a single block.
	PartBlock []string `json:"partBlock,omitempty"`
	POS       []string `json:"pos,omitempty"`
	Grammar   []string `json:"grammar,omitempty"`

	// Sense-level selectors.
	Sense       []string `json:"sense,omitempty"`
	SenseNumber []string `json:"senseNumber,omitempty"`
	Subsense    []string `json:"subsense,omitempty"`
	Definition  []string `json:"definition,omitempty"`
	// DefinitionStrip removes nodes from inside a definition before its text is
	// read, for dictionaries that inline the sense number or POS there.
	DefinitionStrip []string `json:"definitionStrip,omitempty"`
	Labels          []string `json:"labels,omitempty"`
	Topic           []string `json:"topic,omitempty"`
	Patterns        []string `json:"patterns,omitempty"`
	Example         []string `json:"example,omitempty"`
	ExampleText     []string `json:"exampleText,omitempty"`
	Synonyms        []string `json:"synonyms,omitempty"`
	Antonyms        []string `json:"antonyms,omitempty"`

	// Forms locates inflection tables.
	Forms []FormRule `json:"forms,omitempty"`

	// Sections map named regions of the entry onto typed IR fields.
	Sections []SectionRule `json:"sections,omitempty"`

	// WordFamily lists related derived words.
	WordFamily []string `json:"wordFamily,omitempty"`
	// contains filtered or unexported fields
}

Profile is a declarative description of one dictionary's HTML conventions.

A profile never replaces the generic parser: it supplies selectors the generic heuristics would otherwise have to guess at, and anything it leaves unset falls back to generic behaviour. A dictionary with no profile is therefore still usable, just with lower confidence.

func LoadProfiles

func LoadProfiles(data []byte) ([]*Profile, error)

LoadProfiles decodes a JSON array of profiles.

func (*Profile) Compile

func (p *Profile) Compile()

Compile prepares the profile's selectors. It is idempotent.

func (*Profile) Fingerprint

func (p *Profile) Fingerprint(title string, sample *html.Node) int

Fingerprint scores how well this profile matches a dictionary sample. A score of 0 means "does not apply".

type ProfileMatch

type ProfileMatch struct {
	// TitleContains matches against the MDX title or filename.
	TitleContains []string `json:"titleContains,omitempty"`
	// RequireTitle makes a title match mandatory in addition to structural
	// selectors. Use it when sibling products intentionally share one DOM
	// template but require different semantic handling.
	RequireTitle bool `json:"requireTitle,omitempty"`
	// Selectors must all be present in a sample entry. This is the reliable
	// signal; titles vary between repacks of the same dictionary.
	Selectors []string `json:"selectors,omitempty"`
}

ProfileMatch fingerprints a dictionary.

type PronunciationRule

type PronunciationRule struct {
	// Selector picks the node holding the pronunciation.
	Selector []string `json:"selector"`
	// Region is "uk", "us", "other", or "auto" to detect from context.
	Region string `json:"region,omitempty"`
	// IPA is a selector relative to the matched node; empty means the node's
	// own text.
	IPA []string `json:"ipa,omitempty"`
	// Audio names the attribute holding the resource reference, e.g. "href".
	Audio []string `json:"audio,omitempty"`
	// NoAudio marks a rule that contributes a transcription only. Without it a
	// transcription wrapped in an audio link would claim that link, which is
	// how one clip ends up labelled as both British and American.
	NoAudio bool `json:"noAudio,omitempty"`
}

PronunciationRule extracts one pronunciation variant.

type SectionKind

type SectionKind string

SectionKind names the IR field a section feeds.

const (
	SectionIdiom       SectionKind = "idiom"
	SectionPhrase      SectionKind = "phrase"
	SectionPhrasalVerb SectionKind = "phrasalVerb"
	SectionUsage       SectionKind = "usage"
	SectionGrammar     SectionKind = "grammar"
	SectionEtymology   SectionKind = "etymology"
	SectionSynonyms    SectionKind = "synonyms"
	SectionCollocation SectionKind = "collocation"
	SectionGeneric     SectionKind = "generic"
)

type SectionRule

type SectionRule struct {
	Selector []string    `json:"selector"`
	Kind     SectionKind `json:"kind"`
	// Title labels the section in output; defaults to a name derived from Kind.
	Title string `json:"title,omitempty"`
	// Items splits a section holding several entries — a list of idioms, for
	// instance — into one IR entry each.
	Items []string `json:"items,omitempty"`
	// Lemma selects the phrase itself within the section.
	Lemma []string `json:"lemma,omitempty"`
	// Body selects the explanatory content.
	Body []string `json:"body,omitempty"`
	// StripTitle removes this selector's text from the body, for sections whose
	// heading lives inside the block.
	StripTitle []string `json:"stripTitle,omitempty"`
}

SectionRule maps a region of the entry onto a typed section.

type Selector

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

Selector is a compiled CSS-subset selector.

The supported grammar is deliberately small — it is everything the dictionary profiles need and nothing more:

tag            div
class          .Sense
id             #abandon_1
attribute      [href], [class^=phon]
compound       a.speaker.brefile
descendant     .p-g .def-g .d
alternatives   .DEF, .ind

There is no cascade, specificity or pseudo-class support here; this matches nodes, it does not style them.

func ParseSelector

func ParseSelector(raw string) Selector

ParseSelector compiles a selector string. Invalid fragments are dropped rather than raising, so one malformed profile rule cannot break a dictionary.

func ParseSelectors

func ParseSelectors(raws []string) Selector

ParseSelectors compiles a list of selector strings into one Selector whose alternatives are the union of them all.

func (Selector) IsEmpty

func (s Selector) IsEmpty() bool

IsEmpty reports whether the selector matches nothing at all.

func (Selector) Matches

func (s Selector) Matches(node *html.Node) bool

Matches reports whether a node satisfies the selector.

func (Selector) String

func (s Selector) String() string

String returns the original selector text, for diagnostics.

type SemanticLabel

type SemanticLabel string

SemanticLabel identifies headings that dictionaries sometimes place in the same visual slot as a POS even though they introduce a typed section.

const (
	LabelCrossReference SemanticLabel = "crossReference"
	LabelRelated        SemanticLabel = "related"
	LabelPhrase         SemanticLabel = "phrase"
	LabelIdiom          SemanticLabel = "idiom"
	LabelPhrasalVerb    SemanticLabel = "phrasalVerb"
	LabelDerivative     SemanticLabel = "derivative"
	LabelSynonyms       SemanticLabel = "synonyms"
	LabelAntonyms       SemanticLabel = "antonyms"
	LabelExamples       SemanticLabel = "examples"
	LabelCollocations   SemanticLabel = "collocations"
	LabelUsage          SemanticLabel = "usage"
	LabelGrammar        SemanticLabel = "grammar"
)

func ClassifySemanticLabel

func ClassifySemanticLabel(raw string) SemanticLabel

ClassifySemanticLabel returns a section role for a non-POS heading.

type TextOptions

type TextOptions struct {
	// Skip matches nodes whose subtree is excluded entirely.
	Skip Selector
	// SkipNodes excludes specific subtrees by identity, for callers that have
	// already decided which nodes to leave out rather than how to select them.
	SkipNodes map[*html.Node]struct{}
	// SkipHidden drops nodes hidden with inline styles.
	SkipHidden bool
	// Separator is inserted between block-level elements.
	Separator string
}

TextOptions controls text extraction.

Jump to

Keyboard shortcuts

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