Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/manifest.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<i lang="fr">déjà vu</i>` 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

Expand Down
4 changes: 1 addition & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down Expand Up @@ -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
Expand All @@ -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
14 changes: 13 additions & 1 deletion internal/cli/manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})
Expand All @@ -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 {
Expand Down Expand Up @@ -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 <algorithm>:<base64 value>, 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")
}
39 changes: 39 additions & 0 deletions pkg/inspector/guide_cache.go
Original file line number Diff line number Diff line change
@@ -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
}
36 changes: 36 additions & 0 deletions pkg/inspector/inferred_a11y.go
Original file line number Diff line number Diff line change
@@ -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
}
219 changes: 219 additions & 0 deletions pkg/inspector/languages_inspector.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading