// Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tokenizer import ( "archive/zip" "bytes" "context" "fmt" "io" "log" "net/http" "os" "strings" "sync" "testing" "cloud.google.com/go/vertexai/genai" "golang.org/x/text/encoding" "golang.org/x/text/encoding/charmap" "golang.org/x/text/encoding/japanese" "golang.org/x/text/encoding/simplifiedchinese" "golang.org/x/text/transform" ) // corporaInfo holds the name and content of a file in the zip archive type corporaInfo struct { Name string Content []byte } // corporaGenerator is a helper function that downloads a zip archive from a given URL, // extracts the content of each file in the archive, // and returns a slice of corporaInfo objects containing the name and content of each file. func corporaGenerator(url string) ([]corporaInfo, error) { var corpora []corporaInfo // Download the zip file resp, err := http.Get(url) if err != nil { return nil, fmt.Errorf("error downloading file: %v", err) } defer resp.Body.Close() // Read the content of the response body body, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("error reading response body: %v", err) } // Create a zip reader from the downloaded content zipReader, err := zip.NewReader(bytes.NewReader(body), int64(len(body))) if err != nil { return nil, fmt.Errorf("error creating zip reader: %v", err) } // Iterate over each file in the zip archive for _, file := range zipReader.File { fileReader, err := file.Open() if err != nil { return nil, fmt.Errorf("error opening file: %v", err) } // Check if the file is a text file if !file.FileInfo().IsDir() && file.FileInfo().Mode().IsRegular() { content, err := io.ReadAll(fileReader) fileReader.Close() if err != nil { return nil, fmt.Errorf("error reading file content: %v", err) } corpora = append(corpora, corporaInfo{ Name: file.Name[len("udhr/"):], Content: content, }) } } return corpora, nil } // udhrCorpus represents the Universal Declaration of Human Rights (UDHR) corpus. // This corpus contains translations of the UDHR into many languages, // stored in a specific directory structure within a zip archive. // // The files in the corpus USUALLY follow a naming convention: // // _