git » firstones » main » tree

[main] / ipa_test.go

package main

import (
	"bytes"
	"maps"
	"os"
	"slices"
	"strings"
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
)

func TestMapSyllables(t *testing.T) {
	// Glyphs for convenience.
	g1, g2 := mustGetGlyph("SH"), mustGetGlyph("fEEt")
	g3, g4 := mustGetGlyph("R"), mustGetGlyph("All")
	g5, g6 := mustGetGlyph("S"), mustGetGlyph("hOUse")

	cases := []struct {
		glyphs   []Glyph
		slashes  []int
		wlen     int
		expected Word
	}{
		{
			// No slashes.
			glyphs:   []Glyph{g1, g2, g3, g4, g5, g6},
			slashes:  []int{},
			wlen:     8,
			expected: Word{{g1, g2, g3, g4, g5, g6}},
		},
		// Same length as the original word, all possible location for a
		// single slash.
		{
			glyphs:   []Glyph{g1, g2, g3, g4},
			slashes:  []int{0},
			wlen:     4,
			expected: Word{{g1}, {g2, g3, g4}},
		},
		{
			glyphs:   []Glyph{g1, g2, g3, g4},
			slashes:  []int{1},
			wlen:     4,
			expected: Word{{g1}, {g2, g3, g4}},
		},
		{
			glyphs:   []Glyph{g1, g2, g3, g4},
			slashes:  []int{2},
			wlen:     4,
			expected: Word{{g1, g2}, {g3, g4}},
		},
		{
			glyphs:   []Glyph{g1, g2, g3, g4},
			slashes:  []int{3},
			wlen:     4,
			expected: Word{{g1, g2, g3}, {g4}},
		},
		{
			glyphs:   []Glyph{g1, g2, g3, g4},
			slashes:  []int{4},
			wlen:     4,
			expected: Word{{g1, g2, g3}, {g4}},
		},
		{
			// Longer word, with a slash > len(glyphs).
			glyphs:   []Glyph{g1, g2, g3, g4},
			slashes:  []int{6},
			wlen:     8,
			expected: Word{{g1, g2, g3}, {g4}},
		},
		{
			// Slash at 0. This is a special case, where the first syllable is
			// the first glyph.
			glyphs:   []Glyph{g1, g2, g3, g4},
			slashes:  []int{0},
			wlen:     8,
			expected: Word{{g1}, {g2, g3, g4}},
		},
		{
			// Slash at wlen. This is a special case, where the last syllable
			// is the last glyph.
			glyphs:   []Glyph{g1, g2, g3, g4},
			slashes:  []int{8},
			wlen:     8,
			expected: Word{{g1, g2, g3}, {g4}},
		},
		{
			// Multiple slashes.
			glyphs:   []Glyph{g1, g2, g3, g4, g5, g6},
			slashes:  []int{2, 4},
			wlen:     6,
			expected: Word{{g1, g2}, {g3, g4}, {g5, g6}},
		},
		{
			// Multiple slashes in the exact same place.
			glyphs:   []Glyph{g1, g2, g3, g4, g5, g6},
			slashes:  []int{2, 2, 4, 4},
			wlen:     6,
			expected: Word{{g1, g2}, {g3, g4}, {g5, g6}},
		},
		{
			// Multiple slashes, with wlen != len(glyphs).
			glyphs:   []Glyph{g1, g2, g3, g4, g5, g6},
			slashes:  []int{6, 7},
			wlen:     12,
			expected: Word{{g1, g2, g3}, {g4, g5, g6}},
		},
	}
	for i, c := range cases {
		result := mapSyllables(c.glyphs, c.slashes, c.wlen)
		t.Logf("%d: %v %v %d -> %v", i, c.glyphs, c.slashes, c.wlen, result)

		diff := cmp.Diff(c.expected, result,
			cmpopts.EquateComparable(Glyph{}))
		if diff != "" {
			t.Errorf("%d: Mismatch in syllables:\n%s", i, diff)
		}
	}
}

// TestLookups checks that words are resolved consistently, regardless of
// which source they come from (namesIPA or one of the dictionaries), how they
// are spelled, and how the language is selected.
func TestLookups(t *testing.T) {
	cases := []struct {
		word string
		// Language prefixes that must all resolve to `want`. The empty string
		// means no prefix, so the language is detected automatically.
		langs []string
		want  string
		// Language prefixes that must not resolve at all.
		fails []string
	}{
		// namesIPA entries are hand-curated, and reachable from every
		// supported language.
		{
			word:  "catra",
			langs: []string{"", "en", "en-US", "en-GB", "es", "es-MX"},
			want:  "K-sAd-T-R-sAd",
		}, {
			word:  "she-ra",
			langs: []string{"", "en", "es"},
			want:  "SH-fEEt-R-All",
		}, {
			// Also in en_US, as /ˈbaʊ/ (B-hOUse); the name must win.
			word:  "bow",
			langs: []string{"", "en", "es"},
			want:  "B-gO",
		}, {
			// Same, but shadowing an es_MX entry (/sea/, S-sAy-sAd).
			word:  "sea",
			langs: []string{"", "en", "es"},
			want:  "S-fEEt",
		},

		// Dictionary entries: only available in their own language, and
		// picked up by automatic detection.
		{
			word:  "hello",
			langs: []string{"", "en", "en-US", "en-GB"},
			want:  "H-fUn-L-gO",
			fails: []string{"es", "es-MX", "fr"},
		}, {
			word:  "gato",
			langs: []string{"", "es", "es-MX", "es-ES"},
			want:  "G-sAd-T-All",
			fails: []string{"en", "en-US", "fr"},
		},

		// Words in both dictionaries keep their per-language pronunciation.
		// Automatic detection prefers es, as it is tried first.
		{
			word:  "casa",
			langs: []string{"", "es", "es-MX"},
			want:  "K-sAd-S-sAd",
		}, {
			word:  "casa",
			langs: []string{"en", "en-US"},
			want:  "K-All-S-fUn",
		},
	}

	withLang := func(lang, word string) string {
		if lang == "" {
			return word
		}
		return lang + ":" + word
	}

	for _, c := range cases {
		// Lookups are case-insensitive, so every spelling must behave the
		// same way.
		for _, w := range []string{
			c.word,
			strings.ToUpper(c.word[:1]) + c.word[1:],
			strings.ToUpper(c.word),
		} {
			for _, lang := range c.langs {
				in := withLang(lang, w)
				got, err := SmartWordToGlyphs(in)
				switch {
				case err != nil:
					t.Errorf("%q: unexpected error: %v", in, err)
				case got.String() != c.want:
					t.Errorf("%q: got %q, want %q", in, got, c.want)
				}
			}
			for _, lang := range c.fails {
				in := withLang(lang, w)
				if got, err := SmartWordToGlyphs(in); err == nil {
					t.Errorf("%q: expected an error, got %q", in, got)
				}
			}
		}
	}
}

// sampleWords takes n words spread evenly over the given dictionary file.
//
// We read the file directly, instead of going through the dictionaries,
// for two reasons: map iteration order is random, and we want the same words
// on every run; and it keeps the benchmark independent of how the
// dictionaries are embedded and parsed, so results remain comparable across
// changes to that.
func sampleWords(b *testing.B, fname string, n int) []string {
	contents, err := os.ReadFile(fname)
	if err != nil {
		b.Fatal(err)
	}

	every := max(bytes.Count(contents, []byte("\n"))/n, 1)
	words := []string{}
	i := 0
	for line := range strings.Lines(string(contents)) {
		if i%every == 0 {
			if w, _, ok := strings.Cut(line, "\t"); ok {
				words = append(words, w)
			}
		}
		i++
	}
	return words
}

// BenchmarkSmartWordToGlyphs measures the word -> glyphs conversion.
// Note the set of words is small enough to stay in cache, so this measures the
// conversion itself, and not the cost of reaching into a cold dictionary.
func BenchmarkSmartWordToGlyphs(b *testing.B) {
	// A varied mix, with no single source dominating: the character names,
	// and a sample of each dictionary. Both languages are represented, so we
	// cover the words that are found on the first try, as well as the ones
	// that need a failed lookup in the other dictionary first.
	words := slices.Sorted(maps.Keys(namesIPA))
	for _, f := range []string{"ipa/en_US.txt", "ipa/es_MX.txt"} {
		words = append(words, sampleWords(b, f, 100)...)
	}

	i := 0
	for b.Loop() {
		SmartWordToGlyphs(words[i%len(words)])
		i++
	}
}