static String TranslateWithModel(string text, string targetLanguageCode, string sourceLanguageCode, TranslationModel model) { TranslationClient client = TranslationClient.Create(); try { if (DetectLanguage(text).Equals("en")) { return(text); } else { var response = client.TranslateText(text, targetLanguageCode, sourceLanguageCode, model); return(response.TranslatedText); } // Console.WriteLine("Model: {0}", response.Model); } catch (Exception e) { Console.WriteLine("Connection to translate failed."); return(null); } }
public BeGlobalWindowViewModel(BeGlobalWindow mainWindow, BeGlobalTranslationOptions options, bool tellMeAction) { LoginViewModel = new LoginViewModel(options); SettingsViewModel = new SettingsViewModel(options); Options = options; if (options != null) { var mtModel = SettingsViewModel.TranslationOptions.FirstOrDefault(m => m.Model.Equals(options.Model)); if (mtModel != null) { var selectedModelIndex = SettingsViewModel.TranslationOptions.IndexOf(mtModel); SettingsViewModel.SelectedModelOption = SettingsViewModel.TranslationOptions[selectedModelIndex]; } else if (SettingsViewModel.TranslationOptions.Count.Equals(0)) { var translationModel = new TranslationModel { Model = options.Model, DisplayName = options.Model }; SettingsViewModel.TranslationOptions.Add(translationModel); SettingsViewModel.SelectedModelOption = translationModel; } } _mainWindow = mainWindow; _tellMeAction = tellMeAction; _normalizeSourceTextHelper = new NormalizeSourceTextHelper(); }
private void GetModelResponse(RESTConnector.Request req, RESTConnector.Response resp) { TranslationModel model = new TranslationModel(); if (resp.Success) { try { fsData data = null; fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } object obj = model; r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } } catch (Exception e) { Log.Error("NLC", "GetModel Exception: {0}", e.ToString()); resp.Success = false; } } if (((GetModelReq)req).Callback != null) { ((GetModelReq)req).Callback(resp.Success ? model : null); } }
public void SetUser(UserFull p_user) { if (p_user == null) { isEditMode = false; p_user = new UserFull(); // novyuživatel == vychozí start stav } else { State = new StateModel(); State = StatesRepository.Instance.Retrieve(p_user.ID_STA); Translation = new TranslationModel(); TranslationAll = new ObservableCollection <TranslationModel>(TranslationRepository.Instance.GetPossibleTranslations(1, p_user.ID_STA)); //nahraji se přechody } _edditingUser = p_user; if (User != null) { User.ErrorsChanged -= RaiseCanExecuteChanged; } User = new UserFullEditable(); User.ErrorsChanged += RaiseCanExecuteChanged; CopyCustomer(_edditingUser, User); }
public async Task <JsonResult> TranslateTextAsync(string text, string translationType) { var _translationTypeUri = "/" + translationType + ".json"; if ((text == "" || translationType == "") || (text == "" && translationType == "")) { return(Json(new { success = false, message = "Write text you want to translate!" }, JsonRequestBehavior.AllowGet)); } using (var client = new HttpClient()) { string BaseAddress = _baseTranslationsUri + _translationTypeUri; client.BaseAddress = new Uri(BaseAddress); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string jsonText = JsonConvert.SerializeObject(new { text = text }); var response = await client.PostAsync(BaseAddress, new StringContent(jsonText, Encoding.UTF8, "application/json")); string responseTranslation = response.Content.ReadAsStringAsync().Result; var deserializedResponseTranslation = JsonConvert.DeserializeObject <TranslationModel>(responseTranslation); TranslationModel translation = new TranslationModel(); translation.Contents = new contents { TranslationId = translation }; translation.Success = new success { TranslationId = translation }; translation.IsSuccessStatusCode = response.IsSuccessStatusCode; translation.Date = DateTime.Now; if (response.IsSuccessStatusCode) { translation.Contents.text = deserializedResponseTranslation.Contents.text; translation.Contents.translation = deserializedResponseTranslation.Contents.translation; translation.Contents.translated = deserializedResponseTranslation.Contents.translated; translation.StatusCode = response.StatusCode.ToString(); translation.Success.total = deserializedResponseTranslation.Success.total; AddTranslation(translation); return(Json(new { success = true, translated = translation.Contents.translated }, JsonRequestBehavior.AllowGet)); } else { translation.Contents.text = text; translation.Contents.translation = translationType; translation.Contents.translated = null; translation.Error = new error { TranslationId = translation }; translation.Error.code = deserializedResponseTranslation.Error.code; translation.Error.message = deserializedResponseTranslation.Error.message; AddTranslation(translation); return(Json(new { success = false, errorCode = deserializedResponseTranslation.Error.code, errorMessage = deserializedResponseTranslation.Error.message }, JsonRequestBehavior.AllowGet)); } } }
private void OnCreateModel(TranslationModel model, Dictionary <string, object> customData) { Log.Debug("TestLanguageTranslator.OnCreateModel()", "Language Translator - Create model response: {0}", customData["json"].ToString()); _customLanguageModelId = model.model_id; Test(model != null); _createModelTested = true; }
public ActionResult EditRecord(Guid Id, string Table, Guid ForeignId, string Instance) { TranslationModel model = service.GetTranslation(Id); ViewBag.Languages = new SelectList(new LanguageService().GetLanguages(), "ID", "NAME", model.Language.Id); return(View(model)); }
public ActionResult Translations(Guid id) { if (!CheckPermission(PagesPermissions.ManagePages)) { return(new HttpUnauthorizedResult()); } var model = new TranslationModel { Id = id }; var result = new ControlFormResult <TranslationModel>(model) { Title = T("Select Language").Text, UpdateActionName = "Translations", SubmitButtonText = T("OK"), ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; var languages = languageManager.GetActiveLanguages(Constants.ThemeDefault, false); result.RegisterExternalDataSource(x => x.CultureCode, languages.ToDictionary(k => k.CultureCode, v => v.Name)); return(result); }
public IEnumerator TestCreateModel() { Log.Debug("LanguageTranslatorServiceV3IntegrationTests", "Attempting to CreateModel..."); TranslationModel createModelResponse = null; using (FileStream fs = File.OpenRead(forcedGlossaryFilepath)) { using (MemoryStream ms = new MemoryStream()) { fs.CopyTo(ms); service.CreateModel( callback: (DetailedResponse <TranslationModel> response, IBMError error) => { Log.Debug("LanguageTranslatorServiceV3IntegrationTests", "CreateModel result: {0}", response.Response); createModelResponse = response.Result; customModelId = createModelResponse.ModelId; Assert.IsNotNull(createModelResponse); Assert.IsNotNull(customModelId); Assert.IsTrue(createModelResponse.Source == "en"); Assert.IsTrue(createModelResponse.Target == "fr"); Assert.IsTrue(createModelResponse.Name == customModelName); Assert.IsNull(error); }, baseModelId: englishToFrenchModel, forcedGlossary: ms, name: customModelName ); while (createModelResponse == null) { yield return(null); } } } }
/// <summary> /// Save original text and translated text to azure data base service /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void TranslatedText_Tapped(object sender, EventArgs e) { bool answer = await DisplayAlert("Confirm", "Do you want to save?", "Yes", "No"); if (!answer) { return; } if (String.IsNullOrEmpty(RecordedText.Text) || String.IsNullOrEmpty(TranslatedText.Text) || String.IsNullOrEmpty(TranslatedText.Detail)) { return; } TranslationModel model = new TranslationModel() { Text = RecordedText.Text, TranslatedText = TranslatedText.Text, Pronunciation = TranslatedText.Detail }; azureEasyTableClient.BaseAddress = @"http://mobiletranslator.azurewebsites.net/"; azureEasyTableClient.TargetAPI = @"tables/TranslatedText"; bool result = await azureEasyTableClient.PostDataAsync(model); if (result) { await DisplayAlert("Saving", "Save data successful", "OK"); RecordedText.Text = String.Empty; TranslatedText.Text = String.Empty; TranslatedText.Detail = String.Empty; } }
public IEnumerator TestGetModel() { Log.Debug("LanguageTranslatorServiceV3IntegrationTests", "Attempting to GetModel..."); TranslationModel getModelResponse = null; service.GetModel( callback: (DetailedResponse <TranslationModel> response, IBMError error) => { Log.Debug("LanguageTranslatorServiceV3IntegrationTests", "GetModel result: {0}", response.Response); getModelResponse = response.Result; Assert.IsNotNull(getModelResponse); Assert.IsTrue(getModelResponse.ModelId == customModelId); Assert.IsTrue(getModelResponse.Source == "en"); Assert.IsTrue(getModelResponse.Target == "fr"); Assert.IsTrue(getModelResponse.Name == customModelName); Assert.IsNull(error); }, modelId: customModelId ); while (getModelResponse == null) { yield return(null); } }
public void UpdateTranslation(TranslationModel translation) { using (AppTourEntities data = new AppTourEntities()) { try { TRANSLATIONS edited = data.TRANSLATIONS.Single(x => translation.Id == x.ID); if (edited != null) { edited.TABLE_NAME = translation.TableName; edited.FIELD_NAME = translation.FieldName; edited.VALUE = translation.Value; edited.LANGUAGE = data.LANGUAGE.Single(x => x.ID.Equals(translation.Language.Id)); edited.FOREIGN_ID = translation.ForeignId; data.SaveChanges(); } } catch (Exception e) { if (e.InnerException != null) { throw new Exception(e.InnerException.Message); } throw; } } }
/// <summary> /// Get model details. Gets information about a translation model, including training status for custom models. /// </summary> /// <param name="modelId">Model ID of the model to get.</param> /// <param name="customData">Custom data object to pass data including custom request headers.</param> /// <returns><see cref="TranslationModel" />TranslationModel</returns> public TranslationModel GetModel(string modelId, Dictionary <string, object> customData = null) { if (string.IsNullOrEmpty(modelId)) { throw new ArgumentNullException(nameof(modelId)); } TranslationModel result = null; try { IClient client; client = this.Client.WithAuthentication(this.UserName, this.Password); var restRequest = client.GetAsync($"{this.Endpoint}/v2/models/{modelId}"); if (customData != null) { restRequest.WithCustomData(customData); } result = restRequest.As <TranslationModel>().Result; if (result == null) { result = new TranslationModel(); } result.CustomData = restRequest.CustomData; } catch (AggregateException ae) { throw ae.Flatten(); } return(result); }
public TranslationView Render(TranslationModel source, int dictionaryId) { if (source == null) { return(null); } var result = source.Map <TranslationModel, TranslationView>(); result.Language = _enumRenderer.Render((LanguageType)source.LanguageId); var links = new List <LinkView> { LinkRenderer.Render("GetTranslationById", RelTypes.Self, new { id = dictionaryId, translationId = source.Id }), LinkRenderer.Render("GetWordById", RelTypes.Word, new { id = dictionaryId, wordId = source.WordId }) }; var link = LinkRenderer.ReRoute(source.Links.WithRel(RelTypes.Update)); if (link != null) { links.Add(link); } link = LinkRenderer.ReRoute(source.Links.WithRel(RelTypes.Delete)); if (link != null) { links.Add(link); } result.Links = links; return(result); }
private void OnCreateModel(TranslationModel model, string customData) { Log.Debug("TestLanguageTranslator", "Language Translator - Create model response: {0}", customData); _customLanguageModelId = model.model_id; Test(model != null); _createModelTested = true; }
public override List <TranslationModel> GetModels() { var models = new List <TranslationModel>(); if (FileInfo.Name.Count(x => x == '.') > 1) { return(models); } var translationFiles = Directory.GetFiles(FileInfo.DirectoryName, Path.GetFileNameWithoutExtension(FileInfo.Name) + "*" + ".resx"); foreach (var translationFile in translationFiles) { var language = GetLanguageFromResx(translationFile); var serializer = new XmlSerializer(typeof(Root)); var streamReader = new StreamReader(translationFile); var xmlReader = new XmlTextReader(streamReader); var iAm = serializer.Deserialize(xmlReader) as Root; foreach (var translation in iAm.Data) { var existing = models.FirstOrDefault(x => x.key == translation.Name); if (existing == null) { var newTranslationModel = new TranslationModel { key = translation.Name, Translations = new Dictionary <string, string> { { language, translation.Value } } }; models.Add(newTranslationModel); } else { if (existing.Translations.ContainsKey(language)) { Console.WriteLine(language); Console.WriteLine(translation.Name); Console.WriteLine(translation.Value); throw new Exception("Key already exists"); } else { existing.Translations.Add(language, translation.Value); } } } } return(models); }
/// <summary> /// Create model. Uploads a TMX glossary file on top of a domain to customize a translation model. Depending on the size of the file, training can range from minutes for a glossary to several hours for a large parallel corpus. Glossary files must be less than 10 MB. The cumulative file size of all uploaded glossary and corpus files is limited to 250 MB. /// </summary> /// <param name="baseModelId">The model ID of the model to use as the base for customization. To see available models, use the `List models` method.</param> /// <param name="name">An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces and apostrophes. The maximum length is 32 characters. (optional)</param> /// <param name="forcedGlossary">A TMX file with your customizations. The customizations in the file completely overwrite the domain translaton data, including high frequency or high confidence phrase translations. You can upload only one glossary with a file size less than 10 MB per call. (optional)</param> /// <param name="parallelCorpus">A TMX file that contains entries that are treated as a parallel corpus instead of a glossary. (optional)</param> /// <param name="monolingualCorpus">A UTF-8 encoded plain text file that is used to customize the target language model. (optional)</param> /// <returns><see cref="TranslationModel" />TranslationModel</returns> public TranslationModel CreateModel(string baseModelId, string name = null, System.IO.Stream forcedGlossary = null, System.IO.Stream parallelCorpus = null, System.IO.Stream monolingualCorpus = null) { if (string.IsNullOrEmpty(baseModelId)) { throw new ArgumentNullException(nameof(baseModelId)); } TranslationModel result = null; try { var formData = new MultipartFormDataContent(); if (forcedGlossary != null) { var forcedGlossaryContent = new ByteArrayContent((forcedGlossary as Stream).ReadAllBytes()); System.Net.Http.Headers.MediaTypeHeaderValue contentType; System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("application/octet-stream", out contentType); forcedGlossaryContent.Headers.ContentType = contentType; formData.Add(forcedGlossaryContent, "forced_glossary", "filename"); } if (parallelCorpus != null) { var parallelCorpusContent = new ByteArrayContent((parallelCorpus as Stream).ReadAllBytes()); System.Net.Http.Headers.MediaTypeHeaderValue contentType; System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("application/octet-stream", out contentType); parallelCorpusContent.Headers.ContentType = contentType; formData.Add(parallelCorpusContent, "parallel_corpus", "filename"); } if (monolingualCorpus != null) { var monolingualCorpusContent = new ByteArrayContent((monolingualCorpus as Stream).ReadAllBytes()); System.Net.Http.Headers.MediaTypeHeaderValue contentType; System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("text/plain", out contentType); monolingualCorpusContent.Headers.ContentType = contentType; formData.Add(monolingualCorpusContent, "monolingual_corpus", "filename"); } var request = this.Client.WithAuthentication(this.UserName, this.Password) .PostAsync($"{this.Endpoint}/v2/models"); if (!string.IsNullOrEmpty(baseModelId)) { request.WithArgument("base_model_id", baseModelId); } if (!string.IsNullOrEmpty(name)) { request.WithArgument("name", name); } request.WithBodyContent(formData); result = request.As <TranslationModel>().Result; } catch (AggregateException ae) { throw ae.Flatten(); } return(result); }
/// <summary> /// Synchronously creates a <see cref="TranslationClient"/>, using application default credentials if /// no credentials are specified. /// </summary> /// <remarks> /// The credentials are scoped as necessary. /// </remarks> /// <param name="credential">Optional <see cref="GoogleCredential"/>.</param> /// <param name="model">The default translation model to use. Defaults to <see cref="TranslationModel.ServiceDefault"/>.</param> /// <returns>The created <see cref="TranslationClient"/>.</returns> public static TranslationClient Create(GoogleCredential credential = null, TranslationModel model = TranslationModel.ServiceDefault) => new TranslationClientBuilder { Credential = credential?.CreateScoped(Scopes), TranslationModel = model } .Build();
/// <summary> /// Creates a <see cref="TranslationClient"/> from an API key instead of using OAuth2 credentials. /// </summary> /// <remarks> /// You are encouraged to use OAuth2 credentials where possible. This method is primarily provided to make the transition /// from using API keys to OAuth2 credentials straightforward. /// </remarks> /// <param name="apiKey">API key to use. Must not be null.</param> /// <param name="model">The default translation model to use. Defaults to <see cref="TranslationModel.ServiceDefault"/>.</param> /// <returns>The created <see cref="TranslationClient"/>.</returns> public static TranslationClient CreateFromApiKey(string apiKey, TranslationModel model = TranslationModel.ServiceDefault) => new TranslationClientBuilder { ApiKey = GaxPreconditions.CheckNotNull(apiKey, nameof(apiKey)), TranslationModel = model } .Build();
public ActionResult Translations(TranslationModel model) { if (!CheckPermission(PagesPermissions.ManagePages)) { return(new HttpUnauthorizedResult()); } return(new AjaxResult().Redirect(Url.Action("Translate", new { id = model.Id, cultureCode = model.CultureCode }), true)); }
private void NavToAddEditTranslation(TranslationModel p_translation) { AddEditTranslationViewModel Temp = new AddEditTranslationViewModel(p_translation); Temp.Done += NavToTranslation; CurrentPage = Temp; CurrentPageName = "States"; CurrentPage.IsRightsMode = true; //volani permission modulu }
private void OnGetModel(TranslationModel model) { Test(model != null); if (model != null) { Log.Status("TestTranslate", "ModelID: {0}, Source: {1}, Target: {2}, Domain: {3}", model.model_id, model.source, model.target, model.domain); } m_GetModelTested = true; }
internal static void ValidateModel(TranslationModel model) { switch (model) { case TranslationModel.Base: return; case TranslationModel.NeuralMachineTranslation: return; } throw new ArgumentException($"Unknown translation model {model}", nameof(model)); }
internal static string ToApiName(this TranslationModel model) { switch (model) { case TranslationModel.Base: return(BaseApiName); case TranslationModel.NeuralMachineTranslation: return(NeuralMachineTranslationApiName); default: throw new InvalidOperationException($"Unknown translation model {model}"); } }
// [START translate_text_with_model] static void TranslateWithModel(string text, string targetLanguageCode, string sourceLanguageCode, TranslationModel model) { TranslationClient client = TranslationClient.Create(); var response = client.TranslateText(text, targetLanguageCode, sourceLanguageCode, model); Console.WriteLine("Model: {0}", response.Model); Console.WriteLine(response.TranslatedText); }
public void TestAddTranslationShouldReturnTrue() { TranslationModel translation = new TranslationModel(); translation.Contents = new contents(); translation.Success = new success(); translation.Error = new error(); translation.Date = DateTime.Now; translation.Contents.text = "test"; translation.Contents.translation = "test"; Assert.IsTrue(_homeController.AddTranslation(translation)); }
public AddEditTranslationViewModel(TranslationModel p_translation) { CancelCommand = new RelayCommand(OnCancel); SaveCommand = new RelayCommand(OnSave, CanSave); if (p_translation != null) { SetTranslation(TranslationRepository.Instance.RetrieveDetail(p_translation.ID_TRA)); } else { SetTranslation(null); } }
internal static string ToApiName(this TranslationModel model) { switch (model) { // null in an outbound API call means "no client preference" case TranslationModel.ServiceDefault: return(null); case TranslationModel.Base: return(BaseApiName); case TranslationModel.NeuralMachineTranslation: return(NeuralMachineTranslationApiName); default: throw new InvalidOperationException($"Unknown translation model {model}"); } }
public string ToJson(TranslationModel model) { var stringBuilder = new StringBuilder(); stringBuilder.AppendLine("{"); stringBuilder.AppendLine($"\"key\": \"{model.key}\","); foreach (var translation in model.Translations) { stringBuilder.AppendLine($"\"{translation.Key}\": \"{translation.Value.Replace("\"", "\\\"")}\","); } stringBuilder.AppendLine("},"); return(stringBuilder.ToString()); }
/// <summary> /// Get model details. /// /// Gets information about a translation model, including training status for custom models. Use this API call /// to poll the status of your customization request. A successfully completed training will have a status of /// `available`. /// </summary> /// <param name="modelId">Model ID of the model to get.</param> /// <param name="customData">Custom data object to pass data including custom request headers.</param> /// <returns><see cref="TranslationModel" />TranslationModel</returns> public TranslationModel GetModel(string modelId, Dictionary <string, object> customData = null) { if (string.IsNullOrEmpty(modelId)) { throw new ArgumentNullException(nameof(modelId)); } if (string.IsNullOrEmpty(VersionDate)) { throw new ArgumentNullException("versionDate cannot be null."); } TranslationModel result = null; try { IClient client = this.Client; if (_tokenManager != null) { client = this.Client.WithAuthentication(_tokenManager.GetToken()); } if (_tokenManager == null) { client = this.Client.WithAuthentication(this.UserName, this.Password); } var restRequest = client.GetAsync($"{this.Endpoint}/v3/models/{modelId}"); restRequest.WithArgument("version", VersionDate); if (customData != null) { restRequest.WithCustomData(customData); } restRequest.WithHeader("X-IBMCloud-SDK-Analytics", "service_name=language_translator;service_version=v3;operation_id=GetModel"); result = restRequest.As <TranslationModel>().Result; if (result == null) { result = new TranslationModel(); } result.CustomData = restRequest.CustomData; } catch (AggregateException ae) { throw ae.Flatten(); } return(result); }