Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            Markov Bot = new Markov();

            //*
            Bot.LoadAuxiliaries("Auxiliaries.txt");
            Bot.LoadBanList("Bans.txt");
            Bot.LoadSwapList("Swaps.txt");
            Bot.Train("Training.txt");
            Bot.SaveBrain("BRAIN");

            /*/
             * Bot.LoadBrain("BRAIN");
             * //*/
            while (true)
            {
                Console.Write("> ");
                String Text = null;
                while (Text == null)
                {
                    Text = Console.ReadLine();
                }

                Console.WriteLine(Bot.GenerateReply(Text));
            }
        }
Ejemplo n.º 2
0
    private string parseBook(string bookFileName)
    {
        MarkovDict markovDict = new MarkovDict();

        markovDict.initialize();

        using (StreamReader sr = new StreamReader(Application.dataPath + "/Books/" + bookFileName)) {
            string line = null;
            while ((line = sr.ReadLine()) != null)
            {
                Markov markov = new Markov();
                markovDict.mergeWeightedDistribution(markov.getWeightedDistribution(line));
            }
        }

        BinaryFormatter bf = new BinaryFormatter();

        using (FileStream fs = new FileStream(Application.dataPath + "/dict.dat", FileMode.Create)) {
            bf.Serialize(fs, markovDict);
        }

        string result = "";

        foreach (KeyValuePair <string, Dictionary <string, int> > dict in markovDict.weightedDistribution)
        {
            result += "\"" + dict.Key + "\" \t ";
            foreach (KeyValuePair <string, int> pair in dict.Value)
            {
                result += "[\"" + pair.Key + "\" : " + pair.Value.ToString() + "] ";
            }
            result += "\n";
        }

        return(result);
    }
Ejemplo n.º 3
0
        public static string Markov(string input)
        {
            //Load Markov.bin or create new
            Markov mkv = new Markov();

            if (File.Exists("Markov.bin"))
            {
                try { mkv.LoadChainState("Markov"); } catch { }
            }

            //Feed input
            mkv.Feed(input);

            //Generate new sentence
            Random rnd    = new Random();
            string markov = MarkovGenerator.Create(rnd.Next(50, 150), mkv);

            markov = MarkovGenerator.Create(mkv);

            //Save
            mkv.SaveChainState("Markov");

            //Return new sentence
            return(markov);
        }
Ejemplo n.º 4
0
        static void Main(String[] args)
        {
            Markov m = new Markov();

            m.generateMarkovModel();
            m.generateNewName();
        }
Ejemplo n.º 5
0
        // GET: Markov
        public ActionResult Index()
        {
            Random rnd            = new Random();
            var    MarkovInitials = Markov.GetStartingWords();
            int    first          = rnd.Next(MarkovInitials.Count);
            string initial        = MarkovInitials[first];
            string Text           = "";

            Text = Text + initial + " ";
            var MarkovTable = Markov.GetMarkovTable();
            var ListofWords = MarkovTable[initial];


            int    r    = rnd.Next(ListofWords.Count);
            string next = ListofWords[r];

            Text = Text + next + " ";
            for (int i = 0; i < 50; ++i)
            {
                var    ListWords = MarkovTable[next];
                Random rand      = new Random();
                int    s         = rand.Next(ListWords.Count);
                next = ListWords[s];
                string nextword = ListWords[s];
                Text = Text + next + " ";
            }



            return(View((object)Text));
        }
Ejemplo n.º 6
0
 public MarkovService(IServiceProvider services)
 {
     _discord     = services.GetRequiredService <Discord.WebSocket.DiscordSocketClient>();
     _webService  = services.GetRequiredService <WebService>();
     _rand        = services.GetRequiredService <Random>();
     _markovModel = new Markov("markov.json");
 }
Ejemplo n.º 7
0
        } // End Function GetCustomFont

        public static byte[] Generate()
        {
            string captchaText = Markov.generateCaptchaTextMarkovClean(5);

            captchaText = "The quick brown fox jumps over the  lazy dog";
            captchaText = "test123";

            byte[] imageBytes = Generate(captchaText, System.Drawing.Imaging.ImageFormat.Png);
            System.IO.File.WriteAllBytes(FileHelper.MapProjectPath("Img/mesh.png"), imageBytes);

            return(imageBytes);
        } // End Function Generate
Ejemplo n.º 8
0
    void Awake()
    {
        markovChain = new Markov();
        markovChain.CreateGraph(gibberishFilePath);

        mainObjs = new Dictionary <string, GameObject>(kvPairs.Length);

        for (int i = 0; i < kvPairs.Length; i++)
        {
            mainObjs.Add(kvPairs[i].id, kvPairs[i].obj);
        }

        villagers  = new List <Villager>();
        werewolves = new List <Werewolf>();
    }
Ejemplo n.º 9
0
        //Log replies and respond with a random reply
        public static async Task Markov(string message, SocketGuildChannel channel, int frequency)
        {
            string binFilePath = $"Servers\\{channel.Guild.Id.ToString()}\\{channel.Guild.Id.ToString()}";
            Markov mkv         = new Markov();

            try { mkv.LoadChainState(binFilePath); }
            catch { }
            //Sanitize message content
            string newMessage = message;
            var    links      = newMessage.Split("\t\n ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Where(s => s.StartsWith("http://") || s.StartsWith("www.") || s.StartsWith("https://") || s.StartsWith("@"));

            foreach (var link in links)
            {
                newMessage = newMessage.Replace(link, "");
            }

            if (newMessage != "" && Moderation.IsPublicChannel(channel))
            {
                mkv.Feed(newMessage);
            }

            mkv.SaveChainState(binFilePath);

            var    socketChannel = (ISocketMessageChannel)channel;
            Random rnd           = new Random();
            string markov        = MarkovGenerator.Create(mkv);
            int    runs          = 0;

            while (markov.Length < UserSettings.BotOptions.MarkovMinimumLength(channel.Guild.Id) && runs < 20)
            {
                markov = MarkovGenerator.Create(mkv);
                runs++;
            }

            if (rnd.Next(1, 100) <= frequency)
            {
                if (!UserSettings.BotOptions.MarkovBotChannelOnly(channel.Guild.Id))
                {
                    await socketChannel.SendMessageAsync(markov);
                }
                else if (channel.Id == UserSettings.Channels.BotChannelId(channel.Guild.Id))
                {
                    await socketChannel.SendMessageAsync(markov);
                }
            }

            return;
        }
Ejemplo n.º 10
0
    private void Awake()
    {
        _st = SettingsReader.GetInstance();
        _mn = GetComponent <Metronome>();
        R   = new Random();

        //var folder = new DirectoryInfo(Application.dataPath + "/");
        //var files = folder.GetFiles("*.notes", SearchOption.AllDirectories);
        //if (files.Length == 0) throw new Exception("No sample files found.");
        TextAsset prnFile = Resources.Load("input") as TextAsset;


        var sample  = new Markov <string>(" ");
        var content = new List <string>();

        char[] archDelim = new char[] { ' ' };
        string txt       = prnFile.text;

        content = txt.Split(archDelim, StringSplitOptions.RemoveEmptyEntries).ToList();

        //using (var sampleFile = new StreamReader(t.FullName))
        // {
        //while (!sampleFile.EndOfStream)
        // {
        //var line = sampleFile.ReadLine().Trim();
        //    foreach (var entry in line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries))
        //      content.Add(entry);
        //}

        //sampleFile.Close();
        //}

        if (content.Count > 4)
        {
            sample.Train(content, 4);
        }

        _requiredWordCount = (int)_st.AudioLength;
        var result       = sample.GeneratePiece(_requiredWordCount, true);
        var resultString = new StringBuilder();

        foreach (var entry in result)
        {
            resultString.Append(entry + " ");
        }
        _mn.BuildNoteList(result);
    }
        static void Main(string[] args)
        {
            var markov = new Markov("nameResidential", false, 4);
            //var markov = new ExtendedBuildings.Markov("ExtendedBuildings.markov.descriptionsWorkplaces.txt", false, 6);
            Randomizer randomizer = new Randomizer(50);

            for (var i = 0; i < 100; i += 1)
            {
                Console.WriteLine(markov.GetText(ref randomizer, 6, 13, true, true));
            }
            //Console.Write(markov.GetText(120, 220, true));
            var x = Console.ReadLine();

            if (x == "")
            {
            }
        }
Ejemplo n.º 12
0
        public static void Main(string[] args)
        {
            Captcha3D.Generate();

            string ct      = Markov.generateCaptchaTextMarkov(10);
            string ctRand  = Markov.generateCaptchaTextRandom(10);
            string ctClean = Markov.generateCaptchaTextMarkovClean(10);

            System.Console.WriteLine(ct);
            System.Console.WriteLine(ctRand);
            System.Console.WriteLine(ctClean);


            System.Console.WriteLine(System.Environment.NewLine);
            System.Console.WriteLine(" --- Press any key to continue --- ");
            System.Console.ReadKey();
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            Markov bot = new Markov();
            //*
            var sw = Stopwatch.StartNew();

            bot.LoadAuxiliaries("../../Files/Auxiliaries.txt");
            sw.Stop();
            Console.WriteLine($"Auxiliaries {sw.Elapsed.TotalMilliseconds.ToString("N0")} ms");

            sw = Stopwatch.StartNew();
            bot.LoadBanList("../../Files/Bans.txt");
            sw.Stop();
            Console.WriteLine($"Bans {sw.Elapsed.TotalMilliseconds.ToString("N0")} ms");

            sw = Stopwatch.StartNew();
            bot.LoadSwapList("../../Files/Swaps.txt");
            sw.Stop();
            Console.WriteLine($"Swaps {sw.Elapsed.TotalMilliseconds.ToString("N0")} ms");

            sw = Stopwatch.StartNew();
            bot.Train("../../Files/Training.txt");
            sw.Stop();
            Console.WriteLine($"Training {sw.Elapsed.TotalMilliseconds.ToString("N0")} ms");

            sw = Stopwatch.StartNew();
            bot.SaveBrain("../../Files/BRAIN.dat");
            sw.Stop();
            Console.WriteLine($"BRAIN {sw.Elapsed.TotalMilliseconds.ToString("N0")} ms");

            /*/
             * Bot.LoadBrain("../../Files/BRAIN.dat");
             * //*/
            while (true)
            {
                Console.Write("> ");
                String text = null;
                while (text == null)
                {
                    text = Console.ReadLine();
                }

                Console.WriteLine(bot.GenerateReply(text));
            }
        }
Ejemplo n.º 14
0
        private static void TwitterMode()
        {
            var twitter = new Twitter(_config, _log);

            // TODO split this into Twitter.Functions()
            if (twitter.GetRemainingRequests() > 0)
            {
                var markov   = new Markov(_log);
                var timeline = twitter.GetStatuses();

                if (timeline.Count == 0)
                {
                    _log.Write("Couldn't fetch any tweet, exiting...");
                    return;
                }

                foreach (var tweet in timeline)
                {
                    markov.AddSentence(tweet);
                }

                // either post a tweet or write X tweets to a file
                var writeFile     = _config.GetBoolValue(ConfigKeys.Preferences_Local);
                var forceLastWord = _config.GetBoolValue(ConfigKeys.Preferences_ForceLastWord);

                if (writeFile)
                {
                    var generatedTweets = new List <string>();

                    for (var i = 0; i < 1000; i++)
                    {
                        generatedTweets.Add(markov.GenerateSentence(220, forceLastWord));
                    }

                    var filePath = Directory.GetCurrentDirectory() + @"\tweets.txt";
                    File.AppendAllLines(filePath, generatedTweets);

                    _log.Write($"Generated tweets written at {filePath}.");
                }
                else
                {
                    twitter.PostTweet(markov.GenerateSentence(250, forceLastWord));
                }
            }
        }
Ejemplo n.º 15
0
        public static byte[] Generate()
        {
            int    rnd         = (int)MathHelpers.rand(3, 6);
            string captchaText = Markov.generateCaptchaTextMarkovClean(rnd);

            // captchaText = "The quick brown fox jumps over the  lazy dog";
            // captchaText = "test123";
            System.Console.WriteLine(captchaText);


            byte[] imageBytes = Generate(captchaText, System.Drawing.Imaging.ImageFormat.Png);

            lock (fileLock)
            {
                System.IO.File.WriteAllBytes("mesh.png", imageBytes);
                // System.IO.File.WriteAllBytes(captchaText + ".png", imageBytes);
            } // End lock (fileLock)

            return(imageBytes);
        } // End Function Generate
Ejemplo n.º 16
0
    private string getWeightedDistribution(string sentence)
    {
        Markov markov = new Markov();
        Dictionary <string, Dictionary <string, int> > weightedDistribution = markov.getWeightedDistribution(sentence);

        BinaryFormatter bf = new BinaryFormatter();

        MarkovDict markovDict = null;

        if (File.Exists(Application.dataPath + MarkovDict.DataPath))
        {
            using (FileStream fs = new FileStream(Application.dataPath + "/dict.dat", FileMode.Open)) {
                markovDict = bf.Deserialize(fs) as MarkovDict;
            }
        }
        else
        {
            markovDict = new MarkovDict();
            markovDict.initialize();
        }

        markovDict.mergeWeightedDistribution(weightedDistribution);

        using (FileStream fs = new FileStream(Application.dataPath + "/dict.dat", FileMode.Create)) {
            bf.Serialize(fs, markovDict);
        }

        string result = "";

        foreach (KeyValuePair <string, Dictionary <string, int> > dict in markovDict.weightedDistribution)
        {
            result += "\"" + dict.Key + "\" \t ";
            foreach (KeyValuePair <string, int> pair in dict.Value)
            {
                result += "[\"" + pair.Key + "\" : " + pair.Value.ToString() + "] ";
            }
            result += "\n";
        }

        return(result);
    }
Ejemplo n.º 17
0
        private void start_btn_Click(object sender, EventArgs e)
        {
            if (running)
            {
                paused          = false;
                status_lbl.Text = "Running";
                return;
            }

            ResetColor();
            List <Instruction> instructions = new List <Instruction>();

            for (int i = 0; i < dataGridView1.RowCount - 1; i++)
            {
                string   row = dataGridView1[0, i].Value?.ToString() ?? "";
                string[] str = row.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (str.Length < 2)
                {
                    MessageBox.Show("Bad instruction: " + row, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                for (int j = 0; j < 2; j++)
                {
                    if (str[j] == EMPTY_CODE)
                    {
                        str[j] = "";
                    }
                }
                instructions.Add(new Instruction(str[0], str[1], str.Length == 3 && str[2] == "*"));
            }

            history.Items.Clear();
            status_lbl.Text = "Running";
            paused          = false;
            stopped         = false;
            running         = true;
            new Task(() =>
            {
                Markov markov = new Markov(instructions);
                try
                {
                    markov.Execute(word_textbox.Text, m =>
                    {
                        int delay = 0;

                        this.Invoke(new Action(() =>
                        {
                            word_textbox.Text = m.Word;
                            delay             = (int)delay_upDown.Value;
                            if (m.LastInstructionIndex != -1)
                            {
                                history.Items.Insert(0, m.LastInstruction + ": " + m.Word);
                                last_instr_lbl.Text = m.LastInstruction.ToString();

                                dataGridView1.ClearSelection();
                                dataGridView1.Rows[m.LastInstructionIndex].Selected = true;
                                if (mark_check.Checked)
                                {
                                    dataGridView1.Rows[m.LastInstructionIndex].DefaultCellStyle.BackColor = Color.Lime;
                                }
                            }


                            if (progressbar.Value == progressbar.Maximum)
                            {
                                progressbar.Value = 0;
                            }
                            else
                            {
                                progressbar.Value += 33;
                            }
                        }));

                        Thread.Sleep(delay);

                        while (paused && !stopped)
                        {
                            Thread.Sleep(delay);
                        }

                        if (stopped)
                        {
                            m.Stop();
                        }
                    });
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }

                this.Invoke(new Action(() =>
                {
                    running           = false;
                    status_lbl.Text   = "Stopped";
                    progressbar.Value = 0;
                }));
            }).Start();
        }
Ejemplo n.º 18
0
        static async void BotOnMessageReceived(object sender, MessageEventArgs MessageEventArgs)
        {
            Telegram.Bot.Types.Message msg = MessageEventArgs.Message;
            if (msg == null || msg.Type != MessageType.Text)
            {
                return;
            }

            string Answer = "Server Error";

            if (DateTime.UtcNow.Subtract(msg.Date).TotalMinutes > 3)
            {
                await BOT.SendTextMessageAsync(msg.Chat.Id, Answer);

                return;
            }

            if (UserList.ContainsKey(msg.Chat.Id))
            {
                UserList[msg.Chat.Id].LastAccess = DateTime.Now;
            }
            if (!IsRegistered(msg.Chat.Id))
            {
                UserList.Add(msg.Chat.Id, new User()
                {
                    ident = 3
                });
                Json_Data.WriteData();   //регистрация в базе
            }
            if (UserList[msg.Chat.Id].ident == 5)
            {
                bool onOrOff = msg.Text.ToLower() == "включить";
                UserList[msg.Chat.Id].eveningNotify = onOrOff;
                UserList[msg.Chat.Id].ident         = 3;
                Json_Data.WriteData();
                string onOrOffMsg = onOrOff ? "включено" : "выключено";
                Answer = $"Вечернее уведомление *{onOrOffMsg}*.";
            }
            else if (UserList[msg.Chat.Id].ident == 6)
            {
                bool onOrOff = msg.Text.ToLower() == "включить";
                UserList[msg.Chat.Id].morningNotify = onOrOff;
                UserList[msg.Chat.Id].ident         = 3;
                Json_Data.WriteData();
                string onOrOffMsg = onOrOff ? "включено" : "выключено";
                Answer = $"Уведомление за 15 минут до первой пары *{onOrOffMsg}*.";
            }
            else
            {
                try
                {
                    switch (msg.Text.ToLower())             // Обработка команд боту
                    {
                    case "/start":
                        Answer = "Добро пожаловать!\n" + _help;
                        break;

                    case "/joke":
                    case "анекдот":
                        do
                        {
                            Answer = Markov.MakeText(1, random).Replace(" . ", ". ");
                        } while (Answer.Length > 4096);     //Search for new joke if it exceeds Telegram text msg limit
                        break;

                    case "/knowme":
                    case "знаешь меня?":
                        Answer = $"Вы {msg.Chat.FirstName.Replace("`", "").Replace("_", "").Replace("*", "")}.";
                        break;

                    case "/eveningnotify":
                        Answer = $"Сейчас вечернее уведомление *{(UserList[msg.Chat.Id].eveningNotify ? "включено" : "выключено")}*. \nНастройте его.";
                        UserList[msg.Chat.Id].ident = 5;
                        await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, ParseMode.Markdown, replyMarkup : notifierKeyboard);

                        return;

                    case "/morningnotify":
                        Answer = $"Сейчас утреннее уведомление *{(UserList[msg.Chat.Id].morningNotify ? "включено" : "выключено")}*. \nНастройте его.";
                        UserList[msg.Chat.Id].ident = 6;
                        await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, ParseMode.Markdown, replyMarkup : notifierKeyboard);

                        return;


                    case "/stop":
                    case "стоп":
                        UserList.Remove(msg.Chat.Id);
                        Json_Data.WriteData();
                        Answer = "Я вас забыл! Для повторной регистрации пиши /start";
                        await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, replyMarkup : new ReplyKeyboardRemove());

                        return;

                    case "помощь":
                    case "/help":
                        Answer = _help;
                        break;

                    case "/info":
                    case "информация":
                        Answer = "Прекрасный бот для генерации прекрасного настроения!\n" +
                                 "Данный бот, реализованный на марковских цепях, используя базу данных из свыше, чем 100т. анекдотов, способен генерировать новые шедевры комедийного искусства.";
                        break;

                    case "/forceupdate":
                        logger.Info($"Запрошено принудительное обновление, ID: {msg.Chat.Id}, @{msg.Chat.Username}.");

                        logger.Info($"Завершено принудительное обновление, ID: {msg.Chat.Id}, @{msg.Chat.Username}.");
                        Answer = "Данные обновлены!";
                        break;

                    default:
                        Answer = "Введены неверные данные, повторите попытку.";
                        break;
                    }
                }
                catch (System.Net.WebException e)
                {
                    logger.Error(e, "Catched exeption:");
                    Answer = "Ошибка! Вероятно, что-то умерло. Пожалуйста, попробуйте повторить запрос позднее.";
                }
            }
            try
            {
                await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, ParseMode.Markdown, replyMarkup : defaultKeyboard);
            }
            catch (Exception ex) when(ex is System.Net.Http.HttpRequestException && ex.Message.Contains("429"))
            {
                logger.Warn(ex, $"Network error while answering @{msg.Chat.Username}");
            }
            catch (Exception ex) when(ex is Telegram.Bot.Exceptions.ApiRequestException)
            {
                logger.Warn(ex, $"Telegram API error while answering @{msg.Chat.Username}");
            }
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            var markov = new Markov();

            //var markov = new MarkovNextGen();
            Console.Write("markov> ");
            var cmd = Console.ReadLine();

            while (cmd != "exit")
            {
                if (cmd.StartsWith("train"))
                {
                    var rest = cmd.Substring(6);
                    if (File.Exists(rest))
                    {
                        var lines = File.ReadAllLines(rest).ToList();
                        markov.AddToChain(lines);
                    }
                    else
                    {
                        Console.WriteLine("Error: Target file does not exist");
                        Console.WriteLine("Resol: Ignoring invalid train request");
                        Console.WriteLine(Environment.NewLine);
                    }
                }
                else if (cmd.StartsWith("set"))
                {
                    var rest = cmd.Substring(4);
                    if (File.Exists(rest))
                    {
                        markov = new Markov(rest);
                    }
                    else
                    {
                        File.WriteAllText(rest, "{}");
                        markov = new Markov(rest);
                        Console.WriteLine("_Warn: Target file does not exist");
                        Console.WriteLine("Resol: Creating target PDO");
                        Console.WriteLine(Environment.NewLine);
                    }
                }
                else if (cmd.StartsWith("gen"))
                {
                    if (cmd == "gen")                               // Automatic length and random word
                    {
                        Console.WriteLine(markov.Generate());
                    }
                    else
                    {
                        var rest = cmd.Substring(4);
                        if (Int32.TryParse(rest, out int length))   // Length and random word
                        {
                            Console.WriteLine(markov.Generate(length));
                        }
                        else
                        {
                            if (!rest.Contains(" "))                // Automatic length and specific word
                            {
                                Console.WriteLine(markov.Generate(rest));
                            }
                            else                                    // Automatic length and random word
                            {
                                var arguments = rest.Split(' ');
                                if (Int32.TryParse(arguments[0], out int length2))
                                {
                                    Console.WriteLine(markov.Generate(length2, arguments[1]));
                                }
                                else
                                {
                                    Console.WriteLine("Error: Specified length was not an integer");
                                    Console.WriteLine("Resol: Ignoring invalid gen request");
                                    Console.WriteLine(Environment.NewLine);
                                }
                            }
                        }
                    }
                }
                else if (cmd.StartsWith("merge"))
                {
                    var rest    = cmd.Substring(6);
                    var targets = rest.Split(' ');
                    if (targets.Length == 2)        // Merge two files
                    {
                        // File existence check is implemented in Merge methods
                        MarkovUtilities.MergeTo(targets[0], targets[1]);
                    }
                    else if (targets.Length == 3)   // Merge two files into third
                    {
                        // File existence check implemented in Merge methods
                        // Additional target check implemented here
                        if (!File.Exists(targets[2]))
                        {
                            var merged = MarkovUtilities.MergeFrom(targets[0], targets[1]);
                            //var merged = MarkovUtility.MergeFrom(targets[0], targets[1]);
                            var jsonmerged = JsonConvert.SerializeObject(merged, Formatting.Indented);
                            File.WriteAllText(targets[2], jsonmerged);
                        }
                        else
                        {
                            Console.WriteLine("Error: Target file already exists");
                            Console.WriteLine("Resol: Ignoring merge request");
                            Console.WriteLine("_Note: If this is intentional, merge twice");
                            Console.WriteLine(Environment.NewLine);
                        }
                    }
                }
                else if (cmd.StartsWith("load"))
                {
                    // Merges and serialzies PDO file into current chain
                    var rest = cmd.Substring(5);
                    if (File.Exists(rest))
                    {
                        var jsonfrom = File.ReadAllText(rest);
                        var from     = JsonConvert.DeserializeObject <Dictionary <string, Link> >(jsonfrom);
                        markov.AddToChain(from);
                    }
                    else
                    {
                        Console.WriteLine("Error: Target file does not exist");
                        Console.WriteLine("Resol: Ignoring invalid load request");
                        Console.WriteLine(Environment.NewLine);
                    }
                }
                Console.Write("markov> ");
                cmd = Console.ReadLine();
            }
        }
Ejemplo n.º 20
0
        /*
        /// <summary>
        /// Helper
        /// </summary>
        /// <param name="f"></param>
        /// <param name="num"></param>
        /// <returns></returns>
        static double[] _f(Frequency_4x4x4 f, int i)
        {
            double[] d = { f.frequencies[0, 0, i], f.frequencies[0, 1, i], f.frequencies[0, 2, i], f.frequencies[0, 3, i], f.frequencies[1, 0, i], f.frequencies[1, 1, i], f.frequencies[1, 2, i], f.frequencies[1, 3, i], f.frequencies[2, 0, i], f.frequencies[2, 1, i], f.frequencies[2, 2, i], f.frequencies[2, 3, i], f.frequencies[3, 0, i], f.frequencies[3, 1, i], f.frequencies[3, 2, i], f.frequencies[3, 3, i] };
            return d;
        }

        /// <summary>
        /// Helper
        /// </summary>
        /// <param name="f"></param>
        /// <param name="num"></param>
        /// <returns></returns>
        static Frequency_4x4x4 f_(Frequency_4x4x4 f,  double[] f0, int i)
        {
            Frequency_4x4x4 f1 = new Frequency_4x4x4();
            Array.Copy( f.frequencies, f1.frequencies, f1.frequencies.Length);

            f1.frequencies[0, 0, i] = f.frequencies[0, 0, i];
            f1.frequencies[0, 1, i] = f.frequencies[0, 1, i];
            f1.frequencies[0, 2, i] = f.frequencies[0, 2, i];
            f1.frequencies[0, 3, i] = f.frequencies[0, 3, i];
            f1.frequencies[1, 0, i] = f.frequencies[1, 0, i];
            f1.frequencies[1, 1, i] = f.frequencies[1, 1, i];
            f1.frequencies[1, 2, i] = f.frequencies[1, 2, i];
            f1.frequencies[1, 3, i] = f.frequencies[1, 3, i];
            f1.frequencies[2, 0, i] = f.frequencies[2, 0, i];
            f1.frequencies[2, 1, i] = f.frequencies[2, 1, i];
            f1.frequencies[2, 2, i] = f.frequencies[2, 2, i];
            f1.frequencies[2, 3, i] = f.frequencies[2, 3, i];
            f1.frequencies[3, 0, i] = f.frequencies[3, 0, i];
            f1.frequencies[3, 1, i] = f.frequencies[3, 1, i];
            f1.frequencies[3, 2, i] = f.frequencies[3, 2, i];
            f1.frequencies[3, 3, i] = f.frequencies[3, 3, i];

            return f1;
        }
         *
         *
        */
        static void Main(string[] args)
        {
            byte[] videoData = new byte[0];
            byte[] bytes = new byte[0];
            Bitmap b = new Bitmap(1, 1);
            Bitmap b1 = new Bitmap(1, 1);
            Bitmap b2 = new Bitmap(1, 1);
            Bitmap b3 = new Bitmap(1, 1);

            string savefilename = "file";
            byte[] saveFile = new byte[1];
            Frequency_4x4x4 steg = new Frequency_4x4x4();

            Console.WriteLine("XMAS PACKAGER -- (0x00)");
            Console.WriteLine("------------");
            Console.WriteLine("Digital Data Hiding and Forensic Steganalysis for Online Videos");
            Console.WriteLine("What is the video width?");
            int videoWidth = Int32.Parse(Console.ReadLine());
            Console.WriteLine("What is the video height?");
            int videoHeight = Int32.Parse(Console.ReadLine());
            Console.WriteLine("What is the number of frames of the video?");
            int frameLength = Int32.Parse(Console.ReadLine());
            Console.WriteLine("What is the video's filename?");
            string filename = Console.ReadLine();
            Console.WriteLine("What is the stegano file's filename?");
            string sfilename = Console.ReadLine();
            Console.WriteLine("Are you hiding data, reconstructing it, or performing steganalysis? <H/R/S>");
            string hiding = Console.ReadLine();

            if (hiding == "S")
            {

                Console.WriteLine("\n > == Blind Steganalysis using the 3D DCT's high frequencies and K-means Clustering ==");
                Console.WriteLine("\n 1. Specify Cluster Centroids (Recommended) \n 2. CPU-Generated Random Cluster Centroids \n ");
                string cent = Console.ReadLine();
                if (cent == "2")
                {
                    Console.WriteLine("The CPU will generate k random cluster centroids. This may or may not give the best output. \nWhat is k?");
                    int k = Int32.Parse(Console.ReadLine());

                }
                if (cent == "1")
                {
                    Console.WriteLine("To initialize the k means algorithm, you need to select two representative videos so that the program has an understanding of the difference between the two classes. "
                    + "\n\n The first video should have data hidden inside of all frames (Stegano), while the second should have no data hidden inside of any frame. (Clean) \nWhat is k?");
                    int k = Int32.Parse(Console.ReadLine());
                    Console.WriteLine("Specify the filename of the stegano video");
                    string steganovid = Console.ReadLine();
                    Console.WriteLine("Specify the filename of the clean video");
                    string cleanvid = Console.ReadLine();
                    Console.WriteLine("Choose a parameter T for (Typically 0-4)");
                    int T = Int32.Parse(Console.ReadLine());

                    Bitmap[] sData = new Bitmap[4];
                    Bitmap[] cData = new Bitmap[4];

                    //
                    // An explanation of how this all works with apologies for false rates
                    //
                    // With k = 2, we harvest the first four frames of the videos
                    // and group them together into two separate classes (or clusters)
                    // To create two ideal classes:
                    //
                    //
                    //
                    // Ideal Dirty Video
                    // Ideal Clean Video
                    //
                    //
                    //
                    // We then check the similarity/distance between incoming group and existing classes in k-means.
                    // We group by high similarity / low distance
                    // Cosine Distance = (1 - Cosine similarity)
                    //
                    //
                    //
                    // A group contains 4 frames.
                    // Each class is initially represented by a group of first 4 frames from a separate video.
                    //
                    // Really and truly, the "Dirty" and "Clean" are meaningless
                    // Watch, for example, we use k = 2
                    // and set each cluster representative to be a "Ideally Clean" (strong correlations) and "Ideally Dirty" (weak correlations) video
                    // We imagine a Clean video has strong spatial and temporal correlations
                    // and a Dirty video has weak correlations of both.
                    //
                    //
                    // But our attacker's crafty data hiding algorithm might be different from our own
                    // and it might preserve either temporal and spatial correlations or both.
                    //
                    // This would mean that not all dirty videos may exhibit weak correlations.
                    //
                    // We could use larger values of k
                    // To create classes where unique steganography only modifies certain correlations
                    //
                    // All this algorithm is doing is measuring if an input video group has strong and weak correlations
                    // which it captures using intra-frame (spatial) markov features, and inter-frame (temporal) markov features
                    // Which only capture the unique probabilities of transitioning from DCT coefficient to DCT coefficient.
                    //
                    //
                    // The algorithm classifies due to weak spatial and temporal correlations in DCT domain.
                    // It checks to see how similar DCT frequencies are to each other.
                    //
                    // BUT
                    //
                    // One could set k to anything
                    // And have
                    //
                    // Strong Temporal Correlations with Weak Spatial Correlations,
                    // Strong Spatial Correlations with Weak Temporal Correlations,
                    // ...
                    // etc
                    //
                    // (any number of classes)
                    //
                    // and other features are exhibited from YouTube videos, such as the Absolute Central Moment, Kurtosis, Skewness, etc
                    // which introduce the possibility for even more classes
                    //
                    //
                    //
                    // Because Steganography algorithms are very different, some create weak spatial correlations, some, weak temporal correlations.
                    // There are a seemingly limitless number of ways to hide data in videos which all have unique footprints.
                    //
                    // The steganalysis scheme then
                    // but with contiguous spacing (scaled by T) to compensate
                    // for temporal error correcting codes.
                    //
                    // Why?
                    //
                    // Data hiding in online video is unreliable without "temporal error correction",
                    // This means we repeat the message in multiple neighboring frames to improve the reliability of data hiding.
                    //
                    // YouTube compression can be seen as a form of steganographic attack called a Collusion Attack
                    // A Collusion Attack on a video weakens a hidden message by altering the frames around it and creating weak temporal correlation.
                    //
                    // This only means that many of our frames in time series become too different from each other,
                    // which would convince us that there is hidden data in the video using this detection scheme.
                    //
                    // In reality YouTube messes up our hidden data by introducing errors in it and around it by dropping frames and encoding them
                    // with motion vector data, which is why it is necessary to use temporal error correction.
                    //
                    // But with temporal error correction, if we try to perform steganalysis on neighboring frames,
                    // we may get false negatives thanks to error correcting codes.
                    //
                    // With the strong temporal correlation, or, the very close similarity between frames,
                    // temporal error correcting codes fool us into thinking that nothing is there.
                    // Alternatively, we may get true positives thanks to noisy collusion attack
                    // but this is too difficult to determine in advance what we will get with YouTube.
                    // All it will likely do is interfere with our detection scheme
                    //
                    //
                    // Temporal error correction lowers the bitrate in the temporal direction if it repeats the message in time
                    // This creates strong temporal correlations between DCT blocks.
                    // With the model in [1] this would give us a false negative.
                    // This algorithm classifies using WEAK temporal correlations between DCT blocks
                    // But the temporal corrected message has STRONG temporal correction.
                    //
                    //
                    // We just want to get an honest detection reading that isn't affected by error correction or collusion.
                    //
                    //
                    // Likewise, fast moving, choppy, and noisy videos
                    // give many false positives for this reason because they have weak temporal correlations.
                    // and the authors mention this.
                    //
                    // YouTube does not collude videos which have no information as long as they are smooth and slow-moving,
                    // and they usually remain this way after compression
                    //
                    // Slow moving videos with hidden data that isn't temporally corrected are colluded,
                    // but it should not negatively affect the detection performance.
                    //
                    // It is the error correction which is annoying
                    // because it reduces bitrate
                    // a very widely held fact of Forensic Steganalysis is that bitrate reduction can harm Steganalysis
                    // because hiding less information lowers detection rates :(
                    //
                    //
                    Console.WriteLine("A. Initializing Steganalytic Tool (8 Steps)");

                    Console.WriteLine("1. Loading Data");
                    for (int i = 0; i < 4; i++)
                        sData[i] = BitmapFromArray1DSafe(GetBytesFromFile(steganovid, (((videoWidth * videoHeight) * i * T) + (((videoWidth * videoHeight) * i * T) / 2)), videoWidth * videoHeight), videoWidth, videoHeight);;

                    for (int i = 0; i < 4; i++)
                        cData[i] = BitmapFromArray1DSafe(GetBytesFromFile(steganovid, (((videoWidth * videoHeight) * i * T) + (((videoWidth * videoHeight) * i * T) / 2)), videoWidth * videoHeight), videoWidth, videoHeight); ;

                    Console.WriteLine("2. Performing 3D DCT Transform, Acquiring Groups Y(k1,k2,k3,k) for Initial Centroids, calculating Low-Order Statistics");
                    double[,,] sDataGroup = M_Group(sData[0], sData[1], sData[2], sData[3]);
                    double[,,] cDataGroup = M_Group(cData[0], cData[1], cData[2], cData[3]);

                    Console.WriteLine("2. Assembling transform histograms"); ;
                    double smean = m(sDataGroup); Console.WriteLine("Mean of stegano video is" + smean);
                    double cmean = m(cDataGroup); Console.WriteLine("Mean of clean video is " + cmean);

                    double sstd = std(sDataGroup, smean); Console.WriteLine("Sigma of stegano video is " + sstd);
                    double cstd = std(cDataGroup, cmean); Console.WriteLine("Sigma of clean video is " + cstd);

                    Console.WriteLine("\n3. Calculating Kurtosis for Initial Centroids");
                    double sKurtosis = Kurtosis(smean, sstd, flatten(sDataGroup));
                    double cKurtosis = Kurtosis(cmean, cstd, flatten(cDataGroup));
                    Console.WriteLine("Kurtosis for Clean Videos: " + cKurtosis);
                    Console.WriteLine("Kurtosis for Dirty Videos: " + sKurtosis);

                    Console.WriteLine("\n4. Calculating Skewness for Initial Centroids");
                    double sSkewness = Skewness(smean, sstd, flatten(sDataGroup));
                    double cSkewness = Skewness(cmean, cstd, flatten(cDataGroup));
                    Console.WriteLine("Skewness for Clean Videos: " + cSkewness);
                    Console.WriteLine("Skewness for Dirty Videos: " + sSkewness);

                    Console.WriteLine("\n5. Calculating 1st order Absolute Central Moment for Initial Centroids");
                    double s1stabs = AbsCentralMoment(1, videoHeight, videoWidth, flatten(sDataGroup), smean);
                    double c1stabs = AbsCentralMoment(1, videoHeight, videoWidth, flatten(cDataGroup), cmean);
                    Console.WriteLine("1st order Absolute Moment for Clean Videos: " + c1stabs);
                    Console.WriteLine("1st order Absolute Moment for Dirty Videos: " + s1stabs);

                    Console.WriteLine("\n6. Calculating 2nd order Absolute Central Moment for Initial Centroids");
                    double s2ndabs = AbsCentralMoment(2, videoHeight, videoWidth, flatten(sDataGroup), smean);
                    double c2ndabs = AbsCentralMoment(2, videoHeight, videoWidth, flatten(cDataGroup), cmean);
                    Console.WriteLine("2nd order Absolute Moment for Clean Videos: " + c2ndabs);
                    Console.WriteLine("2nd order Absolute Moment for Dirty Videos: " + s2ndabs);

                    Console.WriteLine("\n7. Calculating 3rd order Absolute Central Moment for Initial Centroids");
                    double s3rdabs = AbsCentralMoment(3, videoHeight, videoWidth, flatten(sDataGroup), smean);
                    double c3rdabs = AbsCentralMoment(3, videoHeight, videoWidth, flatten(cDataGroup), cmean);
                    Console.WriteLine("3rd order Absolute Moment for Clean Videos: " + c3rdabs);
                    Console.WriteLine("3rd order Absolute Moment for Dirty Videos: " + s3rdabs);

                    Console.WriteLine("\n8. Calculating Markov Features for Initial Centroids");
                    Markov smv = new Markov();
                    Markov cmv = new Markov();

                    //Reduce feature dimension by T, which is 10
                    sDataGroup = Truncate(sDataGroup);
                    cDataGroup = Truncate(cDataGroup);

                    smv.markov = transition_Tensor(sDataGroup);
                    cmv.markov = transition_Tensor(cDataGroup);

                    Console.WriteLine("\n8. Assembling essential feature Vectors for initializing 2-means");
                    FeatureVector fv1 = featureVector1(smv, s1stabs, s2ndabs, s3rdabs, sSkewness, sKurtosis, -1);
                    FeatureVector fv2 = featureVector1(cmv, c1stabs, c2ndabs, c3rdabs, cSkewness, cKurtosis, -1);

                    Console.WriteLine("Done Initializing! \n\n");

                    Console.WriteLine("B. Gathering Low-order and High-order statistics from target video frames.");

                    Console.ReadLine();
                }

                for (int i = 0; i < frameLength - 3; i++)
                {

                    Console.Write("\n Scanning the video with " + (100 * (((double)i / (double)frameLength))) + "% Completed \n");

                    videoData = GetBytesFromFile(filename, (((videoWidth * videoHeight) * i) + (((videoWidth * videoHeight) * i) / 2)), videoWidth * videoHeight);
                    b = BitmapFromArray1D(videoData, videoWidth, videoHeight);

                    videoData = GetBytesFromFile(filename, (((videoWidth * videoHeight) * (i+1)) + (((videoWidth * videoHeight) * (i+1)) / 2)), videoWidth * videoHeight);
                    b1 = BitmapFromArray1D(videoData, videoWidth, videoHeight);

                    videoData = GetBytesFromFile(filename, (((videoWidth * videoHeight) * (i+2)) + (((videoWidth * videoHeight) * (i+2)) / 2)), videoWidth * videoHeight);
                    b2 = BitmapFromArray1D(videoData, videoWidth, videoHeight);

                    videoData = GetBytesFromFile(filename, (((videoWidth * videoHeight) * (i+3)) + (((videoWidth * videoHeight) * (i+3)) / 2)), videoWidth * videoHeight);
                    b3 = BitmapFromArray1D(videoData, videoWidth, videoHeight);

                    steg = DCT3D_4x4x4(b, b1, b2, b3);

                    videoData = Array1DFromBitmap(b, videoWidth * videoHeight);
                    SaveBytesToFile(filename, (((videoWidth * videoHeight) * i) + (((videoWidth * videoHeight) * i) / 2)), videoWidth * videoHeight, videoData);

                }

            }

            if (hiding == "R")
            {
                Console.WriteLine("Enter the filename to save the reconstructed file to");
                savefilename = Console.ReadLine();
                Console.WriteLine("What is the filesize of the file in bytes? If unknown, type 42");
                filesizespecified = long.Parse(Console.ReadLine());
            }

            Console.WriteLine("What algorithm will you use? <Choose Number> \n \n \n 1. (checkers): Spatial Domain PVD - Very Robust, uses computationally efficient Pixel Value Differencing and Histogram Shifting algorithms. Easily detectable visually however. Payload capacity is large. Reccomended if video is being uploaded to YouTube or highly compressed on disk. Not recommended for covert operation and is weak to known steganalysis attacks.");
            Console.WriteLine("\n \n \n 2. (smiling face): Transform Domain DCT2D 8-D Vector Quantization - Fragile, with borderline robustness, uses computationally intensive Discrete Cosine Transform and eight dimensional vector quantization. Invisible with distortion < 3db (6% visual distortion calculated with PSNR). Payload capacity is large but small once error correction used. Highly recommended if video is stored on hard disk and will not be re-encoded. Recommended for covert operation as embedded data is invisible.");
            string response = Console.ReadLine();

            while (true)
            {
                if (response == "2")
                {
                    Console.WriteLine("What is your thresholding parameter T?");
                    int T = Int32.Parse(Console.ReadLine());
                    Console.WriteLine("What is the error correcting codeword length you'll use? (Set this to 900 or greater for YouTube.)");
                    int rep = Int32.Parse(Console.ReadLine());
                    bytes = GetBytesFromFile(sfilename, 0);
                    acc = new double[8 * bytes.Length];

                    finalFile = new byte[bytes.Length];

                    if (bytes.Length * 8 * rep > videoWidth * videoHeight / 4 / 4)
                    {
                        Console.WriteLine(" * File is much larger than embedding capacity of frame with chosen error code, would you like to embed it across all frames? <Y/n>");
                        string allframes = Console.ReadLine();

                        if (allframes != "Y")

                        {
                            Console.WriteLine("File too large, aborting...");
                        }
                        else
                        {
                            loop = false;
                        }
                    }
                    Frequency_4x4 f = new Frequency_4x4();

                    for (int i = 0; i < frameLength; i++)
                    {
                        if (hiding == "H")
                        {

                            Console.Write("\n Processing.." + (100 * (((double)i / (double)frameLength))) + "% Completed \n");

                            videoData = GetBytesFromFile(filename, (((videoWidth * videoHeight) * i) + (((videoWidth * videoHeight) * i) / 2)), videoWidth * videoHeight);
                            b = BitmapFromArray1DSafe(videoData, videoWidth, videoHeight);
                            b = transform_Embed(b, T, bytes, rep);

                            videoData = Array1DFromBitmapSafe(b, videoWidth * videoHeight);
                            SaveBytesToFile(filename, (((videoWidth * videoHeight) * i) + (((videoWidth * videoHeight) * i) / 2)), videoWidth * videoHeight, videoData);

                        }
                        if (hiding == "R")
                        {

                                if (bytes.Length * rep >= (videoWidth * videoHeight / 8 / 16))
                                    loop = false;

                                filesizespecified = bytes.Length;

                            Console.Write("\n Processing.." + (100 * (((double)i / (double)frameLength))) + "% Completed \n");

                            videoData = GetBytesFromFile(filename, (((videoWidth * videoHeight) * i) + (((videoWidth * videoHeight) * i) / 2)), videoWidth * videoHeight);
                            b = BitmapFromArray1DSafe(videoData, videoWidth, videoHeight);
                            saveFile = transform_Retrieve(b, bytes, T, rep);

                            if (!loop)
                                Console.WriteLine("BER for chunk " + i + " (Bit Error Rate) is " + BER(bytes, saveFile, (int)(pos), (int)(videoWidth * videoHeight / 16 / rep)));
                            if (loop)
                                Console.WriteLine("BER (Bit Error Rate) is " + BER(bytes, saveFile));

                            SaveBytesToFile(savefilename, 0, bytes.Length, saveFile);
                            if (loop)
                                acc = AccArray(saveFile, acc);

                        }

                    }
                    acc = AvgArray(acc, frameLength);
                    Console.WriteLine("P value is " + P(acc));
                    Console.WriteLine("Done!");
                    Console.ReadLine();
                }
                if (response == "1")
                {
                    Console.WriteLine("What is your thresholding parameter T?");
                    int T = Int32.Parse(Console.ReadLine());
                    Console.WriteLine("What is your thresholding parameter G?");
                    int G = Int32.Parse(Console.ReadLine());
                    Console.WriteLine("What is the block size");
                    int block_size = Int32.Parse(Console.ReadLine());
                    Console.WriteLine("What is the spatial error correcting codeword length you'll use? (Set this to 50 or greater for YouTube.)");
                    int rep = Int32.Parse(Console.ReadLine());
                    Console.WriteLine("What is the temporal error correcting codeword length you'll use? (Set this to 50 or greater for YouTube.)");
                    int trep = Int32.Parse(Console.ReadLine());
                    bytes = GetBytesFromFile(sfilename, 0);
                    finalFile = new byte[bytes.Length];
                    acc = new double[8 * bytes.Length];

                    long loc = 0;
                    if (bytes.Length * 8 * rep > videoWidth * videoHeight / block_size / block_size)
                    {
                        Console.WriteLine(" * File is much larger than embedding capacity of frame with chosen error code, would you like to embed it across all frames? <Y/n>");
                        string allframes = Console.ReadLine();

                        if (allframes != "Y")
                        {
                            Console.WriteLine("File too large, aborting...");

                        }

                        else
                        {
                            loop = false;
                        }

                    }

                    for (int i = 0; i < frameLength; i++)
                    {

                        if (hiding == "H")
                        {

                            Console.Write("\n Processing.." + (100 * (((double)i / (double)frameLength))) + "% Completed \n");

                            videoData = GetBytesFromFile(filename, (((videoWidth * videoHeight) * i) + (((videoWidth * videoHeight) * i) / 2)), videoWidth * videoHeight);
                            b = BitmapFromArray1D(videoData, videoWidth, videoHeight);
                            b = spatial_Embed(b, block_size, T, G, bytes, rep, trep);

                            videoData = Array1DFromBitmap(b, videoWidth * videoHeight);
                            SaveBytesToFile(filename, (((videoWidth * videoHeight) * i) + (((videoWidth * videoHeight) * i) / 2)), videoWidth * videoHeight, videoData);

                        }
                        if (hiding == "R")
                        {

                                if (bytes.Length * rep >= (videoWidth * videoHeight / 8 / block_size / block_size))
                                    loop = false;

                                filesizespecified = bytes.Length;

                            Console.Write("\n Processing.." + (100 * (((double)i / (double)frameLength))) + "% Completed.");
                            loc = pos;
                            videoData = GetBytesFromFile(filename, (((videoWidth * videoHeight) * i) + (((videoWidth * videoHeight) * i) / 2)), videoWidth * videoHeight);
                            b = BitmapFromArray1D(videoData, videoWidth, videoHeight);
                            saveFile = spatial_Retrieve(b, block_size, T, G, bytes, rep, trep);

                            if (!loop)
                                if ((i+1) % (trep) == 0)
                                {
                                    Console.WriteLine("BER for chunk " + i + " (Bit Error Rate) is " + BER(bytes, saveFile, (int)(loc), (int)(pos - loc)));
                                    Array.Copy(saveFile, pos, finalFile, pos, pos - loc); //this is the cumulative file
                                    Console.WriteLine((100 * (((double)i / (double)frameLength))) + " % of the file ( " + pos + " ) bytes : total filesize of ( " + bytes.Length + " ) bytes has been saved to " + savefilename);
                                    SaveBytesToFile(savefilename, 0, bytes.Length, finalFile); //save the whole file
                                }

                            if (loop)
                                Console.WriteLine("BER (Bit Error Rate) is " + BER(bytes, saveFile));
                            if (loop)
                                SaveBytesToFile(savefilename, 0, bytes.Length, saveFile); //save this
                            if (loop)
                                acc = AccArray(saveFile, acc);

                        }

                    }
                    acc = AvgArray(acc, frameLength);
                    Console.WriteLine("P value is " + P(acc));
                    Console.WriteLine("SUCCESS! Completed 100%. Please be careful with this video.");
                    Console.ReadLine();
                }
                Console.WriteLine("Try a different response.");
                Console.ReadLine();
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Generates the 205 dimensional feature vector [Markov, abs(p), skew, kurt], p = {1,2,3} essential for classification
        /// *Applies weights (10x) to Kurtosis and Skewness
        /// </summary>
        /// <param name="mv">Markov Object</param>
        /// <param name="abs1">Absolute Central Moment, p = 1</param>
        /// <param name="abs2">Absolute Central Moment, p = 2</param>
        /// <param name="abs3">Absolute Central Moment, p = 3</param>
        /// <param name="skew">Skewness</param>
        /// <param name="kurt">Kurtosis</param>
        /// <returns></returns>
        static FeatureVector featureVector1(Markov mv, double abs1, double abs2, double abs3, double skew, double kurt, int id)
        {
            double[] vec = new double[2 * (markov_t * markov_t) + 5];
            for (int y = 0; y < markov_t; y++) //intra
                for (int x = 0; x < markov_t; x++)
                    vec[((markov_t) * y) + x] = mv.markov[x, y, 0];
            for (int y = 0; y < markov_t; y++) //inter
                for (int x = 0; x < markov_t; x++)
                    vec[((markov_t) * markov_t) + ((markov_t) * y) + x] = mv.markov[x, y, 1];

            vec[2 * (markov_t * markov_t) + 0] = abs1;
            vec[2 * (markov_t * markov_t) + 1] = abs2;
            vec[2 * (markov_t * markov_t) + 2] = abs3;
            vec[2 * (markov_t * markov_t) + 3] = 10 * skew;
            vec[2 * (markov_t * markov_t) + 4] = 10 * kurt;

            FeatureVector f = new FeatureVector((markov_t * markov_t) + 5, id);

            f.vec = vec; // ur pushing the envelope on ambiguity here chief
            return f;
        }
Ejemplo n.º 22
0
        private static void NameRelic(Entity relic, Components.Relic comp)
        {
            string[] tokens = Assets.RelicNames.text.Split(new[] { Environment.NewLine },
                                                           StringSplitOptions.RemoveEmptyEntries);

            int r = Random.Range(0, 11);

            switch (r)
            {
            case 0:     // Noun Noun
            {
                string noun1 = tokens.Random().Split(',')[0];
                string noun2 = tokens.Random().Split(',')[0];
                comp.Name = $"{noun1} {noun2}";
                break;
            }

            case 1:     // Adjective Noun
            {
                string noun = tokens.Random().Split(',')[0];
                string adj  = tokens.Random().Split(',')[1];
                comp.Name = $"{adj} {noun}";
                break;
            }

            case 2:     // Name's Noun
            {
                string noun   = tokens.Random().Split(',')[0];
                Markov markov = new Markov(3);
                comp.Name = $"{markov.GetName()}'s {noun}";
                break;
            }

            case 3:     // Adjective Number
            {
                string adj = tokens.Random().Split(',')[1];
                comp.Name = $"{adj} {Random.Range(0, 1000)}";
                break;
            }

            case 4:     // Noun Number
            {
                string noun = tokens.Random().Split(',')[0];
                comp.Name = $"{noun} {Random.Range(0, 1000)}";
                break;
            }

            case 5:     // Nounmonger
            {
                string noun = tokens.Random().Split(',')[0];
                comp.Name = $"{noun}monger";
                break;
            }

            case 6:     // Nounbringer
            {
                string noun = tokens.Random().Split(',')[0];
                comp.Name = $"{noun}bringer";
                break;
            }

            case 7:     // Noun's Noun
            {
                string noun1 = tokens.Random().Split(',')[0];
                string noun2 = tokens.Random().Split(',')[0];
                comp.Name = $"{noun1}'s {noun2}";
                break;
            }

            case 8:     // Nounborn
            {
                string noun = tokens.Random().Split(',')[0];
                comp.Name = $"{noun}born";
                break;
            }

            case 9:     // Baseitem of Noun
            {
                string noun  = tokens.Random().Split(',')[0];
                string basic =
                    relic.Flyweight.EntityName.First().ToString().ToUpper() +
                    relic.Flyweight.EntityName.Substring(1);
                comp.Name = $"The {basic} of {noun}";
                break;
            }

            default:     // The Noun of Name
            {
                string noun   = tokens.Random().Split(',')[0];
                Markov markov = new Markov(3);
                comp.Name = $"The {noun} of {markov.GetName()}";
                break;
            }
            }
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            Console.WriteLine("Loading Brain");
            Markov Markov = new Markov();

            Markov.LoadBrain("BRAIN");
            Console.WriteLine("Brain Loaded.  Auditing...");

            if (!Markov.Audit())
            {
                throw new InvalidOperationException("Audit Failed");
            }

            Console.WriteLine("Audit Passed.  Connecting to server...");

            IrcClient Client = new IrcClient();

            // *** MAIN PROCESSING
            EventHandler <IrcMessageEventArgs> Replier = delegate(Object Sender, IrcMessageEventArgs Event)
            {
                IrcChannel Channel = (IrcChannel)Sender;

                TextInfo TI = new CultureInfo("en-CA", false).TextInfo;

                if (Event.Text.ToLower() == "!exit" && Event.Source.Name.ToLower() == "sukasa")
                {
                    Client.Quit("*DEAD*");
                    Client.Disconnect();
                }
                else
                {
                    Byte[] Value = new Byte[1];
                    RNG.GetBytes(Value);
                    if ((Value[0] >= 245 || Event.Text.ToLower().Contains("kbot")))
                    {
                        String Reply = DoCapitalization(Markov.GenerateReply(Event.Text));
                        Client.LocalUser.SendMessage(Channel.Name, Reply);
                    }
                    Markov.Learn(Event.Text);
                }
            };

            IrcUserRegistrationInfo RegInfo = new IrcUserRegistrationInfo();

            RegInfo.NickName = "kBot";
            RegInfo.UserName = "******";
            RegInfo.RealName = "4th order Markov chain bot";

            Uri ServerAddress = new Uri("irc://irc.irchighway.net:6667");

            using (var connectedEvent = new ManualResetEventSlim(false))
            {
                Client.Connected += (sender2, e2) => connectedEvent.Set();
                Client.Connect(ServerAddress, RegInfo);

                if (!connectedEvent.Wait(10000))
                {
                    Client.Dispose();
                    Console.WriteLine("Connection to {0} timed out.", ServerAddress);
                    return;
                }

                Console.WriteLine("Connected to {0}.", ServerAddress);

                // *** POST-INIT
                Client.MotdReceived += delegate(Object Sender, EventArgs E)
                {
                    Console.WriteLine("Joining Channels...");
                    Client.Channels.Join("#la-mulana");
                };

                // *** DEBUG OUTPUT
                Client.RawMessageReceived += delegate(Object Sender, IrcRawMessageEventArgs Event)
                {
                    Console.WriteLine(Event.RawContent);
                };

                // *** PING
                Client.PingReceived += delegate(Object Sender, IrcPingOrPongReceivedEventArgs Event)
                {
                    Console.WriteLine("Ping Pong");
                    Client.Ping(Event.Server);
                };

                // *** CHANNEL JOINING
                Client.LocalUser.JoinedChannel += delegate(Object Sender, IrcChannelEventArgs Event)
                {
                    Event.Channel.MessageReceived += Replier;
                };

                // *** MESSAGE ECHOING
                Client.RawMessageSent += delegate(Object Sender, IrcRawMessageEventArgs Event)
                {
                    Console.WriteLine(Event.RawContent);
                };

                // *** ERROR REPORTING
                Client.Error += delegate(Object Sender, IrcErrorEventArgs Event)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(Event.Error.Message);
                    Console.ForegroundColor = ConsoleColor.Gray;
                };

                // *** ERROR REPORTING
                Client.ErrorMessageReceived += delegate(Object Sender, IrcErrorMessageEventArgs Event)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(Event.Message);
                    Console.ForegroundColor = ConsoleColor.Gray;
                };

                // *** ERROR REPORTING
                Client.ProtocolError += delegate(Object Sender, IrcProtocolErrorEventArgs Event)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(Event.Message);
                    Console.ForegroundColor = ConsoleColor.Gray;
                };

                // *** REJOIN AFTER KICK
                Client.LocalUser.LeftChannel += delegate(Object Sender, IrcChannelEventArgs Event)
                {
                    Client.Channels.Join(Event.Channel.Name);
                };

                Int32 Counter = 0;
                while (Client.IsConnected)
                {
                    Thread.Sleep(5);
                    if (++Counter == 12000)
                    {
                        Console.Write("Manual Ping ");
                        Client.Ping();
                        Counter = 0;
                    }
                    while (Console.KeyAvailable)
                    {
                        if (Console.ReadKey().Key == ConsoleKey.Delete)
                        {
                            Client.Disconnect();
                        }
                    }
                }

                Console.WriteLine("Saving Brain");
                Markov.SaveBrain("BRAIN");
            }
        }