Exemplo n.º 1
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.º 2
0
        private int httpGetSync(string URL, string localpath)
        {
            string fileName = Path.GetFileName(localpath);

            if (fileName.EndsWith(".stream%7E"))
            {
                fileName = fileName.Remove(fileName.Length - 3);
                fileName = 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);

                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.DownloadProgressChanged += (s, e) =>
                    {
                        dl.percent = ((double)e.BytesReceived / (double)e.TotalBytesToReceive) * 100.0;
                        control.ShadowBoxText.Text = "Downloading " + fileName + "  (" + dl.percent.ToString("F2") + "%)\n";
                    };

                    //client.DownloadFileCompleted += (s, e) =>
                    //{

                    //};

                    tokenSource = new CancellationTokenSource();

                    try
                    {
                        client.DownloadFileAsync(new Uri(URL), localpath, tokenSource);
                    }
                    catch (WebException ex)
                    {
                        return(-1);
                    }
                }

                catch (Exception ex)
                {
                    MessageTools.Error(ex.ToString());
                }
            }

            return(1);
            // else control.Dispatcher.BeginInvoke(new Action<string>(FinishedDownload), DispatcherPriority.Normal, "");
        }
Exemplo n.º 3
0
        private async Task httpGet(string URL, string localpath)
        {
            string fileName = Path.GetFileName(localpath);

            if (fileName.EndsWith(".stream%7E"))
            {
                fileName = fileName.Remove(fileName.Length - 3);
                fileName = 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);

                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.DownloadProgressChanged += (s, e) =>
                    {
                        dl.percent = ((double)e.BytesReceived / (double)e.TotalBytesToReceive) * 100.0;
                        control.Dispatcher.BeginInvoke(new Action <DownloadStatus>(UpdateOnDownload), DispatcherPriority.Normal, dl);
                    };

                    client.DownloadFileCompleted += (s, e) =>
                    {
                        try
                        {
                            //control.Dispatcher.BeginInvoke(new Action<string>(FinishedDownload), DispatcherPriority.Normal, localpath);

                            string[] files = new string[filesToDownload.Count];
                            int      i     = 0;
                            foreach (string path in filesToDownload)
                            {
                                long length = new System.IO.FileInfo(path).Length;
                                if (length == 0)
                                {
                                    if (File.Exists(path))
                                    {
                                        File.Delete(path);
                                    }
                                }
                                else
                                {
                                    files[i] = path;
                                    i++;
                                }
                            }


                            loadFile(localpath);
                        }
                        catch
                        {
                            //Could happen when we cancel the download.
                        }
                    };

                    //tokenSource = new CancellationTokenSource();

                    CancellationToken token = tokenSource.Token;

                    await Task.Run(() =>
                    {
                        token.Register(() => { client.CancelAsync(); CanceledDownload(); return; });
                        client.DownloadFileAsync(new Uri(URL), localpath);
                    }, token);
                }
                catch (Exception ex)
                {
                    MessageTools.Error(ex.ToString());
                }
            }
            else
            {
                await control.Dispatcher.BeginInvoke(new Action <string>(FinishedDownload), DispatcherPriority.Normal, "");
            }
        }
Exemplo n.º 4
0
        private string runCMLTool(string tool, string mode, List <object> parameters, Dictionary <string, object> arguments, string logName)
        {
            string result  = "";
            string logPath = AppDomain.CurrentDomain.BaseDirectory + "\\" + logName + ".log";

            File.Delete(logPath);

            try
            {
                StringBuilder optionsBuilder = new StringBuilder();

                if (mode != null || mode == "")
                {
                    optionsBuilder.Append("--" + mode + " ");
                }

                foreach (KeyValuePair <string, object> arg in arguments)
                {
                    optionsBuilder.Append("-" + arg.Key + " ");
                    if (arg.Value != null)
                    {
                        optionsBuilder.Append(arg.Value.ToString() + " ");
                    }
                }

                optionsBuilder.Append("-log \"" + logPath + "\" ");

                foreach (object par in parameters)
                {
                    optionsBuilder.Append(par.ToString() + " ");
                }

                string options           = optionsBuilder.ToString();
                string optionsNoPassword = null;
                if (arguments.ContainsKey("password"))
                {
                    optionsNoPassword = options.Replace(arguments["password"].ToString(), "*");
                }
                else
                {
                    optionsNoPassword = options;
                }

                string filename = AppDomain.CurrentDomain.BaseDirectory + "\\" + tool + ".exe";

                runCMLProcess(tool, options);

                result += "\n-------------------------------------------\r\n" + filename + " " + optionsNoPassword + "\n-------------------------------------------\r\n";
                result += File.ReadAllText(logPath);

                if (mode == "train" && arguments.ContainsKey("cooperative"))
                {
                    AnnoTierStatic.Selected.CMLCompleteTrainOptions = options;
                }
                if (mode == "forward" && arguments.ContainsKey("cooperative"))
                {
                    AnnoTierStatic.Selected.CMLCompletePredictOptions = options;
                }
            }
            catch (Exception ex)
            {
                MessageTools.Error(ex.ToString());
            }

            return(result);
        }
Exemplo n.º 5
0
        private void ExportAnnoContinuousToDiscrete()
        {
            if (AnnoTierStatic.Selected != null && !AnnoTierStatic.Selected.isDiscreteOrFree)
            {
                Dictionary <string, UserInputWindow.Input> input = new Dictionary <string, UserInputWindow.Input>();
                input["labels"] = new UserInputWindow.Input()
                {
                    Label = "Class labels (separated by ;)", DefaultValue = "LOW;MEDIUM;HIGH"
                };
                input["thresholds"] = new UserInputWindow.Input()
                {
                    Label = "Upper thresholds (separated by ;)", DefaultValue = "0.33;0.66;1.0"
                };
                input["offset"] = new UserInputWindow.Input()
                {
                    Label = "Optional offset (s)", DefaultValue = "0.0"
                };
                UserInputWindow dialog = new UserInputWindow("Convert to discrete annotation", input);
                dialog.ShowDialog();

                List <string> classes         = new List <string>();
                List <double> upperThresholds = new List <double>();
                double        offset          = 0.0;

                if (dialog.DialogResult == true)
                {
                    string[] labels = dialog.Result("labels").Split(';');
                    for (int i = 0; i < labels.Length; i++)
                    {
                        classes.Add(labels[i]);
                    }

                    string[] thresholds = dialog.Result("thresholds").Split(';');
                    for (int i = 0; i < thresholds.Length; i++)
                    {
                        double thresh = -1;
                        double.TryParse(thresholds[i], out thresh);
                        if (thresh > -1)
                        {
                            upperThresholds.Add(thresh);
                        }
                        else
                        {
                            MessageTools.Warning("Could not parse input");
                        }
                    }

                    if (thresholds.Length == labels.Length - 1)
                    {
                        upperThresholds.Add(1.0);
                    }
                    else if (thresholds.Length == labels.Length + 1)
                    {
                        classes.Add("REST");
                    }
                    else if (thresholds.Length != labels.Length)
                    {
                        MessageBox.Show("Number of labels does not match number of threshholds");
                    }

                    double.TryParse(dialog.Result("offset"), out offset);
                }
                Mouse.SetCursor(Cursors.No);

                AnnoList discretevalues = new AnnoList();
                discretevalues.Scheme         = new AnnoScheme();
                discretevalues.Scheme.Type    = AnnoScheme.TYPE.DISCRETE;
                discretevalues.Meta.Role      = AnnoTier.Selected.AnnoList.Meta.Role;
                discretevalues.Meta.Annotator = AnnoTier.Selected.AnnoList.Meta.Annotator;
                discretevalues.Scheme.Name    = AnnoTier.Selected.AnnoList.Scheme.Name;

                foreach (string label in classes)
                {
                    AnnoScheme.Label item = new AnnoScheme.Label(label, System.Windows.Media.Colors.Black);
                    discretevalues.Scheme.Labels.Add(item);
                }

                AnnoScheme.Label garbage = new AnnoScheme.Label("GARBAGE", Colors.Black);
                discretevalues.Scheme.Labels.Add(garbage);

                double lowThres  = -Double.MaxValue;
                double highThres = 1.0;

                foreach (AnnoListItem ali in AnnoTierStatic.Selected.AnnoList)
                {
                    double val = 0;
                    double.TryParse(ali.Label, out val);

                    for (int i = 0; i < classes.Count; i++)
                    {
                        highThres = upperThresholds[i];
                        if (i > 0)
                        {
                            lowThres = upperThresholds[i - 1];
                        }
                        else
                        {
                            lowThres = -Double.MaxValue;
                        }

                        if (val > lowThres && val <= highThres)
                        {
                            if (!(discretevalues.Count > 0 && discretevalues[discretevalues.Count - 1].Label == classes[i]))
                            {
                                AnnoListItem newItem = new AnnoListItem(ali.Start + offset, ali.Duration, classes[i], "", discretevalues.Scheme.GetColorForLabel(classes[i]));
                                if (newItem.Start < 0.0)
                                {
                                    newItem.Duration = ali.Duration + offset + newItem.Start;
                                    newItem.Start    = 0.0;
                                    newItem.Stop     = newItem.Duration;
                                }
                                if (newItem.Duration > 0.0)
                                {
                                    discretevalues.Add(newItem);
                                }
                            }
                            else
                            {
                                discretevalues[discretevalues.Count - 1].Stop = discretevalues[discretevalues.Count - 1].Stop + ali.Duration;
                            }
                            break;
                        }
                    }
                }

                AnnoTier.UnselectTier();
                handleAnnotation(discretevalues);

                Mouse.SetCursor(System.Windows.Input.Cursors.Arrow);
            }
            else
            {
                MessageBox.Show("Tier is already discrete");
            }
        }
Exemplo n.º 6
0
        public static List <AnnoList> LoadfromElanFile(String filepath)
        {
            List <AnnoList> list = new List <AnnoList>();

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filepath);


                //Get time order references

                XmlNode time_order = doc.SelectSingleNode("//TIME_ORDER");
                List <KeyValuePair <string, string> > time_order_list = new List <KeyValuePair <string, string> >();
                foreach (XmlNode node in time_order.ChildNodes)
                {
                    time_order_list.Add(new KeyValuePair <string, string>(node.Attributes[0].Value.ToString(), node.Attributes[1].Value.ToString()));
                }


                //Get number of tiers

                int i = 0;
                foreach (XmlNode tier in doc.SelectNodes("//TIER"))
                {
                    AnnoList   al     = new AnnoList();
                    AnnoScheme scheme = new AnnoScheme();


                    scheme.Type = AnnoScheme.TYPE.FREE;


                    string tierid = tier.Attributes.GetNamedItem("TIER_ID").Value.ToString();

                    string role = "";
                    try
                    {
                        role = tier.Attributes.GetNamedItem("PARTICIPANT").Value.ToString();
                    }
                    catch { }


                    al = new AnnoList();
                    al.Source.File.Path = filepath;

                    foreach (XmlNode annotation in tier.ChildNodes)
                    {
                        string  label                = null;
                        string  starttmp             = "";
                        string  endtmp               = "";
                        double  start                = -1;
                        double  end                  = -1;
                        double  duration             = -1;
                        XmlNode alignable_annotation = annotation.FirstChild;

                        starttmp = (from kvp in time_order_list where kvp.Key == alignable_annotation.Attributes.GetNamedItem("TIME_SLOT_REF1").Value.ToString() select kvp.Value).ToList()[0];
                        start    = double.Parse(starttmp, CultureInfo.InvariantCulture) / 1000;
                        endtmp   = (from kvp in time_order_list where kvp.Key == alignable_annotation.Attributes.GetNamedItem("TIME_SLOT_REF2").Value.ToString() select kvp.Value).ToList()[0];
                        end      = double.Parse(endtmp, CultureInfo.InvariantCulture) / 1000;
                        label    = alignable_annotation.FirstChild.InnerText;
                        AnnoScheme.Label l = new AnnoScheme.Label(label, Colors.Black);


                        if (scheme.Type == AnnoScheme.TYPE.DISCRETE && scheme.Labels.Find(x => x.Name == label) == null)
                        {
                            scheme.Labels.Add(l);
                        }


                        duration = end - start;
                        al.AddSorted(new AnnoListItem(start, duration, label, "", Colors.Black));


                        //The tier is used as metainformation as well. Might be changed if thats relevant in the future
                    }
                    i++;

                    al.Scheme      = scheme;
                    al.Meta.Role   = role;
                    al.Scheme.Name = tierid;

                    list.Add(al);
                }
            }
            catch (Exception ex)
            {
                MessageTools.Error(ex.ToString());
            }

            return(list);
        }
Exemplo n.º 7
0
        public string CMLPredictBayesFusion(string roleout,
                                            string sessionpath,
                                            string schemespath,
                                            string server,
                                            string username,
                                            string password,
                                            string datapath,
                                            string database,
                                            string outputscheme,
                                            string roles,
                                            string outputannotator,
                                            bool tocontinuous,
                                            string netpath, float filter)
        {
            string result = "";

            string[] split   = server.Split(':');
            string   ip      = split[0];
            string   port    = split[1];
            string   logPath = AppDomain.CurrentDomain.BaseDirectory + "\\" + "cml-fusion.log";

            File.Delete(logPath);

            string cont = (tocontinuous == true) ? "true" : "false";
            string filt = ((filter != -1.0f)  ?  "-filter " + filter : "");


            try
            {
                string options_no_pass = "******" + username +
                                         " -log \"" + logPath + "\"" +
                                         " -role_out \"" + roleout + "\"" +
                                         " -netpath " + "\"" + netpath + "\" " + filt;
                string options   = options_no_pass + " -password " + password;
                string arguments = "\"" + sessionpath + "\" " +
                                   "\"" + schemespath + "\" " +
                                   "\"" + datapath + "\\" + database + "\" " +
                                   ip + " " +
                                   port + " " +
                                   database + " " +
                                   roles + " " +
                                   outputannotator + " " +
                                   outputscheme + " " +
                                   cont;



                Process          process   = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.WindowStyle = ProcessWindowStyle.Normal;
                startInfo.FileName    = AppDomain.CurrentDomain.BaseDirectory + "\\bayesfusion.exe";
                startInfo.Arguments   = "--bayesnetfusion " + options + " " + arguments;
                result           += "\n-------------------------------------------\r\n" + startInfo.FileName + " --bayesnetfusion " + options_no_pass + " " + arguments + "\n-------------------------------------------\r\n";
                process.StartInfo = startInfo;
                process.Start();
                process.WaitForExit();
                //result += File.ReadAllText(logPath);
            }
            catch (Exception ex)
            {
                MessageTools.Error(ex.ToString());
            }

            return(result);
        }
Exemplo n.º 8
0
        public static AnnoList LoadfromFile(string filepath)
        {
            AnnoList list = new AnnoList();

            list.Source.File.Path = filepath;
            list.Scheme           = new AnnoScheme();
            list.Scheme.Labels    = new List <AnnoScheme.Label>();

            //try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filepath);

                XmlNode annotation = doc.SelectSingleNode("annotation");

                XmlNode info = annotation.SelectSingleNode("info");
                list.Source.File.Type = info.Attributes["ftype"].Value == AnnoSource.FileSource.TYPE.ASCII.ToString() ? AnnoSource.FileSource.TYPE.ASCII : AnnoSource.FileSource.TYPE.BINARY;
                int size = int.Parse(info.Attributes["size"].Value);

                XmlNode meta = annotation.SelectSingleNode("meta");
                if (meta != null)
                {
                    if (meta.Attributes["role"] != null)
                    {
                        list.Meta.Role = meta.Attributes["role"].Value;
                    }
                    if (meta.Attributes["annotator"] != null)
                    {
                        list.Meta.Annotator = meta.Attributes["annotator"].Value;
                    }
                }

                XmlNode scheme = annotation.SelectSingleNode("scheme");
                if (scheme.Attributes["name"] != null)
                {
                    list.Scheme.Name = scheme.Attributes["name"].Value;
                }
                string type = "FREE";
                if (scheme.Attributes["type"] != null)
                {
                    type = scheme.Attributes["type"].Value;
                }

                if (type == AnnoScheme.TYPE.DISCRETE.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.DISCRETE;
                }
                else if (type == AnnoScheme.TYPE.CONTINUOUS.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.CONTINUOUS;
                }
                else if (type == AnnoScheme.TYPE.FREE.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.FREE;
                }

                else if (type == AnnoScheme.TYPE.POINT.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.POINT;
                }
                else if (type == AnnoScheme.TYPE.POLYGON.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.POLYGON;
                }
                else if (type == AnnoScheme.TYPE.GRAPH.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.GRAPH;
                }
                else if (type == AnnoScheme.TYPE.SEGMENTATION.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.SEGMENTATION;
                }

                if (scheme.Attributes["color"] != null)
                {
                    list.Scheme.MinOrBackColor = (Color)ColorConverter.ConvertFromString(scheme.Attributes["color"].Value);
                }
                else if (scheme.Attributes["mincolor"] != null)
                {
                    list.Scheme.MinOrBackColor = (Color)ColorConverter.ConvertFromString(scheme.Attributes["mincolor"].Value);
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                {
                    list.Scheme.MinOrBackColor = Defaults.Colors.GradientMin;
                }

                if (scheme.Attributes["maxcolor"] != null)
                {
                    list.Scheme.MaxOrForeColor = (Color)ColorConverter.ConvertFromString(scheme.Attributes["maxcolor"].Value);
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                {
                    list.Scheme.MaxOrForeColor = Defaults.Colors.GradientMax;
                }

                Dictionary <string, string> LabelIds = new Dictionary <string, string>();

                if (list.Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                {
                    foreach (XmlNode item in scheme)
                    {
                        LabelIds.Add(item.Attributes["id"].Value, item.Attributes["name"].Value);

                        Color color = Defaults.Colors.Foreground;
                        if (item.Attributes["color"] != null)
                        {
                            color = (Color)ColorConverter.ConvertFromString(item.Attributes["color"].Value);
                        }
                        AnnoScheme.Label lcp = new AnnoScheme.Label(item.Attributes["name"].Value, color);
                        list.Scheme.Labels.Add(lcp);
                    }

                    AnnoScheme.Label garbage = new AnnoScheme.Label("GARBAGE", Defaults.Colors.Foreground);
                    list.Scheme.Labels.Add(garbage);
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.FREE)
                {
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                {
                    list.Scheme.MinScore   = double.Parse(scheme.Attributes["min"].Value);
                    list.Scheme.MaxScore   = double.Parse(scheme.Attributes["max"].Value);
                    list.Scheme.SampleRate = double.Parse(scheme.Attributes["sr"].Value);
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.POINT ||
                         list.Scheme.Type == AnnoScheme.TYPE.POLYGON || list.Scheme.Type == AnnoScheme.TYPE.GRAPH ||
                         list.Scheme.Type == AnnoScheme.TYPE.SEGMENTATION)
                {
                    list.Scheme.SampleRate     = double.Parse(scheme.Attributes["sr"].Value);
                    list.Scheme.NumberOfPoints = int.Parse(scheme.Attributes["num"].Value);
                }

                if (File.Exists(filepath + "~"))

                {
                    if (list.Source.File.Type == AnnoSource.FileSource.TYPE.ASCII)
                    {
                        StreamReader sr    = new StreamReader(filepath + "~", System.Text.Encoding.UTF8);
                        string       line  = null;
                        double       start = 0.0;

                        while ((line = sr.ReadLine()) != null)
                        {
                            string[] data = line.Split(';');
                            if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                            {
                                double value = double.NaN;
                                double.TryParse(data[0], out value);
                                double       confidence = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
                                AnnoListItem e          = new AnnoListItem(start, 1 / list.Scheme.SampleRate, value, "", Defaults.Colors.Foreground, confidence);
                                list.Add(e);
                                start = start + 1 / list.Scheme.SampleRate;
                            }
                            else if (list.Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                            {
                                start = Convert.ToDouble(data[0], CultureInfo.InvariantCulture);
                                double stop  = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
                                double dur   = stop - start;
                                string label = "";
                                if (int.Parse(data[2]) < 0)
                                {
                                    label = "GARBAGE";
                                }
                                else
                                {
                                    LabelIds.TryGetValue(data[2], out label);
                                }
                                Color color = Colors.Black;

                                if (list.Scheme.Labels.Find(x => x.Name == label) != null)
                                {
                                    color = list.Scheme.Labels.Find(x => x.Name == label).Color;
                                }

                                double       confidence = Convert.ToDouble(data[3], CultureInfo.InvariantCulture);
                                AnnoListItem e          = new AnnoListItem(start, dur, label, "", color, confidence);
                                list.AddSorted(e);
                            }
                            else if (list.Scheme.Type == AnnoScheme.TYPE.FREE)
                            {
                                start = Convert.ToDouble(data[0], CultureInfo.InvariantCulture);
                                double stop       = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
                                double dur        = stop - start;
                                string label      = data[2];
                                double confidence = Convert.ToDouble(data[3], CultureInfo.InvariantCulture);
                                Color  color      = Colors.Black;
                                if (data.Length > 4)
                                {
                                    string[] metapairs = data[4].Split('=');
                                    for (int i = 0; i < metapairs.Length; i++)
                                    {
                                        if (metapairs[i].Contains("color"))
                                        {
                                            color = (Color)ColorConverter.ConvertFromString(metapairs[i + 1]);
                                            break;
                                        }
                                    }
                                }
                                AnnoListItem e = new AnnoListItem(start, dur, label, "", color, confidence);
                                list.AddSorted(e);
                            }

                            else if (list.Scheme.Type == AnnoScheme.TYPE.POINT)
                            {
                                string    frameLabel      = data[0];
                                double    frameConfidence = Convert.ToDouble(data[data.Count() - 1], CultureInfo.InvariantCulture);
                                PointList points          = new PointList();
                                for (int i = 1; i < data.Count() - 1; ++i)
                                {
                                    string pd = data[i].Replace("(", "");
                                    pd = pd.Replace(")", "");
                                    string[] pointData = pd.Split(':');
                                    points.Add(new PointListItem(double.Parse(pointData[1]), double.Parse(pointData[2]), pointData[0], double.Parse(pointData[3])));
                                }
                                AnnoListItem ali = new AnnoListItem(start, 1 / list.Scheme.SampleRate, frameLabel, "", list.Scheme.MinOrBackColor, frameConfidence, true, points);
                                list.Add(ali);
                                start = start + 1 / list.Scheme.SampleRate;
                            }
                        }
                        sr.Close();
                    }
                    else if (list.Source.File.Type == AnnoSource.FileSource.TYPE.BINARY)
                    {
                        BinaryReader binaryReader = new BinaryReader(File.Open(filepath + "~", FileMode.Open));
                        long         length       = (binaryReader.BaseStream.Length);

                        double start = 0.0;
                        while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
                        {
                            if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                            {
                                double       value      = (double)binaryReader.ReadSingle();
                                double       confidence = (double)binaryReader.ReadSingle();
                                AnnoListItem e          = new AnnoListItem(start, 1 / list.Scheme.SampleRate, value, "", Defaults.Colors.Foreground, confidence);
                                list.Add(e);
                                start = start + 1 / list.Scheme.SampleRate;
                            }
                            else if (list.Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                            {
                                start = binaryReader.ReadDouble();
                                double stop  = binaryReader.ReadDouble();
                                double dur   = stop - start;
                                string label = "";
                                int    index = binaryReader.ReadInt32();
                                if (index < 0)
                                {
                                    label = "GARBAGE";
                                }
                                else
                                {
                                    LabelIds.TryGetValue(index.ToString(), out label);
                                }
                                Color color = Colors.Black;

                                if (list.Scheme.Labels.Find(x => x.Name == label) != null)
                                {
                                    color = list.Scheme.Labels.Find(x => x.Name == label).Color;
                                }
                                double       confidence = Math.Round(binaryReader.ReadSingle(), 3, MidpointRounding.AwayFromZero);
                                AnnoListItem e          = new AnnoListItem(start, dur, label, "", color, confidence);
                                list.AddSorted(e);
                            }
                            else if (list.Scheme.Type == AnnoScheme.TYPE.FREE)
                            {
                                start = binaryReader.ReadDouble();
                                double       stop         = binaryReader.ReadDouble();
                                double       dur          = stop - start;
                                int          stringlength = (int)binaryReader.ReadUInt32();
                                byte[]       labelasbytes = (binaryReader.ReadBytes(stringlength));
                                string       label        = System.Text.Encoding.Default.GetString(labelasbytes);
                                Color        color        = Colors.Black;
                                double       confidence   = Math.Round(binaryReader.ReadSingle(), 3, MidpointRounding.AwayFromZero);
                                AnnoListItem e            = new AnnoListItem(start, dur, label, "", color, confidence);
                                list.AddSorted(e);
                            }
                        }

                        binaryReader.Close();
                    }
                }


                //Plugin logic should be called after parsing
                if (meta != null && meta.Attributes["trigger"] != null)
                {
                    string[] triggers = meta.Attributes["trigger"].Value.Split(';');
                    foreach (string trigger in triggers)
                    {
                        try
                        {
                            Match match = Regex.Match(trigger, @"([^{]+)\{([^}]*)\}");
                            if (match.Success && match.Groups.Count == 3)
                            {
                                string dllName   = match.Groups[1].Value;
                                string arguments = match.Groups[2].Value;
                                Dictionary <string, object> args = arguments.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                                   .Select(part => part.Split('='))
                                                                   .ToDictionary(split => split[0], split => (object)split[1]);
                                PluginCaller pluginCaller = new PluginCaller(dllName + ".dll", dllName);
                                AnnoTrigger  annoTrigger  = new AnnoTrigger(list, pluginCaller, args);
                                list.Meta.Trigger.Add(annoTrigger);
                            }
                            else
                            {
                                MessageTools.Warning("could not parse trigger '" + trigger + "'");
                            }
                        }
                        catch (Exception)
                        {
                            MessageTools.Warning("could not parse trigger '" + trigger + "'");
                        }
                    }
                }

                if (meta != null && meta.Attributes["pipeline"] != null)
                {
                    string[] pipelines = meta.Attributes["pipeline"].Value.Split(';');
                    foreach (string pipeline in pipelines)
                    {
                        try
                        {
                            Pipeline pipe = new Pipeline(list, pipeline);
                            list.Meta.Pipeline.Add(pipe);
                        }
                        catch (Exception)
                        {
                            MessageTools.Warning("could not parse pipeline '" + pipeline + "'");
                        }
                    }
                }
            }
            //catch(Exception e)
            //{
            //    MessageBox.Show("An exception occured while reading annotation from '" + filepath + "'");
            //}

            return(list);
        }
Exemplo n.º 9
0
        public static AnnoList LoadFromEventFile(String filepath)
        {
            AnnoList list = new AnnoList();

            try
            {
                XDocument doc    = XDocument.Load(filepath);
                var       events = doc.Descendants("event");

                //list.Scheme.Type = AnnoScheme.TYPE.DISCRETE;
                //list.Scheme.Labels = new List<AnnoScheme.Label>();

                foreach (var e in events)
                {
                    string label    = null;
                    string meta     = "";
                    double start    = -1;
                    double duration = -1;
                    Type   type     = Type.EMPTY;

                    var sender_attr = e.Attribute("sender");
                    var event_attr  = e.Attribute("event");
                    label = (event_attr == null ? "" : event_attr.Value);
                    //+ "@"
                    //+ (sender_attr == null ? "" : sender_attr.Value);
                    var from_attr = e.Attribute("from");
                    if (from_attr != null)
                    {
                        start = double.Parse(from_attr.Value) / 1000.0;
                    }
                    var dur_attr = e.Attribute("dur");
                    if (dur_attr != null)
                    {
                        duration = double.Parse(dur_attr.Value) / 1000.0;
                    }
                    var type_attr = e.Attribute("type");
                    if (type_attr != null)
                    {
                        switch (type_attr.Value)
                        {
                        case "MAP":
                            type = Type.MAP;
                            break;

                        case "TUPLE":
                            type = Type.TUPLE;
                            break;

                        case "STRING":
                            type = Type.STRING;
                            break;

                        //depricated, matched to tuple
                        case "FLOATS":
                            type = Type.TUPLE;
                            break;

                        //depricated, matched to map
                        case "NTUPLE":
                            type = Type.MAP;
                            break;
                        }
                    }

                    switch (type)
                    {
                    case Type.MAP:
                        var tuples = e.Descendants("tuple");
                        foreach (var tuple in tuples)
                        {
                            var string_attr = tuple.Attribute("string");
                            var value_attr  = tuple.Attribute("value");
                            meta = meta + ((string_attr == null ? "" : string_attr.Value)
                                           + "="
                                           + (value_attr == null ? "" : value_attr.Value)) + ";";
                        }
                        break;


                    case Type.STRING:
                        if (e.Value != "")
                        {
                            label = e.Value;
                        }

                        break;

                    case Type.TUPLE:
                        meta = e.Value == null ? "" : e.Value;
                        break;
                    }

                    AnnoScheme.Label asl = new AnnoScheme.Label(label, Colors.Black);
                    if (!list.Scheme.Labels.Any(item => item.Name == asl.Name))
                    {
                        list.Scheme.Labels.Add(asl);
                    }

                    var state_attr = e.Attribute("state");
                    if (state_attr.Value.ToString().ToUpper() == "COMPLETED")
                    {
                        Color color = Colors.Black;

                        //if (list.Scheme.Labels.Find(x => x.Name == label) != null)
                        //{
                        //    color = list.Scheme.Labels.Find(x => x.Name == label).Color;
                        //}

                        list.AddSorted(new AnnoListItem(start, duration, label, meta, color));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageTools.Error(ex.ToString());
            }

            //AnnoScheme.Label garbage = new AnnoScheme.Label("GARBAGE", Colors.Black);
            //list.Scheme.Labels.Add(garbage);


            return(list);
        }
Exemplo n.º 10
0
        public static AnnoScheme GetAnnotationScheme(string annoName, AnnoScheme.TYPE annoType)
        {
            MongoClient    mongo    = new MongoClient(ServerConnectionString);
            IMongoDatabase database = mongo.GetDatabase(Properties.Settings.Default.DatabaseName);

            AnnoScheme scheme = new AnnoScheme();

            scheme.Type = annoType;

            var annoSchemes = database.GetCollection <BsonDocument>(DatabaseDefinitionCollections.Schemes);
            var builder     = Builders <BsonDocument> .Filter;

            FilterDefinition <BsonDocument> annoSchemeFilter = builder.Eq("name", annoName) & builder.Eq("type", annoType.ToString());
            BsonDocument annoSchemeDocument = null;

            try
            {
                annoSchemeDocument = annoSchemes.Find(annoSchemeFilter).Single();
                if (annoSchemeDocument["type"].ToString() == annoType.ToString())
                {
                    scheme.Name = annoSchemeDocument["name"].ToString();
                    if (scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                    {
                        scheme.MinScore       = annoSchemeDocument["min"].ToDouble();
                        scheme.MaxScore       = annoSchemeDocument["max"].ToDouble();
                        scheme.SampleRate     = annoSchemeDocument["sr"].ToDouble();
                        scheme.MinOrBackColor = (Color)ColorConverter.ConvertFromString(annoSchemeDocument["min_color"].ToString());
                        scheme.MaxOrForeColor = (Color)ColorConverter.ConvertFromString(annoSchemeDocument["max_color"].ToString());
                    }
                    else if (scheme.Type == AnnoScheme.TYPE.DISCRETE)
                    {
                        scheme.MinOrBackColor = (Color)ColorConverter.ConvertFromString(annoSchemeDocument["color"].ToString());
                        BsonArray schemeLabelsArray = annoSchemeDocument["labels"].AsBsonArray;
                        string    SchemeLabel       = "";
                        string    SchemeColor       = "#000000";
                        for (int j = 0; j < schemeLabelsArray.Count; j++)
                        {
                            try
                            {
                                if (schemeLabelsArray[j]["isValid"].AsBoolean == true)
                                {
                                    SchemeLabel = schemeLabelsArray[j]["name"].ToString();
                                    SchemeColor = schemeLabelsArray[j]["color"].ToString();
                                    AnnoScheme.Label lcp = new AnnoScheme.Label(schemeLabelsArray[j]["name"].ToString(), (Color)ColorConverter.ConvertFromString(schemeLabelsArray[j]["color"].ToString()));
                                    scheme.Labels.Add(lcp);
                                }
                            }
                            catch
                            {
                                SchemeLabel = schemeLabelsArray[j]["name"].ToString();
                                SchemeColor = schemeLabelsArray[j]["color"].ToString();
                                AnnoScheme.Label lcp = new AnnoScheme.Label(schemeLabelsArray[j]["name"].ToString(), (Color)ColorConverter.ConvertFromString(schemeLabelsArray[j]["color"].ToString()));
                                scheme.Labels.Add(lcp);
                            }
                        }
                    }
                    else if (scheme.Type == AnnoScheme.TYPE.FREE)
                    {
                        scheme.MinOrBackColor = (Color)ColorConverter.ConvertFromString(annoSchemeDocument["color"].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageTools.Warning(ex.ToString());
            }

            return(scheme);
        }
Exemplo n.º 11
0
        public bool SaveToFile(string filePath, string delimiter = ";")
        {
            Dictionary <string, string> LabelIds = new Dictionary <string, string>();

            try
            {
                StreamWriter sw = new StreamWriter(filePath, false, System.Text.Encoding.Default);
                sw.WriteLine("<?xml version=\"1.0\" ?>");
                sw.WriteLine("<annotation ssi-v=\"3\">");

                sw.WriteLine("    <info ftype=\"" + Source.File.Type.ToString() + "\" size=\"" + this.Count + "\" />");
                sw.WriteLine("    <meta annotator=\"" + Meta.AnnotatorFullName + "\" role=\"" + Meta.Role + "\"/>");
                if (Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                {
                    sw.WriteLine("    <scheme name=\"" + this.Scheme.Name + "\" type=\"CONTINUOUS\" sr=\"" + this.Scheme.SampleRate + "\" min=\"" + this.Scheme.MinScore + "\" max=\"" + this.Scheme.MaxScore + "\" mincolor=\"" + this.Scheme.MinOrBackColor + "\" maxcolor=\"" + this.Scheme.MaxOrForeColor + "\" />");
                }
                else if (Scheme.Type == AnnoScheme.TYPE.FREE)
                {
                    sw.WriteLine("    <scheme name=\"" + this.Scheme.Name + "\" type=\"FREE\" color=\"" + this.Scheme.MinOrBackColor + "\"/>");
                }
                else if (Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                {
                    sw.WriteLine("    <scheme name=\"" + this.Scheme.Name + "\" type=\"DISCRETE\"  color=\"" + this.Scheme.MinOrBackColor + "\">");
                    int index = 0;

                    foreach (AnnoScheme.Label lp in this.Scheme.Labels)
                    {
                        if (lp.Name != "GARBAGE")
                        {
                            sw.WriteLine("        <item name=\"" + lp.Name + "\" id=\"" + index + "\" color=\"" + lp.Color + "\" />");
                            LabelIds.Add(lp.Name, index.ToString());
                            index++;
                        }
                    }
                    sw.WriteLine("    </scheme>");
                }

                else if (Scheme.Type == AnnoScheme.TYPE.POINT)
                {
                    sw.WriteLine("    <scheme name=\"" + this.Scheme.Name + "\" type=\"POINT\" sr=\"" + this.Scheme.SampleRate + "\" num=\"" + this.Scheme.NumberOfPoints + "\" color=\"" + this.Scheme.MinOrBackColor + "\" />");
                }
                else if (Scheme.Type == AnnoScheme.TYPE.POLYGON)
                {
                    sw.WriteLine("    <scheme name=\"" + this.Scheme.Name + "\" type=\"CONTINUOUS\" sr=\"" + this.Scheme.SampleRate + "\" num=\"" + this.Scheme.NumberOfPoints + "\" color=\"" + this.Scheme.MinOrBackColor + "\" />");
                }
                else if (Scheme.Type == AnnoScheme.TYPE.GRAPH)
                {
                    sw.WriteLine("    <scheme name=\"" + this.Scheme.Name + "\" type=\"CONTINUOUS\" sr=\"" + this.Scheme.SampleRate + "\" num=\"" + this.Scheme.NumberOfPoints + "\" color=\"" + this.Scheme.MinOrBackColor + "\"  />");
                }
                else if (Scheme.Type == AnnoScheme.TYPE.SEGMENTATION)
                {
                    sw.WriteLine("    <scheme name=\"" + this.Scheme.Name + "\" type=\"CONTINUOUS\" sr=\"" + this.Scheme.SampleRate + "\" num=\"" + this.Scheme.NumberOfPoints + "\" color=\"" + this.Scheme.MinOrBackColor + "\" />");
                }

                sw.WriteLine("</annotation>");
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageTools.Error(ex.ToString());
                return(false);
            }

            try
            {
                if (Source.File.Type == AnnoSource.FileSource.TYPE.ASCII)
                {
                    StreamWriter sw = new StreamWriter(filePath + "~", false, System.Text.Encoding.Default);
                    if (Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                    {
                        foreach (AnnoListItem e in this)
                        {
                            sw.WriteLine(e.Score + delimiter + e.Confidence);
                        }
                    }
                    else if (Scheme.Type == AnnoScheme.TYPE.FREE)
                    {
                        foreach (AnnoListItem e in this)
                        {
                            if (e.Color != Scheme.MaxOrForeColor)
                            {
                                sw.WriteLine(e.Start + delimiter + e.Stop + delimiter + e.Label + delimiter + e.Confidence);
                            }
                            else
                            {
                                sw.WriteLine(e.Start + delimiter + e.Stop + delimiter + e.Label + delimiter + e.Confidence + delimiter + "color=" + e.Color.ToString());
                            }
                        }
                    }
                    else if (Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                    {
                        string index = "";

                        foreach (AnnoListItem e in this)
                        {
                            if (e.Label != "GARBAGE")
                            {
                                LabelIds.TryGetValue(e.Label, out index);
                                sw.WriteLine(e.Start + delimiter + e.Stop + delimiter + index + delimiter + e.Confidence);
                            }
                            else
                            {
                                sw.WriteLine(e.Start + delimiter + e.Stop + delimiter + -1 + delimiter + e.Confidence);
                            }
                        }
                    }

                    else if (Scheme.Type == AnnoScheme.TYPE.POINT)
                    {
                        foreach (AnnoListItem e in this)
                        {
                            string output = "";
                            output += e.Label + delimiter;
                            for (int i = 0; i < e.Points.Count; ++i)
                            {
                                output += '(' + e.Points[i].Label + ':' + e.Points[i].XCoord + ':' + e.Points[i].YCoord + ":" + e.Points[i].Confidence + ')' + delimiter;
                            }
                            sw.WriteLine(output + e.Confidence);
                        }
                    }
                    else if (Scheme.Type == AnnoScheme.TYPE.POLYGON)
                    {
                        foreach (AnnoListItem e in this)
                        {
                            sw.WriteLine(e.Label + delimiter + e.Confidence);
                        }
                    }
                    else if (Scheme.Type == AnnoScheme.TYPE.GRAPH)
                    {
                        foreach (AnnoListItem e in this)
                        {
                            sw.WriteLine(e.Label + delimiter + e.Confidence);
                        }
                    }
                    else if (Scheme.Type == AnnoScheme.TYPE.SEGMENTATION)
                    {
                        foreach (AnnoListItem e in this)
                        {
                            sw.WriteLine(e.Label + delimiter + e.Confidence);
                        }
                    }

                    sw.Close();
                }
                else
                {
                    BinaryWriter bw = new BinaryWriter(new FileStream(filePath + "~", FileMode.Create));
                    if (Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                    {
                        foreach (AnnoListItem e in this)
                        {
                            bw.Write((float)e.Score);
                            bw.Write((float)e.Confidence);
                        }
                    }
                    else if (Scheme.Type == AnnoScheme.TYPE.FREE)
                    {
                        foreach (AnnoListItem e in this)
                        {
                            bw.Write(e.Start);
                            bw.Write(e.Stop);
                            bw.Write((uint)e.Label.Length);
                            byte[] label = System.Text.Encoding.UTF8.GetBytes(e.Label);
                            bw.Write(label);
                            bw.Write((float)e.Confidence);
                        }
                    }
                    else if (Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                    {
                        string index = "";
                        foreach (AnnoListItem e in this)
                        {
                            uint ind = unchecked ((uint)-1);
                            if (e.Label != "GARBAGE")
                            {
                                LabelIds.TryGetValue(e.Label, out index);
                                ind = uint.Parse(index);
                            }
                            bw.Write(e.Start);
                            bw.Write(e.Stop);
                            bw.Write(ind);
                            bw.Write((float)e.Confidence);
                        }
                    }
                    bw.Close();
                }

                HasChanged = false;
                AnnoList newAnno = new AnnoList();
                newAnno.Source.File.Path = filePath;
            }
            catch (Exception ex)
            {
                MessageTools.Error(ex.ToString());
                return(false);
            }

            return(true);
        }
Exemplo n.º 12
0
        private void navigatorNewAnno_Click(object sender, RoutedEventArgs e)
        {
            if (Time.TotalDuration > 0)
            {
                AnnoTierNewSchemeWindow dialog = new AnnoTierNewSchemeWindow();
                dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                dialog.ShowDialog();

                if (dialog.DialogResult == true)
                {
                    AnnoScheme.TYPE annoType = dialog.Result();

                    if (DatabaseLoaded)
                    {
                        databaseAddNewAnnotation(annoType);
                    }
                    else
                    {
                        if (annoType == AnnoScheme.TYPE.FREE)
                        {
                            AnnoTierNewFreeSchemeWindow dialog2 = new AnnoTierNewFreeSchemeWindow();
                            dialog2.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                            dialog2.ShowDialog();

                            if (dialog2.DialogResult == true)
                            {
                                AnnoScheme annoScheme = dialog2.Result;
                                AnnoList   annoList   = new AnnoList()
                                {
                                    Scheme = annoScheme
                                };
                                addAnnoTier(annoList);
                            }
                        }
                        else if (annoType == AnnoScheme.TYPE.DISCRETE)
                        {
                            AnnoTierNewDiscreteSchemeWindow dialog2 = new AnnoTierNewDiscreteSchemeWindow();
                            dialog2.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                            dialog2.ShowDialog();

                            if (dialog2.DialogResult == true)
                            {
                                AnnoList annoList = dialog2.GetAnnoList();
                                addAnnoTier(annoList);
                            }
                        }
                        else if (annoType == AnnoScheme.TYPE.CONTINUOUS)
                        {
                            double defaultSr = 25.0;

                            foreach (IMedia m in mediaList.Medias)
                            {
                                if (m.IsVideo())
                                {
                                    defaultSr = m.GetSampleRate();
                                    break;
                                }
                            }

                            AnnoTierNewContinuousSchemeWindow.Input input = new AnnoTierNewContinuousSchemeWindow.Input()
                            {
                                SampleRate = defaultSr, MinScore = 0.0, MaxScore = 1.0, MinColor = Colors.LightBlue, MaxColor = Colors.Red
                            };
                            AnnoTierNewContinuousSchemeWindow dialog2 = new AnnoTierNewContinuousSchemeWindow(input);
                            dialog2.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                            dialog2.ShowDialog();
                            if (dialog2.DialogResult == true)
                            {
                                AnnoScheme annoScheme = dialog2.Result;
                                AnnoList   annoList   = new AnnoList()
                                {
                                    Scheme = annoScheme
                                };
                                addAnnoTier(annoList);
                            }
                        }
                    }
                }
            }
            else
            {
                MessageTools.Warning("Nothing to annotate, load some data first.");
            }
        }
Exemplo n.º 13
0
        public static bool LoadDataV2b(Signal signal, FileStream fs)
        {
            uint total = signal.number * signal.dim * signal.bytes;

            byte[] data_buffer = new byte[total];

            fs.Read(data_buffer, 0, (int)total);

            int index = 0;
            int step  = (int)signal.bytes;

            switch (signal.type)
            {
            case Signal.Type.SHORT:
            {
                if (signal.bytes == sizeof(short))
                {
                    for (UInt32 i = 0; i < signal.number; i++)
                    {
                        for (UInt32 j = 0; j < signal.dim; j++)
                        {
                            signal.data[i * signal.dim + j] = (float)BitConverter.ToInt16(data_buffer, index);
                            index += step;
                        }
                    }
                }
                else
                {
                    MessageTools.Error("Invalid number of bytes (" + signal.bytes + ") for data type 'short'");
                    return(false);
                }
            }
            break;

            case Signal.Type.USHORT:
            {
                if (signal.bytes == sizeof(ushort))
                {
                    for (UInt32 i = 0; i < signal.number; i++)
                    {
                        for (UInt32 j = 0; j < signal.dim; j++)
                        {
                            signal.data[i * signal.dim + j] = (float)BitConverter.ToUInt16(data_buffer, index);
                            index += step;
                        }
                    }
                }
                else
                {
                    MessageTools.Error("Invalid number of bytes (" + signal.bytes + ") for data type 'short'");
                    return(false);
                }
            }
            break;

            case Signal.Type.INT:
            {
                if (signal.bytes == sizeof(int))
                {
                    for (UInt32 i = 0; i < signal.number; i++)
                    {
                        for (UInt32 j = 0; j < signal.dim; j++)
                        {
                            signal.data[i * signal.dim + j] = (float)BitConverter.ToInt32(data_buffer, index);
                            index += step;
                        }
                    }
                }
                else
                {
                    MessageTools.Error("Invalid number of bytes (" + signal.bytes + ") for data type 'short'");
                    return(false);
                }
            }
            break;

            case Signal.Type.UINT:
            {
                if (signal.bytes == sizeof(uint))
                {
                    for (UInt32 i = 0; i < signal.number; i++)
                    {
                        for (UInt32 j = 0; j < signal.dim; j++)
                        {
                            signal.data[i * signal.dim + j] = (float)BitConverter.ToUInt32(data_buffer, index);
                            index += step;
                        }
                    }
                }
                else
                {
                    MessageTools.Error("Invalid number of bytes (" + signal.bytes + ") for data type 'short'");
                    return(false);
                }
            }
            break;

            case Signal.Type.FLOAT:
            {
                if (signal.bytes == sizeof(float))
                {
                    for (UInt32 i = 0; i < signal.number; i++)
                    {
                        for (UInt32 j = 0; j < signal.dim; j++)
                        {
                            signal.data[i * signal.dim + j] = BitConverter.ToSingle(data_buffer, index);
                            index += step;
                        }
                    }
                }
                else
                {
                    MessageTools.Error("Invalid number of bytes (" + signal.bytes + ") for data type 'float'");
                    return(false);
                }
            }
            break;

            case Signal.Type.DOUBLE:
            {
                if (signal.bytes == sizeof(double))
                {
                    for (UInt32 i = 0; i < signal.number; i++)
                    {
                        for (UInt32 j = 0; j < signal.dim; j++)
                        {
                            signal.data[i * signal.dim + j] = (float)BitConverter.ToDouble(data_buffer, index);
                            index += step;
                        }
                    }
                }
                else
                {
                    MessageTools.Error("Invalid number of bytes (" + signal.bytes + ") for data type 'float'");
                    return(false);
                }
            }
            break;
            }

            return(true);
        }
Exemplo n.º 14
0
        public static Signal LoadStreamFile(string filepath)
        {
            Signal signal = new Signal();

            try
            {
                if (filepath.EndsWith("~"))
                {
                    filepath = filepath.Remove(filepath.Length - 1);
                }

                XmlDocument doc = new XmlDocument();


                // parse filename
                signal.filePath = filepath;
                string[] tmp = filepath.Split('\\');
                signal.fileName = tmp[tmp.Length - 1];
                signal.name     = Path.GetFileNameWithoutExtension(signal.fileName);

                doc.Load(filepath);

                XmlNode node = null;

                node = doc.SelectSingleNode("//info");
                string ftype_s = node.Attributes["ftype"].Value.ToUpper();
                signal.rate  = double.Parse(node.Attributes["sr"].Value);
                signal.dim   = uint.Parse(node.Attributes["dim"].Value);
                signal.bytes = uint.Parse(node.Attributes["byte"].Value);
                string type_s = node.Attributes["type"].Value.ToUpper();
                for (uint i = 0; i < TypeName.Length; i++)
                {
                    if (type_s == TypeName[i])
                    {
                        signal.type = (Type)i;
                        break;
                    }
                }
                string delim = " ";
                if (node.Attributes["delim"] != null)
                {
                    delim = node.Attributes["delim"].Value;
                }

                node = doc.SelectSingleNode("//meta");
                if (node != null)
                {
                    foreach (XmlAttribute attribute in node.Attributes)
                    {
                        signal.Meta.Add(attribute.Name, attribute.Value);
                    }
                }

                uint num = 0;
                foreach (XmlNode n in doc.SelectNodes("//chunk"))
                {
                    num += uint.Parse(n.Attributes["num"].Value);
                }

                signal.time   = 0;
                signal.number = num;
                if (!(signal.number > 0 && signal.dim > 0))
                {
                    MessageTools.Error("empty stream file '" + filepath + "'");
                    return(null);
                }
                signal.data = new float[signal.dim * signal.number];
                try {
                    if (ftype_s == "ASCII")
                    {
                        StreamReader fs_data = new StreamReader(filepath + "~");
                        if (!LoadDataV2a(signal, fs_data, delim.ToCharArray()))
                        {
                            MessageTools.Error("could not read stream data '" + filepath + "'");
                            return(null);
                        }
                        fs_data.Close();
                    }
                    else
                    {
                        FileStream fs_data = new FileStream(filepath + "~", FileMode.Open, FileAccess.Read);
                        if (!LoadDataV2b(signal, fs_data))
                        {
                            MessageTools.Error("could not read stream data '" + filepath + "'");
                            return(null);
                        }
                        fs_data.Close();
                    }
                }
                catch { }


                signal.minmax();
                signal.loaded = true;
            }
            catch (Exception e)
            {
                MessageBoxResult result = MessageBox.Show("File " + filepath + " is corrupted! Should it be deleted?", "Attention", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    File.Delete(filepath);
                    File.Delete(filepath + "~");
                }


                return(null);
            }

            return(signal);
        }
Exemplo n.º 15
0
        private void exportSSISampleList()
        {
            String userName = userNameTextBox.Text;
            String annoPath = (String)annoComboBox.SelectedItem;
            ItemCollection signalItems = signalSelectedListBox.Items;

            if (userName.Length == 0 || annoPath == null || signalItems.IsEmpty)
            {
                MessageTools.Error("Select a user name and annotation and at least one signal.");
                return;
            }

            SaveFileDialog dialog = new SaveFileDialog();
            dialog.InitialDirectory = Path.GetDirectoryName(annoPath);
            dialog.Filter = "Sample files (*.samples)|*.samples|All files (*.*)|*.*";
            if (dialog.ShowDialog() == true)
            {
                string samplesPath = dialog.FileName;
                StringBuilder signalPaths = new StringBuilder();
                bool first = true;
                foreach (string item in signalItems)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        signalPaths.Append(';');
                    }
                    signalPaths.Append(item);
                }

                if(!File.Exists("anno2samp.exe"))
                {
                    try
                    {
                        string url = "https://github.com/hcmlab/nova/blob/master/bin/anno2samp.exe?raw=true";
                        WebClient Client = new WebClient();
                        Client.DownloadFile(url, AppDomain.CurrentDomain.BaseDirectory + "anno2samp.exe");
                    }
                    catch
                    {
                        MessageBox.Show("Tools for creating Samplelists are not available, please check your internet connection.");
                        return;
                    }
                  
                }




                Process process = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName = "anno2samp.exe";
                startInfo.Arguments = userName + " " + annoPath + " " + signalPaths + " " + samplesPath;
                if (continuousCheckBox.IsChecked == true)
                {
                    startInfo.Arguments += " -frame " + frameTextBox.Text + " -delta " + deltaTextBox.Text + " -percent " + percentTextBox.Text;
                    if (labelTextBox.Text.Length > 0)
                    {
                        startInfo.Arguments += " -label " + labelTextBox.Text;
                    }

                    if(!annoPath.Contains(".annotation")) startInfo.Arguments += " -legacy";


                }
                process.StartInfo = startInfo;
                process.Start();
                process.WaitForExit();

                if (process.ExitCode == 0)
                {
                    MessageBox.Show("Samplelist successfully created in " + samplesPath);
                }

            }
        }
Exemplo n.º 16
0
        public string CompleteTier(int context, AnnoTier tier, string stream, double confidence = -1.0, double minGap = 0.0, double minDur = 0.0)
        {
            string result = "";

            Directory.CreateDirectory(Properties.Settings.Default.DatabaseDirectory + "\\" + Properties.Settings.Default.DatabaseName + "\\models");

            string username = Properties.Settings.Default.MongoDBUser;
            string password = Properties.Settings.Default.MongoDBPass;
            string session  = Properties.Settings.Default.LastSessionId;
            string datapath = Properties.Settings.Default.DatabaseDirectory;
            string ipport   = Properties.Settings.Default.DatabaseAddress;

            string[] split     = ipport.Split(':');
            string   ip        = split[0];
            string   port      = split[1];
            string   database  = Properties.Settings.Default.DatabaseName;
            string   role      = tier.AnnoList.Meta.Role;
            string   scheme    = tier.AnnoList.Scheme.Name;
            string   annotator = tier.AnnoList.Meta.Annotator;

            bool isTrained = false;
            bool isForward = false;

            try
            {
                {
                    string arguments = " -cooperative "
                                       + "-context " + context +
                                       " -username " + username +
                                       " -password " + password +
                                       " -filter " + session +
                                       " -log cml.log " +
                                       "\"" + datapath + "\\" + database + "\" " +
                                       ip + " " +
                                       port + " " +
                                       database + " " +
                                       role + " " +
                                       scheme + " " +
                                       annotator + " " +
                                       "\"" + stream + "\"";

                    Process          process   = new Process();
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    startInfo.FileName    = "cmltrain.exe";
                    startInfo.Arguments   = "--train" + arguments;
                    result           += startInfo.Arguments + "\n-------------------------------------------\r\n";
                    process.StartInfo = startInfo;
                    process.Start();
                    process.WaitForExit();
                    result += File.ReadAllText("cml.log");

                    if (process.ExitCode == 0)
                    {
                        isTrained = true;
                    }
                    else
                    {
                        return(result);
                    }
                }
                {
                    string arguments = " -cooperative "
                                       + "-context " + context +
                                       " -username " + username +
                                       " -password " + password +
                                       " -filter " + session +
                                       " -confidence " + confidence +
                                       " -mingap " + minGap +
                                       " -mindur " + minDur +
                                       " -log cml.log " +
                                       "\"" + datapath + "\\" + database + "\" " +
                                       ip + " " +
                                       port + " " +
                                       database + " " +
                                       role + " " +
                                       scheme + " " +
                                       annotator + " " +
                                       "\"" + stream + "\"";


                    Process          process   = new Process();
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    startInfo.FileName    = "cmltrain.exe";
                    startInfo.Arguments   = "--forward" + arguments;
                    result           += startInfo.Arguments + "\n-------------------------------------------\r\n";
                    process.StartInfo = startInfo;
                    process.Start();
                    process.WaitForExit();
                    result += File.ReadAllText("cml.log");

                    if (process.ExitCode == 0)
                    {
                        isForward = true;
                    }
                    else
                    {
                        return(result);
                    }
                }

                if (isTrained && isForward)
                {
                    databaseReload(tier);
                }
            }
            catch (Exception ex)
            {
                MessageTools.Error(ex.ToString());
            }

            return(result);
        }