Ejemplo n.º 1
0
        public void PostRequestChord(string input)
        {
            try
            {
                using (Py.GIL())
                {
                    PyList pyTest = new PyList();


                    Console.WriteLine(input);

                    if (input.Contains("c") == false)
                    {
                        listaNotas.Add(input);
                    }
                    if (input.Contains("c"))
                    {
                        listaNotas.Remove(input.Remove(input.Length - 1));
                    }


                    using (PyScope scope = Py.CreateScope())
                    {
                        for (int i = 0; i < listaNotas.Count; i++)
                        {
                            pyTest.Append(new PyString(listaNotas[i]));
                            Console.WriteLine(listaNotas[i]);
                        }

                        scope.Set("test", pyTest);
                        dynamic chord   = scope.Get("test");
                        dynamic pychord = scope.Import("pychord");
                        dynamic music21 = scope.Import("music21");
                        dynamic myChord = pychord.analyzer.find_chords_from_notes(chord);


                        if (Convert.ToString(myChord) == "[]")
                        {
                            myChord = music21.chord.Chord(chord);
                            myChord = myChord.pitchedCommonName;
                        }

                        Console.WriteLine(myChord);

                        string value = Convert.ToString(myChord);
                        notaSalida.Text = value;
                    }
                }
            }


            catch
            {
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Migrates Python 2 code to Python 3 using Pythons 2to3 library.
        /// </summary>
        /// <param name="code">Python 2 code that needs to be migrated</param>
        /// <returns></returns>
        internal static string MigrateCode(string code)
        {
            InstallPython();

            if (!PythonEngine.IsInitialized)
            {
                PythonEngine.Initialize();
                PythonEngine.BeginAllowThreads();
            }

            IntPtr gs = PythonEngine.AcquireLock();

            try
            {
                using (Py.GIL())
                {
                    string output;
                    var    asm = Assembly.GetExecutingAssembly();

                    using (PyScope scope = Py.CreateScope())
                    {
                        scope.Set(INPUT_NAME, code.ToPython());

                        var path = Path.GetDirectoryName(asm.Location);

                        scope.Set(PATH_NAME, path.ToPython());
                        scope.Exec(Get2To3MigrationScript(asm));

                        output = scope.Contains(RETURN_NAME) ? scope.Get(RETURN_NAME).ToString() : string.Empty;
                    }

                    // If the code contains tabs, normalize the whitespaces. This is a Python 3 requirement
                    // that's not addressed by 2to3.
                    if (output.Contains("\t"))
                    {
                        using (PyScope scope = Py.CreateScope())
                        {
                            scope.Set(INPUT_NAME, output.ToPython());
                            scope.Exec(GetReindentationScript(asm));
                            output = scope.Contains(RETURN_NAME) ? scope.Get(RETURN_NAME).ToString() : string.Empty;
                        }
                    }

                    return(output);
                }
            }

            finally
            {
                PythonEngine.ReleaseLock(gs);
            }
        }
Ejemplo n.º 3
0
        public void CallMultiplier()
        {
            PythonEngine.Initialize();
            string scriptfile = GetScriptPath("callmultiplier.py");


            using (Py.GIL())
            {
                PyScope mod = LoadModule(Path.GetFileNameWithoutExtension(scriptfile), scriptfile, null);

                //
                // Shows how to make call directly using objects.
                //
                PyObject func = mod.Get("multiplyThese");
                dynamic  r    = func.Invoke(new PyObject[] { new PyFloat(3.0), new PyFloat(1.5) });

                Assert.AreEqual <double>(4.5, (double)r);
            }
            PythonEngine.Shutdown();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Called when the evaluation has completed successfully or failed
        /// </summary>
        /// <param name="isSuccessful">Whether the evaluation succeeded or not</param>
        /// <param name="scope">The scope in which the code is executed</param>
        /// <param name="code">The code to that was evaluated</param>
        /// <param name="bindingValues">The binding values - these are already added to the scope when called</param>
        private void OnEvaluationEnd(bool isSuccessful,
                                     PyScope scope,
                                     string code,
                                     IList bindingValues)
        {
            // Call deprecated events until they are completely removed.
            EvaluationEnd?.Invoke(isSuccessful ?
                                  EvaluationState.Success :
                                  EvaluationState.Failed, scope, code, bindingValues);

            if (EvaluationFinished != null)
            {
                EvaluationFinished(isSuccessful ? Dynamo.PythonServices.EvaluationState.Success : Dynamo.PythonServices.EvaluationState.Failed,
                                   code, bindingValues, (n) => {
                    return(OutputMarshaler.Marshal(scope.Get(n)));
                });
                Analytics.TrackEvent(
                    Dynamo.Logging.Actions.End,
                    Dynamo.Logging.Categories.PythonOperations,
                    "CPythonEvaluation");
            }
        }
Ejemplo n.º 5
0
        public Sudoku Solve(Sudoku s)
        {
            using (Py.GIL())
            {
                using (PyScope scope = Py.CreateScope())
                {
                    // convert the sudoku object to a PyObject
                    PyObject pySudoku = s.ToPython();

                    // create a Python variable "sudoku"
                    scope.Set("sudoku", pySudoku);

                    // the sudoku object may now be used in Pythonn
                    string code = "fullName = person.FirstName + ' ' + person.LastName";
                    scope.Exec(code);
                    s = scope.Get <Sudoku>("sudoku");
                }


                return(s);
                // PythonEngine.Exec("doStuff()");
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        ///     Executes a Python script with custom variable names. Script may be a string
        ///     read from a file, for example. Pass a list of names (matching the variable
        ///     names in the script) to bindingNames and pass a corresponding list of values
        ///     to bindingValues.
        /// </summary>
        /// <param name="code">Python script as a string.</param>
        /// <param name="bindingNames">Names of values referenced in Python script.</param>
        /// <param name="bindingValues">Values referenced in Python script.</param>
        public static object EvaluatePythonScript(
            string code,
            IList bindingNames,
            [ArbitraryDimensionArrayImport] IList bindingValues)
        {
            var evaluationSuccess = true;

            if (code == null)
            {
                return(null);
            }

            InstallPython();

            if (!PythonEngine.IsInitialized)
            {
                PythonEngine.Initialize();
                PythonEngine.BeginAllowThreads();
            }

            IntPtr gs = PythonEngine.AcquireLock();

            try
            {
                using (Py.GIL())
                {
                    if (globalScope == null)
                    {
                        globalScope = CreateGlobalScope();
                    }

                    using (PyScope scope = Py.CreateScope())
                    {
                        // Reset the 'sys.path' value to the default python paths on node evaluation.
                        var pythonNodeSetupCode = "import sys" + Environment.NewLine + "sys.path = sys.path[0:3]";
                        scope.Exec(pythonNodeSetupCode);

                        ProcessAdditionalBindings(scope, bindingNames, bindingValues);

                        int amt = Math.Min(bindingNames.Count, bindingValues.Count);

                        for (int i = 0; i < amt; i++)
                        {
                            scope.Set((string)bindingNames[i], InputMarshaler.Marshal(bindingValues[i]).ToPython());
                        }

                        try
                        {
                            OnEvaluationBegin(scope, code, bindingValues);
                            scope.Exec(code);
                            var result = scope.Contains("OUT") ? scope.Get("OUT") : null;

                            return(OutputMarshaler.Marshal(result));
                        }
                        catch (Exception e)
                        {
                            evaluationSuccess = false;
                            var traceBack = GetTraceBack(e);
                            if (!string.IsNullOrEmpty(traceBack))
                            {
                                // Throw a new error including trace back info added to the message
                                throw new InvalidOperationException($"{e.Message} {traceBack}", e);
                            }
                            else
                            {
                                throw e;
                            }
                        }
                        finally
                        {
                            OnEvaluationEnd(evaluationSuccess, scope, code, bindingValues);
                        }
                    }
                }
            }
            finally
            {
                PythonEngine.ReleaseLock(gs);
            }
        }
Ejemplo n.º 7
0
 public void TestExec()
 {
     using (Py.GIL())
     {
         ps.Set("bb", 100); //declare a global variable
         ps.Set("cc", 10);  //declare a local variable
         ps.Exec("aa = bb + cc + 3");
         var result = ps.Get <int>("aa");
         Assert.AreEqual(113, result);
     }
 }
Ejemplo n.º 8
0
        private List <byte[]> CreateNSBTXes(SaveForm SF)
        {
            List <byte[]> NSBTXes = new List <byte[]>();

            using (Py.GIL())
            {
                dynamic TexturePy = Python.Runtime.Py.Import("ndspy.texture");

                using (PyScope scope = Py.CreateScope())
                {
                    scope.Exec("import ndspy.texture");

                    for (int j = 0; j < 3; j++)
                    {
                        scope.Exec("nsbtx = ndspy.texture.NSBTX()");

                        for (int i = 0 + (255 * j); i < 255 + (255 * j); i++)
                        {
                            SF.SetMessage("Encoding Tile " + (i + 1) + " (Format: " + TextureFormats[i] + ")");

                            Console.WriteLine("Tex " + i);
                            Bitmap   TileBitmap = new Bitmap(16, 16);
                            Graphics g          = Graphics.FromImage(TileBitmap);
                            g.DrawImage(this.MainPNG, new Rectangle(new Point(0, 0), new Size(16, 16)), Helpers.GetRectangleForTileID(i), GraphicsUnit.Pixel);

                            EncodedImage Enc = null;

                            if (TextureFormats[i] == 7)
                            {
                                Enc = Images.EncodeImage_RGB555(TileBitmap);
                            }
                            else if (TextureFormats[i] == 5)
                            {
                                Enc = Images.Encode_Tex4x4(TileBitmap, 16);
                            }
                            else
                            {
                                PalettedImage p = Images.CreatePalettedImage(TileBitmap, this.TextureFormats[i]);
                                Enc = Images.EncodeImage(p, TextureFormats[i]);
                            }

                            string  Name = "Tile " + i.ToString();
                            dynamic Tex  = TexturePy.Texture.fromFlags(0, 0, true, true, false, false, TileBitmap.Width, TileBitmap.Height,
                                                                       this.TextureFormats[i], false, 0, 0x80010040, Enc.Texture, Enc.Texture2);
                            dynamic Pal = TexturePy.Palette.fromColors(0, 0, 0, Enc.Palette);

                            scope.Set("Name", Name.ToPython());
                            scope.Set("Tex", Tex);
                            scope.Set("Pal", Pal);
                            scope.Exec("nsbtx.textures.append((Name,Tex))");
                            scope.Exec("nsbtx.palettes.append((Name,Pal))");
                        }

                        scope.Exec("nsbtxf = nsbtx.save()");
                        NSBTXes.Add(scope.Get <byte[]>("nsbtxf"));
                    }
                }
            }

            return(NSBTXes);
        }
Ejemplo n.º 9
0
        protected override async Task <object[]> EvaluateInternal(object[] inputs, CancellationToken cancel)
        {
            if (parserError != null)
            {
                throw parserError;
            }

            var script = this.Script;

            if (script == null)
            {
                return(new object[0]);       // no script available
            }

            object[] returnValue = null;

            void evalAction()
            {
                // create new python scope
                using (PyScope ps = Py.CreateScope())
                {
                    if (!string.IsNullOrEmpty(filename))
                    {
                        ps.Set("__file__", filename);
                    }

                    // load script into scope
                    ps.Execute(script);

                    ps.Set("context", this.Runtime.ScriptContext.ToPython());
                    ps.Set("store", this.Graph.ValueStore.ToPython());

                    // process module inputs and convert them to python objects
                    int firstArgIndex = inputs.Length - argumentPins.Count;
                    var args          = CreateArguments(inputs, firstArgIndex);

                    // call python method
                    string   functionName = (string)inputs[FUNCTION_NAME_PIN_INDEX] ?? DEFAULT_FUNCTION_NAME;
                    PyObject fn           = ps.Get(functionName);

                    PyObject pyResult = null;
                    try
                    {
                        pyResult = fn.Invoke(args);
                    }
                    catch (PythonException e)
                    {
                        throw new XamlaPythonException(e);
                    }

                    // convert result back to clr object
                    var result = PyConvert.ToClrObject(pyResult, signature.ReturnType);

                    if (result == null)
                    {
                        returnValue = new object[] { null }
                    }
                    ;
                    else if (!result.GetType().IsTuple())
                    {
                        returnValue = new object[] { result }
                    }
                    ;
                    else
                    {
                        returnValue = TypeHelpers.GetTupleValues(result);
                    }
                }
            }

            int useMainThreadPinIndex = 2;

            if (this.flowMode != FlowMode.NoFlow)
            {
                useMainThreadPinIndex += 1;
            }
            bool useMainThread = (bool)inputs[useMainThreadPinIndex];

            if (useMainThread)
            {
                await mainThread.Enqueue(evalAction, cancel);
            }
            else
            {
                using (Py.GIL())
                {
                    evalAction();
                }
            }

            if (this.flowMode != FlowMode.NoFlow)
            {
                return((new object[] { Flow.Default }.Concat(returnValue)).ToArray());
            }
            else
            {
                return(returnValue);
            }
        }
Ejemplo n.º 10
0
        public void TestPythonInterop()
        {
            var jsonSerializerOptions = new JsonSerializerOptions
            {
                WriteIndented = true,
                Converters    =
                {
                    new JsonStringEnumConverter(),
                    new SimpleHypergridJsonConverter(),
                    new DimensionJsonConverter(),
                },
            };

            string csContinuousJsonString      = JsonSerializer.Serialize(continuous, jsonSerializerOptions);
            string csDiscreteJsonString        = JsonSerializer.Serialize(discrete, jsonSerializerOptions);
            string csOrdinalJsonString         = JsonSerializer.Serialize(ordinal, jsonSerializerOptions);
            string csCategoricalJsonString     = JsonSerializer.Serialize(categorical, jsonSerializerOptions);
            string csSimpleHypergridJsonString = JsonSerializer.Serialize(allKindsOfDimensions, jsonSerializerOptions);

            using (Py.GIL())
            {
                using PyScope pythonScope = Py.CreateScope();

                pythonScope.Set("cs_continuous_dimension_json_string", csContinuousJsonString);
                pythonScope.Set("cs_discrete_dimension_json_string", csDiscreteJsonString);
                pythonScope.Set("cs_ordinal_dimension_json_string", csOrdinalJsonString);
                pythonScope.Set("cs_categorical_dimension_json_string", csCategoricalJsonString);
                pythonScope.Set("cs_simple_hypergrid_json_string", csSimpleHypergridJsonString);

                pythonScope.Exec(PythonScriptsAndJsons.CreateDimensionsAndSpacesScript);
                pythonScope.Exec(PythonScriptsAndJsons.DeserializeDimensionsScript);

                bool   successfullyDeserializedDimensions = pythonScope.Get("success").As <bool>();
                string exceptionMessage = string.Empty;
                if (!successfullyDeserializedDimensions)
                {
                    exceptionMessage = pythonScope.Get("exception_message").As <string>();
                }

                Assert.True(successfullyDeserializedDimensions, exceptionMessage);

                pythonScope.Exec(PythonScriptsAndJsons.DeserializeSimpleHypergridScript);

                bool successfullyDeserializedSimpleHypergrid = pythonScope.Get("success").As <bool>();
                if (!successfullyDeserializedSimpleHypergrid)
                {
                    exceptionMessage = pythonScope.Get("exception_message").As <string>();
                }

                Assert.True(successfullyDeserializedSimpleHypergrid, exceptionMessage);

                string          pySimpleHypergridJsonString           = pythonScope.Get("py_simple_hypergrid_json_string").As <string>();
                SimpleHypergrid simpleHypergridDeserializedFromPython = JsonSerializer.Deserialize <SimpleHypergrid>(pySimpleHypergridJsonString, jsonSerializerOptions);

                Assert.True(simpleHypergridDeserializedFromPython.Name == "all_kinds_of_dimensions");
                Assert.True(simpleHypergridDeserializedFromPython.Dimensions.Count == 4);

                string reserializedHypergrid = JsonSerializer.Serialize(simpleHypergridDeserializedFromPython, jsonSerializerOptions);

                pythonScope.Set("cs_reserialized_hypergrid_json_string", reserializedHypergrid);
                pythonScope.Exec(PythonScriptsAndJsons.ValidateReserializedHypergridScript);

                bool successfullyValidatedReserializedHypergrid = pythonScope.Get("success").As <bool>();
                if (!successfullyValidatedReserializedHypergrid)
                {
                    exceptionMessage = pythonScope.Get("exception_message").As <string>();
                }

                Assert.True(successfullyValidatedReserializedHypergrid, exceptionMessage);
            }

            string currentDirectory = Directory.GetCurrentDirectory();

            Console.WriteLine($"Current directory {currentDirectory}");
        }