Programmatically Pre-translate a Project with Language Weaver as a MT resource

Hi,

Got a strange one here.

I have a C# program that creates a project via a template, adds source files and pre-translates using the relevant Language pair resources specified in the project template.

The code works perfectly with any project templates that have:

  • A translation memory
  • And/or have a DeepL plugin

I have created a new template that uses Cloud-based resources (Language Weaver with the correct language pair, using Generic - NMT).

I run same program (no code changes) and it creates the project, adds the source files and runs through the code to do the pre-translate.

But, when I manually open the created project it has not done the pre-translate.

I can manually do a pre-translate and it does use LW to perform MT. 

Is there anything wrong with the code below that's stopping the PT?

Here's the method that does the PT:

internal void PreTranslateFilesMT(int minimumrate)
{

if (newProject != null)
{
    Console.WriteLine("START MT PreTranslateFiles with memory enabled");

    Console.WriteLine("Setting project minimum pre-translate match to {0}", minimumrate);
    var settings = newProject.GetSettings();
    var preTranslateSettings = settings.GetSettingsGroup<TranslateTaskSettings>();
    preTranslateSettings.NoTranslationMemoryMatchFoundAction.Value = NoTranslationMemoryMatchFoundAction.ApplyAutomatedTranslation;
    preTranslateSettings.MinimumMatchScore.Value = minimumrate;
    newProject.UpdateSettings(settings);
    newProject.Save();
    var targetFiles = newProject.GetTargetLanguageFiles();

    newProject.RunAutomaticTasks(targetFiles.GetIds(), new[]
    {
        AutomaticTaskTemplateIds.PreTranslateFiles,
    });
    newProject.Save();
    Console.WriteLine("END MT PreTranslateFiles with memory enabled");
}
else
    Console.WriteLine("NULL new project!");

}

Thanks

Mark

Parents Reply Children
  •  

    Hi,

    I'm not sure whether you want a separate ticket for this but a similar problem occurs when creating packages for a project containing Cloud-based resources...

    The scenario is:

    1. Create a project using my normal project create API program. (As stated above, it does not do a pre-translate if Cloud-based resources are used).
    2. Open the project using Trados interactively.
    3. Run a pre-translate. This does work and provides lots of NMT translations.
    4. Close the project.
    5. Run my normal Trados package create program. This has always worked before. This time it fails.
    6. I open the project using Trados interactively.
    7. Remove the Cloud-based resource entry from the project.
    8. Close the project.
    9. Run my normal Trados package create program. It works.

    Yet again, having a project with Cloud-based resources is causing problems in API programs that do not happen when running interactively.

    1.             bool packageIsCreated = false;
                  while (!packageIsCreated)
                  {
                      Console.WriteLine("{0}", projectPackage.Status);
                      switch (projectPackage.Status)
                      {
                          case PackageStatus.Cancelling:
                          case PackageStatus.InProgress:
                          case PackageStatus.Scheduled:
                          case PackageStatus.NotStarted:
                              packageIsCreated = false;
                              break;
                          case PackageStatus.Cancelled:
                          case PackageStatus.Completed:
                          case PackageStatus.Failed:
                          case PackageStatus.Invalid:
                              packageIsCreated = true;
                              break;
                          default:
                              break;
                      }
                  }
      
                  if (projectPackage.Status != PackageStatus.Completed)
                  {
                      Console.WriteLine("Package problem: {0}", projectPackage.Status);
                      throw new Exception("A problem occurred during package creation.");
                  }
  • Hey , we are working on providing a sample project that will help developers understand the requirements when working with LC projects/resources from project automation environment.

    What you're missing in your project is potentially the credentials, incl token, API key... that are needed in this case.  We'll circle back to you once we have completed the sample project that should help provide you the information you need to adapt your source code.

  • Interesting!

    I did have to supply credentials and API key when I coded the DeepL usage. That was because I did not include that info in the project template.

    With the LC coding, I did include the credentials and API key in the project template so my assumption was any project created from the template would automatically use those bits of info.

    Very keen to see your sample project.

    Thanks for your support

    Mark

  • Hi Mark,

    The sample project for creating a project with a Language Cloud translation provider using the Project Automation API can be found here. It includes all the necessary code to help you set up the project and add the Language Cloud translation provider.

    To create a project and successfully add the Language Cloud translation provider, it’s crucial that the credentials (including API keys and tokens) are provided. Additionally, you must ensure that you are logged in to Language Cloud for the provider to function correctly within your automation environment.

    In the code snippet below (from Program.cs in the sample), after the FileBasedProject instance is created, the translation provider is added to the project along with the required credentials. This is followed by logging in to Language Cloud before running the project tasks.

     private static void Main(string[] args)
     {
         // Change the path with the actual directory where projects should be saved...
         var projectsDirectory = @"";
    
         // Change the path with the actual project template path
         var templatePath = @"";
    
         if (!Directory.Exists(projectsDirectory))
         {
             Directory.CreateDirectory(projectsDirectory);
         }
    
         var sourceLanguage = "en-US";
         var targetLanguage = "de-DE";
    
         var projectDirectory = GetOutputProjectDirectory(projectsDirectory);
    
         var projectName = "TestProject-" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" +
                    DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second;
    
         var projectInfo = new ProjectInfo
         {
             Name = projectName,
             SourceLanguage = new Language(sourceLanguage),
             TargetLanguages = new[] { new Language(targetLanguage) },
             LocalProjectFolder = projectDirectory
         };
    
    
         FileBasedProject project;
         if (!string.IsNullOrEmpty(templatePath))
         {
             project = new FileBasedProject(projectInfo, new ProjectTemplateReference(templatePath));                
         }
         else
         {
             project = new FileBasedProject(projectInfo);
         }
    
         UpdateProjectProviderSettings(project);
    
         // Update this variable with the actual URI of the translation provider.
         // You can retrieve this value from an existing project or project template (.sdlproj/.sdltpl).
         // To do this, open the project file in a text editor of your choice.
         // Look for the XML element <CascadeEntryProvider> and its child elements.
         // These elements should contain the URI for the translation provider.
         //
         // For example:
         // - URIs starting with "languagecloud.translation.https://" indicate a Translation Engine.
         //
         // Copy the complete URI from the project/template file and assign it to the variable below.
         //
         // Example URI: 
         // If a project template is used, you would typically need to map the URI from the project template file to the actual URI.
         // For the sake of this example, change this value with the actual tpUri string.
         // This is because, when the project automation api is used, the credentials need to be provided explicitly as it works outside the context of Trados Studio.
         var tpUriString = @""; // Paste URI here
    
         // The API key can be obtained from the Language Cloud web interface.
         // Navigate to: Users -> Integrations -> API Keys.
         // Copy the API key from this section.
         var apiKey = ""; // Paste the API Key here
    
         if (string.IsNullOrEmpty(templatePath))
         {
             var tpConfig = project.GetTranslationProviderConfiguration();
    
             var tpReference = new TranslationProviderReference(new Uri(tpUriString), null, true);
             var tpCascadeEntry = new TranslationProviderCascadeEntry(tpReference, true, true, false);
             tpConfig.Entries.Add(tpCascadeEntry);
             project.UpdateTranslationProviderConfiguration(tpConfig);
         }
    
         project.Credentials.AddCredential(new Uri(tpUriString), apiKey);
    
         project.Save();
    
         // Update the second parameter with the actual path to the source files.
         // Example: @"C:\Path\To\SourceFiles"
         AddFilesToProject(project, @""); // Paste the source files path
    
         //Login to LC for projects with Translation Engine providers 
         var lcService = new LCService();
         lcService.LoginToLC();
    
         RunScanTaskFiles(project);
         RunAnalyzeTaskFiles(project, targetLanguage);
         RunPreTranslateFiles(project, targetLanguage);
    
         project.Save();
     }

    Please feel free to explore the provided sample, and let us know if you need further assistance.

    Best regards,

    Alexandru Florescu

  • Hi,

    Many thanks for the sample - I've downloaded the latest version of the code sample files. When I try to compile the "StandAloneConsoleApp_PretranslateUsingProvider" project I'm getting 2 specific compiler errors in the LCService class file.

    I've double-checked all assembly references are there.

    Am I missing something else?
    Best Regards
    Mark

    Severity Code Description Project File Line Suppression State
    Error CS1061 'ILanguageCloudIdentityApi' does not contain a definition for 'LoginWithToken' and no accessible extension method 'LoginWithToken' accepting a first argument of type 'ILanguageCloudIdentityApi' could be found (are you missing a using directive or an assembly reference?) TradosProjectCreateLanguageWeaver C:\Git\U4TranslationTools\CSharpCode\TradosProjectCreateLanguageWeaver\TradosProjectCreateLanguageWeaver\LC\LCService.cs 50 Active

    Severity Code Description Project File Line Suppression State
    Error CS0246 The type or namespace name 'LoginData' could not be found (are you missing a using directive or an assembly reference?) TradosProjectCreateLanguageWeaver C:\Git\U4TranslationTools\CSharpCode\TradosProjectCreateLanguageWeaver\TradosProjectCreateLanguageWeaver\LC\LCService.cs 44 Active

  • Hello Mark!

    Thank you for your post.

    It seems likely that you might be using an older version of Trados Studio. The pre-translate functionality with cloud resources (including LoginWithToken) was introduced with Trados Studio 2024 (Studio 18). If you're using an earlier version, that would explain why the methods and classes (such as LoginWithToken and LoginData) are not available.

    I suggest checking which version of Trados Studio you are using, and make sure it's Studio 2024 (Studio18). Updating to the latest version should resolve the issue, as the necessary API features are available in these versions.

    Let me know if that helps or if you're still encountering any issues!

    Best Regards,
    Alexandru Florescu

  • Ah, that will explain it. 

    I'm on Trados Studio 2021 SR2 - 16.2.12.9338

    Do you know if Trados 2024 can co-exist on the same machine with my current version, so I can do some testing?

    I'm a bit nervous of fully committing to the upgrade now as I have lots of Trados projects out for translation. It would be bad news if I could not reimport the packages! 

  • Hi Mark - yes Studio 2021, 2022 and 2024 all live side-by-side so this aspect should be OK. Thanks, Daniel

    Daniel Brockmann
    Team Trados @ RWS

  • wow - that's what I call super-fast support!

    One small point, Are saying there will be separate Trados global option instances for each version of Trados on the same machine? 

  • Just looking at the upgrade via my RWS account. It appears I need to go from Trados 2021 -> Trados 2022, then a separate upgrade from Trados 2022 -> Trados 2024?

    Or can I just install the Trados 2024 installer?