Documentation
¶
Overview ¶
Package parser turns heterogeneous dictionary HTML into the Entry IR.
Index ¶
- Constants
- func Ancestors(node *html.Node) []*html.Node
- func Attr(node *html.Node, name string) string
- func AttrOK(node *html.Node, name string) (string, bool)
- func CanonicalForm(raw string) string
- func CanonicalPOS(raw string) string
- func CanonicalPOSVocabulary() []string
- func ClassSet(node *html.Node) map[string]struct{}
- func CleanIPA(raw string) string
- func DescriptorText(node *html.Node) string
- func DetectRegion(descriptors ...string) entryir.Region
- func HeadwordMatchesKey(headword, key string) bool
- func IsKnownLabel(raw string) bool
- func LooksLikeIPA(raw string) bool
- func Normalize(text string) string
- func Parse(raw []byte, opts Options) (*entryir.Entry, error)
- func ParseSenseNumber(raw string) string
- func Query(root *html.Node, sel Selector) *html.Node
- func QueryAll(root *html.Node, sel Selector) []*html.Node
- func QueryAllNested(root *html.Node, sel Selector) []*html.Node
- func RemoveMatching(root *html.Node, sel Selector) int
- func ScopedVisibleText(raw []byte, profile *Profile) string
- func Text(node *html.Node, opts TextOptions) string
- func VisibleText(raw []byte) string
- func Walk(root *html.Node, visit func(*html.Node) bool)
- type AudioResolver
- type AudioResolverFunc
- type FormRule
- type ImageResolver
- type ImageResolverFunc
- type Options
- type Profile
- type ProfileMatch
- type PronunciationRule
- type SectionKind
- type SectionRule
- type Selector
- type SemanticLabel
- type TextOptions
Constants ¶
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 CanonicalForm ¶
CanonicalForm normalizes an inflection label, returning "" when unrecognised.
func CanonicalPOS ¶
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 DescriptorText ¶
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 ¶
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
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 ¶
IsKnownLabel reports whether text reads as a dictionary usage label.
func LooksLikeIPA ¶
LooksLikeIPA reports whether text is plausibly a phonetic transcription.
func ParseSenseNumber ¶
ParseSenseNumber extracts a sense number from a label, or "" if it is prose.
func QueryAll ¶
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 ¶
QueryAllNested behaves like QueryAll but also descends into matches, which is needed where subsenses share their parent's class.
func RemoveMatching ¶
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
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
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.
Types ¶
type AudioResolver ¶
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 ¶
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
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
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"`
// PresentationCSS is a stylesheet for the dictionary-layout Markdown view,
// applied after the dictionary's own. It hides interface chrome that stays
// visible even with the real stylesheet — tab labels of collapsed panels,
// toggle buttons, script-drawn charts. It is not a substitute for a
// missing stylesheet, and deliberately not Ignore, which serves the parser
// and drops content the page view must keep, such as the printed headword.
PresentationCSS string `json:"presentationCSS,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 ¶
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 ¶
Fingerprint scores how well this profile matches a dictionary sample. A score of 0 means "does not apply".
func (*Profile) PresentationScope ¶ added in v1.3.0
PresentationScope narrows a parsed record for the dictionary-layout view to the profile's entry root. A nil profile leaves the document whole.
Root applies here for the same reason it applies to parsing: a record that ships several regional editions of one entry should show one of them.
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 ¶
ParseSelector compiles a selector string. Invalid fragments are dropped rather than raising, so one malformed profile rule cannot break a dictionary.
func ParseSelectors ¶
ParseSelectors compiles a list of selector strings into one Selector whose alternatives are the union of them all.
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, or text nodes, 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.