Пример #1
0
        public void CanSaveTrainedModel()
        {
            var model = new StringMarkov();

            model.Learn(ExampleData);
            model.Save(ModelFileName);

            var forLoading = new StringMarkov().Load <StringMarkov>(ModelFileName, model.Level);

            Assert.AreEqual(model.Level, forLoading.Level);
            Assert.AreEqual(model.SourceLines, forLoading.SourceLines);
        }
Пример #2
0
        public void SavedFileDoesntContainModelDictionary()
        {
            var model = new StringMarkov();

            model.Learn(ExampleData);
            model.Save(ModelFileName);

            string  fileContents = File.ReadAllText(ModelFileName);
            dynamic loaded       = JsonConvert.DeserializeObject <dynamic>(fileContents);

            Assert.IsNull(loaded.Model);
        }
Пример #3
0
        public void CanLearnLinesWithTrainedModel()
        {
            var model = new StringMarkov();

            model.Learn(ExampleData);

            Assert.AreEqual(ExampleData.Count(s => s.Split(' ').Length > model.Level), model.SourcePhrases.Count);
            CollectionAssert.AreEquivalent(ExampleData.Where(s => s.Split(' ').Length > model.Level), model.SourcePhrases);

            model.Learn("I do not like green eggs and hams");
            Assert.AreEqual(ExampleData.Count() + 1, model.SourcePhrases.Count);
        }
Пример #4
0
        private static void StringWalk(string[] sourceText, int level = 1)
        {
            StringMarkov model = new StringMarkov(level);

            model.Learn(sourceText);
            string format = model.Walk().First();

            while (format.Trim() == String.Empty)
            {
                format = model.Walk().First();
            }
            Console.WriteLine(format);
        }
Пример #5
0
        public void SavedFileContainsLevel()
        {
            var model = new StringMarkov();

            model.Learn(ExampleData);
            model.Save(ModelFileName);

            string  fileContents = File.ReadAllText(ModelFileName);
            dynamic loaded       = JsonConvert.DeserializeObject <dynamic>(fileContents);

            Assert.IsNotNull(loaded.Level);
            Assert.AreEqual(2, (int)loaded.Level);
        }
Пример #6
0
        public void LearningDuplicateLinesAreIgnored()
        {
            var model = new StringMarkov();

            model.Learn(ExampleData);
            model.Learn(ExampleData);

            var e1 = ExampleData.Except(model.SourceLines).ToList();

            Assert.AreEqual(ExampleData.Count(), model.SourceLines.Count);
            Assert.That(ExampleData.ToList(), Is.EquivalentTo(model.SourceLines));
            Assert.That(model.SourceLines, Is.Unique);
        }
Пример #7
0
        public void GenerateQuotes(int n)
        {
            int numeroCadenas = 4;
            var model         = new StringMarkov(n);

            Console.WriteLine("\nTraining ...");
            model.Learn(lines);

            Console.WriteLine("============================================");
            for (int i = 0; i < numeroCadenas; i++)
            {
                Console.WriteLine("[" + i + "]: " + model.Walk().First());
            }
        }
Пример #8
0
        public void CanLoadWithGivenLevel(int newLevel)
        {
            var model = new StringMarkov(1);

            model.Learn(ExampleData);
            model.Save(ModelFileName);

            var forLoading = new StringMarkov().Load <StringMarkov>(ModelFileName, newLevel);

            Assert.AreEqual(newLevel, forLoading.Level);
            Assert.AreEqual(model.SourceLines, forLoading.SourceLines);

            Assert.AreEqual(newLevel, forLoading.Model.Max(a => a.Key.Before.Length));
        }
Пример #9
0
        public void CanLearnDuplicatesDoesNotAddDupeSourceLinesAddsDupeTransitions()
        {
            var model = new StringMarkov();

            model.Learn("Testing the model");
            model.Learn("Testing the model");

            CollectionAssert.AreEquivalent(new List <string> {
                "Testing the model"
            }, model.SourceLines);
            Assert.AreEqual(1, model.SourceLines.Count);
            Assert.AreEqual(8, model.Model.Sum(x => x.Value.Count));
            Assert.That(model.SourceLines, Is.Unique);
        }
Пример #10
0
        public void CanWalkUsingSeed()
        {
            var model = new StringMarkov();

            model.Learn(ExampleData);

            var results = model.Walk(100, "This is a line");

            Assert.AreEqual(100, results.Count());
            foreach (var result in results)
            {
                Assert.That(result, Is.StringStarting("This is a line"));
            }
        }
Пример #11
0
        public void CanWalkLoadedModel()
        {
            var model = new StringMarkov(1);

            model.Learn(ExampleData);
            model.Save(ModelFileName);

            var newModel = new StringMarkov().Load <StringMarkov>(ModelFileName);

            var lines = newModel.Walk();

            Logger.Info(string.Join("\r\n", lines));
            Assert.AreEqual(1, lines.Count());
            Assert.That(lines.First(), Is.Not.Empty);
        }
Пример #12
0
        public MultiTextMarkovChainHelper(DiscordSocketClient client, DiscordContextFactory dbFactory, int depth)
        {
            _semaphore = new SemaphoreSlim(0, 1);
            _dbFactory = dbFactory;
            _db        = _dbFactory.Create(new DbContextFactoryOptions());
            _client    = client;
            Depth      = depth;

            if (depth > 0)
            {
                _markovChain = new StringMarkov(depth);
            }

            _timer = new Timer(async e => await SaveAsync().ConfigureAwait(false), null, 600000, 600000);
        }
Пример #13
0
        public void WalkCreatesNewContent(int walkCount)
        {
            var model = new StringMarkov();

            model.Learn(ExampleData);
            model.EnsureUniqueWalk = true;

            var results = model.Walk(walkCount);

            CollectionAssert.IsNotSubsetOf(results, ExampleData);
            foreach (var result in results)
            {
                Assert.That(result, Is.Not.Empty);
                CollectionAssert.DoesNotContain(ExampleData, result);
            }
        }
Пример #14
0
        public void CanWalkWithUniqueOutputUsingSeed()
        {
            var model = new StringMarkov();

            model.Learn(ExampleData);
            model.EnsureUniqueWalk = true;

            var results = model.Walk(1000, "This is a line");

            foreach (var result in results)
            {
                Assert.That(result, Is.StringStarting("This is a line"));
            }

            Assert.AreEqual(results.Count(), results.Distinct().Count());
        }
Пример #15
0
        public bool BeginWriting(DocumentFeatures features_, string path, int studentSeed_, int sourceSeed_, float integrity = 1.0f)
        {
            // generate author
            // generate username

            features    = features_;
            studentSeed = studentSeed_;
            sourceSeed  = sourceSeed_;

            student = SubmissionGenerator.EssayParagraph.Duplicate(studentSeed);

            if (isTruthful == false)
            {
                source = SubmissionGenerator.EssayParagraph.Duplicate(sourceSeed);
            }

            return(_Create(path));
        }
        public async Task SendHelp(CommandContext ctx)
        {
            try
            {
                string[] lines = File.ReadAllLines(Path.Combine(Globals.AppPath, "Data", "help.txt"));

                StringMarkov model = new StringMarkov(1);

                model.Learn(lines);

                await ctx.RespondAsync(model.Walk().First());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Пример #17
0
        public async Task <string> MarkovReddit(string subreddit)
        {
            int walkSize = 1;

            if (subreddit.Split(' ').Length > 5)
            {
                walkSize = 2;
            }
            var model = new StringMarkov(walkSize)
            {
                EnsureUniqueWalk = true
            };

            foreach (string sub in subreddit.Split(' '))
            {
                model.Learn(await GetTitlesFromSubreddit(sub));
            }
            return(model.Walk(15).Skip(5).OrderByDescending(x => x.Length).Take(5).GetRandom());
        }
Пример #18
0
        public void ProcessMarkov(List <string> inputHeadlines)
        {
            ProcessHeadlines();
            // Create a new model
            var model = new StringMarkov(1);

            // Train the model
            model.Learn(Headlines.ToArray());

            for (int i = 0; i < 3; i++)
            {
                generatedHeadline += model.Walk(3).First() + ".\n";
                Console.WriteLine(generatedHeadline);
            }

            // Create some permutations

            Console.Read();
        }
        public void RetrainedModelIsNotSameIfLevelIsDifferent(int retrainDepth, bool expectSameModel)
        {
            var model = new StringMarkov();

            model.Learn(ExampleData);
            var dict = new ConcurrentDictionary <NgramContainer <string>, List <string> >(model.Chain.ChainDictionary); // this will break for non string type models during testing until fixed

            model.Retrain(retrainDepth);

            if (expectSameModel)
            {
                //CollectionAssert.AreEquivalent(dict, model.Model);
                Assert.AreEqual(dict.Sum(a => a.Key.Ngrams.Count()), model.Chain.ChainDictionary.Sum(a => a.Key.Ngrams.Count()));
            }
            else
            {
                //CollectionAssert.AreNotEquivalent(dict, model.Model);
                Assert.AreNotEqual(dict.Sum(a => a.Key.Ngrams.Count()), model.Chain.ChainDictionary.Sum(a => a.Key.Ngrams.Count()));
            }
        }
Пример #20
0
    protected void Start()
    {
        if (csvInput != null)
        {
            List <string> lyrics = csvInput.Data["lyrics"];

            if (true)
            {
                input.Clear();

                string[] lineDelim = new[] { "\r\n", "\r", "\n" };
                foreach (string lyric in lyrics)
                {
                    string[] lines = lyric.Split(lineDelim, System.StringSplitOptions.None);

                    for (int i = 0; i < lines.Length - 1; i += 2)
                    {
                        input.Add(lines[i] + " " + lines[i + 1]);
                    }
                }
            }            /*
                          * else {
                          *
                          *     input = lyrics;
                          *
                          * }*/
        }

        model = new StringMarkov(n);
        model.EnsureUniqueWalk = true;

        // Train the model
        model.Learn(input);

        if (rand == null)
        {
            rand = gameObject.AddComponent <Rand> ();
        }
    }
Пример #21
0
        public static List <string> ReadKills()
        {
            List <string> kills = new List <string>();

            KillsUsed.Clear();
            Killgen = new StringMarkov();

            if (File.Exists("TextFiles/kills.txt"))
            {
                try
                {
                    StreamReader sr = new StreamReader("TextFiles/kills.txt");
                    while (sr.Peek() >= 0)
                    {
                        string killS = sr.ReadLine();

                        if (killS.Length > 1 && !(killS[0] == '/' && killS[1] == '/'))
                        {
                            kills.Add(killS);
                            Killgen.Learn(killS);
                        }
                    }

                    sr.Close();
                }
                catch (IOException e)
                {
                    Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss] ", CultureInfo.CreateSpecificCulture("en-GB")) + "Failed to read kills. " + e.Message);
                }
            }
            else
            {
                //TODO: Save settings
                //Settings.Default.killEnabled = false;
                //Settings.Default.Save();
            }

            return(kills);
        }
Пример #22
0
    public void GenerateText()
    {
        // Some training data
        var lines = new string[]
        {
            "Frankly, my dear, I don't give a damn.",
            "Mama always said life was like a box of chocolates. You never know what you're gonna get.",
            "Many wealthy people are little more than janitors of their possessions."
        };

        // Create a new model
        var model = new StringMarkov(1);

        // Train the model
        model.Learn(lines);

        // Create some permutations

        string txt = model.Walk().First();

        text.text = txt;
    }
Пример #23
0
        public async Task <string> ImiChat(IInvocationContext context)
        {
            IBufferedChannel bufferedChannel = context.Channel as IBufferedChannel;

            if (bufferedChannel != null)
            {
                if (!_models.ContainsKey(bufferedChannel.Name))
                {
                    StringMarkov markov = new StringMarkov(1)
                    {
                        EnsureUniqueWalk = true
                    };
                    DateTimeOffset          offset   = DateTimeOffset.UtcNow;
                    List <IBufferedMessage> messages = await bufferedChannel.GetMessagesAsync(offset, SearchDirection.Before, 5000);

                    markov.Learn(messages.Where(x => x.User.Name != context.OriginClient.Username && !string.IsNullOrEmpty(x.Text?.Trim()) && !x.Text.IsCommand()).Select(x => x.Text));
                    _models[bufferedChannel.Name] = markov;
                }

                return(_models[context.Channel.Name].Walk(10).OrderByDescending(x => x.Length).Take(5).GetRandom());
            }
            throw new Exception("Not buffered channel.");
        }
Пример #24
0
 public ImitateChat(IMessageBus messageBus)
 {
     messageBus.Received += MessageBus_Received;
     foreach (string path in Directory.GetFiles(PathExtensions.ResourceDir, "*.*markov"))
     {
         try
         {
             var tempMarkov = new StringMarkov().Load <StringMarkov>(path);
             if (Path.GetExtension(path) == "usermarkov")
             {
                 _userModels[ulong.Parse(Path.GetFileNameWithoutExtension(path))] = tempMarkov;
             }
             else
             {
                 _models[Path.GetFileNameWithoutExtension(path)] = tempMarkov;
             }
         }
         catch (Exception e)
         {
             Log.Error($"Unable to load markov file: {path}");
         }
     }
 }
Пример #25
0
        public bool loadRyaFile()
        {
            stringMarkov = new StringMarkov();

            if (File.Exists("TextFiles/rya.txt"))
            {
                try
                {
                    StreamReader sr = new StreamReader("TextFiles/rya.txt");
                    while (sr.Peek() >= 0)
                    {
                        string ryaL = sr.ReadLine().ToLower();
                        if (ryaL.Split().Length > 2)
                        {
                            stringMarkov.Learn(ryaL);
                        }
                    }

                    sr.Close();

                    isReady = true;

                    return(true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error Reading File: " + ex.Message);
                    return(false);
                }
            }
            else
            {
                Console.WriteLine("File Not Found");
                return(false);
            }
        }
Пример #26
0
 static KillUser()
 {
     KillsUsed = new List <int>();
     Killgen   = new StringMarkov();
     Kills     = ReadKills();
 }
Пример #27
0
        public void ParameterlessConstructorUsesLevel2()
        {
            var model = new StringMarkov();

            Assert.AreEqual(2, model.Level);
        }
Пример #28
0
        public void LearnNullStringDoesNotThrow()
        {
            var model = new StringMarkov();

            Assert.DoesNotThrow(() => model.Learn(null));
        }
Пример #29
0
        public void LearnEmptyStringDoesNotThrow()
        {
            var model = new StringMarkov();

            Assert.DoesNotThrow(() => model.Learn(""));
        }
Пример #30
0
        internal async Task RespondWithAnswer(String[] dataset, String start = "", String user = "")
        {
            int chainLength = 2;

            if (IsNumber(start) && start != "")
            {
                chainLength = int.Parse(start);
                start       = "";
            }
            StringMarkov model = new StringMarkov(chainLength);

            model.Learn(dataset);
            Random  rnd1          = new Random();
            String  sentence      = "";
            int     startSpawn    = 0;
            Boolean acceptable    = false;
            int     totalAttempts = 0;

            while (sentence.Split('c').Length < 4 && !acceptable)
            {
                acceptable = false;
                sentence   = start;
                int i = 0;
                startSpawn += 1;
                while (i < 30)
                {
                    try
                    {
                        String[] newWord      = model.GetMatches(sentence.Trim()).ToArray();
                        Double   len          = Convert.ToDouble(newWord.Length - 1);
                        Double   rnd          = Convert.ToDouble(rnd1.NextDouble());
                        Double   decision     = Math.Floor(rnd * len);
                        String   selectedWord = newWord[Convert.ToInt32(decision)];
                        if (selectedWord == null)
                        {
                            break;
                        }
                        sentence = sentence + " " + selectedWord;

                        i += 1;
                    }
                    catch (Exception exc)
                    {
                        i              = 31;
                        totalAttempts += 1;
                        if (totalAttempts > 1000)
                        {
                            await ReplyAsync("Sorry, no can do - " + user + " doesn't talk much");

                            return;
                        }
                    }
                    totalAttempts += 1;
                    if (totalAttempts > 1000)
                    {
                        await ReplyAsync("Sorry, no can do - " + user + " doesn't talk much");

                        return;
                    }
                }
                totalAttempts += 1;
                if (totalAttempts > 1000)
                {
                    await ReplyAsync("Sorry, no can do - " + user + " doesn't talk much");

                    return;
                }
                if (!dataset.Contains(sentence.Trim(' ')))
                {
                    acceptable = true;
                }
            }
            await ReplyAsync("```" + sentence + "``` - " + user);
        }