Exemplo n.º 1
0
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (MainHandler.ENABLE_PYTHON)
            {
                MainHandler.killExplanationBackend();
            }

            if (!viewh.clearWorkspace())
            {
                e.Cancel = true;
            }
            try
            {
                var dir = new DirectoryInfo(Path.GetDirectoryName(Properties.Settings.Default.CMLTempTrainerPath));
                foreach (var file in dir.EnumerateFiles(Path.GetFileName(Properties.Settings.Default.CMLTempTrainerPath) + "latestcmlmodel*"))
                {
                    file.Delete();
                }

                foreach (var file in dir.EnumerateFiles(Path.GetFileName(Properties.Settings.Default.CMLTempTrainerPath) + Properties.Settings.Default.CMLTempTrainerName + "*"))
                {
                    file.Delete();
                }
            }
            catch { }
        }
        public DatabaseCMLExtractFeaturesWindow(MainHandler handler, Mode mode)
        {
            InitializeComponent();

            this.handler = handler;
            this.mode    = mode;

            if (mode == Mode.MERGE)
            {
                ExtractPanel.Visibility     = Visibility.Collapsed;
                NParallelLabel.Visibility   = Visibility.Collapsed;
                NParallelTextBox.Visibility = Visibility.Collapsed;
                ExtractButton.Content       = "Merge";
                Title = "Merge Features";
                StreamsBox.SelectionMode = SelectionMode.Extended;
            }
            else
            {
                HelpLabel.Content = "Features are extracted every frame over a window that is extended by the left and right context.\r\n1.2s\t= 1.2 Seconds\r\n10ms\t= 10 Milliseconds\r\n500\t= 500 Samples";
            }

            GetDatabases(DatabaseHandler.DatabaseName);

            handleSelectionChanged = true;
        }
        private void Ok_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.DataServerLogin = serverLogin.Text;
            Properties.Settings.Default.DataServerPass  = MainHandler.Encode(serverPassword.Password);
            Properties.Settings.Default.Save();


            if (SessionsBox.SelectedItem != null)
            {
                DatabaseSession session = (DatabaseSession)SessionsBox.SelectedItem;
                if (DatabaseHandler.ChangeSession(session.Name))
                {
                    // DialogResult = true;
                }
            }


            if (StreamsBox.SelectedItem != null)
            {
                closeAfterDownload = true;
                downloadSelectedFiles();
            }
            else
            {
                DialogResult = true;
                Close();
            }
        }
Exemplo n.º 4
0
        public DatabaseCMLCompleteWindow(MainHandler handler)
        {
            InitializeComponent();

            this.handler = handler;
            StreamListBox.Items.Add("close.mfccdd[-f 0.04 -d 0]");

            foreach (AnnoTier tier in handler.AnnoTiers)
            {
                //  if (tier.AnnoList.FromDB && tier.AnnoList.AnnotationScheme.name == "voiceactivity")
                {
                    TierListBox.Items.Add(tier.AnnoList.Scheme.Name);
                }
            }

            StreamListBox.SelectedIndex = 0;
            TierListBox.SelectedIndex   = 0;

            ContextTextBox.Text      = Properties.Settings.Default.CMLContext.ToString();
            TierListBox.SelectedItem = Properties.Settings.Default.CMLDefaultScheme;

            ConfidenceCheckBox.IsChecked  = Properties.Settings.Default.CMLSetConf;
            FillGapCheckBox.IsChecked     = Properties.Settings.Default.CMLFill;
            RemoveLabelCheckBox.IsChecked = Properties.Settings.Default.CMLRemove;

            ConfidenceTextBox.Text  = Properties.Settings.Default.CMLDefaultConf.ToString();
            FillGapTextBox.Text     = Properties.Settings.Default.CMLDefaultGap.ToString();
            RemoveLabelTextBox.Text = Properties.Settings.Default.CMLDefaultMinDur.ToString();
        }
Exemplo n.º 5
0
        public Settings()
        {
            InitializeComponent();
            Certainty.Text                 = Properties.Settings.Default.UncertaintyLevel.ToString();
            Annotator.Text                 = Properties.Settings.Default.Annotator;
            DefaultZoom.Text               = Properties.Settings.Default.DefaultZoomInSeconds.ToString();
            Segmentmindur.Text             = Properties.Settings.Default.DefaultMinSegmentSize.ToString();
            Samplerate.Text                = Properties.Settings.Default.DefaultDiscreteSampleRate.ToString();
            DrawwaveformCheckbox.IsChecked = Properties.Settings.Default.DrawVideoWavform;
            ContinuousHotkeysnum.Text      = Properties.Settings.Default.ContinuousHotkeysNumber.ToString();
            string[] tokens = Properties.Settings.Default.DatabaseAddress.Split(':');
            if (tokens.Length == 2)
            {
                DBHost.Text = tokens[0];
                DBPort.Text = tokens[1];
            }


            string[] history = Properties.Settings.Default.serverhistory.Split(';');

            DBHost.DropItems       = history;
            DBHost.DropdownClosed += split;



            DBUser.Text                   = Properties.Settings.Default.MongoDBUser;
            DBPassword.Password           = MainHandler.Decode(Properties.Settings.Default.MongoDBPass);
            DBConnnect.IsChecked          = Properties.Settings.Default.DatabaseAutoLogin;
            UpdatesCheckbox.IsChecked     = Properties.Settings.Default.CheckUpdateOnStart;
            OverwriteAnnotation.IsChecked = Properties.Settings.Default.DatabaseAskBeforeOverwrite;
            DownloadDirectory.Text        = Properties.Settings.Default.DatabaseDirectory;
            CMLDirectory.Text             = Properties.Settings.Default.CMLDirectory;
        }
Exemplo n.º 6
0
 private void ControlLoaded(object sender, RoutedEventArgs e)
 {
     if (ActualWidth > 0 && handler == null)
     {
         handler = new MainHandler(this);
         OnHandlerLoaded?.Invoke(handler);
     }
 }
Exemplo n.º 7
0
 private void ControlLoaded(object sender, RoutedEventArgs e)
 {
     if (this.ActualWidth > 0 && this.handler == null)
     {
         this.handler = new MainHandler(this);
         if (OnHandlerLoaded != null)
         {
             OnHandlerLoaded(this.handler);
         }
     }
 }
        private void AddScheme_Click(object sender, RoutedEventArgs e)
        {
            AnnoScheme scheme = MainHandler.AddSchemeDialog();

            if (scheme != null)
            {
                if (DatabaseHandler.AddScheme(scheme))
                {
                    GetSchemes(scheme.Name);
                }
            }
        }
Exemplo n.º 9
0
        private void OkClick(object sender, RoutedEventArgs e)
        {
            if ((MainHandler.Encode(CurrentPasswordField.Password) == Properties.Settings.Default.MongoDBPass && PasswordField.Password != "") || PasswordField.Password == "")
            {
                DialogResult = true;
                Close();
            }

            else
            {
                MessageBox.Show("Current Password is wrong. Please try again or contact an Administrator.");
            }
        }
Exemplo n.º 10
0
        public DatabaseAnnoMainWindow()
        {
            InitializeComponent();

            serverLogin.Text        = Properties.Settings.Default.DataServerLogin;
            serverPassword.Password = MainHandler.Decode(Properties.Settings.Default.DataServerPass);

            GetDatabases(DatabaseHandler.DatabaseName);

            showonlymine.IsChecked       = Properties.Settings.Default.DatabaseShowOnlyMine;
            showOnlyUnfinished.IsChecked = Properties.Settings.Default.DatabaseShowOnlyFinished;
            hideMissing.IsChecked        = Properties.Settings.Default.DBHideMissingStreams;
        }
Exemplo n.º 11
0
        public DatabaseCMLFusionPredictWindow(MainHandler handler)
        {
            InitializeComponent();

            this.handler = handler;

            Loaded += DatabaseCMLTrainAndPredictWindow_Loaded;

            Title = "Predict Bayesian Network";
            ApplyButton.Content          = "Predict";
            TrainOptionsPanel.Visibility = Visibility.Visible;
            ForceCheckBox.Visibility     = Visibility.Visible;
        }
Exemplo n.º 12
0
        private void showSettings()
        {
            Settings s = new Settings();

            s.Tab.SelectedIndex     = 0;
            s.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            s.ShowDialog();

            if (s.DialogResult == true)
            {
                bool reconnect = false;

                if (Properties.Settings.Default.MongoDBUser != s.MongoUser() ||
                    Properties.Settings.Default.DatabaseAddress != s.DatabaseAddress() ||
                    Properties.Settings.Default.MongoDBPass != MainHandler.Encode(s.MongoPass()))
                {
                    reconnect = true;
                }


                Properties.Settings.Default.UncertaintyLevel           = s.Uncertainty();
                Properties.Settings.Default.Annotator                  = s.AnnotatorName();
                Properties.Settings.Default.DatabaseAddress            = s.DatabaseAddress();
                Properties.Settings.Default.MongoDBUser                = s.MongoUser() != "" ?  s.MongoUser() : "invalid username";
                Properties.Settings.Default.MongoDBPass                = MainHandler.Encode(s.MongoPass());
                Properties.Settings.Default.DatabaseAutoLogin          = s.DBAutoConnect();
                Properties.Settings.Default.DefaultZoomInSeconds       = double.Parse(s.ZoomInseconds());
                Properties.Settings.Default.DefaultMinSegmentSize      = double.Parse(s.SegmentMinDur());
                Properties.Settings.Default.DefaultDiscreteSampleRate  = double.Parse(s.SampleRate());
                Properties.Settings.Default.CheckUpdateOnStart         = s.CheckforUpdatesonStartup();
                Properties.Settings.Default.ContinuousHotkeysNumber    = int.Parse(s.ContinuousHotkeyLevels());
                Properties.Settings.Default.DatabaseAskBeforeOverwrite = s.DBAskforOverwrite();
                Properties.Settings.Default.DrawVideoWavform           = s.DrawvideoWavform();
                Properties.Settings.Default.EnablePython               = s.EnablePython();
                Properties.Settings.Default.EnablePythonDebug          = s.EnablePythonDebug();

                Properties.Settings.Default.Save();


                foreach (AnnoTier tier in AnnoTiers)
                {
                    tier.TimeRangeChanged(MainHandler.Time);
                }

                if (reconnect)
                {
                    databaseConnect();
                }
            }
        }
Exemplo n.º 13
0
        private void viewHandlerLoaded(MainHandler handler)
        {
            viewh = handler;

            KeyDown        += OnKeyDown;
            PreviewKeyDown += handler.OnPreviewKeyDown;
            KeyDown        += handler.OnKeyDown;
            KeyUp          += handler.OnKeyUp;

            HandleClArgs(Environment.GetCommandLineArgs());

            ((App)Application.Current).ReceiveExternalClArgs += (app, clArgs) =>
            {
                HandleClArgs(clArgs.Args);
            };
        }
Exemplo n.º 14
0
        public DatabaseCMLBayesNetWindow(MainHandler handler)
        {
            InitializeComponent();

            this.handler = handler;

            Loaded += DatabaseCMLTrainAndPredictWindow_Loaded;

            HelpTrainLabel.Content = "Filename of the Trainingsset.\r\n\rAnnotations are chunked in frames of this size (in ms).\r\n\rDiscretisize continuous Annotations\r\n\rContinous Annotations are discretized in these classes (seperate by ;)\r\n\rTimesteps (0 for static)\r\n\rIf checked, node format is role__scheme, else annotations are added up ";


            Title = "Train Bayesian Network  ";
            ApplyButton.Content  = "Create Samples";
            ApplyButton2.Content = "Train";
            ShowAllSessionsCheckBox.Visibility = Visibility.Collapsed;
            TrainOptionsPanel.Visibility       = Visibility.Visible;
            ForceCheckBox.Visibility           = Visibility.Visible;
        }
 private void EditScheme_Click(object sender, RoutedEventArgs e)
 {
     if (SchemesBox.SelectedItem != null)
     {
         string     name   = (string)SchemesBox.SelectedItem;
         AnnoScheme scheme = DatabaseHandler.GetAnnotationScheme(name);
         if (scheme != null)
         {
             if (MainHandler.UpdateSchemeDialog(ref scheme))
             {
                 if (DatabaseHandler.UpdateScheme(name, scheme))
                 {
                     GetSchemes(scheme.Name);
                 }
             }
         }
     }
 }
Exemplo n.º 16
0
        private void annoList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListView grid = (ListView)sender;

            if (grid.SelectedIndex >= 0 && grid.SelectedIndex < grid.Items.Count)
            {
                AnnoListItem item = (AnnoListItem)grid.SelectedItem;
                control.annoListControl.editComboBox.SelectedItem = item.Label;
                double samplerate = MainHandler.getMaxVideoSampleRate();
                double offset     = (1.0f / samplerate);
                Time.CurrentPlayPosition = item.Start;


                mediaList.Move(item.Start + offset);
                moveSignalCursor(item.Start);

                if (item.Start >= timeline.SelectionStop)
                {
                    float factor = (float)(((item.Start - Time.SelectionStart) / (Time.SelectionStop - Time.SelectionStart)));
                    control.timeLineControl.rangeSlider.MoveAndUpdate(true, factor);
                }
                else if (item.Stop <= timeline.SelectionStart)
                {
                    float factor = (float)(((Time.SelectionStart - item.Start)) / (Time.SelectionStop - Time.SelectionStart));
                    control.timeLineControl.rangeSlider.MoveAndUpdate(false, factor);
                }

                foreach (AnnoListItem a in AnnoTierStatic.Selected.AnnoList)
                {
                    if (a.Start == item.Start && a.Stop == item.Stop && item.Label == a.Label)
                    {
                        AnnoTierStatic.SelectLabel(AnnoTierStatic.Selected.GetSegment(a));
                        control.annoListControl.editComboBox.SelectedItem = item.Label;
                        break;
                    }
                }

                if (item.isGeometric)
                {
                    int position = (int)(Time.CurrentPlayPosition * AnnoTierStatic.Selected.AnnoList.Scheme.SampleRate);
                    geometricSelectItem(item, position);
                }
            }
        }
Exemplo n.º 17
0
        private async void getExplanation(object sender, RoutedEventArgs e)
        {
            SeriesCollection.Clear();
            explanationButton.IsEnabled = false;

            //containerExplainedImages.Children.Clear();

            Dictionary <string, float> explanationData = await getExplanationFromBackend();

            if (explanationData == null)
            {
                MainHandler.restartExplanationBackend();
                this.explanationButton.IsEnabled = true;

                return;
            }


            //Labels = new string[explanationData.Count];
            ChartValues <float> importanceScores = new ChartValues <float>();

            explanationChart.AxisX[0].Labels = new string[explanationData.Count];

            int i = 0;

            foreach (var entry in explanationData)
            {
                importanceScores.Add(entry.Value);
                explanationChart.AxisX[0].Labels[i] = entry.Key;
                i++;
            }

            SeriesCollection.Add(new ColumnSeries
            {
                Title  = "",
                Values = importanceScores
            });

            Formatter = value => value.ToString("N");

            DataContext = this;

            this.explanationButton.IsEnabled = true;
        }
Exemplo n.º 18
0
        public DatabaseCMLTrainAndPredictWindow(MainHandler handler, Mode mode)
        {
            InitializeComponent();

            this.handler = handler;
            this.mode    = mode;

            if (mode == Mode.COMPLETE)
            {
                ModeTabControl.Visibility = Visibility.Collapsed;
            }
            else
            {
                ModeTabControl.SelectedIndex = (int)mode;
            }

            Loaded += Window_Loaded;

            HelpTrainLabel.Content   = "To balance the number of samples per class samples can be removed ('under') or duplicated ('over').\r\n\r\nDuring training the current feature frame can be extended by adding left and / or right frames.\r\n\r\nThe default output name may be altered.";
            HelpPredictLabel.Content = "Apply thresholds to fill up gaps between segments of the same class\r\nand remove small segments (in seconds).\r\n\r\nSet confidence to a fixed value.";
        }
Exemplo n.º 19
0
        private void DatabasePassMenu_Click(object sender, RoutedEventArgs e)
        {
            DatabaseUser blankuser = new DatabaseUser()
            {
                Name = Properties.Settings.Default.MongoDBUser
            };

            blankuser = DatabaseHandler.GetUserInfo(blankuser);

            DatabaseUserManageWindow dialog = new DatabaseUserManageWindow(blankuser.Name, blankuser.Fullname, blankuser.Email, blankuser.Expertise);

            dialog.ShowDialog();

            if (dialog.DialogResult == true)
            {
                DatabaseUser user = new DatabaseUser()
                {
                    Name      = dialog.GetName(),
                    Fullname  = dialog.GetFullName(),
                    Password  = dialog.GetPassword(),
                    Email     = dialog.Getemail(),
                    Expertise = dialog.GetExpertise()
                };

                DatabaseHandler.ChangeUserCustomData(user);

                if (user.Password != "" && user.Password != null)
                {
                    if (DatabaseHandler.ChangeUserPassword(user))
                    {
                        MessageBox.Show("Password Change successful!");
                        Properties.Settings.Default.MongoDBPass = MainHandler.Encode(user.Password);
                        databaseConnect();
                    }
                }
            }
        }
        public DatabaseCMLTransferWindow(MainHandler handler)
        {
            InitializeComponent();

            this.handler = handler;
            //TODO Hard coded mfccs for now, this should be more dynamic in the future.
            StreamListBox.Items.Add("close.mfccdd[-f 0.04 -d 0]");

            try
            {
                mongo = new MongoClient(connectionstring);
                int count = 0;
                while (mongo.Cluster.Description.State.ToString() == "Disconnected")
                {
                    Thread.Sleep(100);
                    if (count++ >= 25)
                    {
                        throw new MongoException("Unable to connect to the database. Please make sure that " + mongo.Settings.Server.Host + ":" + mongo.Settings.Server.Port + " is online and you entered your credentials correctly!");
                    }
                }

                authlevel = DatabaseHandler.CheckAuthentication(Properties.Settings.Default.MongoDBUser, "admin");
                database  = mongo.GetDatabase(Properties.Settings.Default.DatabaseName);
                if (authlevel > 0)
                {
                    GetAnnotationSchemes();
                    GetRoles();
                    GetAnnotators();
                    GetSessionsTraining();
                    GetSessionsForward();

                    ContextTextBox.Text           = Properties.Settings.Default.CMLContext.ToString();
                    AnnotatorListBox.SelectedItem = Properties.Settings.Default.CMLDefaultAnnotator;
                    TierListBox.SelectedItem      = Properties.Settings.Default.CMLDefaultScheme;

                    ConfidenceCheckBox.IsChecked  = Properties.Settings.Default.CMLSetConf;
                    FillGapCheckBox.IsChecked     = Properties.Settings.Default.CMLFill;
                    RemoveLabelCheckBox.IsChecked = Properties.Settings.Default.CMLRemove;

                    ConfidenceTextBox.Text  = Properties.Settings.Default.CMLDefaultConf.ToString();
                    FillGapTextBox.Text     = Properties.Settings.Default.CMLDefaultGap.ToString();
                    RemoveLabelTextBox.Text = Properties.Settings.Default.CMLDefaultMinDur.ToString();



                    string[] roles = Properties.Settings.Default.CMLDefaultRole.Split(';');
                    for (int i = 0; i < roles.Length; i++)
                    {
                        RoleListBox.SelectedItems.Add(roles[i]);
                    }

                    StreamListBox.SelectedIndex = 0;
                }
                else
                {
                    MessageBox.Show("You have no rights to access the database list");
                    authlevel = DatabaseHandler.CheckAuthentication(Properties.Settings.Default.MongoDBUser, Properties.Settings.Default.DatabaseName);
                }
            }
            catch { };
        }
Exemplo n.º 21
0
        private void Apply_Click(object sender, RoutedEventArgs e)
        {
            bool force = ForceCheckBox.IsChecked.Value;

            string database = DatabaseHandler.DatabaseName;

            string[] sessions = new string[SessionsBox.SelectedItems.Count];
            int      i        = 0;

            foreach (DatabaseSession item in SessionsBox.SelectedItems)
            {
                sessions[i] = item.Name;
                i++;
            }

            string[] schemes = new string[SchemeandAnnotatorBox.Items.Count];
            int      s       = 0;

            foreach (SchemeAnnotatorPair item in SchemeandAnnotatorBox.Items)
            {
                schemes[s] = item.Name + ":" + item.Annotator;
                s++;
            }

            string rolesList = "";
            var    roles     = RolesBox.SelectedItems;

            foreach (string role in roles)
            {
                if (rolesList == "")
                {
                    rolesList += role;
                }
                else
                {
                    rolesList += ";" + role;
                }
            }

            Properties.Settings.Default.SettingCMLDefaultBN = NetworkBox.SelectedItem.ToString();


            if (RolesBox.SelectedItem != null)
            {
                Properties.Settings.Default.CMLDefaultRole = RolesBox.SelectedItem.ToString();
            }

            if (AnnotatorInputBox.SelectedItem != null)
            {
                Properties.Settings.Default.CMLDefaultAnnotator = AnnotatorInputBox.SelectedItem.ToString();
            }


            if (SchemeOutputBox.SelectedItem != null)
            {
                Properties.Settings.Default.CMLDefaultScheme = SchemeOutputBox.SelectedItem.ToString();
            }


            Properties.Settings.Default.CMLDefaultAnnotatorPrediction = AnnotatorsBox.SelectedItem.ToString();


            Properties.Settings.Default.Save();

            logTextBox.Text = "";

            string outputscheme = SchemeOutputBox.SelectedItem.ToString();

            string annotator = DatabaseHandler.Annotators.Find(n => n.FullName == Properties.Settings.Default.CMLDefaultAnnotatorPrediction).Name;

            string roleout = Outrole.SelectedItem.ToString();

            bool           tocontinuous = false;
            DatabaseScheme outscheme    = DatabaseHandler.Schemes.Find(n => n.Name == outputscheme);

            if (outscheme.Type == AnnoScheme.TYPE.CONTINUOUS)
            {
                tocontinuous = true;
            }

            string cmlfolderpath = Properties.Settings.Default.CMLDirectory + "\\" +
                                   Defaults.CML.FusionFolderName + "\\" +
                                   Defaults.CML.FusionBayesianNetworkFolderName + "\\";

            string netpath       = cmlfolderpath + NetworkBox.SelectedItem.ToString();
            string schemespath   = cmlfolderpath + "schemes.set";
            string sessionsspath = cmlfolderpath + "sessions.set";

            System.IO.File.WriteAllLines(schemespath, schemes);
            System.IO.File.WriteAllLines(sessionsspath, sessions);
            float filter = -1.0f;

            if (smoothcheckbox.IsChecked == true)
            {
                float.TryParse(WindowSmoothBox.Text, out filter);
            }



            logTextBox.Text += handler.CMLPredictBayesFusion(roleout, sessionsspath, schemespath, Properties.Settings.Default.DatabaseAddress, Properties.Settings.Default.MongoDBUser, MainHandler.Decode(Properties.Settings.Default.MongoDBPass), Properties.Settings.Default.DatabaseDirectory, database, outputscheme, rolesList, annotator, tocontinuous, netpath, filter);
        }
Exemplo n.º 22
0
        private async Task httpPost(string URL, string localpath)
        {
            string login    = Properties.Settings.Default.DataServerLogin;
            string password = MainHandler.Decode(Properties.Settings.Default.DataServerPass);

            string fileName = Path.GetFileName(localpath);

            if (fileName.EndsWith(".stream%7E"))
            {
                fileName = fileName.Remove(fileName.Length - 3);
                fileName = fileName + "~";
            }

            numberOfActiveParallelDownloads++;
            filesToDownload.Add(localpath);

            if (!File.Exists(localpath))
            {
                DownloadStatus dl = new DownloadStatus();
                dl.File    = localpath;
                dl.percent = 0.0;
                dl.active  = true;
                statusOfDownloads.Add(dl);

                try
                {
                    Action EmptyDelegate = delegate() { };
                    control.ShadowBoxText.Text               = "Downloading '" + fileName + "'";
                    control.ShadowBox.Visibility             = Visibility.Visible;
                    control.shadowBoxCancelButton.Visibility = Visibility.Visible;
                    control.UpdateLayout();
                    control.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
                    // Create a new WebClient instance.

                    WebClient client = new WebClient();

                    client.UploadProgressChanged += (s, e) =>
                    {
                        double percent = ((double)e.BytesReceived / (double)e.TotalBytesToReceive) * 100.0;
                        string param   = localpath + "#" + percent.ToString("F2");
                        control.Dispatcher.BeginInvoke(new Action <DownloadStatus>(UpdateOnDownload), DispatcherPriority.Normal, dl);
                    };

                    client.UploadValuesCompleted += (s, e) =>
                    {
                        try
                        {
                            byte[] response = e.Result;
                            File.WriteAllBytes(localpath, response);
                            control.Dispatcher.BeginInvoke(new Action <string>(FinishedDownload), DispatcherPriority.Normal, localpath);
                        }
                        catch
                        {
                            //Could happen when we cancel the download.
                        }
                    };

                    Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, URL);

                    CancellationToken token = tokenSource.Token;

                    await Task.Run(() =>
                    {
                        token.Register(() => { client.CancelAsync(); CanceledDownload(); return; });

                        //Here we assume that the session is stored as simple ID. (as it is done in the Noxi Database). If the SessionID really is a string, this step is not needed.
                        string resultString = Regex.Match(DatabaseHandler.SessionName, @"\d+").Value;
                        int sid             = Int32.Parse(resultString);

                        var values = new NameValueCollection();
                        values.Add("username", login);
                        values.Add("password", password);
                        values.Add("session_id", sid.ToString());
                        values.Add("filename", fileName);

                        Uri url = new Uri(URL);
                        client.UploadValuesAsync(url, values);
                    }, token);
                }
                catch (Exception ex)
                {
                    MessageTools.Error(ex.ToString());
                }
            }
            else
            {
                await control.Dispatcher.BeginInvoke(new Action <string>(FinishedDownload), DispatcherPriority.Normal, "");
            }
        }
Exemplo n.º 23
0
        private async Task SFTP(string url, string localpath)
        {
            bool iscanceled = false;

            string[] split    = url.Split(':');
            string[] split2   = split[1].Split(new char[] { '/' }, 4);
            string   ftphost  = split2[2];
            string   fileName = split2[3].Substring(split2[3].LastIndexOf("/") + 1, (split2[3].Length - split2[3].LastIndexOf("/") - 1));
            string   folder   = split2[3].Remove(split2[3].Length - fileName.Length);

            string login    = Properties.Settings.Default.DataServerLogin;
            string password = MainHandler.Decode(Properties.Settings.Default.DataServerPass);

            lastDownloadFileName = fileName;

            string ftpfilepath = "/" + folder + fileName;

            filesToDownload.Add(localpath);
            numberOfActiveParallelDownloads++;

            if (!File.Exists(localpath))
            {
                DownloadStatus dl = new DownloadStatus();
                dl.File    = localpath;
                dl.percent = 0.0;
                dl.active  = true;
                statusOfDownloads.Add(dl);

                Sftp sftp = new Sftp(ftphost, login, password);
                try
                {
                    sftp.OnTransferProgress += (src, dst, transferredBytes, totalBytes, message) =>
                    {
                        dl.percent = ((double)transferredBytes / (double)totalBytes) * 100.0;
                        control.Dispatcher.BeginInvoke(new Action <DownloadStatus>(UpdateOnDownload), DispatcherPriority.Normal, dl);
                    };

                    Action EmptyDelegate = delegate() { };
                    control.ShadowBoxText.Text               = "Connecting to Server...";
                    control.ShadowBox.Visibility             = Visibility.Visible;
                    control.shadowBoxCancelButton.Visibility = Visibility.Visible;
                    control.UpdateLayout();
                    control.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
                    sftp.Connect();

                    CancellationToken token = tokenSource.Token;

                    await Task.Run(() =>
                    {
                        if (sftp.Connected)
                        {
                            token.Register(() => { sftp.Cancel(); iscanceled = true; while (sftp.Connected)
                                                   {
                                                       Thread.Sleep(100);
                                                   }
                                                   CanceledDownload(); return; });
                            if (!iscanceled)
                            {
                                try
                                {
                                    sftp.Get(ftpfilepath, localpath);
                                    sftp.Close();
                                }
                                catch
                                {
                                    sftp.Cancel();
                                    sftp.Close();
                                }
                            }
                        }
                    }, token);
                }
                catch
                {
                    if (null != sftp && sftp.Connected)
                    {
                        sftp.Cancel();
                    }
                    MessageBox.Show("Can't login to data server, not authorized!");
                }
            }

            if (!iscanceled)
            {
                await control.Dispatcher.BeginInvoke(new Action <string>(FinishedDownload), DispatcherPriority.Normal, localpath);
            }
        }
Exemplo n.º 24
0
        private async void getExplanation(object sender, RoutedEventArgs e)
        {
            containerImageToBeExplained.Visibility = Visibility.Visible;
            explainingLabel.Visibility             = Visibility.Visible;
            BlurEffect blur = new BlurEffect();

            blur.Radius                 = 20;
            explanationImage.Effect     = blur;
            explanationButton.IsEnabled = false;

            containerExplainedImages.Children.Clear();

            List <Tuple <int, double, BitmapImage> > explanationData = await getExplanationFromBackend();

            if (explanationData == null)
            {
                MainHandler.restartExplanationBackend();

                this.explainingLabel.Visibility = Visibility.Hidden;
                blur        = new BlurEffect();
                blur.Radius = 0;
                this.explanationImage.Effect     = blur;
                this.explanationButton.IsEnabled = true;

                return;
            }

            for (int i = 0; i < explanationData.Count; i++)
            {
                System.Windows.Controls.StackPanel wrapper = new System.Windows.Controls.StackPanel();
                string className = "";

                if (this.idToClassName.ContainsKey(explanationData[i].Item1))
                {
                    className = this.idToClassName[explanationData[i].Item1];
                }
                else
                {
                    className = explanationData[i].Item1 + "";
                }

                System.Windows.Controls.Label info = new System.Windows.Controls.Label
                {
                    Content = "Class: " + className + " Score: " + explanationData[i].Item2.ToString("0.###")
                };

                System.Windows.Controls.Image img = new System.Windows.Controls.Image
                {
                    Source = explanationData[i].Item3,
                };

                int ratio = getRatio(explanationData.Count);

                img.Height = (this.containerExplainedImages.ActualHeight - explanationData.Count * 2 * 5) / ratio;
                img.Width  = (this.containerExplainedImages.ActualWidth - explanationData.Count * 2 * 5) / ratio;


                wrapper.Margin = new Thickness(5);
                wrapper.Children.Add(info);
                wrapper.Children.Add(img);

                this.containerExplainedImages.Children.Add(wrapper);
            }

            this.containerImageToBeExplained.Visibility = Visibility.Hidden;
            this.explainingLabel.Visibility             = Visibility.Hidden;
            blur        = new BlurEffect();
            blur.Radius = 0;
            this.explanationImage.Effect     = blur;
            this.explanationButton.IsEnabled = true;
        }
Exemplo n.º 25
0
        private void PlayTimer_Tick(object sender, EventArgs e)
        {
            int elapsed = (int)((Environment.TickCount - playLastTick) * PlayerSpeed);

            Time.CurrentPlayPosition += elapsed / 1000.0;

            playLastTick = Environment.TickCount;

            if (Time.CurrentPlayPosition >= timeline.TotalDuration)
            {
                Stop();
            }
            else
            {
                if (Time.CurrentPlayPosition >= Time.SelectionStop && control.navigator.autoScrollCheckBox.IsChecked == true)
                {
                    double factor = (((Time.CurrentPlayPosition - Time.SelectionStart) / (Time.SelectionStop - Time.SelectionStart)));

                    control.timeLineControl.rangeSlider.followmedia = true;
                    control.timeLineControl.rangeSlider.MoveAndUpdate(true, factor);
                }
                else if (Time.CurrentPlayPosition >= Time.SelectionStop && control.navigator.autoScrollCheckBox.IsChecked == false)
                {
                    control.timeLineControl.rangeSlider.followmedia = false;
                    if (AnnoTierStatic.Label != null)
                    {
                        AnnoTierStatic.Label.select(true);
                    }
                    Stop();
                }
            }

            double samplerate = MainHandler.getMaxVideoSampleRate();
            double offset     = 1.0f / samplerate;

            foreach (IMedia media in mediaList)
            {
                if (media.GetMediaType() != MediaType.AUDIO &&
                    media.GetMediaType() != MediaType.VIDEO)
                {
                    media.Move(Time.CurrentPlayPosition);
                }
            }

            updatePositionLabels(Time.CurrentPlayPosition);
            signalCursor.X = Time.PixelFromTime(Time.CurrentPlayPosition + (offset * 2.5));

            if (AnnoTierStatic.Selected != null && AnnoTierStatic.Selected.IsGeometric)
            {
                control.annoListControl.annoDataGrid.SelectedItems.Clear();
                int position = (int)((Time.CurrentPlayPosition + 0.04) * AnnoTierStatic.Selected.AnnoList.Scheme.SampleRate);
                if (position < control.annoListControl.annoDataGrid.Items.Count)
                {
                    AnnoListItem ali = (AnnoListItem)control.annoListControl.annoDataGrid.Items[position];
                    if (ali.Points.Count > 0)
                    {
                        geometricOverlayUpdate(ali, AnnoScheme.TYPE.POINT, position);
                    }
                }
            }
        }
Exemplo n.º 26
0
        private void Apply_Click(object sender, RoutedEventArgs e)
        {
            Trainer trainer = (Trainer)TrainerPathComboBox.SelectedItem;
            bool    force   = mode == Mode.COMPLETE || ForceCheckBox.IsChecked.Value;

            if (!File.Exists(trainer.Path))
            {
                MessageTools.Warning("file does not exist '" + trainer.Path + "'");
                return;
            }

            string database = DatabaseHandler.DatabaseName;

            DatabaseStream stream = (DatabaseStream)StreamsBox.SelectedItem;

            string sessionList = "";
            var    sessions    = SessionsBox.SelectedItems;

            foreach (DatabaseSession session in sessions)
            {
                if (sessionList == "")
                {
                    sessionList += session.Name;
                }
                else
                {
                    sessionList += ";" + session.Name;
                }
            }

            DatabaseScheme scheme = (DatabaseScheme)SchemesBox.SelectedItem;

            string rolesList = "";
            var    roles     = RolesBox.SelectedItems;

            foreach (DatabaseRole role in roles)
            {
                if (rolesList == "")
                {
                    rolesList += role.Name;
                }
                else
                {
                    rolesList += ";" + role.Name;
                }
            }

            DatabaseAnnotator annotator = (DatabaseAnnotator)AnnotatorsBox.SelectedItem;

            string trainerLeftContext  = LeftContextTextBox.Text;
            string trainerRightContext = RightContextTextBox.Text;
            string trainerBalance      = ((ComboBoxItem)BalanceComboBox.SelectedItem).Content.ToString();

            logTextBox.Text = "";

            if (mode == Mode.TRAIN ||
                mode == Mode.COMPLETE)
            {
                string   streamName  = "";
                string[] streamParts = stream.Name.Split('.');
                if (streamParts.Length <= 1)
                {
                    streamName = stream.Name;
                }
                else
                {
                    streamName = streamParts[1];
                    for (int i = 2; i < streamParts.Length; i++)
                    {
                        streamName += "." + streamParts[i];
                    }
                }


                string trainerDir = Properties.Settings.Default.CMLDirectory + "\\" +
                                    Defaults.CML.ModelsFolderName + "\\" +
                                    Defaults.CML.ModelsTrainerFolderName + "\\" +
                                    scheme.Type.ToString().ToLower() + "\\" +
                                    scheme.Name + "\\" +
                                    stream.Type + "{" +
                                    streamName + "}\\" +
                                    trainer.Name + "\\";

                Directory.CreateDirectory(trainerDir);

                string trainerName    = TrainerNameTextBox.Text == "" ? trainer.Name : TrainerNameTextBox.Text;
                string trainerOutPath = mode == Mode.COMPLETE ? tempTrainerPath : trainerDir + trainerName;

                if (force || !File.Exists(trainerOutPath + ".trainer"))
                {
                    try
                    {
                        logTextBox.Text += handler.CMLTrainModel(trainer.Path,
                                                                 trainerOutPath,
                                                                 Properties.Settings.Default.DatabaseDirectory,
                                                                 Properties.Settings.Default.DatabaseAddress,
                                                                 Properties.Settings.Default.MongoDBUser,
                                                                 MainHandler.Decode(Properties.Settings.Default.MongoDBPass),
                                                                 database,
                                                                 sessionList,
                                                                 scheme.Name,
                                                                 rolesList,
                                                                 annotator.Name,
                                                                 stream.Name,
                                                                 trainerLeftContext,
                                                                 trainerRightContext,
                                                                 trainerBalance,
                                                                 mode == Mode.COMPLETE);
                    }

                    catch (Exception ex)
                    {
                        logTextBox.Text += ex;
                    }
                }
                else
                {
                    logTextBox.Text += "skip " + trainerOutPath + "\n";
                }
            }

            if (mode == Mode.PREDICT ||
                mode == Mode.COMPLETE)
            {
                if (true || force)
                {
                    double confidence = -1.0;
                    if (ConfidenceCheckBox.IsChecked == true && ConfidenceTextBox.IsEnabled)
                    {
                        double.TryParse(ConfidenceTextBox.Text, out confidence);
                        Properties.Settings.Default.CMLDefaultConf = confidence;
                    }
                    double minGap = 0.0;
                    if (FillGapCheckBox.IsChecked == true && FillGapTextBox.IsEnabled)
                    {
                        double.TryParse(FillGapTextBox.Text, out minGap);
                        Properties.Settings.Default.CMLDefaultGap = minGap;
                    }
                    double minDur = 0.0;
                    if (RemoveLabelCheckBox.IsChecked == true && RemoveLabelTextBox.IsEnabled)
                    {
                        double.TryParse(RemoveLabelTextBox.Text, out minDur);
                        Properties.Settings.Default.CMLDefaultMinDur = minDur;
                    }
                    Properties.Settings.Default.Save();

                    try
                    {
                        logTextBox.Text += handler.CMLPredictAnnos(mode == Mode.COMPLETE ? tempTrainerPath : trainer.Path,
                                                                   Properties.Settings.Default.DatabaseDirectory,
                                                                   Properties.Settings.Default.DatabaseAddress,
                                                                   Properties.Settings.Default.MongoDBUser,
                                                                   MainHandler.Decode(Properties.Settings.Default.MongoDBPass),
                                                                   database,
                                                                   sessionList,
                                                                   scheme.Name,
                                                                   rolesList,
                                                                   annotator.Name,
                                                                   stream.Name,
                                                                   trainerLeftContext,
                                                                   trainerRightContext,
                                                                   confidence,
                                                                   minGap,
                                                                   minDur,
                                                                   mode == Mode.COMPLETE);
                    }

                    catch (Exception ex)
                    {
                        logTextBox.Text += ex;
                    }
                }
            }

            if (mode == Mode.EVALUATE)
            {
                string evalOutPath = Properties.Settings.Default.CMLDirectory + "\\" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
                try

                {
                    logTextBox.Text += handler.CMLEvaluateModel(evalOutPath,
                                                                trainer.Path,
                                                                Properties.Settings.Default.DatabaseDirectory,
                                                                Properties.Settings.Default.DatabaseAddress,
                                                                Properties.Settings.Default.MongoDBUser,
                                                                MainHandler.Decode(Properties.Settings.Default.MongoDBPass),
                                                                database,
                                                                sessionList,
                                                                scheme.Name,
                                                                rolesList,
                                                                annotator.Name,
                                                                stream.Name,
                                                                LosoCheckBox.IsChecked.Value);

                    if (File.Exists(evalOutPath))
                    {
                        ConfmatWindow confmat = new ConfmatWindow(evalOutPath);
                        confmat.ShowDialog();
                        File.Delete(evalOutPath);
                    }
                }

                catch (Exception ex)
                {
                    logTextBox.Text += ex;
                }
            }

            if (mode == Mode.COMPLETE)
            {
                handler.ReloadAnnoTierFromDatabase(AnnoTierStatic.Selected, false);

                var dir = new DirectoryInfo(Path.GetDirectoryName(tempTrainerPath));
                foreach (var file in dir.EnumerateFiles(Path.GetFileName(tempTrainerPath) + "*"))
                {
                    file.Delete();
                }

                Close();
            }
        }