Skip to content
translatedPublic

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

70 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Lara Go SDK

Go Version License

This SDK empowers you to build your own branded translation AI leveraging our translation fine-tuned language model.

All major translation features are accessible, making it easy to integrate and customize for your needs.

🌍 Features:

  • Text Translation: Single strings, multiple strings, and complex text blocks
  • Document Translation: Word, PDF, and other document formats with status monitoring
  • Translation Memory: Store and reuse translations for consistency
  • Glossaries: Enforce terminology standards across translations
  • Styleguides: Define tone, voice, and writing style rules for translations
  • Audio Translation: Translate audio files with status monitoring
  • Audio Transcript Translation: Retrieve translated transcripts with per-segment timings
  • Image Translation: Translate whole images or extract and translate text blocks
  • Language Detection: Automatic source language identification
  • Advanced Options: Translation instructions and more

πŸ“š Documentation

Lara's SDK full documentation is available at https://developers.laratranslate.com/

πŸš€ Quick Start

Installation

go get github.com/translated/lara-go

Basic Usage

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/translated/lara-go/lara"
)

func main() {
    // Set your credentials using environment variables (recommended)
    accessKeyID := os.Getenv("LARA_ACCESS_KEY_ID")
    accessKeySecret := os.Getenv("LARA_ACCESS_KEY_SECRET")

    // Create translator instance
    laraTranslator := lara.NewTranslator(lara.NewCredentials(accessKeyID, accessKeySecret), nil)

    // Simple text translation
    result, err := laraTranslator.Translate("Hello, world!", "en-US", "fr-FR", lara.TranslateOptions{})
    if err != nil {
        log.Printf("Translation error: %v", err)
        return
    }

    fmt.Printf("Translation: %s\n", *result.Translation.String)
    // Output: Translation: Bonjour, le monde !
}

πŸ“– Examples

The examples/ directory contains comprehensive examples for all SDK features.

All examples use environment variables for credentials, so set them first:

export LARA_ACCESS_KEY_ID="your-access-key-id"
export LARA_ACCESS_KEY_SECRET="your-access-key-secret"

Text Translation

  • text_translation.go - Complete text translation examples
    • Single string translation
    • Multiple strings translation
    • Translation with instructions
    • TextBlocks translation (mixed translatable/non-translatable content)
    • Auto-detect source language
    • Advanced translation options
    • Get available languages
cd examples
go run text_translation.go

Document Translation

  • document_translation.go - Document translation examples
    • Basic document translation
    • Advanced options with memories and glossaries
    • Step-by-step document translation with status monitoring
cd examples
go run document_translation.go

Translation Memory Management

  • memories_management.go - Memory management examples
    • Create, list, update, delete memories
    • Add individual translations
    • Multiple memory operations
    • TMX file import with progress monitoring
    • TMX import with callback URL (async notification)
    • Async memory export with callback URL
    • Translation deletion
    • Translation with TUID and context
cd examples
go run memories_management.go

Glossary Management

  • glossaries_management.go - Glossary management examples
    • Create, list, update, delete glossaries
    • CSV import with status monitoring
    • Glossary export (sync and async)
    • Glossary terms count
    • Import status checking
cd examples
go run glossaries_management.go

Styleguide Management

  • styleguides_management.go - Styleguide management examples
    • Create, list, get, update, delete styleguides
    • Update name, content, or both at once
    • Handling of non-existent styleguides
cd examples
go run styleguides_management.go

Audio Translation

  • audio_translation.go - Audio translation examples
    • Basic audio translation
    • Advanced options with memories and glossaries
    • Step-by-step audio translation with status monitoring
cd examples
go run audio_translation.go

Audio Transcript Translation

  • audio_transcript_translation.go - Audio transcript translation examples
    • Basic transcript translation
    • Advanced options with memories and glossaries
    • Step-by-step transcript translation with status monitoring
cd examples
go run audio_transcript_translation.go

Image Translation

  • image_translation.go - Image translation examples
    • Basic image translation
    • Advanced options with memories and glossaries
    • Extract and translate text from an image
cd examples
go run image_translation.go

Language Detection

  • language_detection.go - Language detection examples
    • Detect language from a single string
    • Detect language from multiple strings
    • Detect with hint parameter
    • Detect with passlist (allowlist) parameter
cd examples
go run language_detection.go

πŸ”§ API Reference

Core Components

πŸ” Authentication

The SDK supports authentication via access key and secret:

credentials := lara.NewCredentials("your-access-key-id", "your-access-key-secret")
laraTranslator := lara.NewTranslator(credentials, nil)

Environment Variables (Recommended):

export LARA_ACCESS_KEY_ID="your-access-key-id"
export LARA_ACCESS_KEY_SECRET="your-access-key-secret"
accessKeyID := os.Getenv("LARA_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("LARA_ACCESS_KEY_SECRET")
credentials := lara.NewCredentials(accessKeyID, accessKeySecret)

🌍 Translator

// Create translator with credentials
laraTranslator := lara.NewTranslator(credentials, nil)

Text Translation

// Basic translation
result, err := laraTranslator.Translate("Hello", "en-US", "fr-FR", lara.TranslateOptions{})

// Multiple strings
result, err := laraTranslator.Translate([]string{"Hello", "World"}, "en-US", "fr-FR", lara.TranslateOptions{})

// TextBlocks (mixed translatable/non-translatable content)
textBlocks := []lara.TextBlock{
    {Text: "Translatable text", Translatable: true},
    {Text: "<br>", Translatable: false},  // Non-translatable HTML
    {Text: "More translatable text", Translatable: true}
}
result, err := laraTranslator.Translate(textBlocks, "en-US", "fr-FR", lara.TranslateOptions{})

// With advanced options
result, err := laraTranslator.Translate("Hello", "en-US", "fr-FR", lara.TranslateOptions{
    Instructions: []string{"Formal tone"},
    AdaptTo:      []string{"mem_1A2b3C4d5E6f7G8h9I0jKl"},  // Replace with actual memory IDs
    Glossaries:   []string{"gls_1A2b3C4d5E6f7G8h9I0jKl"},  // Replace with actual glossary IDs
    Style:        lara.TranslationStyleFluid,
    TimeoutMs:    10000,
})

Reasoning Effort

Set ReasoningEffort to low, medium, or high to control translation reasoning effort. Reasoning must be enabled. Omit the option to use the server default; the API validates the combination.

reasoning := true
result, err := laraTranslator.Translate("Hello", "en-US", "it-IT", lara.TranslateOptions{
    Reasoning:       &reasoning,
    ReasoningEffort: lara.ReasoningEffortHigh,
})

Text Translation with Image Context

Pass ImageContext to use an image as visual context for translating text, with reasoning enabled:

reasoning := true
options := lara.TranslateOptions{
    Reasoning: &reasoning,
    ImageContext: lara.ImageContext{URL: "https://example.com/storefront.png"},
}
result, err := laraTranslator.Translate("Open", "en-US", "it-IT", options)
if err != nil {
    log.Fatal(err)
}
fmt.Println(*result.Translation.String)
if result.Warnings != nil && result.Warnings.Reasoning != nil {
    for _, warning := range result.Warnings.Reasoning.Warnings {
        log.Println(warning.Code, warning.Message)
    }
}

You can also supply a single-element array or an inline image:

// With encoding/base64 and os imported:
data, err := os.ReadFile("storefront.png")
if err != nil {
    log.Fatal(err)
}
options.ImageContext = []lara.ImageContext{
    {URL: "data:image/png;base64," + base64.StdEncoding.EncodeToString(data)},
}

The API accepts at most one image: an HTTPS URL or a base64 PNG, JPEG or WebP data URL. Inline images must match their declared MIME type and contain at most 5 MiB of decoded data; the serialized request body is limited to 16 MiB. Omitting ImageContext or passing []lara.ImageContext{} preserves text-only behavior. Validation is performed by the API, which returns 400 for invalid input and 413 for size violations.

If the image cannot be used, the server may retry the entire request with reasoning without images. The result then includes an image_context_unavailable warning under warnings.reasoning.warnings in the API response, exposed by the typed warning models shown above. warnings.reasoning.applied is true when reasoning succeeds without images, or false (with an error containing statusCode and message) when the server falls back to standard translation. Reference retrieval and prosa failures are available under warnings.references and warnings.prosa.

Language Detection

// Basic detection
result, err := laraTranslator.Detect("Bonjour le monde!", "", nil)

// Multiple strings
result, err := laraTranslator.Detect([]string{"Hello", "World"}, "", nil)

// With hint
result, err := laraTranslator.Detect("Ciao mondo!", "it-IT", nil)

// With passlist (allowlist)
result, err := laraTranslator.Detect("Hola mundo!", "", []string{"en-US", "fr-FR", "es-ES"})

// With both hint and passlist
result, err := laraTranslator.Detect("Guten Tag!", "de-DE", []string{"de-DE", "en-US", "fr-FR"})

// Access results
fmt.Printf("Language: %s\n", result.Language)
fmt.Printf("Content Type: %s\n", result.ContentType)

Quality Estimation

Use QualityEstimation() to score how well a translation matches its source. Pass a single sentence/translation pair to get a single result, or two parallel arrays to get one result per pair.

// Single pair
result, err := laraTranslator.QualityEstimation(
    "en-US",
    "it-IT",
    "Hello, how are you today?",
    "Ciao, come stai oggi?",
)
single := result.(*lara.QualityEstimationResult)
fmt.Printf("Score: %v\n", single.Score) // e.g. 0.768

// Batch
result, err = laraTranslator.QualityEstimation(
    "en-US",
    "it-IT",
    []string{"Good morning.", "The weather is nice."},
    []string{"Buongiorno.", "Il tempo Γ¨ bello."},
)
batch := result.([]lara.QualityEstimationResult)
for _, r := range batch {
    fmt.Printf("Score: %v\n", r.Score) // e.g. 0.751, 0.713
}

πŸ“– Document Translation

Simple document translation

filePath := "/path/to/your/document.txt"  // Replace with actual file path
filename := "document.txt"
source := "en-US"
target := "fr-FR"
reader, err := laraTranslator.Documents.Translate(&filePath, &filename, &source, target)

// With options
options := &lara.DocumentTranslateOptions{
    DocumentUploadOptions: lara.DocumentUploadOptions{
        AdaptTo:    []string{"mem_1A2b3C4d5E6f7G8h9I0jKl"},  // Replace with actual memory IDs
        Glossaries: []string{"gls_1A2b3C4d5E6f7G8h9I0jKl"},  // Replace with actual glossary IDs
        Style:      lara.TranslationStyleFluid,
    },
}
reader, err := laraTranslator.Documents.TranslateWithOptions(&filePath, &filename, &source, target, options)

Document translation with status monitoring

Document upload

//Optional: upload options
uploadOptions := &lara.DocumentUploadOptions{
    AdaptTo:    []string{"mem_1A2b3C4d5E6f7G8h9I0jKl"},  // Replace with actual memory IDs
    Glossaries: []string{"gls_1A2b3C4d5E6f7G8h9I0jKl"}  // Replace with actual glossary IDs
}

document, err := laraTranslator.Documents.UploadWithOptions(&filePath, &filename, &source, target, uploadOptions)

Document translation status monitoring

status, err := laraTranslator.Documents.Status(document.ID)

Download translated document

reader, err := laraTranslator.Documents.Download(document.ID)

🎡 Audio Translation

Simple audio translation

filePath := "/path/to/your/audio.mp3"
filename := "audio.mp3"
source := "en-US"
target := "fr-FR"
reader, err := laraTranslator.Audio.Translate(&filePath, &filename, &source, target)

Audio translation with options

options := &lara.AudioUploadOptions{
    AdaptTo:    []string{"mem_1A2b3C4d5E6f7G8h9I0jKl"},  // Replace with actual memory IDs
    Glossaries: []string{"gls_1A2b3C4d5E6f7G8h9I0jKl"},  // Replace with actual glossary IDs
}
reader, err := laraTranslator.Audio.TranslateWithOptions(&filePath, &filename, &source, target, options)

Step-by-step audio translation

// Upload
audio, err := laraTranslator.Audio.Upload(&filePath, &filename, &source, target)

// Check status
status, err := laraTranslator.Audio.Status(audio.ID)

// Download translated audio
reader, err := laraTranslator.Audio.Download(audio.ID)

πŸŽ™οΈ Audio Transcript Translation

Simple transcript translation

filePath := "/path/to/your/audio.mp3"
filename := "audio.mp3"
source := "en-US"
target := "fr-FR"
result, err := laraTranslator.Audio.TranslateTranscript(&filePath, &filename, &source, target)

Transcript translation with options

options := &lara.AudioTranscriptUploadOptions{
    AdaptTo:    []string{"mem_1A2b3C4d5E6f7G8h9I0jKl"},  // Replace with actual memory IDs
    Glossaries: []string{"gls_1A2b3C4d5E6f7G8h9I0jKl"},  // Replace with actual glossary IDs
}
result, err := laraTranslator.Audio.TranslateTranscriptWithOptions(&filePath, &filename, &source, target, options)

Step-by-step transcript translation

// Upload
audio, err := laraTranslator.Audio.UploadForTranscription(&filePath, &filename, &source, target)

// Check status
status, err := laraTranslator.Audio.Status(audio.ID)

// Retrieve translated transcript
result, err := laraTranslator.Audio.GetTranslatedTranscript(audio.ID)

πŸ–ΌοΈ Image Translation

filePath := "/path/to/your/image.png"  // Replace with actual file path
source := "en-US"
target := "fr-FR"

// Translate image and receive the translated image bytes
imageBytes, err := laraTranslator.Images.Translate(&filePath, &source, target)

// Extract and translate text blocks from an image
result, err := laraTranslator.Images.TranslateText(&filePath, &source, target)

Request layout to preserve paragraph positions, line boxes, colors, direction, and alignment:

includeLayout := true
result, err := laraTranslator.Images.TranslateTextWithOptions(&filePath, &source, target,
    &lara.ImageTextTranslateOptions{IncludeLayout: &includeLayout})
if err != nil { log.Fatal(err) }
if len(result.Paragraphs) > 0 {
    result.Paragraphs[0].Translation = "Bonjour !"
}
rendered, err := laraTranslator.Images.RenderTranslatedWithOptions(
    &filePath, &result.SourceLanguage, target, result.Paragraphs,
    &lara.ImageRenderOptions{Model: lara.TextRemovalOverlay})
if err != nil { log.Fatal(err) }
if err := os.WriteFile("rendered.png", rendered, 0644); err != nil { log.Fatal(err) }

IncludeLayout is independent of Verbose; when it is true, every paragraph contains complete layout metadata and can be passed directly to overlay or inpainting rendering. Rendering uses the supplied translations without translating again and defaults to generative_fast. Use RenderTranslatedWithOptions and ImageRenderOptions to choose a model or set NoTrace. overlay and inpainting require BBox, LinesBBoxes, TextInfo, and Alignment on every paragraph. Generative models accept text-only paragraphs or complete layout. Memory and glossary matches are omitted from rendering requests.

🧠 Memory Management

// Create memory
memory, err := laraTranslator.Memories.Create("MyMemory")

// Create memory with external ID (MyMemory integration)
memory, err := laraTranslator.Memories.CreateWithExternalID("Memory from MyMemory", "aabb1122")  // Replace with actual external ID

// ListPaginated supports optional name filtering and pagination. With nil or empty
// options, it returns the complete list of memories without pagination.
// Providing Search, Page or Size enables pagination.
memoryResult, err := laraTranslator.Memories.ListPaginated(nil)
if err != nil {
    log.Fatal(err)
}
memories, memoryTotal := memoryResult.Items, memoryResult.Total

// Providing Page or Size enables pagination (Page starts at 1; Size: 1-200).
// The missing parameter defaults to Page 1 or Size 20.
page, size := 2, 50
memoryPage, err := laraTranslator.Memories.ListPaginated(&lara.ResourceQueryOptions{
    Page: &page,
    Size: &size,
})
memoryDefaultSize, err := laraTranslator.Memories.ListPaginated(&lara.ResourceQueryOptions{Page: &page}) // Page 2, 20 per page
memoryFirstPage, err := laraTranslator.Memories.ListPaginated(&lara.ResourceQueryOptions{Size: &size}) // Page 1, 50 per page

// Pass Search to filter by displayed name (case- and accent-insensitive).
// It matches substrings and preserves spaces.
// Combine Search with Page and Size to paginate matching results.
// If omitted, Page defaults to 1 and Size to 20.
search := "Marketing"
memorySearch, err := laraTranslator.Memories.ListPaginated(&lara.ResourceQueryOptions{
    Search: &search,
    Page:   &page,
    Size:   &size,
})

// List() is deprecated; use ListPaginated instead.

// Important: To update/overwrite a translation unit you must provide a tuid. Calls without a tuid always create a new unit and will not update existing entries.
// Add translation to single memory
memoryImport, err := laraTranslator.Memories.AddTranslation("mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour")

// Add translation to multiple memories
memoryImport, err := laraTranslator.Memories.AddTranslationMultiple([]string{"mem_1A2b3C4d5E6f7G8h9I0jKl", "mem_2XyZ9AbC8dEf7GhI6jKlMn"}, "en-US", "fr-FR", "Hello", "Bonjour")

// Add with context
memoryImport, err := laraTranslator.Memories.AddTranslationWithContext(
    "mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", "greeting_003",
    "sentenceBefore", "sentenceAfter"
)

// TMX import from file
tmxFilePath := "/path/to/your/memory.tmx"  // Replace with actual TMX file path
memoryImport, err := laraTranslator.Memories.ImportTmxFromPath("mem_1A2b3C4d5E6f7G8h9I0jKl", tmxFilePath)

// TMX import with a callback URL (notified when the import completes)
memoryImport, err = laraTranslator.Memories.ImportTmxFromPathWithCallback(
    "mem_1A2b3C4d5E6f7G8h9I0jKl",
    tmxFilePath,
    "https://your-server.example.com/lara/import-callback",
)

// Async memory export - returns a job ID; the result is delivered to your callback URL when ready
exportJob, err := laraTranslator.Memories.ExportAsync(
    "mem_1A2b3C4d5E6f7G8h9I0jKl",
    "https://your-server.example.com/lara/export-callback",
)
jobID := exportJob.JobID

// Async memory export with explicit format
exportJob, err = laraTranslator.Memories.ExportAsyncWithFormat(
    "mem_1A2b3C4d5E6f7G8h9I0jKl",
    "https://your-server.example.com/lara/export-callback",
    lara.MemoryExportFormatTmx, // or lara.MemoryExportFormatJtm
)

// Delete translation
// Important: if you omit tuid, all entries that match the provided fields will be removed
deleteJob, err := laraTranslator.Memories.DeleteTranslation(
        "mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour"
)

// Wait for import completion
import "time"
maxWaitTime := 300 * time.Second // 5 minutes
completedImport, err := laraTranslator.Memories.WaitForImport(memoryImport, nil, &maxWaitTime)

// Share with the account or a group; shares can be renamed, listed, and revoked
// Omit the name with AddAccountShare/AddGroupShare to reuse the resource's own name
teamMemory, err := laraTranslator.Memories.AddAccountShareWithName(memory.ID, "Team memory")
shares, err := laraTranslator.Memories.GetShares(teamMemory.ID)
_, err = laraTranslator.Memories.RenameAccountShare(memory.ID, "Company memory")
_, err = laraTranslator.Memories.AddGroupShareWithName(memory.ID, "grp_1A2b3C4d5E6f7G8h9I0jKl", "Marketing memory")
_, err = laraTranslator.Memories.RevokeGroupShare(memory.ID, "grp_1A2b3C4d5E6f7G8h9I0jKl")
_, err = laraTranslator.Memories.RevokeAccountShare(memory.ID)

πŸ“š Glossary Management

// Create glossary
glossary, err := laraTranslator.Glossaries.Create("MyGlossary")

// ListPaginated supports optional name filtering and pagination. With nil or empty
// options, it returns the complete list of glossaries without pagination.
// Providing Search, Page or Size enables pagination.
glossaryResult, err := laraTranslator.Glossaries.ListPaginated(nil)
if err != nil {
    log.Fatal(err)
}
glossaries, glossaryTotal := glossaryResult.Items, glossaryResult.Total

// Providing Page or Size enables pagination (Page starts at 1; Size: 1-200).
// The missing parameter defaults to Page 1 or Size 20.
page, size := 2, 50
glossaryPage, err := laraTranslator.Glossaries.ListPaginated(&lara.ResourceQueryOptions{
    Page: &page,
    Size: &size,
})
glossaryDefaultSize, err := laraTranslator.Glossaries.ListPaginated(&lara.ResourceQueryOptions{Page: &page}) // Page 2, 20 per page
glossaryFirstPage, err := laraTranslator.Glossaries.ListPaginated(&lara.ResourceQueryOptions{Size: &size}) // Page 1, 50 per page

// Pass Search to filter by displayed name (case- and accent-insensitive).
// It matches substrings and preserves spaces.
// Combine Search with Page and Size to paginate matching results.
// If omitted, Page defaults to 1 and Size to 20.
search := "Marketing"
glossarySearch, err := laraTranslator.Glossaries.ListPaginated(&lara.ResourceQueryOptions{
    Search: &search,
    Page:   &page,
    Size:   &size,
})

// List() is deprecated; use ListPaginated instead.

// Import a glossary file (use GlossaryFileFormatTbx for TBX files)
glossaryFilePath := "/path/to/your/glossary.csv"
glossaryImport, err := laraTranslator.Glossaries.ImportFileFromPath("gls_1A2b3C4d5E6f7G8h9I0jKl", glossaryFilePath,
    &lara.GlossaryImportOptions{ContentType: lara.GlossaryFileFormatCsvTableUni})

// Pass nil options for unidirectional CSV.
// A callback can be supplied independently:
// laraTranslator.Glossaries.ImportFileFromPath(glossary.ID, glossaryFilePath,
//     &lara.GlossaryImportOptions{CallbackURL: callbackURL})

// Check import status
importStatus, err := laraTranslator.Glossaries.GetImportStatus(glossaryImport.ID)

// Wait for import completion
import "time"
maxWaitTime := 300 * time.Second // 5 minutes
completedImport, err := laraTranslator.Glossaries.WaitForImport(glossaryImport, nil, &maxWaitTime)

// Export glossary
source := "en-US"
csvData, err := laraTranslator.Glossaries.Export("gls_1A2b3C4d5E6f7G8h9I0jKl", "csv/table-uni", &source)

// Async glossary export - returns a job ID; the result is delivered to your callback URL when ready
exportJob, err := laraTranslator.Glossaries.ExportAsync(
    "gls_1A2b3C4d5E6f7G8h9I0jKl",
    "https://your-server.example.com/lara/export-callback",
    "csv/table-uni",
    &source,
)
jobID := exportJob.JobID

// Get glossary terms count
counts, err := laraTranslator.Glossaries.Counts("gls_1A2b3C4d5E6f7G8h9I0jKl")

// Glossaries support the same account and group sharing workflow
_, err = laraTranslator.Glossaries.AddAccountShareWithName(glossary.ID, "Team glossary")
glossaryShares, err := laraTranslator.Glossaries.GetShares(glossary.ID)
_, err = laraTranslator.Glossaries.RevokeAccountShare(glossary.ID)

πŸ“‹ Styleguide Management

// Create styleguide
styleguide, err := laraTranslator.Styleguides.Create("MyStyleguide", "Always use formal language.")

// ListPaginated supports optional name filtering and pagination. With nil or empty
// options, it returns the complete list of styleguides without pagination.
// Providing Search, Page or Size enables pagination.
styleguideResult, err := laraTranslator.Styleguides.ListPaginated(nil)
if err != nil {
    log.Fatal(err)
}
styleguides, styleguideTotal := styleguideResult.Items, styleguideResult.Total

// Providing Page or Size enables pagination (Page starts at 1; Size: 1-200).
// The missing parameter defaults to Page 1 or Size 20.
page, size := 2, 50
styleguidePage, err := laraTranslator.Styleguides.ListPaginated(&lara.ResourceQueryOptions{
    Page: &page,
    Size: &size,
})
styleguideDefaultSize, err := laraTranslator.Styleguides.ListPaginated(&lara.ResourceQueryOptions{Page: &page}) // Page 2, 20 per page
styleguideFirstPage, err := laraTranslator.Styleguides.ListPaginated(&lara.ResourceQueryOptions{Size: &size}) // Page 1, 50 per page

// Pass Search to filter by displayed name (case- and accent-insensitive).
// It matches substrings and preserves spaces.
// Combine Search with Page and Size to paginate matching results.
// If omitted, Page defaults to 1 and Size to 20.
search := "Marketing"
styleguideSearch, err := laraTranslator.Styleguides.ListPaginated(&lara.ResourceQueryOptions{
    Search: &search,
    Page:   &page,
    Size:   &size,
})

// List() is deprecated; use ListPaginated instead.

// Get a specific styleguide
styleguide, err = laraTranslator.Styleguides.Get("stg_1A2b3C4d5E6f7G8h9I0jKl")

// Update styleguide β€” pass nil for fields you don't want to change
// Update only the name
name := "UpdatedStyleguide"
styleguide, err = laraTranslator.Styleguides.Update("stg_1A2b3C4d5E6f7G8h9I0jKl", &name, nil)

// Update only the content
content := "Always use informal language."
styleguide, err = laraTranslator.Styleguides.Update("stg_1A2b3C4d5E6f7G8h9I0jKl", nil, &content)

// Update both
styleguide, err = laraTranslator.Styleguides.Update("stg_1A2b3C4d5E6f7G8h9I0jKl", &name, &content)

// Share a styleguide and inspect visible account, group, and user shares
_, err = laraTranslator.Styleguides.AddGroupShareWithName(styleguide.ID, "grp_1A2b3C4d5E6f7G8h9I0jKl", "Marketing styleguide")
styleguideShares, err := laraTranslator.Styleguides.GetShares(styleguide.ID)

// Delete styleguide
styleguide, err = laraTranslator.Styleguides.Delete("stg_1A2b3C4d5E6f7G8h9I0jKl")

Translation Options

type TranslateOptions struct {
    AdaptTo      []string                   // Memory IDs to adapt to
    Glossaries   []string                   // Glossary IDs to use
    Instructions []string                   // Translation instructions
    Style        TranslationStyle           // Translation style (fluid, faithful, creative)
    ContentType  string                     // Content type (text/plain, text/html, etc.)
    TimeoutMs    int                        // Request timeout in milliseconds
    SourceHint   string                     // Hint for source language detection
    NoTrace      *bool                      // Disable request tracing
    Verbose      *bool                      // Enable verbose response
}

Language Codes

The SDK supports full language codes (e.g., en-US, fr-FR, es-ES) as well as simple codes (e.g., en, fr, es):

// Full language codes (recommended)
result, err := laraTranslator.Translate("Hello", "en-US", "fr-FR", lara.TranslateOptions{})

// Simple language codes
result, err := laraTranslator.Translate("Hello", "en", "fr", lara.TranslateOptions{})

🌐 Supported Languages

The SDK supports all languages available in the Lara API. Use the Languages() method to get the current list:

languages, err := laraTranslator.Languages()
fmt.Printf("Supported languages: %v\n", languages)

Asset permissions

Memories, glossaries, styleguides, and their share entries expose PermissionMask from the API's permission_mask field. Masks use read (r), write (w), export (e), and share (s) positions; - means absent. Supported masks are r---, rw--, r-e-, r--s, rwe-, rw-s, r-es, and rwes.

On memory, glossary, and styleguide resources, PermissionMask is optional and is nil when omitted by the API, including POST, PUT, and DELETE resource responses. GET list and detail responses report the combined effective mask from the caller's applicable shares. Resources embedded in GET /shares responses report the selected share's stored mask; individual share entries report their own required stored mask.

The legacy permissions field and its read/write compatibility API have been removed. Use PermissionMask to inspect the read, write, export, and share bits. Share-entry masks are required, matching the service contract. Resource masks remain optional.

βš™οΈ Configuration

Error Handling

The SDK provides detailed error information:

result, err := laraTranslator.Translate("Hello", "en-US", "fr-FR", lara.TranslateOptions{})
if err != nil {
    if laraErr, ok := err.(*lara.LaraError); ok {
        fmt.Printf("API Error [%d]: %s\n", laraErr.Status, laraErr.Message)
        fmt.Printf("Error type: %s\n", laraErr.Type)
    } else {
        fmt.Printf("SDK Error: %v\n", err)
    }
    return
}

πŸ“‹ Requirements

  • Go 1.19 or higher
  • Valid Lara API credentials

πŸ§ͺ Testing

Run the examples to test your setup:

# All examples use environment variables for credentials, so set them first:
export LARA_ACCESS_KEY_ID="your-access-key-id"
export LARA_ACCESS_KEY_SECRET="your-access-key-secret"
# Run basic text translation example
cd examples
go run text_translation.go

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

Happy translating! 🌍✨

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages