private void Translate() { Cursor = Cursors.WaitCursor; try { string from = ((GoogleTranslate.ComboBoxItem)comboBoxFrom.SelectedItem).Value; string to = ((GoogleTranslate.ComboBoxItem)comboBoxTo.SelectedItem).Value; buttonGoogle.Text = string.Empty; // google translate buttonGoogle.Text = new GoogleTranslator1().Translate(from, to, new List <Paragraph> { new Paragraph { Text = textBoxSourceText.Text } }, new StringBuilder()).FirstOrDefault(); // ms translator if (!string.IsNullOrEmpty(Configuration.Settings.Tools.MicrosoftTranslatorApiKey) && !string.IsNullOrEmpty(Configuration.Settings.Tools.MicrosoftTranslatorTokenEndpoint)) { var translator = new MicrosoftTranslator(Configuration.Settings.Tools.MicrosoftTranslatorApiKey, Configuration.Settings.Tools.MicrosoftTranslatorTokenEndpoint, Configuration.Settings.Tools.MicrosoftTranslatorCategory); var result = translator.Translate(from, to, new List <Paragraph> { new Paragraph { Text = textBoxSourceText.Text } }, new StringBuilder()); buttonMicrosoft.Text = result[0]; } } finally { Cursor = Cursors.Default; } }
public TranslationMiddleware(MicrosoftTranslator translator, ChatbotStateAccessor accessor) { _translator = translator ?? throw new ArgumentNullException(nameof(translator)); _accessor = accessor ?? throw new System.ArgumentNullException(nameof(accessor)); _dialogs = new DialogSet(_accessor.ConversationDialogState); }
public DispatchBot(IBotServices botServices, ILogger <DispatchBot> logger, UserState userState, MicrosoftTranslator translator) { _logger = logger; _botServices = botServices; _userState = userState ?? throw new NullReferenceException(nameof(userState)); _translator = translator ?? throw new ArgumentNullException(nameof(translator)); _languagePreference = userState.CreateProperty <string>("LanguagePreference"); }
public MultilingualCardAction(string language) { _language = language; // Translation key from settings var translatorKey = Ready19.RockTheBot.Startup.TranslationKey; _translator = new MicrosoftTranslator(translatorKey); }
public void TranslateText() { var s = "Hello, world!"; var ms = new MicrosoftTranslator("English", "Finnish"); //var tl = ms.Translate(s); //Assert.AreEqual("Moi maailma!", tl); Assert.Pass("Auto pass to reduce character consumption"); }
public TranslationBot( ApplicationContext context, ILogger <TranslationBot> logger, MicrosoftTranslator translator) { _context = context ?? throw new ArgumentNullException(nameof(context)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _translator = translator ?? throw new ArgumentNullException(nameof(translator)); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddBot <MainBot>(options => { var secretKey = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; // Read BotConfiguration.bot and register it in IServiceCollection var botConfig = BotConfiguration.Load(botFilePath ?? @". \ BotConfiguration.bot", secretKey); services.AddSingleton(_ => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded. ({botConfig})")); // Optional. Logging and error handling var logger = LoggerFactory.CreateLogger <MainBot>(); options.OnTurnError = async(context, ex) => { logger.LogError($"Exception caught: {ex}"); await context.SendActivityAsync("Sorry, it looks like something went wrong."); }; // Obtain information on the endpoint of the current environment from BotConfiguration.bot. If not, it is an error. var environment = IsProduction ? "production" : "development"; var endpointService = botConfig .Services .FirstOrDefault(x => x.Type == "endpoint" && x.Name == environment) as EndpointService ?? throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); // Add Bot's authentication information options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); // For development purposes only!In - memory store.The actual number seems to be Blob or something var storage = new MemoryStorage(); var conversationState = new ConversationState(storage); var userState = new UserState(storage); options.State.Add(conversationState); options.State.Add(userState); // Translation var translatorKey = "2faace0dff53457ca8538f7a635f73a8"; var translator = new MicrosoftTranslator(translatorKey); var translationMiddleware = new TranslationMiddleware(translator, userState.CreateProperty <string>("LanguagePreference")); options.Middleware.Add(translationMiddleware); }); // Add MainBotAccessor for state management services.AddSingleton(sp => { var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value ?? throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors"); var conversationState = options.State.OfType <ConversationState>().FirstOrDefault() ?? throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors."); var userState = options.State.OfType <UserState>().FirstOrDefault() ?? throw new InvalidOperationException("UserState must be defined and added before adding user-scoped state accessors."); return(new MainBotAccessors(conversationState, userState)); }); }
public void Execute(IUBotStudio ubotStudio, Dictionary <string, string> parameters) { var clientId = parameters["Client Id"].Trim(); var clientSecret = parameters["Client Secret"].Trim(); var text = parameters["Text"]; var originalLanguage = parameters["Original Language"]; var destinationLanguage = parameters["Destination Language"]; MicrosoftTranslator microsoftTranslator = new MicrosoftTranslator(clientId, clientSecret); _returnValue = microsoftTranslator.Translate(text, originalLanguage, destinationLanguage); }
private void StartExecution() { var sourceLang = (Language)this.cbSourceLanguage.SelectedItem; var destinationLang = (Language)this.cbDestinationLanguage.SelectedItem; var translator = new MicrosoftTranslator(sourceLang, destinationLang); // Get AuthorizationKey from https://account.azure.com/ Translate Text service translator.AuthorizationKey = this.tbKey.Text; var executor = new ResxTranslator(this.tbRootFolder.Text, translator); executor.Start(this.cxBUseFallbackResx.Checked); }
private void Translate() { Cursor = Cursors.WaitCursor; try { string from = (comboBoxFrom.SelectedItem as GoogleTranslate.ComboBoxItem).Value; string to = (comboBoxTo.SelectedItem as GoogleTranslate.ComboBoxItem).Value; string languagePair = from + "|" + to; buttonGoogle.Text = string.Empty; // google translate bool romanji = languagePair.EndsWith("|romanji", StringComparison.InvariantCulture); if (romanji) { languagePair = from + "|ja"; } var screenScrapingEncoding = GoogleTranslate.GetScreenScrapingEncoding(languagePair); buttonGoogle.Text = GoogleTranslate.TranslateTextViaScreenScraping(textBoxSourceText.Text, languagePair, screenScrapingEncoding, romanji); // ms translator if (!string.IsNullOrEmpty(Configuration.Settings.Tools.MicrosoftTranslatorApiKey)) { var translator = new MicrosoftTranslator(Configuration.Settings.Tools.MicrosoftTranslatorApiKey); var result = translator.Translate(from, to, new List <string> { textBoxSourceText.Text }, new StringBuilder()); buttonMicrosoft.Text = result[0]; } else { using (var gt = new GoogleTranslate()) { var subtitle = new Subtitle(); subtitle.Paragraphs.Add(new Paragraph(0, 0, textBoxSourceText.Text)); gt.Initialize(subtitle, string.Empty, false, Encoding.UTF8); from = FixMsLocale(from); to = FixMsLocale(to); gt.DoMicrosoftTranslate(from, to); buttonMicrosoft.Text = gt.TranslatedSubtitle.Paragraphs[0].Text; } } } finally { Cursor = Cursors.Default; } }
private void Translate() { Cursor = Cursors.WaitCursor; try { string from = ((GoogleTranslate.ComboBoxItem)comboBoxFrom.SelectedItem).Value; string to = ((GoogleTranslate.ComboBoxItem)comboBoxTo.SelectedItem).Value; buttonGoogle.Text = string.Empty; // google translate buttonGoogle.Text = new GoogleTranslator1().Translate(from, to, new List <Paragraph> { new Paragraph { Text = textBoxSourceText.Text } }, new StringBuilder()).FirstOrDefault(); // ms translator if (!string.IsNullOrEmpty(Configuration.Settings.Tools.MicrosoftTranslatorApiKey)) { var translator = new MicrosoftTranslator(Configuration.Settings.Tools.MicrosoftTranslatorApiKey); var result = translator.Translate(from, to, new List <Paragraph> { new Paragraph { Text = textBoxSourceText.Text } }, new StringBuilder()); buttonMicrosoft.Text = result[0]; } else { using (var gt = new GoogleTranslate()) { var subtitle = new Subtitle(); subtitle.Paragraphs.Add(new Paragraph(0, 0, textBoxSourceText.Text)); gt.Initialize(subtitle, string.Empty, false, Encoding.UTF8); from = FixMsLocale(from); to = FixMsLocale(to); gt.DoMicrosoftTranslate(from, to); buttonMicrosoft.Text = gt.TranslatedSubtitle.Paragraphs[0].Text; } } } finally { Cursor = Cursors.Default; } }
public WelcomeUserBot(WelcomeUserStateAccessors statePropertyAccessor, MicrosoftTranslator translator, LuisServices luisservices) { this._welcomeUserStateAccessors = statePropertyAccessor ?? throw new System.ArgumentNullException("state accessor can't be null"); // Translator this._translator = translator; // LUIS definition this._luisServices = luisservices; // Dialog Waterfalls this._dialogs = new DialogSet(statePropertyAccessor.ConversationDialogState); this._dialogs.Add(new WaterfallDialog("introDialog", new WaterfallStep[] { ChoiceCardStepAsync, ShowCardStepAsync })); this._dialogs.Add(new WaterfallDialog("hotelDialog", new WaterfallStep[] { LocationStepAsync, HotelStepAsync, GuestsStepAsync, RoomSelectionStepAsync, CheckInStepAsync, CheckOutStepAsync, LastStepAsync })); // Prompts this._dialogs.Add(new ChoicePrompt("regionPrompt")); this._dialogs.Add(new TextPrompt("hotelPrompt")); this._dialogs.Add(new ChoicePrompt("roomPrompt")); this._dialogs.Add(new ChoicePrompt("cardPrompt")); this._dialogs.Add(new NumberPrompt <int>("guestPrompt")); this._dialogs.Add(new DateTimePrompt("checkinPrompt")); this._dialogs.Add(new DateTimePrompt("checkoutPrompt")); }
public VTTTranslator(string key) { translator = new MicrosoftTranslator(key); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">Specifies the contract for a <see cref="IServiceCollection"/> of service descriptors.</param> public void ConfigureServices(IServiceCollection services) { services.AddBot <RockTheBot>(options => { var secretKey = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; if (!File.Exists(botFilePath)) { throw new FileNotFoundException($"The .bot configuration file was not found. botFilePath: {botFilePath}"); } // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection. var botConfig = BotConfiguration.Load(botFilePath ?? @".\rockthebot.bot", secretKey); services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot configuration file could not be loaded. botFilePath: {botFilePath}")); // Retrieve current endpoint. var environment = _isProduction ? "production" : "development"; var service = botConfig.Services.FirstOrDefault(s => s.Type == "endpoint" && s.Name == environment); if (!(service is EndpointService endpointService)) { throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); } //options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); //BOT ID and Pass are stored as env variables and injected by Kubernetes at runtime options.CredentialProvider = new SimpleCredentialProvider( Environment.GetEnvironmentVariable("_ROCKTHEBOTAPPID") ?? string.Empty, Environment.GetEnvironmentVariable("_ROCKTHEBOTAPPPWD") ?? string.Empty); // Creates a logger for the application to use. ILogger logger = _loggerFactory.CreateLogger <RockTheBot>(); // Catches any errors that occur during a conversation turn and logs them. options.OnTurnError = async(turnContext, exception) => { logger.LogError($"Exception caught : {exception}"); // By-pass the middleware by sending the Activity directly on the Adapter. var activity = MessageFactory.Text("Sorry, it looks like something went wrong."); activity.ApplyConversationReference(turnContext.Activity.GetConversationReference()); await turnContext.Adapter.SendActivitiesAsync(turnContext, new[] { activity }, default(CancellationToken)); }; // The Memory Storage used here is for local bot debugging only. When the bot // is restarted, everything stored in memory will be gone. IStorage dataStore = new MemoryStorage(); // For production bots use the Azure Blob or // Azure CosmosDB storage providers. For the Azure // based storage providers, add the Microsoft.Bot.Builder.Azure // Nuget package to your solution. That package is found at: // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/ // Uncomment the following lines to use Azure Blob Storage // Storage configuration name or ID from the .bot file. // const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>"; // var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId); // if (!(blobConfig is BlobStorageService blobStorageConfig)) // { // throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'."); // } // // Default container name. // const string DefaultBotContainer = "<DEFAULT-CONTAINER>"; // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container; // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer); // Create and add conversation state. var convoState = new ConversationState(dataStore); options.State.Add(convoState); // Create and add user state. var userState = new UserState(dataStore); options.State.Add(userState); // Translation key from settings TranslationKey = Configuration.GetValue <string>("translatorKey"); if (string.IsNullOrEmpty(TranslationKey)) { throw new InvalidOperationException("Microsoft Text Translation API key is missing. Please add your translation key to the 'translatorKey' setting."); } // Translation middleware setup var translator = new MicrosoftTranslator(TranslationKey); //TODO: complete the code! }); // Create and register state accessors. // Accessors created here are passed into the IBot-derived class on every turn. services.AddSingleton(sp => { // We need to grab the conversationState we added on the options in the previous step var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value; if (options == null) { throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors"); } var conversationState = options.State.OfType <ConversationState>().FirstOrDefault(); if (conversationState == null) { throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors."); } var userState = options.State.OfType <UserState>().FirstOrDefault(); if (userState == null) { throw new InvalidOperationException("UserState must be defined and added before adding user-scoped state accessors."); } // Create the custom state accessor. // State accessors enable other components to read and write individual properties of state. var accessors = new RockTheBotAccessors(conversationState, userState) { ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"), LanguagePreference = userState.CreateProperty <string>("LanguagePreference"), WelcomeUserState = userState.CreateProperty <WelcomeUserState>(RockTheBotAccessors.WelcomeUserName), LanguageKey = userState.CreateProperty <string>(RockTheBotAccessors.TranslationKey), }; return(accessors); }); // add config to the DI container services.AddSingleton <IConfiguration>(Configuration); services.AddSingleton <IRockTheBotServices, RockTheBotServices>(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Get available languages from DB var dbCultures = new List <CultureInfo>(); using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope()) { var context = serviceScope.ServiceProvider.GetRequiredService <SportContext>(); context.Database.EnsureCreated(); SeedData.Initialize(context); var languages = context.SportLanguage.Select(s => s.Language).Distinct(); foreach (var language in languages) { dbCultures.Add(new CultureInfo(language)); } } if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Get machine translation languages, if any var key = Startup.Configuration["MicrosoftTranslator:Key"]; var endpoint = Startup.Configuration["MicrosoftTranslator:Endpoint"]; if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(endpoint)) { var machineTranslator = new MicrosoftTranslator(key, endpoint); var languages = machineTranslator.GetLanguages(); foreach (var language in languages) { if (dbCultures.Find(c => c.Name == language.Id) == null) { dbCultures.Add(new CultureInfo(language.Id)); } } } // Use db languages to set the available languages for localization var supportedCultures = dbCultures.ToArray(); var options = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en"), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }; app.UseRequestLocalization(options); app.UseRouting(); app.UseCors("ApiPolicy"); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }