diff --git a/docs/manifest.md b/docs/manifest.md index fd956e5..e7353d2 100644 --- a/docs/manifest.md +++ b/docs/manifest.md @@ -47,6 +47,29 @@ It takes one of the following arguments: | `feature` | `MathML` | If the publication contains any resource with MathML (check for the presence of the `contains` property where the value is `mathml` in `readingOrder` or `resources` in RWPM). | | `feature` | `synchronizedAudioText` | If the publication contains any reference to Media Overlays. | | `feature` | `pageBreakMarkers` | :warning: This rule requires the `--inspect-html` flag. If any of the publication's (X)HTML documents contains a page break marker (`epub:type="pagebreak"` or `role="doc-pagebreak"`). | +| `language` | BCP-47 language tags | :warning: This rule requires the `--inspect-html` flag, and is only used with `--infer-a11y=split`: inferred languages are never merged with the authored metadata. The languages declared in the publication's (X)HTML documents (`lang` or `xml:lang`), ordered by the number of strings found in each language, most used first. | + +#### Inferred languages + +The inferred `language` is not part of the accessibility metadata that a publication can declare, which is why it's only available in the inferred accessibility object: + +```sh +readium manifest --inspect-html --infer-a11y=split publication.epub +``` + +```json +"https://readium.org/webpub-manifest#inferredAccessibility": { + "accessMode": ["visual"], + "feature": ["tableOfContents"], + "language": ["fr", "en-US"] +} +``` + +- A string is a block of text (a paragraph, a heading, a list item…), or a run of text in another language inside of one, such as `déjà vu` in an English paragraph. The length of the text is not taken into account. +- Languages with the same number of strings are listed in the order they first appear in the publication. +- Text with no language declared on it or on any of its ancestors is not counted. Nothing is inferred for a publication that doesn't declare any language in its documents. +- Tags are normalized to their canonical form (`en_us` becomes `en-US`, the deprecated `iw` becomes `he`) and keep their region and script, so `en` and `en-US` are two different languages. Tags that are not valid are ignored. +- Like `language` in the publication's metadata, a single language is written as a string instead of an array. ## Inspecting images diff --git a/go.mod b/go.mod index 1ca8b3a..68493a5 100644 --- a/go.mod +++ b/go.mod @@ -28,6 +28,7 @@ require ( github.com/zeebo/xxh3 v1.1.0 golang.org/x/image v0.47.0 golang.org/x/net v0.61.0 + golang.org/x/text v0.43.0 google.golang.org/api v0.307.0 lukechampine.com/blake3 v1.4.1 ) @@ -111,7 +112,6 @@ require ( golang.org/x/oauth2 v0.37.0 // indirect golang.org/x/sync v0.24.0 // indirect golang.org/x/sys v0.49.0 // indirect - golang.org/x/text v0.43.0 // indirect golang.org/x/time v0.16.0 // indirect google.golang.org/genproto v0.0.0-20260715232425-e75dac1f907d // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260715232425-e75dac1f907d // indirect @@ -120,5 +120,3 @@ require ( google.golang.org/protobuf v1.36.12 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) - -// replace github.com/readium/go-toolkit => ../go-toolkit diff --git a/internal/cli/manifest.go b/internal/cli/manifest.go index b807876..00563d3 100644 --- a/internal/cli/manifest.go +++ b/internal/cli/manifest.go @@ -211,6 +211,10 @@ Examples: return fmt.Errorf("publication does not have a %s service, which is required for HTML inspection", pub.GuidedNavigationService_Name) } + // Every HTML inspector reads the guides of the same documents: + // generate each of them only once + service = inspector.CacheGuides(service) + inspectors = append(inspectors, &inspector.ImageUsage{ GuidedNavigationService: service, }) @@ -223,6 +227,14 @@ Examples: Mode: config.InferA11yMetadata, }) } + + // So can the languages of the text. This inference is riskier than + // the others: it's never merged with the publication's own metadata + if config.InferA11yMetadata == streamer.InferA11yMetadataSplit { + inspectors = append(inspectors, &inspector.Languages{ + GuidedNavigationService: service, + }) + } } if len(inspectors) > 0 { @@ -272,5 +284,5 @@ func init() { manifestCmd.Flags().BoolVar(&inspectImagesFlag, "inspect-images", false, "Inspect images in the manifest. Their links will be enhanced with size, width and height, and hashes") manifestCmd.Flags().StringSliceVar(&inferIgnoreImageHashesFlag, "infer-a11y-ignore-image-hashes", nil, "Ignore the given hashes when inferring textual accessibility. Hashes are in the format :, separated by commas.") manifestCmd.Flags().StringVar(&inferIgnoreImageDirectoryFlag, "infer-a11y-ignore-image-dir", "", "Ignore the images in a given directory when inferring textual accessibility.") - manifestCmd.Flags().BoolVar(&inspectHtmlFlag, "inspect-html", false, "When inspecting the manifest, use the (X)HTML of documents to enhance accuracy of metadata. Combined with --infer-a11y, also infers the pageBreakMarkers accessibility feature from page breaks found in the documents") + manifestCmd.Flags().BoolVar(&inspectHtmlFlag, "inspect-html", false, "When inspecting the manifest, use the (X)HTML of documents to enhance accuracy of metadata. Combined with --infer-a11y, also infers the pageBreakMarkers accessibility feature from page breaks found in the documents, and with --infer-a11y=split, the languages of their text") } diff --git a/pkg/inspector/guide_cache.go b/pkg/inspector/guide_cache.go new file mode 100644 index 0000000..8b879f3 --- /dev/null +++ b/pkg/inspector/guide_cache.go @@ -0,0 +1,39 @@ +package inspector + +import ( + "context" + + "github.com/readium/go-toolkit/pkg/guidednavigation" + "github.com/readium/go-toolkit/pkg/pub" +) + +// CacheGuides wraps a guided navigation service so that the guide of each +// resource is generated only once, however many inspectors read it. +// +// Every guide stays in memory for as long as the returned service does, and the +// same document is handed to each caller, which must not modify it. The +// returned service is not safe for concurrent use. +func CacheGuides(service pub.GuidedNavigationService) pub.GuidedNavigationService { + return &cachedGuides{ + GuidedNavigationService: service, + docs: make(map[string]*guidednavigation.GuidedNavigationDocument), + } +} + +type cachedGuides struct { + pub.GuidedNavigationService + docs map[string]*guidednavigation.GuidedNavigationDocument +} + +// GuideForResource implements pub.GuidedNavigationService +func (c *cachedGuides) GuideForResource(ctx context.Context, href string) (*guidednavigation.GuidedNavigationDocument, error) { + if doc, ok := c.docs[href]; ok { + return doc, nil + } + doc, err := c.GuidedNavigationService.GuideForResource(ctx, href) + if err != nil { + return nil, err + } + c.docs[href] = doc + return doc, nil +} diff --git a/pkg/inspector/inferred_a11y.go b/pkg/inspector/inferred_a11y.go new file mode 100644 index 0000000..f3cb1be --- /dev/null +++ b/pkg/inspector/inferred_a11y.go @@ -0,0 +1,36 @@ +package inspector + +import ( + "github.com/readium/go-toolkit/pkg/manifest" +) + +// setInferredA11y sets a single key of the inferred accessibility object stored +// in the metadata's OtherMetadata, creating the object when there is none. +// +// The object's other keys are left as they are. It can hold keys that +// [manifest.A11y] doesn't model, such as the inferred languages, so it must not +// be rewritten from an A11y: that would drop them. +// +// The value has to be in the form decoded JSON takes, like the rest of the +// object: [manifest.Metadata.InferredAccessibility] reads nothing else. For a +// list, that's what [jsonStrings] returns. +func setInferredA11y(metadata *manifest.Metadata, key string, value any) { + inferred, ok := metadata.OtherMetadata[manifest.InferredAccessibilityMetadataKey].(map[string]any) + if !ok { + inferred = make(map[string]any) + if metadata.OtherMetadata == nil { + metadata.OtherMetadata = make(map[string]any) + } + metadata.OtherMetadata[manifest.InferredAccessibilityMetadataKey] = inferred + } + inferred[key] = value +} + +// jsonStrings returns a list of strings in the form decoded JSON takes. +func jsonStrings[T ~string](values []T) []any { + list := make([]any, len(values)) + for i, value := range values { + list[i] = string(value) + } + return list +} diff --git a/pkg/inspector/languages_inspector.go b/pkg/inspector/languages_inspector.go new file mode 100644 index 0000000..c06b8db --- /dev/null +++ b/pkg/inspector/languages_inspector.go @@ -0,0 +1,219 @@ +package inspector + +import ( + "cmp" + "context" + "encoding/xml" + stderrors "errors" + "io" + "slices" + "strings" + + "github.com/pkg/errors" + "github.com/readium/go-toolkit/pkg/guidednavigation" + "github.com/readium/go-toolkit/pkg/manifest" + "github.com/readium/go-toolkit/pkg/pub" + "golang.org/x/text/language" +) + +// Languages infers the list of languages used in a publication's (X)HTML +// documents through their guided navigation representation, and stores it as +// the "language" of the inferred accessibility object in OtherMetadata. +// +// The languages are ordered by the number of strings found in each of them, +// most used first. Languages with the same number of strings keep the order in +// which they were first encountered. A string is either: +// - a guided navigation text, counted in its own language unless all of its +// content is in other languages +// - a run of text in another language inside of a text, which the HTML +// converter expresses in the text's SSML with an xml:lang attribute +// +// Only declared languages are counted: text with no language in effect is +// ignored. Tags are normalized to their canonical BCP-47 form, and region or +// script subtags are kept, so "en" and "en-US" are two different languages. +// +// This inference is riskier than the others, so unlike them it is never merged +// into the publication's own metadata. The inspector always writes to the +// inferred accessibility object, and is only meant to be used when inferred +// accessibility metadata is split from the authored one. +type Languages struct { + GuidedNavigationService pub.GuidedNavigationService + + counts map[string]int // Number of strings for each language + order []string // Languages, in the order they were first encountered + uniqueDocs map[string]struct{} +} + +// Name implements Inspector +func (n *Languages) Name() string { + return "languages" +} + +// InspectHREF implements Inspector +func (n *Languages) InspectHREF(href manifest.HREF) (*manifest.HREF, error) { + // Identity + return nil, nil +} + +// InspectLink implements Inspector +func (n *Languages) InspectLink(link manifest.Link) (*manifest.Link, error) { + if link.MediaType == nil || !link.MediaType.IsHTML() { + return nil, nil + } + + href := link.Href.String() + if n.uniqueDocs == nil { + n.uniqueDocs = make(map[string]struct{}) + } + if _, ok := n.uniqueDocs[href]; ok { + // Already counted this doc + return nil, nil + } + n.uniqueDocs[href] = struct{}{} + + if !n.GuidedNavigationService.HasGuideForResource(href) { + return nil, nil + } + + doc, err := n.GuidedNavigationService.GuideForResource(context.TODO(), href) + if err != nil { + return nil, errors.Wrap(err, "failed loading guide for resource "+href) + } + n.count(doc.Guided) + + return nil, nil +} + +// count adds the strings of the given objects and their descendants. +func (n *Languages) count(objs []guidednavigation.GuidedNavigationObject) { + for i := range objs { + text := objs[i].Text + if text.Plain != "" || text.SSML != "" { + inline, base := ssmlLanguages(text.SSML) + if base { + n.add(text.Language) + } + for _, lang := range inline { + n.add(lang) + } + } + n.count(objs[i].Children) + } +} + +// add counts one more string in the given language. +func (n *Languages) add(tag string) { + lang := normalizeLanguage(tag) + if lang == "" { + return + } + if n.counts == nil { + n.counts = make(map[string]int) + } + if _, ok := n.counts[lang]; !ok { + n.order = append(n.order, lang) + } + n.counts[lang]++ +} + +// normalizeLanguage returns the canonical form of a BCP-47 language tag, or an +// empty string when there is nothing usable in it. A well-formed tag with a +// subtag that doesn't exist is still used, without that subtag. +func normalizeLanguage(tag string) string { + tag = strings.TrimSpace(tag) + if tag == "" { + return "" + } + parsed, err := language.Parse(tag) + if err != nil { + var unknownSubtag language.ValueError + if !stderrors.As(err, &unknownSubtag) { + // Not well-formed + return "" + } + } + // The raw base language: Tag.Base would guess one when there is none + if base, _, _ := parsed.Raw(); base.String() == "und" { + // Undetermined, possibly with a region or script: no language to count + return "" + } + return parsed.String() +} + +const xmlNamespace = "http://www.w3.org/XML/1998/namespace" + +// ssmlLanguages reads the SSML of a guided navigation text. It returns the +// language of each element that declares one with xml:lang, in document order, +// and whether any text is left in the language of the text itself. +// +// The markup is a fragment generated by the HTML converter. If it can't be +// read to the end, what was found until then is returned and the text counts +// as having content in its own language, same as a text with no SSML. +func ssmlLanguages(ssml string) (inline []string, base bool) { + if ssml == "" { + return nil, true + } + + decoder := xml.NewDecoder(strings.NewReader(ssml)) + decoder.Strict = false // The fragment uses the readium: prefix without binding it + + // Whether each open element is in another language than the text's own + var foreign []bool + for { + token, err := decoder.Token() + if err == io.EOF { + return inline, base + } else if err != nil { + return inline, true + } + + switch t := token.(type) { + case xml.StartElement: + inForeign := len(foreign) > 0 && foreign[len(foreign)-1] + for _, attr := range t.Attr { + if attr.Name.Local == "lang" && (attr.Name.Space == xmlNamespace || attr.Name.Space == "xml") && attr.Value != "" { + inline = append(inline, attr.Value) + inForeign = true + break + } + } + foreign = append(foreign, inForeign) + case xml.EndElement: + if len(foreign) > 0 { + foreign = foreign[:len(foreign)-1] + } + case xml.CharData: + if (len(foreign) == 0 || !foreign[len(foreign)-1]) && strings.TrimSpace(string(t)) != "" { + base = true + } + } + } +} + +// InspectManifest implements Inspector +func (n *Languages) InspectManifest(m manifest.Manifest) (*manifest.Manifest, error) { + if len(n.order) == 0 { + return nil, nil + } + + // Most used first. The sort is stable, so ties keep their order of appearance + languages := slices.Clone(n.order) + slices.SortStableFunc(languages, func(a, b string) int { + return cmp.Compare(n.counts[b], n.counts[a]) + }) + + // Like the metadata's own language, a single one is written as a string + if len(languages) == 1 { + setInferredA11y(&m.Metadata, "language", languages[0]) + } else { + setInferredA11y(&m.Metadata, "language", jsonStrings(languages)) + } + + return &m, nil +} + +// InspectMetadata implements Inspector +func (n *Languages) InspectMetadata(metadata manifest.Metadata) (*manifest.Metadata, error) { + // Identity + return nil, nil +} diff --git a/pkg/inspector/languages_inspector_test.go b/pkg/inspector/languages_inspector_test.go new file mode 100644 index 0000000..5ee4ffd --- /dev/null +++ b/pkg/inspector/languages_inspector_test.go @@ -0,0 +1,282 @@ +package inspector + +import ( + "encoding/json" + "testing" + + "github.com/readium/go-toolkit/pkg/guidednavigation" + "github.com/readium/go-toolkit/pkg/manifest" + "github.com/readium/go-toolkit/pkg/mediatype" + "github.com/readium/go-toolkit/pkg/streamer" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// text is a guided navigation text object in the given language. +func text(lang string) guidednavigation.GuidedNavigationObject { + return guidednavigation.GuidedNavigationObject{ + Text: guidednavigation.GuidedNavigationText{Plain: "Some text", Language: lang}, + } +} + +// ssmlText is a guided navigation text object in the given language, with SSML markup. +func ssmlText(lang string, ssml string) guidednavigation.GuidedNavigationObject { + return guidednavigation.GuidedNavigationObject{ + Text: guidednavigation.GuidedNavigationText{Plain: "Some text", SSML: ssml, Language: lang}, + } +} + +func inspectLanguages(t *testing.T, m manifest.Manifest, inspectors ...Inspector) manifest.Manifest { + t.Helper() + run := CreateInspection(inspectors) + result := m.Copy(run) + require.NoError(t, run.Error()) + return result +} + +// inferredLanguage returns the raw "language" value of the inferred accessibility object. +func inferredLanguage(t *testing.T, m manifest.Manifest) any { + t.Helper() + inferred, ok := m.Metadata.OtherMetadata[manifest.InferredAccessibilityMetadataKey].(map[string]any) + if !ok { + return nil + } + return inferred["language"] +} + +func singleDoc(objs ...guidednavigation.GuidedNavigationObject) (*stubGuideService, manifest.Manifest) { + svc := &stubGuideService{docs: map[string]*guidednavigation.GuidedNavigationDocument{"ch1.xhtml": guide(objs...)}} + return svc, manifest.Manifest{ReadingOrder: manifest.LinkList{htmlLink("ch1.xhtml")}} +} + +func TestLanguages_OrderedByStringCount(t *testing.T) { + svc := &stubGuideService{docs: map[string]*guidednavigation.GuidedNavigationDocument{ + // German comes first, but is the least used + "ch1.xhtml": guide(text("de"), text("fr"), text("en")), + "ch2.xhtml": guide( + text("en"), + // Nested, as the HTML converter does for blocks + guidednavigation.GuidedNavigationObject{Children: []guidednavigation.GuidedNavigationObject{ + text("fr"), + {Children: []guidednavigation.GuidedNavigationObject{text("en")}}, + }}, + ), + }} + m := manifest.Manifest{ReadingOrder: manifest.LinkList{htmlLink("ch1.xhtml"), htmlLink("ch2.xhtml")}} + + result := inspectLanguages(t, m, &Languages{GuidedNavigationService: svc}) + + assert.Equal(t, []any{"en", "fr", "de"}, inferredLanguage(t, result)) + assert.Nil(t, result.Metadata.Accessibility) + assert.Empty(t, result.Metadata.Languages, "the publication's own languages are left alone") +} + +func TestLanguages_TiesKeepOrderOfAppearance(t *testing.T) { + svc, m := singleDoc(text("ja"), text("en"), text("fr"), text("en"), text("ja"), text("fr")) + + // Maps are involved: make sure the order doesn't depend on their iteration + for range 20 { + svc.calls = nil + result := inspectLanguages(t, m, &Languages{GuidedNavigationService: svc}) + assert.Equal(t, []any{"ja", "en", "fr"}, inferredLanguage(t, result)) + } +} + +func TestLanguages_SingleLanguageIsAString(t *testing.T) { + svc, m := singleDoc(text("en"), text("en")) + + result := inspectLanguages(t, m, &Languages{GuidedNavigationService: svc}) + + assert.Equal(t, "en", inferredLanguage(t, result)) + + out, err := json.Marshal(result.Metadata.OtherMetadata[manifest.InferredAccessibilityMetadataKey]) + require.NoError(t, err) + assert.JSONEq(t, `{"language": "en"}`, string(out)) +} + +func TestLanguages_NormalizesTags(t *testing.T) { + svc, m := singleDoc( + text("EN-us"), text("en_US"), text(" en-US "), // The same language + text("en"), text("en"), // Not the same as en-US: regions are kept + text("zh-hant-tw"), + text("iw"), // Deprecated code for Hebrew + ) + + result := inspectLanguages(t, m, &Languages{GuidedNavigationService: svc}) + + assert.Equal(t, []any{"en-US", "en", "zh-Hant-TW", "he"}, inferredLanguage(t, result)) +} + +func TestLanguages_IgnoresUndeclaredAndInvalid(t *testing.T) { + svc, m := singleDoc( + text(""), // No language in effect + text("not a tag"), // Not well-formed + text("und"), // Undetermined + text("english"), // Too long to be a language subtag + text("jp"), // Well-formed, but there is no such language (Japanese is "ja") + text("zz-ZZ"), // Same, with a region that does exist + paragraph, pagebreak, // No language either + ) + + result := inspectLanguages(t, m, &Languages{GuidedNavigationService: svc}) + + assert.Equal(t, []string{"ch1.xhtml"}, svc.calls) + assert.Nil(t, result.Metadata.OtherMetadata, "nothing is written when no language is found") +} + +func TestLanguages_UnknownSubtagIsDropped(t *testing.T) { + // Well-formed, but there is no such region or script + svc, m := singleDoc(text("en-QK"), text("en-Abcd"), text("en-GB")) + + result := inspectLanguages(t, m, &Languages{GuidedNavigationService: svc}) + + assert.Equal(t, []any{"en", "en-GB"}, inferredLanguage(t, result)) +} + +func TestLanguages_CountsInlineRuns(t *testing.T) { + svc, m := singleDoc( + // Markup as generated by the HTML converter + ssmlText("en", `This job requires a certain savoir faire that can only be acquired over time.`), + ssmlText("en", `A déjà vu, a je ne sais quoi & some Zeitgeist.`), + text("de"), + text("de"), + ) + + result := inspectLanguages(t, m, &Languages{GuidedNavigationService: svc}) + + // fr: 3 inline runs, en: 2 texts, de: 2 texts and 1 inline run + assert.Equal(t, []any{"fr", "de", "en"}, inferredLanguage(t, result)) +} + +func TestLanguages_TextWhollyInOtherLanguages(t *testing.T) { + svc, m := singleDoc( + // Nothing in this text is in English, despite its base language + ssmlText("en", `Bonjour Guten Tag`), + // Emphasis in the base language still makes it English + ssmlText("en", `Hello Bonjour`), + text("ja"), text("ja"), text("ja"), + ) + + result := inspectLanguages(t, m, &Languages{GuidedNavigationService: svc}) + + // ja: 3, fr: 2, then de and en with 1 each, in order of appearance + assert.Equal(t, []any{"ja", "fr", "de", "en"}, inferredLanguage(t, result)) +} + +func TestLanguages_BrokenSSMLStillCountsText(t *testing.T) { + // No text in English was seen before the markup breaks, but it can't be ruled out + svc, m := singleDoc(ssmlText("en", `Bonjour `)) + + result := inspectLanguages(t, m, &Languages{GuidedNavigationService: svc}) + + // A text's own language is counted before its inline runs + assert.Equal(t, []any{"en", "fr"}, inferredLanguage(t, result)) +} + +func TestLanguages_KeepsExistingInferred(t *testing.T) { + svc, m := singleDoc(text("en"), text("fr"), text("en")) + m.Metadata.OtherMetadata = map[string]any{"other": "value"} + // What the streamer's own inference would have stored + require.NoError(t, m.Metadata.SetOtherMetadata(manifest.InferredAccessibilityMetadataKey, &manifest.A11y{ + AccessModes: []manifest.A11yAccessMode{manifest.A11yAccessModeVisual}, + Features: []manifest.A11yFeature{manifest.A11yFeatureTableOfContents}, + })) + + result := inspectLanguages(t, m, &Languages{GuidedNavigationService: svc}) + + assert.Equal(t, []any{"en", "fr"}, inferredLanguage(t, result)) + assert.Equal(t, "value", result.Metadata.OtherMetadata["other"]) + inferred := result.Metadata.InferredAccessibility() + require.NotNil(t, inferred) + assert.Equal(t, []manifest.A11yAccessMode{manifest.A11yAccessModeVisual}, inferred.AccessModes) + assert.Equal(t, []manifest.A11yFeature{manifest.A11yFeatureTableOfContents}, inferred.Features) +} + +// The inferred accessibility object is shared between inspectors: neither of +// them may drop what the other one wrote, whichever runs first. +func TestLanguages_WithPageBreakMarkers(t *testing.T) { + newInspectors := func(svc *stubGuideService) (Inspector, Inspector) { + return &Languages{GuidedNavigationService: svc}, + &PageBreakMarkers{GuidedNavigationService: svc, Mode: streamer.InferA11yMetadataSplit} + } + + for name, order := range map[string]func(languages, pageBreaks Inspector) []Inspector{ + "languages first": func(l, p Inspector) []Inspector { return []Inspector{l, p} }, + "page breaks first": func(l, p Inspector) []Inspector { return []Inspector{p, l} }, + } { + t.Run(name, func(t *testing.T) { + svc, m := singleDoc(text("en"), pagebreak, text("fr"), text("en")) + m.Metadata.OtherMetadata = map[string]any{} + require.NoError(t, m.Metadata.SetOtherMetadata(manifest.InferredAccessibilityMetadataKey, &manifest.A11y{ + Features: []manifest.A11yFeature{manifest.A11yFeatureTableOfContents}, + })) + + result := inspectLanguages(t, m, order(newInspectors(svc))...) + + assert.Equal(t, []any{"en", "fr"}, inferredLanguage(t, result)) + inferred := result.Metadata.InferredAccessibility() + require.NotNil(t, inferred) + assert.Equal(t, []manifest.A11yFeature{manifest.A11yFeatureTableOfContents, manifest.A11yFeaturePageBreakMarkers}, inferred.Features) + }) + } +} + +func TestLanguages_ScansEachDocumentOnce(t *testing.T) { + svc := &stubGuideService{docs: map[string]*guidednavigation.GuidedNavigationDocument{"ch1.xhtml": guide(text("en"), text("fr"), text("fr"))}} + doc := htmlLink("ch1.xhtml") + img := manifest.Link{Href: manifest.MustNewHREFFromString("cover.png", false), MediaType: &mediatype.PNG} + m := manifest.Manifest{ + ReadingOrder: manifest.LinkList{doc, img}, + Resources: manifest.LinkList{doc}, + TableOfContents: manifest.LinkList{doc}, + } + + result := inspectLanguages(t, m, &Languages{GuidedNavigationService: svc}) + + assert.Equal(t, []string{"ch1.xhtml"}, svc.calls) + // Counted three times, English would come first + assert.Equal(t, []any{"fr", "en"}, inferredLanguage(t, result)) +} + +func TestLanguages_PropagatesConversionError(t *testing.T) { + svc := &stubGuideService{docs: map[string]*guidednavigation.GuidedNavigationDocument{"ch1.xhtml": nil}} + m := manifest.Manifest{ReadingOrder: manifest.LinkList{htmlLink("ch1.xhtml")}} + + run := CreateInspection([]Inspector{&Languages{GuidedNavigationService: svc}}) + m.Copy(run) + + require.Error(t, run.Error()) + assert.Contains(t, run.Error().Error(), "languages") + assert.Contains(t, run.Error().Error(), "failed converting ch1.xhtml") +} + +func TestCacheGuides_GeneratesEachGuideOnce(t *testing.T) { + svc := &stubGuideService{docs: map[string]*guidednavigation.GuidedNavigationDocument{ + "ch1.xhtml": guide(text("en")), + "ch2.xhtml": guide(text("fr"), text("fr")), + }} + cached := CacheGuides(svc) + m := manifest.Manifest{ReadingOrder: manifest.LinkList{htmlLink("ch1.xhtml"), htmlLink("ch2.xhtml")}} + + result := inspectLanguages(t, m, + &ImageUsage{GuidedNavigationService: cached}, + &PageBreakMarkers{GuidedNavigationService: cached, Mode: streamer.InferA11yMetadataSplit}, + &Languages{GuidedNavigationService: cached}, + ) + + assert.Equal(t, []string{"ch1.xhtml", "ch2.xhtml"}, svc.calls) + assert.Equal(t, []any{"fr", "en"}, inferredLanguage(t, result)) + assert.False(t, cached.HasGuideForResource("missing.xhtml")) +} + +func TestCacheGuides_DoesNotCacheErrors(t *testing.T) { + svc := &stubGuideService{docs: map[string]*guidednavigation.GuidedNavigationDocument{"ch1.xhtml": nil}} + cached := CacheGuides(svc) + + _, err := cached.GuideForResource(t.Context(), "ch1.xhtml") + require.Error(t, err) + _, err = cached.GuideForResource(t.Context(), "ch1.xhtml") + require.Error(t, err) + + assert.Equal(t, []string{"ch1.xhtml", "ch1.xhtml"}, svc.calls) +} diff --git a/pkg/inspector/page_break_markers_inspector.go b/pkg/inspector/page_break_markers_inspector.go index 6e2db81..e22fa2e 100644 --- a/pkg/inspector/page_break_markers_inspector.go +++ b/pkg/inspector/page_break_markers_inspector.go @@ -111,12 +111,9 @@ func (n *PageBreakMarkers) InspectManifest(m manifest.Manifest) (*manifest.Manif a11y = &manifest.A11y{} } a11y.Merge(inferred) - if m.Metadata.OtherMetadata == nil { - m.Metadata.OtherMetadata = make(map[string]any) - } - if err := m.Metadata.SetOtherMetadata(manifest.InferredAccessibilityMetadataKey, a11y); err != nil { - return nil, errors.Wrap(err, "failed storing inferred accessibility metadata") - } + // Only the features changed, and only they are written back: the + // inferred object can hold keys that A11y doesn't model + setInferredA11y(&m.Metadata, "feature", jsonStrings(a11y.Features)) default: return nil, nil