/// <summary> /// Loads mod's scripting features. /// Returns true if successful. /// </summary> public static bool LoadEngine(bool verbose = false) { if (PythonEnvironment.LoadPythonAssembly()) { try { PythonEnvironment.InitializeEngine(); CreateScriptingEnvironment(); _component = Mod.Controller.AddComponent <ScriptComponent>(); if (verbose) { ModConsole.AddMessage(LogType.Log, $"[LenchScripterMod]: {Python.Execute("sys.version")}"); } Mod.LoadedScripter = true; } catch (Exception e) { if (verbose) { ModConsole.AddMessage(LogType.Log, "[LenchScripterMod]: Error while initializing python engine:", e.ToString()); } Mod.LoadedScripter = false; } } else { Mod.LoadedScripter = false; } return(Mod.LoadedScripter); }
public override int Run(string[] remainingArguments) { Console.OutputEncoding = Encoding.UTF8; GradientLog.WarningWriter = GradientLog.OutputWriter = Console.Error; if (!string.IsNullOrEmpty(this.CondaEnv)) { GradientSetup.UsePythonEnvironment(PythonEnvironment.EnumerateCondaEnvironments() .Single(env => Path.GetFileName(env.Home) == this.CondaEnv)); } var generator = new Gpt2TextGenerator( modelName: this.ModelName, checkpoint: this.Checkpoint, sampleLength: this.MaxLength); uint seed = this.Seed ?? GetRandomSeed(); string text = generator.GenerateSample(seed); while (text.StartsWith(generator.EndOfText)) { text = text.Substring(generator.EndOfText.Length); } int end = text.IndexOf(generator.EndOfText, StringComparison.Ordinal); if (end < 0) { Console.Error.WriteLine("Text generated from this seed is longer than max-length."); Console.WriteLine(text); return(-2); } Console.Write(text.Substring(0, end)); return(0); }
// Use this for initialization void Start() { m_pyEnv = new PythonEnvironment(); m_pyEnv.RunCommand(INITIALIZATION_CODE); m_pyOutput = string.Empty; m_pyCode = "for i in xrange(5):\n g = UnityEngine.GameObject.CreatePrimitive(UnityEngine.PrimitiveType.Sphere)\n g.name = 'PySphere' + str(i)\nprint 'Created 5 spheres'\n"; }
public override void Launch(LaunchConfig config) { switch (_cmdName.Trim()) { case "RegisterExplorerContextMenu": { if (ShellIntegration.RegisterContextMenu()) { ErrorLog.Inst.ShowInfo("Explorer Context Menu Registration Completed."); } } break; case "WriteConfigRegistryValues": { var launchTool = Editors.EditorFactory.Inst.GetEditor(RuntimeInfo.Generic); launchTool.UpdateRegistry(Configs_Root.Inst.Configs); ErrorLog.Inst.ShowInfo("Environment Registry Integration completed"); } break; case "UpdatePythonScriptFolder": { var pythonEnv = new PythonEnvironment(); pythonEnv.UpdateScripts(Configs_Root.Inst); ErrorLog.Inst.ShowInfo("Updating Python Environment Scripts folder is completed"); } break; } }
private void Start() { var engine = PythonEnvironment.CreateEngine(); var scope = engine.CreateScope(); var source = "print('Hello World')"; engine.Execute(source, scope); }
// Use this for initialization void Start() { m_pyEnv = new PythonEnvironment(); m_pyEnv.RunCommand(INITIALIZATION_CODE); m_pyEnv.ExposeVariable("Behavior", typeof(PyTest.PyBehaviorBase)); m_pyOutput = string.Empty; m_pyCode = "from UnityEngine import GameObject, Vector3, PrimitiveType\nfrom MyScripts import MyCustomClass\n\nfor i in xrange(5):\n g = GameObject.CreatePrimitive(PrimitiveType.Sphere)\n g.name = 'PySphere' + str(i)\n g.transform.position = Vector3(i, i, 0)\n g.AddComponent(MyCustomClass)\n c = g.GetComponent(MyCustomClass)\n c.someValue = i\nprint 'Created 5 spheres'\n"; }
private void Start() { var engine = PythonEnvironment.CreateEngine(); var scope = engine.CreateScope(); var source = "import UnityEngine\nUnityEngine.Debug.Log('Unity Hello World')"; engine.IncludeUnityLibraries(); engine.Execute(source, scope); }
private void OnDestroy() { DestroyScriptingEnvironment(); PythonEnvironment.DestroyEngine(); Destroy(DependencyInstaller.Instance); Destroy(BlockHandlerController.Instance); Destroy(Watchlist.Instance); Destroy(IdentifierDisplay.Instance); Destroy(ScriptOptions.Instance); }
private void Start() { var engine = PythonEnvironment.CreateEngine(); var scope = engine.CreateScope(); var source = "import random\nvalue = random.choice([1, 2, 3, 4, 5, 6, 7])"; engine.IncludeNativeLibrary(); engine.IncludeUnityLibraries(); engine.Execute(source, scope); Debug.Log(scope.GetVariable <int>("value")); }
/// <summary> /// Executes Python code and updates output value. /// </summary> protected override void Update() { if (!PythonEnvironment.Loaded) { return; } if (!Running && initialised) { // Stops running if not initialised initialised = false; Running = false; } if (!Running) { return; } if (initialised) { try { // Attempts to run the update code. var result = update.Invoke(); if (result == null) { Error = "Update code does not return a value."; Running = false; } else if (result is float || result is int || result is double) { OutputValue = Mathf.Clamp(Convert.ToSingle(result), -1f, 1f); } else { Error = "Update code returns " + result.GetType() + "\ninstead of number."; Running = false; } } catch (Exception e) { // On raised exception, it displays it and stops execution. if (e.InnerException != null) { e = e.InnerException; } Error = PythonEnvironment.FormatException(e); Running = false; initialised = false; } } else { // Initializes axis when starting through Running toggle. Initialise(); } }
private void Awake() { engine = PythonEnvironment.CreateEngine(); scope = engine.CreateScope(); engine.IncludeNativeLibrary(); engine.IncludeUnityLibraries(); var script = engine.CreateScriptSourceFromString(ScriptSource.text); var binary = script.Compile(); binary.Execute(scope); scope.GetVariable <function>(FunctionInitialize != null ? FunctionInitialize: "OnInitialize")?.Invoke(this); scope.GetVariable <function>(FunctionAwake != null ? FunctionAwake : "OnAwake")?.Invoke(this); }
/// <summary> /// Initializes Python environment and compiles code. /// Sets Running to true if successfull. /// </summary> protected override void Initialise() { if (!PythonEnvironment.Loaded) { return; } init = null; update = null; initialised = false; if (!Running && !Game.IsSimulating) { return; } Error = null; Running = false; if (GlobalScope) { if (PythonEnvironment.ScripterEnvironment == null) { InitGlobalScope(); } python = PythonEnvironment.ScripterEnvironment; } else { python = new PythonEnvironment(); } try { // Attempts to compile initialisation and update code. init = python.Compile(InitialisationCode); update = python.Compile(UpdateCode); // Executes initialisation code and checks it's scope for linked axes. init.Invoke(); LinkAxes(); } catch (Exception e) { if (e.InnerException != null) { e = e.InnerException; } Error = PythonEnvironment.FormatException(e); return; } Running = true; initialised = true; }
public override GH_LoadingInstruction PriorityLoad() { try { _gha_environment = CreateEnvironment(); LoadExternalPythonAssemblies(); SetupMainDirListener(); } catch (Exception ex) { Global_Proc.ASSERT(Guid.Empty, "GhPython last exception boundary", ex); } return(GH_LoadingInstruction.Proceed); }
/// <summary> /// Sets the Python engine version and reloads. /// </summary> public static void SetVersionAndReload(string version) { var requiresReload = PythonEnvironment.Version != version; PythonEnvironment.Version = version; if (!requiresReload) { return; } if (LoadEngine(true)) { return; } PythonEnvironment.DestroyEngine(); DependencyInstaller.InstallIronPython(); }
// Use this for initialization void Start() { spheres = new List <GameObject>(); m_pyEnv = new PythonEnvironment(); m_pyEnv.RunCommand(INITIALIZATION_CODE); m_pyEnv.RunCommand("from UnityEngine import GameObject, Vector3, PrimitiveType, Mathf"); PythonEnvironment.CommandResult r = m_pyEnv.RunCommand("from json import decoder"); if (r.exception != null) { Debug.Log(r.exception.ToString()); } m_pyEnv.ExposeVariable("Behavior", typeof(PyTest.PyBehaviorBase)); spheres.Add(GameObject.CreatePrimitive(PrimitiveType.Sphere)); m_pyEnv.ExposeVariable("timer", timer); m_pyCode = System.IO.File.ReadAllText("Test.py"); input = new PythonInput(); input.index = new int[20]; for (int i = 0; i < input.index.Length; i++) { input.index[i] = i; } input.timer = new float[20]; for (int i = 0; i < input.index.Length; i++) { input.timer[i] = i * 1f; } string json = JsonUtility.ToJson(input); }
public static void Error(Exception e) { _component.enabled = false; Debug.Log($"<b><color=#FF0000>Python error: {e.Message}</color></b>\n{PythonEnvironment.FormatException(e)}"); OnError?.Invoke(); }
private static void DestroyScriptingEnvironment() { Python = null; }
private static void CreateScriptingEnvironment() { Python = new PythonEnvironment(); }
public void SetupEnvironment() { PythonScriptScope = PythonEnvironment.CreateScope(); }
private static void InstallIronPython() { if (PythonEnvironment.LoadPythonAssembly()) { download_button_text = "Complete"; return; } downloading_in_progress = true; download_button_text = "0.0 %"; if (!Directory.Exists(Application.dataPath + "/Mods/Resources/LenchScripter/lib/")) { Directory.CreateDirectory(Application.dataPath + "/Mods/Resources/LenchScripter/lib/"); } try { for (int file_index = 0; file_index < files_required; file_index++) { using (var client = new WebClient()) { var i = file_index; // delete existing file if (File.Exists(Application.dataPath + file_paths[i])) { File.Delete(Application.dataPath + file_paths[i]); } // progress handler client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) => { received_size[i] = e.BytesReceived; float progress = (Convert.ToSingle(received_size.Sum()) / Convert.ToSingle(total_size.Sum()) * 100f); download_button_text = progress.ToString("0.0") + " %"; }; // completion handler client.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { if (e.Error != null) { // set error messages spaar.ModLoader.ModConsole.AddMessage(LogType.Log, "[ACM]: Error downloading file:" + file_paths[i].Split('/').Last()); spaar.ModLoader.ModConsole.AddMessage(LogType.Error, "\t" + e.Error.Message); downloading_in_progress = false; download_button_text = "Error"; // delete failed file if (File.Exists(Application.dataPath + file_paths[i])) { File.Delete(Application.dataPath + file_paths[i]); } } else { spaar.ModLoader.ModConsole.AddMessage(LogType.Log, "[ACM]: File downloaded: " + file_paths[i].Split('/').Last()); files_downloaded++; if (files_downloaded == files_required) { // finish download and load assemblies download_button_text = "Complete"; PythonEnvironment.LoadPythonAssembly(); } } }; // start download client.DownloadFileAsync( file_uris[i], Application.dataPath + file_paths[i]); } } } catch (Exception e) { Debug.Log("[ACM]: Error while downloading:"); Debug.LogException(e); downloading_in_progress = false; download_button_text = "Error"; } }
/// <summary> /// Called on python console command. /// </summary> /// <param name="args"></param> /// <param name="namedArgs"></param> /// <returns></returns> internal string PythonCommand(string[] args, IDictionary <string, string> namedArgs) { if (args.Length == 0) { return("Executes a Python expression."); } string expression = ""; for (int i = 0; i < args.Length; i++) { expression += args[i] + " "; } try { var result = PythonEnvironment.ScripterEnvironment.Execute(expression); return(result != null?result.ToString() : ""); } catch (Exception e) { if (e.InnerException != null) { e = e.InnerException; } Debug.Log("<b><color=#FF0000>Python error: " + e.Message + "</color></b>\n" + PythonEnvironment.FormatException(e)); return(""); } }
private void LoadScript() { try { if (scriptFile != null) { PythonEnvironment.ScripterEnvironment.LoadScript(scriptFile); } else if (scriptCode != null) { PythonEnvironment.ScripterEnvironment.LoadCode(scriptCode); } ScriptOptions.Instance.SuccessMessage = "Successfully compiled code."; } catch (Exception e) { if (e.InnerException != null) { e = e.InnerException; } ScriptOptions.Instance.ErrorMessage = "Error while compiling code.\nSee console (Ctrl+K) for more info."; Debug.Log("<b><color=#FF0000>Python error: " + e.Message + "</color></b>\n" + PythonEnvironment.FormatException(e)); } }
private ILyricsGenerator CreateGradientLyrics() { string condaEnvName = this.Configuration.GetValue <string>("PYTHON_CONDA_ENV_NAME", null); if (!string.IsNullOrEmpty(condaEnvName)) { GradientSetup.UsePythonEnvironment(PythonEnvironment.EnumerateCondaEnvironments() .Single(env => Path.GetFileName(env.Home) == condaEnvName)); } var logger = this.LoggerFactory.CreateLogger <Startup>(); bool download = this.Configuration.GetValue("Model:Download", defaultValue: true); string gpt2Root = this.Configuration.GetValue("GPT2_ROOT", Environment.CurrentDirectory); string checkpointName = this.Configuration.GetValue("Model:Checkpoint", "latest"); string modelName = this.Configuration.GetValue <string>("Model:Type", null) ?? throw new ArgumentNullException("Model:Type"); string modelRoot = Path.Combine(gpt2Root, "models", modelName); logger.LogInformation($"Using model from {modelRoot}"); if (!File.Exists(Path.Combine(modelRoot, "encoder.json"))) { if (download) { logger.LogInformation($"downloading {modelName} parameters"); ModelDownloader.DownloadModelParameters(gpt2Root, modelName); logger.LogInformation($"downloaded {modelName} parameters"); } else { throw new FileNotFoundException($"Can't find GPT-2 model in " + modelRoot); } } string runName = this.Configuration.GetValue <string>("Model:Run", null) ?? throw new ArgumentNullException("Model:Run"); string checkpoint = Gpt2Checkpoints.ProcessCheckpointConfig(gpt2Root, checkpointName, modelName: modelName, runName: runName); logger.LogInformation($"Using model checkpoint: {checkpoint}"); if (checkpoint == null || !File.Exists(checkpoint + ".index")) { if (download && checkpointName == "latest") { logger.LogInformation($"downloading the latest checkpoint for {modelName}, run {runName}"); checkpoint = ModelDownloader.DownloadCheckpoint( root: gpt2Root, modelName: modelName, runName: runName); logger.LogInformation("download successful"); } else { if (!download) { logger.LogWarning("Model downloading is disabled. See corresponding appsettings file."); } else if (checkpointName != "latest") { logger.LogWarning("Only the 'latest' model can be downloaded. You wanted: " + checkpointName); } throw new FileNotFoundException("Can't find checkpoint " + checkpoint + ".index"); } } return(new Gpt2LyricsGenerator( gpt2Root: gpt2Root, modelName: modelName, checkpoint: checkpoint, logger: this.LoggerFactory.CreateLogger <Gpt2LyricsGenerator>(), condaEnv: condaEnvName)); }
public void Execute(string source) { ScriptSource script = PythonEnvironment.CreateScriptSourceFromString(source); script.Execute(PythonScriptScope); }
private static bool LoadOneAddon(PythonEnvironment p, string path) { var engine = p.Engine as dynamic; var runtime = engine.Runtime; var ops = engine.Operations; if (ExternalUnsafe.HasZoneIdetifier(path)) { if (MessageBox.Show("A FILE IS BLOCKED: \n\n" + path + "\n\nBefore being able to use it, this file should be unblocked.\n" + "Do you want attempt to unblock it now?", "GhPython Assembly is blocked", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2, MessageBoxOptions.DefaultDesktopOnly) == DialogResult.Yes) { if (!ExternalUnsafe.Unblock(path)) { Global_Proc.ASSERT(Guid.Empty, "You need to unblock \"" + path + "\" manually."); return(false); } } } AssemblyName assName; try { assName = AssemblyName.GetAssemblyName(path); } catch (SecurityException ex) { Global_Proc.ASSERT(Guid.Empty, "You have not enough rights to load \"" + path + "\".", ex); return(false); } catch (BadImageFormatException ex) { Global_Proc.ASSERT(Guid.Empty, "The assembly \"" + path + "\" has a bad format.", ex); return(false); } catch (FileLoadException ex) { Global_Proc.ASSERT(Guid.Empty, "The assembly \"" + path + "\" is found but cannot be loaded.", ex); return(false); } var appDomain = AppDomain.CreateDomain("Temp"); try { var farAssembly = appDomain.CreateInstanceFrom(path, "DLRCachedCode"); } catch (FileLoadException ex) { int error = Marshal.GetHRForException(ex); if (error == -0x40131515) { Global_Proc.ASSERT(Guid.Empty, "The file \"" + path + "\" is blocked.", ex); return(false); } Global_Proc.ASSERT(Guid.Empty, "The assembly at \"" + path + "\" cannot be loaded.", ex); return(false); } catch (BadImageFormatException ex) { Global_Proc.ASSERT(Guid.Empty, "This assembly \"" + path + "\" has a bad inner format.", ex); return(false); } catch (TypeLoadException ex) { Global_Proc.ASSERT(Guid.Empty, "\"" + path + "\" is not a valid Python assembly. Please remove it.", ex); return(false); } catch (MissingMethodException ex) { Global_Proc.ASSERT(Guid.Empty, "This assembly \"" + path + "\" is ruined.", ex); return(false); } finally { if (appDomain != null) { AppDomain.Unload(appDomain); } } Assembly assembly = Assembly.LoadFile(path); var cachedCode = assembly.GetType("DLRCachedCode", false, false); if (cachedCode == null) { return(false); //should be already ruled out } dynamic info = cachedCode.InvokeMember("GetScriptCodeInfo", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new object[0]); string[] modules = info.GetValue(2)[0]; runtime.LoadAssembly(assembly); bool toReturn = false; foreach (var module in modules) { var statement = "import " + module; p.Script.ExecuteScript(statement); dynamic ns = p.Script.GetVariable(module); var dict = ns.Get__dict__(); var vars = dict.Keys; foreach (var v in vars) { var text = v as string; if (text == null) { continue; } object o = dict[text]; if (o == null) { continue; } Type type = o.GetType(); if (type.FullName != "IronPython.Runtime.Types.PythonType") { continue; } var basesEnum = (IEnumerable)type.InvokeMember( "get_BaseTypes", BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Instance, null, o, null); if (basesEnum == null) { continue; } foreach (var baseObj in basesEnum) { Type finalSystemType = (Type)baseObj.GetType().InvokeMember( "get_FinalSystemType", BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Instance, null, baseObj, null); if (finalSystemType == null) { continue; } if (typeof(IGH_Component).IsAssignableFrom(finalSystemType)) { var instance = Instantiate(ops as object, o); var proxy = new PythonInstantiatorProxy(instance, o, ops as object, path); toReturn |= Grasshopper.GH_InstanceServer.ComponentServer.AddProxy(proxy); } } } p.Script.ExecuteScript("del " + module); } return(toReturn); }
/// <summary> /// Mod functionality. /// Calls Python functions. /// </summary> private void Update() { // Initialize block handlers if (Game.IsSimulating && !BlockHandlerController.Initialised) { BlockHandlerController.InitializeBlockHandlers(); } // Initialize block identifiers if (!Game.IsSimulating && rebuildIDs) { rebuildIDs = false; BlockHandlerController.InitializeBuildingBlockIDs(); } // Execute code on first call if (Game.IsSimulating && PythonEnvironment.Loaded && enableScript && (scriptFile != null || scriptCode != null)) { LoadScript(); scriptFile = null; scriptCode = null; } // Toggle watchlist visibility if (PythonEnvironment.Loaded && Keybindings.Get("Watchlist").Pressed()) { Watchlist.Instance.Visible = !Watchlist.Instance.Visible; } // Toggle options visibility if (PythonEnvironment.Loaded && Keybindings.Get("Script Options").Pressed()) { ScriptOptions.Instance.Visible = !ScriptOptions.Instance.Visible; } if (!Game.IsSimulating) { // Show block identifiers if (PythonEnvironment.Loaded && Keybindings.Get("Show Block ID").IsDown()) { ShowBlockIdentifiers(); } } if (!Game.IsSimulating) { return; } // Call script update. try { if (!runtime_error) { PythonEnvironment.ScripterEnvironment?.CallUpdate(); } } catch (Exception e) { runtime_error = true; if (e.InnerException != null) { e = e.InnerException; } ScriptOptions.Instance.ErrorMessage = "Runtime error.\nSee console (Ctrl+K) for more info."; Debug.Log("<b><color=#FF0000>Python error: " + e.Message + "</color></b>\n" + PythonEnvironment.FormatException(e)); } }
/// <summary> /// Calls Python functions at a fixed rate. /// </summary> private void FixedUpdate() { if (!Game.IsSimulating) { return; } // Call script update. try { if (!runtime_error) { PythonEnvironment.ScripterEnvironment?.CallFixedUpdate(); } } catch (Exception e) { runtime_error = true; if (e.InnerException != null) { e = e.InnerException; } ScriptOptions.Instance.ErrorMessage = "Runtime error.\nSee console (Ctrl+K) for more info."; Debug.Log("<b><color=#FF0000>Python error: " + e.Message + "</color></b>\n" + PythonEnvironment.FormatException(e)); } }
private static void InstallIronPython() { downloading_in_progress = true; download_button_text = "0.0 %"; info_text = "<b>Please wait</b>\n"; if (!Directory.Exists(Application.dataPath + "/Mods/Resources/LenchScripter/lib/")) { Directory.CreateDirectory(Application.dataPath + "/Mods/Resources/LenchScripter/lib/"); } try { for (int file_index = 0; file_index < files_required; file_index++) { using (var client = new WebClient()) { var i = file_index; // delete existing file if (File.Exists(Application.dataPath + file_paths[i])) { File.Delete(Application.dataPath + file_paths[i]); } // progress handler client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) => { received_size[i] = e.BytesReceived; float progress = (Convert.ToSingle(received_size.Sum()) / Convert.ToSingle(total_size.Sum()) * 100f); download_button_text = progress.ToString("0.0") + " %"; }; // completion handler client.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { if (e.Error != null) { // set error messages ModConsole.AddMessage(LogType.Log, "[LenchScripterMod]: Error downloading file:" + file_paths[i].Split('/').Last()); ModConsole.AddMessage(LogType.Error, "\t" + e.Error.Message); info_text = file_paths[i].Split('/').Last() + " <color=red>✘</color>" + "\n\n<b><color=red>Download failed</color></b>\n" + e.Error.Message; downloading_in_progress = false; download_button_text = "Retry"; // delete failed file if (File.Exists(Application.dataPath + file_paths[i])) { File.Delete(Application.dataPath + file_paths[i]); } } else { ModConsole.AddMessage(LogType.Log, "[LenchScripterMod]: File downloaded: " + file_paths[i].Split('/').Last()); info_text += "\n" + file_paths[i].Split('/').Last() + " <color=green>✓</color>"; files_downloaded++; if (files_downloaded == files_required) { // finish download and load assemblies if (PythonEnvironment.LoadPythonAssembly()) { download_button_text = "Complete"; ScripterMod.LoadScripter(); Instance.Visible = false; Destroy(Instance); } else { download_button_text = "Retry"; info_text = "<b><color=red>Download failed</color></b>\nFailed to initialize Python engine."; } downloading_in_progress = false; } } }; // start download client.DownloadFileAsync( file_uris[i], Application.dataPath + file_paths[i]); } } } catch (Exception e) { Debug.Log("[LenchScripterMod]: Error while downloading:"); Debug.LogException(e); downloading_in_progress = false; download_button_text = "Retry"; info_text = "<b><color=red>Download failed</color></b>\n" + e.Message; } }