| 1 |
// Copyright 2024 Google LLC |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
package tokenizer |
| 15 |
|
| 16 |
import ( |
| 17 |
"archive/zip" |
| 18 |
"bytes" |
| 19 |
"context" |
| 20 |
"fmt" |
| 21 |
"io" |
| 22 |
"log" |
| 23 |
"net/http" |
| 24 |
"os" |
| 25 |
"strings" |
| 26 |
"sync" |
| 27 |
"testing" |
| 28 |
|
| 29 |
"cloud.google.com/go/vertexai/genai" |
| 30 |
|
| 31 |
"golang.org/x/text/encoding" |
| 32 |
"golang.org/x/text/encoding/charmap" |
| 33 |
"golang.org/x/text/encoding/japanese" |
| 34 |
"golang.org/x/text/encoding/simplifiedchinese" |
| 35 |
"golang.org/x/text/transform" |
| 36 |
) |
| 37 |
|
| 38 |
// corporaInfo holds the name and content of a file in the zip archive |
| 39 |
type corporaInfo struct { |
| 40 |
Name string |
| 41 |
Content []byte |
| 42 |
} |
| 43 |
|
| 44 |
// corporaGenerator is a helper function that downloads a zip archive from a given URL, |
| 45 |
// extracts the content of each file in the archive, |
| 46 |
// and returns a slice of corporaInfo objects containing the name and content of each file. |
| 47 |
func corporaGenerator(url string) ([]corporaInfo, error) { |
| 48 |
var corpora []corporaInfo |
| 49 |
|
| 50 |
// Download the zip file |
| 51 |
resp, err := http.Get(url) |
| 52 |
if err != nil { |
| 53 |
return nil, fmt.Errorf("error downloading file: %v", err) |
| 54 |
} |
| 55 |
defer resp.Body.Close() |
| 56 |
|
| 57 |
// Read the content of the response body |
| 58 |
body, err := io.ReadAll(resp.Body) |
| 59 |
if err != nil { |
| 60 |
return nil, fmt.Errorf("error reading response body: %v", err) |
| 61 |
} |
| 62 |
|
| 63 |
// Create a zip reader from the downloaded content |
| 64 |
zipReader, err := zip.NewReader(bytes.NewReader(body), int64(len(body))) |
| 65 |
if err != nil { |
| 66 |
return nil, fmt.Errorf("error creating zip reader: %v", err) |
| 67 |
} |
| 68 |
|
| 69 |
// Iterate over each file in the zip archive |
| 70 |
for _, file := range zipReader.File { |
| 71 |
fileReader, err := file.Open() |
| 72 |
if err != nil { |
| 73 |
return nil, fmt.Errorf("error opening file: %v", err) |
| 74 |
} |
| 75 |
|
| 76 |
// Check if the file is a text file |
| 77 |
if !file.FileInfo().IsDir() && file.FileInfo().Mode().IsRegular() { |
| 78 |
content, err := io.ReadAll(fileReader) |
| 79 |
fileReader.Close() |
| 80 |
if err != nil { |
| 81 |
return nil, fmt.Errorf("error reading file content: %v", err) |
| 82 |
} |
| 83 |
|
| 84 |
corpora = append(corpora, corporaInfo{ |
| 85 |
Name: file.Name[len("udhr/"):], |
| 86 |
Content: content, |
| 87 |
}) |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
return corpora, nil |
| 92 |
} |
| 93 |
|
| 94 |
// udhrCorpus represents the Universal Declaration of Human Rights (UDHR) corpus. |
| 95 |
// This corpus contains translations of the UDHR into many languages, |
| 96 |
// stored in a specific directory structure within a zip archive. |
| 97 |
// |
| 98 |
// The files in the corpus USUALLY follow a naming convention: |
| 99 |
// |
| 100 |
// <Language>_<Script>-<Encoding> |
| 101 |
// |
| 102 |
// For example: |
| 103 |
// - English_English-UTF8 |
| 104 |
// - French_Français-Latin1 |
| 105 |
// - Spanish_Español-UTF8 |
| 106 |
// |
| 107 |
// The Language and Script parts are self-explanatory. |
| 108 |
// The Encoding part indicates the character encoding used in the file. |
| 109 |
// |
| 110 |
// This corpus is used to test the token counting functionality |
| 111 |
// against a diverse set of languages and encodings. |
| 112 |
type udhrCorpus struct { |
| 113 |
EncodingByFileSuffix map[string]encoding.Encoding |
| 114 |
EncodingByFilename map[string]encoding.Encoding |
| 115 |
|
| 116 |
// Skip lists files that should be skipped during testing. |
| 117 |
// This is useful for excluding files that are known to cause issues |
| 118 |
// or are not relevant for the test. |
| 119 |
Skip map[string]bool |
| 120 |
} |
| 121 |
|
| 122 |
// newUdhrCorpus initializes a new udhrCorpus with encoding patterns and skip set |
| 123 |
// func newUdhrCorpus() *udhrCorpus { |
| 124 |
func newUdhrCorpus() *udhrCorpus { |
| 125 |
|
| 126 |
EncodingByFileSuffix := map[string]encoding.Encoding{ |
| 127 |
"Latin1": charmap.ISO8859_1, |
| 128 |
"Hebrew": charmap.ISO8859_8, |
| 129 |
"Arabic": charmap.Windows1256, |
| 130 |
"UTF8": encoding.Nop, |
| 131 |
"Cyrillic": charmap.Windows1251, |
| 132 |
"SJIS": japanese.ShiftJIS, |
| 133 |
"GB2312": simplifiedchinese.HZGB2312, |
| 134 |
"Latin2": charmap.ISO8859_2, |
| 135 |
"Greek": charmap.ISO8859_7, |
| 136 |
"Turkish": charmap.ISO8859_9, |
| 137 |
"Baltic": charmap.ISO8859_4, |
| 138 |
"EUC": japanese.EUCJP, |
| 139 |
"VPS": charmap.Windows1258, |
| 140 |
"Agra": encoding.Nop, |
| 141 |
"T61": charmap.ISO8859_3, |
| 142 |
} |
| 143 |
|
| 144 |
// For non-conventional filenames: |
| 145 |
EncodingByFilename := map[string]encoding.Encoding{ |
| 146 |
"Czech_Cesky-UTF8": charmap.Windows1250, |
| 147 |
"Polish-Latin2": charmap.Windows1250, |
| 148 |
"Polish_Polski-Latin2": charmap.Windows1250, |
| 149 |
"Amahuaca": charmap.ISO8859_1, |
| 150 |
"Turkish_Turkce-Turkish": charmap.ISO8859_9, |
| 151 |
"Lithuanian_Lietuviskai-Baltic": charmap.ISO8859_4, |
| 152 |
"Abkhaz-Cyrillic+Abkh": charmap.Windows1251, |
| 153 |
"Azeri_Azerbaijani_Cyrillic-Az.Times.Cyr.Normal0117": charmap.Windows1251, |
| 154 |
"Azeri_Azerbaijani_Latin-Az.Times.Lat0117": charmap.ISO8859_2, |
| 155 |
} |
| 156 |
|
| 157 |
// The skip list comes from the NLTK source code which says these are unsupported encodings, |
| 158 |
// or in general encodings Go doesn't support. |
| 159 |
// See NLTK source code reference: https://github.com/nltk/nltk/blob/f6567388b4399000b9aa2a6b0db713bff3fe332a/nltk/corpus/reader/udhr.py#L14 |
| 160 |
Skip := map[string]bool{ |
| 161 |
// The following files are not fully decodable because they |
| 162 |
// were truncated at wrong bytes: |
| 163 |
"Burmese_Myanmar-UTF8": true, |
| 164 |
"Japanese_Nihongo-JIS": true, |
| 165 |
"Chinese_Mandarin-HZ": true, |
| 166 |
"Chinese_Mandarin-UTF8": true, |
| 167 |
"Gujarati-UTF8": true, |
| 168 |
"Hungarian_Magyar-Unicode": true, |
| 169 |
"Lao-UTF8": true, |
| 170 |
"Magahi-UTF8": true, |
| 171 |
"Marathi-UTF8": true, |
| 172 |
"Tamil-UTF8": true, |
| 173 |
"Magahi-Agrarpc": true, |
| 174 |
"Magahi-Agra": true, |
| 175 |
// encoding not supported in Go. |
| 176 |
"Vietnamese-VIQR": true, |
| 177 |
"Vietnamese-TCVN": true, |
| 178 |
// The following files are encoded for specific fonts: |
| 179 |
"Burmese_Myanmar-WinResearcher": true, |
| 180 |
"Armenian-DallakHelv": true, |
| 181 |
"Tigrinya_Tigrigna-VG2Main": true, |
| 182 |
"Amharic-Afenegus6..60375": true, |
| 183 |
"Navaho_Dine-Navajo-Navaho-font": true, |
| 184 |
// The following files are unintended: |
| 185 |
"Czech-Latin2-err": true, |
| 186 |
"Russian_Russky-UTF8~": true, |
| 187 |
} |
| 188 |
|
| 189 |
return &udhrCorpus{ |
| 190 |
EncodingByFileSuffix: EncodingByFileSuffix, |
| 191 |
EncodingByFilename: EncodingByFilename, |
| 192 |
Skip: Skip, |
| 193 |
} |
| 194 |
} |
| 195 |
|
| 196 |
// getEncoding returns the encoding for a given filename based on patterns |
| 197 |
func (ucr *udhrCorpus) getEncoding(filename string) (encoding.Encoding, bool) { |
| 198 |
if enc, exists := ucr.EncodingByFilename[filename]; exists { |
| 199 |
return enc, true |
| 200 |
} |
| 201 |
|
| 202 |
parts := strings.Split(filename, "-") |
| 203 |
encodingKey := parts[len(parts)-1] |
| 204 |
if enc, exists := ucr.EncodingByFileSuffix[encodingKey]; exists { |
| 205 |
return enc, true |
| 206 |
} |
| 207 |
|
| 208 |
return nil, false |
| 209 |
} |
| 210 |
|
| 211 |
// shouldSkip checks if the file should be skipped |
| 212 |
func (ucr *udhrCorpus) shouldSkip(filename string) bool { |
| 213 |
return ucr.Skip[filename] |
| 214 |
} |
| 215 |
|
| 216 |
// decodeBytes decodes the given byte slice using the specified encoding |
| 217 |
func decodeBytes(enc encoding.Encoding, content []byte) (string, error) { |
| 218 |
decodedBytes, _, err := transform.Bytes(enc.NewDecoder(), content) |
| 219 |
if err != nil { |
| 220 |
return "", fmt.Errorf("error decoding bytes: %v", err) |
| 221 |
} |
| 222 |
return string(decodedBytes), nil |
| 223 |
} |
| 224 |
|
| 225 |
const defaultModel = "gemini-1.0-pro" |
| 226 |
const defaultLocation = "us-central1" |
| 227 |
|
| 228 |
func TestCountTokensWithCorpora(t *testing.T) { |
| 229 |
projectID := os.Getenv("VERTEX_PROJECT_ID") |
| 230 |
if testing.Short() { |
| 231 |
t.Skip("skipping live test in -short mode") |
| 232 |
} |
| 233 |
|
| 234 |
if projectID == "" { |
| 235 |
t.Skip("set a VERTEX_PROJECT_ID env var to run live tests") |
| 236 |
} |
| 237 |
ctx := context.Background() |
| 238 |
client, err := genai.NewClient(ctx, projectID, defaultLocation) |
| 239 |
if err != nil { |
| 240 |
t.Fatal(err) |
| 241 |
} |
| 242 |
defer client.Close() |
| 243 |
model := client.GenerativeModel(defaultModel) |
| 244 |
ucr := newUdhrCorpus() |
| 245 |
|
| 246 |
tok, err := New(defaultModel) |
| 247 |
if err != nil { |
| 248 |
log.Fatal(err) |
| 249 |
} |
| 250 |
|
| 251 |
corporaURL := "https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages/corpora/udhr.zip" |
| 252 |
corporaFiles, err := corporaGenerator(corporaURL) |
| 253 |
if err != nil { |
| 254 |
t.Fatalf("Failed to generate corpora: %v", err) |
| 255 |
} |
| 256 |
|
| 257 |
// Manage up to 10 corpora run simultaneously |
| 258 |
workLimiter := make(chan struct{}, 10) |
| 259 |
defer close(workLimiter) |
| 260 |
var wg sync.WaitGroup |
| 261 |
for _, corpora := range corporaFiles { |
| 262 |
wg.Add(1) |
| 263 |
go func(corpora corporaInfo) { |
| 264 |
workLimiter <- struct{}{} |
| 265 |
defer func() { |
| 266 |
<-workLimiter |
| 267 |
wg.Done() |
| 268 |
}() |
| 269 |
if ucr.shouldSkip(corpora.Name) { |
| 270 |
log.Printf("Skipping file: %s\n", corpora.Name) |
| 271 |
return |
| 272 |
} |
| 273 |
|
| 274 |
enc, found := ucr.getEncoding(corpora.Name) |
| 275 |
if !found { |
| 276 |
log.Printf("No encoding found for file: %s\n", corpora.Name) |
| 277 |
return |
| 278 |
} |
| 279 |
|
| 280 |
decodedContent, err := decodeBytes(enc, corpora.Content) |
| 281 |
if err != nil { |
| 282 |
log.Fatalf("Failed to decode bytes: %v", err) |
| 283 |
} |
| 284 |
|
| 285 |
localNtoks, err := tok.CountTokens(genai.Text(decodedContent)) |
| 286 |
if err != nil { |
| 287 |
log.Fatal(err) |
| 288 |
} |
| 289 |
remoteNtoks, err := model.CountTokens(ctx, genai.Text(decodedContent)) |
| 290 |
if err != nil { |
| 291 |
log.Fatal(corpora.Name, err) |
| 292 |
} |
| 293 |
if localNtoks.TotalTokens != remoteNtoks.TotalTokens { |
| 294 |
t.Errorf("expected %d(remote count-token results), but got %d(local count-token results)", remoteNtoks, localNtoks) |
| 295 |
} |
| 296 |
}(corpora) |
| 297 |
} |
| 298 |
wg.Wait() |
| 299 |
} |