PHP code example of translated / lara-sdk

1. Go to this page and download the library: Download translated/lara-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

translated / lara-sdk example snippets




use Lara\LaraCredentials;
use Lara\Translator;
use Lara\LaraException;

// Set your credentials using environment variables (recommended)
$credentials = new LaraCredentials(
    getenv('LARA_ACCESS_KEY_ID'),
    getenv('LARA_ACCESS_KEY_SECRET')
);

// Create translator instance
$lara = new Translator($credentials);

// Simple text translation
try {
    $result = $lara->translate("Hello, world!", "en-US", "fr-FR");
    echo "Translation: " . $result->getTranslation() . PHP_EOL;
    // Output: Translation: Bonjour, le monde !
} catch (LaraException $error) {
    echo "Translation error: " . $error->getMessage() . PHP_EOL;
}

$credentials = new LaraCredentials("your-access-key-id", "your-access-key-secret");
$lara = new Translator($credentials);

$credentials = new LaraCredentials(
    getenv('LARA_ACCESS_KEY_ID'),
    getenv('LARA_ACCESS_KEY_SECRET')
);

// Create translator with credentials
$lara = new Translator($credentials);

// Basic translation
$result = $lara->translate("Hello", "en-US", "fr-FR");

// Multiple strings
$result = $lara->translate(["Hello", "World"], "en-US", "fr-FR");

// TextBlocks (mixed translatable/non-translatable content)
use Lara\TextBlock;

$textBlocks = [
    new TextBlock('Translatable text', true),
    new TextBlock('<br>', false),  // Non-translatable HTML
    new TextBlock('More translatable text', true),
];
$result = $lara->translate($textBlocks, "en-US", "fr-FR");

// With advanced options  
$options = new TranslateOptions([
    'instructions' => ["Formal tone"],
    'adaptTo' => ["mem_1A2b3C4d5E6f7G8h9I0jKl"],  // Replace with actual memory IDs
    'glossaries' => ["gls_1A2b3C4d5E6f7G8h9I0jKl"],  // Replace with actual glossary IDs
    'style' => "fluid",
    'timeoutInMillis' => 10000
]);

$result = $lara->translate("Hello", "en-US", "fr-FR", $options);

// Single pair
$single = $lara->qualityEstimation(
    "en-US",
    "it-IT",
    "Hello, how are you today?",
    "Ciao, come stai oggi?"
);
echo $single->getScore(); // e.g. 0.768

// Batch
$batch = $lara->qualityEstimation(
    "en-US",
    "it-IT",
    ["Good morning.", "The weather is nice."],
    ["Buongiorno.", "Il tempo è bello."]
);
foreach ($batch as $r) {
    echo $r->getScore() . "\n"; // e.g. 0.751, 0.713
}

$filePath = "/path/to/your/document.txt";  // Replace with actual file path
$fileStream = $lara->documents->translate($filePath, "en-US", "fr-FR");

// With options
$options = new DocumentTranslateOptions();
$options->setAdaptTo(["mem_1A2b3C4d5E6f7G8h9I0jKl"]);  // Replace with actual memory IDs
$options->setGlossaries(["gls_1A2b3C4d5E6f7G8h9I0jKl"]);  // Replace with actual glossary IDs

$fileStream = $lara->documents->translate($filePath, "en-US", "fr-FR", $options);

//Optional: upload options
$uploadOptions = new DocumentUploadOptions();
$uploadOptions->setAdaptTo(["mem_1A2b3C4d5E6f7G8h9I0jKl"]);  // Replace with actual memory IDs
$uploadOptions->setGlossaries(["gls_1A2b3C4d5E6f7G8h9I0jKl"]);  // Replace with actual glossary IDs

$document = $lara->documents->upload($filePath, "en-US", "fr-FR", $uploadOptions);

$status = $lara->documents->status($document->getId());

$downloadOptions = new DocumentDownloadOptions();

$fileStream = $lara->documents->download($document->getId(), $downloadOptions);

use Lara\ImageTranslationOptions;
use Lara\ImageTextTranslationOptions;
use Lara\ImageLayoutParagraph;
use Lara\ImageParagraph;

$imagePath = "/path/to/your/image.png";

// Translate image and receive a translated image stream
$translatedImageStream = $lara->images->translate($imagePath, "en", "fr", new ImageTranslationOptions([
    'model' => 'generative_fast',
    'style' => 'faithful'
]));
$output = fopen("translated.png", "wb");
stream_copy_to_stream($translatedImageStream, $output);
fclose($output);
fclose($translatedImageStream);

// Request complete layout metadata for classic rendering.
$textBlocks = $lara->images->translateText($imagePath, "en", "fr", new ImageTextTranslationOptions([
    'e($output);
    fclose($renderedImage);

    // Generative models accept text-only paragraphs. Omit model for generative_fast.
    $textOnlyParagraphs = array_map(function ($paragraph) {
        return new ImageParagraph($paragraph->getText(), $paragraph->getTranslation());
    }, $paragraphs);
    $renderedImage = $lara->images->renderTranslated($imagePath, null, "fr", $textOnlyParagraphs);
    $output = fopen("edited-generative.png", "wb");
    stream_copy_to_stream($renderedImage, $output);
    fclose($output);
    fclose($renderedImage);
}

// Create memory
$memory = $lara->memories->create("MyMemory");

// Create memory with external ID (MyMemory integration)
$memory = $lara->memories->create("Memory from MyMemory", "aabb1122");  // Replace with actual external ID

// 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 = $lara->memories->addTranslation("mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", "greeting_001");

// Add translation to multiple memories
$memoryImport = $lara->memories->addTranslation(
    ["mem_1A2b3C4d5E6f7G8h9I0jKl", "mem_2XyZ9AbC8dEf7GhI6jKlMn"],  // Replace with actual memory IDs
    "en-US", "fr-FR", "Hello", "Bonjour", "greeting_002"
);

// Add with context
$memoryImport = $lara->memories->addTranslation(
    "mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", "tuid", 
    "sentenceBefore", "sentenceAfter"
);

// TMX import from file
$tmxFilePath = "/path/to/your/memory.tmx";  // Replace with actual TMX file path
$memoryImport = $lara->memories->importTmx("mem_1A2b3C4d5E6f7G8h9I0jKl", $tmxFilePath);

// TMX import with a callback URL (notified when the import completes)
$memoryImport = $lara->memories->importTmx(
    "mem_1A2b3C4d5E6f7G8h9I0jKl",
    $tmxFilePath,
    false, // uncompressed input
    "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 = $lara->memories->exportAsync(
    "mem_1A2b3C4d5E6f7G8h9I0jKl",
    "https://your-server.example.com/lara/export-callback",
    "tmx" // optional, defaults to the server-side default ("tmx" or "jtm")
);
$jobId = $exportJob->getJobId();

// Delete translation
// Important: if you omit tuid, all entries that match the provided fields will be removed
$deleteJob = $lara->memories->deleteTranslation(
    "mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", "greeting_001"
);

// Wait for import completion
$completedImport = $lara->memories->waitForImport($memoryImport, 300); // 5 minutes

// Share with the account or a group; shares can be renamed, listed, and revoked
$lara->memories->addAccountShare($memory->getId(), "Team memory");
$lara->memories->renameAccountShare($memory->getId(), "Company memory");
$lara->memories->addGroupShare($memory->getId(), "grp_1A2b3C4d5E6f7G8h9I0jKl", "Marketing memory");
$shares = $lara->memories->getShares($memory->getId());
$lara->memories->revokeGroupShare($memory->getId(), "grp_1A2b3C4d5E6f7G8h9I0jKl");
$lara->memories->revokeAccountShare($memory->getId());

// Create glossary
$glossary = $lara->glossaries->create("MyGlossary");

// Import a glossary file (use \Lara\GlossaryFileFormat::TBX for TBX files)
$glossaryFilePath = "/path/to/your/glossary.csv";
$glossaryImport = $lara->glossaries->importFile("gls_1A2b3C4d5E6f7G8h9I0jKl", $glossaryFilePath,
    new \Lara\GlossaryImportOptions(['contentType' => \Lara\GlossaryFileFormat::CSV_TABLE_UNI]));

// Options default to unidirectional CSV.
// A callback can be supplied on its own:
// $lara->glossaries->importFile($glossary->getId(), $glossaryFilePath,
//     new \Lara\GlossaryImportOptions(['callbackUrl' => $callbackUrl]));

// Check import status
$importStatus = $lara->glossaries->getImportStatus($glossaryImport->getId());

// Wait for import completion
$completedImport = $lara->glossaries->waitForImport($glossaryImport, 300); // 5 minutes

// Export glossary
$csvData = $lara->glossaries->export("gls_1A2b3C4d5E6f7G8h9I0jKl", "csv/table-uni", "en-US");

// Async glossary export - returns a job ID; the result is delivered to your callback URL when ready
$exportJob = $lara->glossaries->exportAsync(
    "gls_1A2b3C4d5E6f7G8h9I0jKl",
    "https://your-server.example.com/lara/export-callback",
    "csv/table-uni",
    "en-US"
);
$jobId = $exportJob->getJobId();

// Get glossary terms count
$counts = $lara->glossaries->counts("gls_1A2b3C4d5E6f7G8h9I0jKl");

// Glossaries support the same account and group sharing workflow
$lara->glossaries->addAccountShare($glossary->getId(), "Team glossary");
$glossaryShares = $lara->glossaries->getShares($glossary->getId());
$lara->glossaries->revokeAccountShare($glossary->getId());

// Create styleguide
$styleguide = $lara->styleguides->create("MyStyleguide", "Always use formal language.");

// List all styleguides
$styleguides = $lara->styleguides->getAll();

// Get a specific styleguide
$styleguide = $lara->styleguides->get("stg_1A2b3C4d5E6f7G8h9I0jKl");

// Update styleguide — pass null for fields you don't want to change
// Update only the name
$styleguide = $lara->styleguides->update("stg_1A2b3C4d5E6f7G8h9I0jKl", "UpdatedStyleguide");

// Update only the content
$styleguide = $lara->styleguides->update("stg_1A2b3C4d5E6f7G8h9I0jKl", null, "Always use informal language.");

// Update both
$styleguide = $lara->styleguides->update("stg_1A2b3C4d5E6f7G8h9I0jKl", "UpdatedStyleguide", "Always use informal language.");

// Share a styleguide and inspect visible account, group, and user shares
$lara->styleguides->addGroupShare($styleguide->getId(), "grp_1A2b3C4d5E6f7G8h9I0jKl", "Marketing styleguide");
$styleguideShares = $lara->styleguides->getShares($styleguide->getId());

// Delete styleguide
$styleguide = $lara->styleguides->delete("stg_1A2b3C4d5E6f7G8h9I0jKl");

// Constructor array pattern (recommended)
$options = new TranslateOptions([
    'adaptTo' => ["mem_1A2b3C4d5E6f7G8h9I0jKl"],              // Memory IDs to adapt to
    'glossaries' => ["gls_1A2b3C4d5E6f7G8h9I0jKl"],           // Glossary IDs to use
    'instructions' => ["instruction"],                        // Translation instructions
    'style' => "fluid",                                       // Translation style (fluid, faithful, creative)
    'contentType' => "text/plain",                            // Content type (text/plain, text/html, etc.)
    'multiline' => true,                                      // Enable multiline translation
    'timeoutInMillis' => 10000,                               // Request timeout in milliseconds
    'sourceHint' => "en",                                     // Hint for source language detection
    'noTrace' => false,                                       // Disable request tracing
    'verbose' => false,                                       // Enable verbose response
]);

// Alternative setter pattern
$options = new TranslateOptions();
$options->setSourceHint("en-US");
$options->setAdaptTo(["mem_1A2b3C4d5E6f7G8h9I0jKl", "mem_2XyZ9AbC8dEf7GhI6jKlMn"]);  // Replace with actual memory IDs
$options->setInstructions(["Formal tone", "Use technical terminology"]);
$options->setGlossaries(["gls_1A2b3C4d5E6f7G8h9I0jKl", "gls_2XyZ9AbC8dEf7GhI6jKlMn"]);  // Replace with actual glossary IDs
$options->setContentType("text/html");
$options->setMultiline(true);
$options->setTimeoutInMillis(15000);
$options->setNoTrace(false);
$options->setVerbose(true);
$options->setStyle("faithful");

// Full language codes (recommended)
$result = $lara->translate("Hello", "en-US", "fr-FR");

// Simple language codes
$result = $lara->translate("Hello", "en", "fr");

$languages = $lara->getLanguages();
echo "Supported languages: " . implode(', ', $languages) . PHP_EOL;

try {
    $result = $lara->translate("Hello", "en-US", "fr-FR");
    echo "Translation: " . $result->getTranslation() . PHP_EOL;
} catch (LaraException $e) {
    echo "API Error: " . $e->getMessage() . PHP_EOL;
} catch (LaraTimeoutException $e) {
    echo "Timeout Error: " . $e->getMessage() . PHP_EOL;
}
bash
cd examples
php text_translation.php
bash
cd examples
php document_translation.php
bash
cd examples
php image_translation.php
bash
cd examples
php memories_management.php
bash
cd examples
php glossaries_management.php
bash
cd examples
php styleguides_management.php
bash
# Run basic text translation example
cd examples
php text_translation.php