private void SendConfigurationIfRequired() { var configForExternalProcess = ConfigForExternalProcess; if (configForExternalProcess != null) { var id = Guid.NewGuid(); try { var request = new ConfigurationMessage { Id = id, Config = ConfigForExternalProcess, }; var payload = ExtProtocolConvert.Encode(request); _process.StandardInput.WriteLine(payload); } catch (Exception e) { XuaLogger.AutoTranslator.Error(e, $"An error occurred while sending configuration to external process for '{GetType().Name}'."); } } }
private void ReaderLoop(object state) { try { if (_process == null) { string fullPath = ExecutablePath; if (!Path.IsPathRooted(fullPath)) { try { fullPath = Path.Combine(Paths.GameRoot, ExecutablePath); } catch { fullPath = Path.Combine(Environment.CurrentDirectory, ExecutablePath); } } _process = new Process(); _process.StartInfo.FileName = fullPath; _process.StartInfo.Arguments = Arguments; _process.StartInfo.WorkingDirectory = new FileInfo(ExecutablePath).Directory.FullName; _process.EnableRaisingEvents = false; _process.StartInfo.UseShellExecute = false; _process.StartInfo.CreateNoWindow = true; _process.StartInfo.RedirectStandardInput = true; _process.StartInfo.RedirectStandardOutput = true; _process.StartInfo.RedirectStandardError = true; _process.Start(); // wait a second... _process.WaitForExit(2500); } if (_process.HasExited) { return; } SendConfigurationIfRequired(); _initializing = false; while (!_disposed) { var returnedPayload = _process.StandardOutput.ReadLine(); var response = ExtProtocolConvert.Decode(returnedPayload); HandleProtocolMessageResponse(response); } } catch (Exception e) { _failed = true; _initializing = false; XuaLogger.AutoTranslator.Error(e, "Error occurred while reading standard output from external process."); } }
/// <summary> /// Attempt to translated the provided untranslated text. Will be used in a "coroutine", /// so it can be implemented in an asynchronous fashion. /// </summary> public IEnumerator Translate(ITranslationContext context) { EnsureInitialized(); while (_initializing && !_failed) { yield return(new WaitForSeconds(0.2f)); } if (_failed) { context.Fail("External process failed."); } var result = new ProtocolTransactionHandle(); var id = Guid.NewGuid(); lock ( _sync ) { _transactionHandles[id] = result; } try { var request = new TranslationRequest { Id = id, SourceLanguage = context.SourceLanguage, DestinationLanguage = context.DestinationLanguage, UntranslatedTexts = context.UntranslatedTexts }; var payload = ExtProtocolConvert.Encode(request); _process.StandardInput.WriteLine(payload); } catch (Exception e) { result.SetCompleted(null, e.Message); } // yield-wait for completion var iterator = result.GetSupportedEnumerator(); while (iterator.MoveNext()) { yield return(iterator.Current); } if (!result.Succeeded) { context.Fail("Error occurred while retrieving translation. " + result.Error); } context.Complete(result.Results); }
private void ReaderLoop( object state ) { try { if( _process == null ) { _process = new Process(); _process.StartInfo.FileName = ExecutablePath; _process.StartInfo.Arguments = Arguments; _process.EnableRaisingEvents = false; _process.StartInfo.UseShellExecute = false; _process.StartInfo.CreateNoWindow = true; _process.StartInfo.RedirectStandardInput = true; _process.StartInfo.RedirectStandardOutput = true; _process.StartInfo.RedirectStandardError = true; _process.Start(); // wait a second... _process.WaitForExit( 2500 ); } if( _process.HasExited ) { return; } _initializing = false; while( !_disposed ) { var returnedPayload = _process.StandardOutput.ReadLine(); var response = ExtProtocolConvert.Decode( returnedPayload ); HandleProtocolMessageResponse( response ); } } catch( Exception e ) { _failed = true; _initializing = false; XuaLogger.Current.Error( e, "Error occurred while reading standard output from external process." ); } }
/// <summary> /// Attempt to translated the provided untranslated text. Will be used in a "coroutine", /// so it can be implemented in an asynchronous fashion. /// </summary> public IEnumerator Translate(ITranslationContext context) { EnsureInitialized(); while (_initializing && !_failed) { var instruction = Features.GetWaitForSecondsRealtime(0.2f); if (instruction != null) { yield return(instruction); } else { yield return(null); } } if (_failed) { context.Fail("External process failed."); } var totalDelay = (float)(Rng.Next((int)((MaxDelay - MinDelay) * 1000)) + (MinDelay * 1000)) / 1000; var timeSinceLast = TimeSupport.Time.realtimeSinceStartup - _lastRequestTimestamp; if (timeSinceLast < totalDelay) { var remainingDelay = totalDelay - timeSinceLast; var instruction = Features.GetWaitForSecondsRealtime(remainingDelay); if (instruction != null) { yield return(instruction); } else { float start = TimeSupport.Time.realtimeSinceStartup; var end = start + remainingDelay; while (TimeSupport.Time.realtimeSinceStartup < end) { yield return(null); } } } _lastRequestTimestamp = TimeSupport.Time.realtimeSinceStartup; var result = new ProtocolTransactionHandle(); var id = Guid.NewGuid(); lock ( _sync ) { _transactionHandles[id] = result; } try { var request = new TranslationRequest { Id = id, SourceLanguage = context.SourceLanguage, DestinationLanguage = context.DestinationLanguage, UntranslatedTextInfos = context.UntranslatedTextInfos.Select(x => x.ToTransmittable()).ToArray() }; var payload = ExtProtocolConvert.Encode(request); _process.StandardInput.WriteLine(payload); } catch (Exception e) { result.SetCompleted(null, e.Message, StatusCode.Unknown); } // yield-wait for completion var iterator = result.GetSupportedEnumerator(); while (iterator.MoveNext()) { yield return(iterator.Current); } if (!result.Succeeded) { context.Fail("Error occurred while retrieving translation. " + result.Error); } context.Complete(result.Results); }
public async Task RunAsync() { using (var stdout = Console.OpenStandardOutput()) using (var writer = new StreamWriter(stdout)) using (var stdin = Console.OpenStandardInput()) using (var reader = new StreamReader(stdin)) { writer.AutoFlush = true; while (true) { var receivedPayload = reader.ReadLine(); if (string.IsNullOrEmpty(receivedPayload)) { return; } var message = ExtProtocolConvert.Decode(receivedPayload) as TranslationRequest; if (message == null) { return; } var context = new TranslationContext(message.UntranslatedTexts, message.SourceLanguage, message.DestinationLanguage); try { await Endpoint.Translate(context); } catch (Exception e) { context.FailWithoutThrowing("An error occurred in the pipeline.", e); } ProtocolMessage response; if (!string.IsNullOrEmpty(context.ErrorMessage) || context.Error != null) { string errorMessage = context.ErrorMessage; if (context.Error != null) { if (!string.IsNullOrEmpty(errorMessage)) { errorMessage += Environment.NewLine; } errorMessage += context.Error.ToString(); } response = new TranslationError { Id = message.Id, Reason = errorMessage }; } else { response = new TranslationResponse { Id = message.Id, TranslatedTexts = context.TranslatedTexts }; } var translatedPayload = ExtProtocolConvert.Encode(response); writer.WriteLine(translatedPayload); } } }
static void Main(string[] args) { // Implementation of this is based off of texel-sensei's LEC implementation try { if (args.Length == 0) { Console.WriteLine("This program is automatically run during a game session if LEC is selected, and will be automatically stopped afterwards. This program cannot be run independently."); Console.WriteLine("Press any key to exit."); Console.ReadKey(); return; } var powerTranslatorPathPayload = args[0]; var powerTranslatorPath = Encoding.UTF8.GetString(Convert.FromBase64String(powerTranslatorPathPayload)); var dllPath = Path.Combine(powerTranslatorPath, @"Nova\JaEn\EngineDll_je.dll"); using (var translator = new LecTranslationLibrary(dllPath)) { using (var stdout = Console.OpenStandardOutput()) using (var writer = new StreamWriter(stdout)) using (var stdin = Console.OpenStandardInput()) using (var reader = new StreamReader(stdin)) { writer.AutoFlush = true; while (true) { var receivedPayload = reader.ReadLine(); if (string.IsNullOrEmpty(receivedPayload)) { return; } var message = ExtProtocolConvert.Decode(receivedPayload) as TranslationRequest; if (message == null) { return; } var translatedTexts = new string[message.UntranslatedTexts.Length]; for (int i = 0; i < message.UntranslatedTexts.Length; i++) { var untranslatedText = message.UntranslatedTexts[i]; var translatedText = translator.Translate(untranslatedText); translatedTexts[i] = translatedText; } var response = new TranslationResponse { Id = message.Id, TranslatedTexts = translatedTexts }; var translatedPayload = ExtProtocolConvert.Encode(response); writer.WriteLine(translatedPayload); } } } } catch (Exception) { // "Graceful shutdown" } }
static void Main(string[] args) { try { if (args.Length == 0) { Console.WriteLine("This program is automatically run during a game session if ezTrans is selected, and will be automatically stopped afterwards. This program cannot be run independently."); Console.WriteLine("Press any key to exit."); Console.ReadKey(); return; } var powerTranslatorPathPayload = args[0]; var powerTranslatorPath = Encoding.UTF8.GetString(Convert.FromBase64String(powerTranslatorPathPayload)); var datPath = Path.Combine(powerTranslatorPath, @"Dat"); //initialize path var dllPath = Path.Combine(powerTranslatorPath, @"J2KEngineH.dll"); //Ehnd engine path if (!File.Exists(dllPath)) { dllPath = Path.Combine(powerTranslatorPath, @"J2KEngine.dll"); } using (var translator = new ezTransTranslationLibrary(dllPath)) { if (!translator.InitEx("CSUSER123455", datPath)) //initialize ezTrans { throw new Exception("J2K_InitializeEx Failed."); } using (var stdout = Console.OpenStandardOutput()) using (var writer = new StreamWriter(stdout)) using (var stdin = Console.OpenStandardInput()) using (var reader = new StreamReader(stdin)) { writer.AutoFlush = true; while (true) { var receivedPayload = reader.ReadLine(); if (string.IsNullOrEmpty(receivedPayload)) { return; } var message = ExtProtocolConvert.Decode(receivedPayload) as TranslationRequest; if (message == null) { return; } var translatedTexts = new string[message.UntranslatedTexts.Length]; for (int i = 0; i < message.UntranslatedTexts.Length; i++) { var untranslatedText = message.UntranslatedTexts[i]; var translatedText = translator.Translate(untranslatedText); translatedTexts[i] = translatedText; } var response = new TranslationResponse { Id = message.Id, TranslatedTexts = translatedTexts }; var translatedPayload = ExtProtocolConvert.Encode(response); writer.WriteLine(translatedPayload); } } } } catch (Exception) { // "Graceful shutdown" } }