private void convertAnnoContinuousToDiscrete_Click(object sender, RoutedEventArgs e) { if (AnnoTierStatic.Selected != null) { if (AnnoTierStatic.Selected.AnnoList.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS) { ExportAnnoContinuousToDiscrete(); } else if (AnnoTierStatic.Selected.AnnoList.Scheme.Type == AnnoScheme.TYPE.FREE) { AnnoList newlist = AnnoList.ConvertFreetoDiscreteAnnotation(AnnoTierStatic.Selected.AnnoList); AnnoTier.Unselect(); addAnnoTierFromList(newlist); } } }
public void addAnnoTier(AnnoList anno) { setAnnoList(anno); AnnoTier tier = new AnnoTier(anno); control.annoTierControl.Add(tier); control.timeLineControl.rangeSlider.OnTimeRangeChanged += tier.TimeRangeChanged; annoTiers.Add(tier); annoLists.Add(anno); AnnoTierStatic.Select(tier); tier.TimeRangeChanged(Time); updateNavigator(); }
private void updateAnnoInfo(AnnoTier annoTier) { if (annoTier == null) { return; } AnnoList annoList = annoTier.AnnoList; control.annoSettingsButton.Visibility = Visibility.Visible; control.annoStatusFileNameOrOIDLabel.Text = annoList.Name; if (annoList.Source.HasFile) { control.annoStatusFileNameOrOIDLabel.ToolTip = annoList.Source.File.Path; } else if (annoList.Source.HasDatabase) { control.annoStatusFileNameOrOIDLabel.ToolTip = annoList.Source.Database.OID; } else { control.annoStatusFileNameOrOIDLabel.ToolTip = "Not saved yet"; } control.annoStatusSchemeNameLabel.Text = annoList.Scheme.Name; if (annoList.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS) { control.annoStatusSchemeTypeLabel.Text = annoList.Scheme.Type.ToString(); control.annoStatusSchemeContinuousPanel.Visibility = Visibility.Visible; control.annoSchemeContinuousSrLabel.Text = annoList.Scheme.SampleRate.ToString() + " Hz"; control.annoSchemeContinuousMinLabel.Text = "min " + annoList.Scheme.MinScore.ToString(); control.annoSchemeContinuousMaxLabel.Text = "max " + annoList.Scheme.MaxScore.ToString(); } else { control.annoStatusSchemeTypeLabel.Text = annoList.Scheme.Type.ToString(); control.annoStatusSchemeContinuousPanel.Visibility = Visibility.Collapsed; } control.annoStatusAnnotatorLabel.Text = annoList.Meta.AnnotatorFullName != "" ? annoList.Meta.AnnotatorFullName : annoList.Meta.Annotator; control.annoStatusRoleLabel.Text = annoList.Meta.Role; control.annoCloseButton.Visibility = playIsPlaying ? Visibility.Hidden : Visibility.Visible; }
//public void sendmail(string adressto, string subject, string body) //{ // //dummy code, need some logic but hey, automated notifications // MailMessage objeto_mail = new MailMessage(); // SmtpClient client = new SmtpClient(); // client.Port = 25; // client.Host = "smtp.internal.mycompany.com"; // client.Timeout = 10000; // client.DeliveryMethod = SmtpDeliveryMethod.Network; // client.UseDefaultCredentials = false; // client.Credentials = new System.Net.NetworkCredential("user", "Password"); // objeto_mail.From = new MailAddress("*****@*****.**"); // objeto_mail.To.Add(new MailAddress(adressto)); // objeto_mail.Subject = subject; // objeto_mail.Body = body; // client.Send(objeto_mail); //} public static string LoadRoles(AnnoList annoList) { string role = null; List <string> roles = new List <string>(); MongoClient mongo = Client; IMongoDatabase database = Database; IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>(DatabaseDefinitionCollections.Roles); var sessions = collection.Find(_ => true).ToList(); foreach (var document in sessions) { if (document["isValid"].AsBoolean == true) { roles.Add(document["name"].ToString()); } } int auth = DatabaseHandler.CheckAuthentication(Properties.Settings.Default.MongoDBUser, Properties.Settings.Default.DatabaseName); bool hasauth = false; if (auth > 3) { hasauth = true; } string name = annoList.Scheme.Name; DatabaseSelectionWindow dbw = new DatabaseSelectionWindow(roles, hasauth, "Tier: " + name + ". Who is annotated? ", DatabaseDefinitionCollections.Roles); dbw.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; dbw.ShowDialog(); if (dbw.DialogResult == true) { role = dbw.Result().ToString(); } return(role); }
private void Window_Loaded(object sender, RoutedEventArgs e) { switchMode(); GetDatabases(DatabaseHandler.DatabaseName); if (mode == Mode.COMPLETE) { AnnoList annoList = AnnoTierStatic.Selected.AnnoList; DatabaseScheme scheme = ((List <DatabaseScheme>)SchemesBox.ItemsSource).Find(s => s.Name == annoList.Scheme.Name); if (scheme != null) { SchemesBox.SelectedItem = scheme; SchemesBox.ScrollIntoView(scheme); } DatabaseRole role = ((List <DatabaseRole>)RolesBox.ItemsSource).Find(r => r.Name == annoList.Meta.Role); if (role != null) { RolesBox.SelectedItem = role; RolesBox.ScrollIntoView(role); } DatabaseAnnotator annotator = ((List <DatabaseAnnotator>)AnnotatorsBox.ItemsSource).Find(a => a.Name == Properties.Settings.Default.MongoDBUser); if (annotator != null) { AnnotatorsBox.SelectedItem = annotator; AnnotatorsBox.ScrollIntoView(annotator); } DatabaseSession session = ((List <DatabaseSession>)SessionsBox.ItemsSource).Find(s => s.Name == DatabaseHandler.SessionName); if (session != null) { SessionsBox.SelectedItem = session; SessionsBox.ScrollIntoView(session); } Update(); } ApplyButton.Focus(); handleSelectionChanged = true; }
private void loadAnnoFile(string filename) { if (!File.Exists(filename)) { MessageTools.Error("Annotation file not found '" + filename + "'"); return; } AnnoList annoList = AnnoList.LoadfromFile(filename); addAnnoTierFromList(annoList); foreach (AnnoTrigger trigger in annoList.Meta.Trigger) { mediaList.Add(trigger); } foreach (Pipeline pipeline in annoList.Meta.Pipeline) { mediaList.Add(pipeline); } }
public Pipeline(AnnoList annoList, string pipelinepath) { this.annoList = annoList; this.pipelinepath = pipelinepath; client = new UdpClient("127.0.0.1", 1111); //check if xmlpipe is available, else download it from git string SSIbinaryGitPath = "https://github.com/hcmlab/ssi/raw/master/bin/x64/vc140/"; string xmlpipeexe = "xmlpipe.exe"; string xmlpipeexePath = AppDomain.CurrentDomain.BaseDirectory + xmlpipeexe; if (!(File.Exists(xmlpipeexePath))) { DownloadFile(SSIbinaryGitPath + xmlpipeexe, xmlpipeexePath); } //call the pipeline in wait state CallXMLPipe(pipelinepath); }
public AnnoList ExportToAnno() { AnnoList annoList = new AnnoList(); annoList.Scheme = new AnnoScheme(); annoList.Scheme.Type = AnnoScheme.TYPE.CONTINUOUS; annoList.Scheme.MinScore = min[ShowDim]; annoList.Scheme.MaxScore = max[ShowDim]; annoList.Scheme.SampleRate = rate; AnnoListItem annoListItem; double dur = 1 / rate; for (int i = 0; i < number; i++) { annoListItem = new AnnoListItem(i * dur, dur, data[i * dim + ShowDim].ToString(), "", annoList.Scheme.MaxOrForeColor); annoList.Add(annoListItem); annoList.Scheme.Name = Name; } return(annoList); }
private void ImportAnnoFromElan(string filename) { int annoListnum = annoLists.Count; bool addemptytiers = false; List <AnnoList> lists = AnnoList.LoadfromElanFile(filename); if (lists.Exists(n => n.Count == 0)) { MessageBoxResult mb = MessageBox.Show("At least one tier is empty, should empty tiers be excluded?", "Attention", MessageBoxButton.YesNo); if (mb == MessageBoxResult.No) { addemptytiers = true; } } double maxdur = 0; if (lists != null) { foreach (AnnoList list in lists) { if (list.Count > 0) { maxdur = list[list.Count - 1].Stop; } if (list.Count > 0 || addemptytiers) { annoLists.Add(list); addAnnoTier(list); } } } updateTimeRange(maxdur); if (annoListnum == 0 && maxdur > Properties.Settings.Default.DefaultZoomInSeconds && Properties.Settings.Default.DefaultZoomInSeconds != 0) { fixTimeRange(Properties.Settings.Default.DefaultZoomInSeconds); } }
public AnnoTier addAnnoTier(AnnoList anno) { if (this.annoTrackGrid.RowDefinitions.Count > 0) { // add splitter RowDefinition split_row = new RowDefinition(); split_row.Height = new GridLength(1, GridUnitType.Auto); this.annoTrackGrid.RowDefinitions.Add(split_row); GridSplitter splitter = new GridSplitter(); splitter.ResizeDirection = GridResizeDirection.Rows; splitter.Height = 3; splitter.HorizontalAlignment = HorizontalAlignment.Stretch; splitter.VerticalAlignment = VerticalAlignment.Stretch; splitter.ShowsPreview = true; Grid.SetColumnSpan(splitter, 1); Grid.SetColumn(splitter, 0); Grid.SetRow(splitter, this.annoTrackGrid.RowDefinitions.Count - 1); this.annoTrackGrid.Children.Add(splitter); } // add anno track RowDefinition row = new RowDefinition(); row.Height = new GridLength(1, GridUnitType.Star); this.annoTrackGrid.RowDefinitions.Add(row); if (anno.Scheme.MinOrBackColor == Colors.Transparent) { anno.Scheme.MinOrBackColor = selectColor(this.annoTrackGrid.RowDefinitions.Count - 1); } AnnoTier tier = new AnnoTier(anno); Grid.SetColumn(tier, 0); Grid.SetRow(tier, this.annoTrackGrid.RowDefinitions.Count - 1); this.annoTrackGrid.Children.Add(tier); return(tier); }
private void ExportSignalToContinuous() { if (SignalTrackStatic.Selected != null && SignalTrackStatic.Selected.Signal != null) { Signal signal = SignalTrackStatic.Selected.Signal; if (signal != null && !SignalTrackStatic.Selected.Signal.IsAudio) { AnnoList annoList = signal.ExportToAnno(); string newFilePath = FileTools.SaveFileDialog(signal.FileName, ".annotation", "Annotation (*.annotation)|*.annotation", Path.GetDirectoryName(signal.FilePath)); annoList.Source.File.Path = newFilePath; if (annoList.Save()) { MessageBoxResult mb = MessageBoxResult.None; mb = MessageBox.Show("Load converted annotation?", "Success", MessageBoxButton.YesNo); if (mb == MessageBoxResult.Yes) { loadAnnoFile(newFilePath); } } } } }
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); }
private void ResampleScheme_Click(object sender, RoutedEventArgs e) { if (SchemesBox.SelectedItem != null) { string name = (string)SchemesBox.SelectedItem; AnnoScheme oldScheme = DatabaseHandler.GetAnnotationScheme(name); AnnoScheme newScheme = DatabaseHandler.GetAnnotationScheme(name); if (newScheme.Type != AnnoScheme.TYPE.CONTINUOUS) { MessageBox.Show("Only continuous annotations can be resampled"); return; } newScheme.Name = newScheme.Name + "_resampled"; AnnoTierNewContinuousSchemeWindow window = new AnnoTierNewContinuousSchemeWindow(ref newScheme); window.ShowDialog(); if (window.DialogResult == true) { if (DatabaseHandler.AddScheme(newScheme)) { List <DatabaseAnnotation> existingAnnos = DatabaseHandler.GetAnnotations(oldScheme); if (existingAnnos.Count > 0) { AnnoList al_t = DatabaseHandler.LoadAnnoList(existingAnnos[0].Id); double old_sr = al_t.Scheme.SampleRate; double factor = 0; if (old_sr > newScheme.SampleRate) { factor = old_sr / newScheme.SampleRate; } else if (old_sr < newScheme.SampleRate) { factor = newScheme.SampleRate / old_sr; } else { factor = 1; } if (factor % 1 != 0) { MessageBox.Show("New samplerate must be a number divisible by old samplerate."); return; } foreach (DatabaseAnnotation anno in existingAnnos) { AnnoList al = DatabaseHandler.LoadAnnoList(anno.Id); DatabaseHandler.resampleAnnotationtoNewScheme(al, newScheme, al_t.Scheme); } GetSchemes(); } else { MessageBox.Show("Scheme created, but no existing Annotations found, nothing was converted."); } } } } }
private void ExportFrameWiseAnnotations(double chunksize, char seperator, string restclass, string filepath, List <AnnoList> annoLists, bool ishead, string sessionname, int tempsteps = 0) { string headline = ""; double maxdur = 0; bool skipwarning = false; string[][] history = new string[annoLists.Count][]; for (int a = 0; a < annoLists.Count; a++) { history[a] = new string[tempsteps]; if (ishead) { headline += annoLists[a].Meta.Role + "_" + annoLists[a].Scheme.Name + seperator; for (int i = 0; i < tempsteps; i++) { history[a][i] = restclass; headline += annoLists[a].Meta.Role + "_" + annoLists[a].Scheme.Name + "_" + (i + 1) + seperator; } } double localdur = 0; if (annoLists[a].Count > 0) { localdur = annoLists[a][annoLists[a].Count - 1].Stop * 1000; } maxdur = Math.Max(maxdur, localdur); } try { using (System.IO.StreamWriter file = new System.IO.StreamWriter(filepath, true)) { if (ishead) { headline = headline.Remove(headline.Length - 1); file.WriteLine(headline); string[] split = headline.Split(seperator); SheetRows = split.Length; } headline = ""; List <AnnoList> newlists = new List <AnnoList>(); double targetsr = 1000.0 / chunksize; foreach (AnnoList al in annoLists) { if (al.Scheme.Type == AnnoScheme.TYPE.DISCRETE || al.Scheme.Type == AnnoScheme.TYPE.FREE) { AnnoList list = ConvertDiscreteAnnoListToContinuousList(al, chunksize, maxdur, restclass); newlists.Add(list); } else if (al.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS) { if (al.Scheme.SampleRate != targetsr) { AnnoList newlist = ResampleContinuousList(al, targetsr); if (newlist == null) { MessageBox.Show("Samplerates do not fit!"); return; } newlists.Add(newlist); } else { newlists.Add(al); } } } double minSize = double.MaxValue; foreach (AnnoList a in newlists) { if (a.Count < minSize) { minSize = a.Count; } } string discretelabel = ""; for (int a = 0; a < newlists.Count; a++) { for (int i = 0; i < tempsteps; i++) { if (newlists[a].Scheme.Type == AnnoScheme.TYPE.CONTINUOUS && discretisizeeckbox.IsChecked == true) { double value = newlists[a][i].Score; discretelabel = discretize(value, newlists[a].Scheme.MinScore, newlists[a].Scheme.MaxScore, newlists[a].Scheme.Labels); history[a][i] = discretelabel; } else if (newlists[a].Scheme.Type == AnnoScheme.TYPE.CONTINUOUS && discretisizeeckbox.IsChecked == false) { history[a][i] = newlists[a][i].Score.ToString(); } else { history[a][i] = newlists[a][i].Label; } } } for (int i = 0; i < minSize; i++) { for (int a = 0; a < newlists.Count; a++) { if (newlists[a].Scheme.Type == AnnoScheme.TYPE.CONTINUOUS && discretisizeeckbox.IsChecked == true) { double value = newlists[a][i].Score; discretelabel = discretize(value, newlists[a].Scheme.MinScore, newlists[a].Scheme.MaxScore, newlists[a].Scheme.Labels); headline += discretelabel + seperator; } else if ((newlists[a].Scheme.Type == AnnoScheme.TYPE.CONTINUOUS && discretisizeeckbox.IsChecked == false)) { headline += newlists[a][i].Score + seperator; } else { headline += newlists[a][i].Label + seperator; } if (tempsteps > 0) { for (int k = 0; k < tempsteps; k++) { headline += history[a][k] + seperator; } for (int k = tempsteps - 1; k > 0; k--) { history[a][k] = history[a][k - 1]; } if (newlists[a].Scheme.Type == AnnoScheme.TYPE.CONTINUOUS && discretisizeeckbox.IsChecked == true) { history[a][0] = discretelabel; } else if (newlists[a].Scheme.Type == AnnoScheme.TYPE.CONTINUOUS && discretisizeeckbox.IsChecked == false) { history[a][0] = newlists[a][i].Score.ToString(); } else { history[a][0] = newlists[a][i].Label; } } } headline = headline.Remove(headline.Length - 1); string[] splitline = headline.Split(seperator); if (splitline.Length == SheetRows) { file.WriteLine(headline); } else { skipwarning = true; } headline = ""; } Action EmptyDelegate = delegate() { }; this.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate); } } catch (Exception ex) { MessageBox.Show("Could not create Sampled Annotations Data File! " + ex, "Warning", MessageBoxButton.OK, MessageBoxImage.Error); } }
private void Apply_Click(object sender, RoutedEventArgs e) { Properties.Settings.Default.SettingCMLDefaultBN = NetworkSelectionBox.SelectedItem.ToString(); Properties.Settings.Default.CMLDefaultAnnotator = AnnotatorsBox.SelectedItem.ToString(); Properties.Settings.Default.CMLDefaultRole = RolesBox.SelectedItem.ToString(); Properties.Settings.Default.CMLDefaultScheme = SchemesBox.SelectedItem.ToString(); Properties.Settings.Default.CMLDefaultTrainer = NetworkSelectionBox.SelectedItem.ToString(); Properties.Settings.Default.Save(); bool force = ForceCheckBox.IsChecked.Value; string database = DatabaseHandler.DatabaseName; var sessions = SessionsBox.SelectedItems; logTextBox.Text = ""; string networkrDir = Properties.Settings.Default.CMLDirectory + "\\" + Defaults.CML.FusionFolderName + "\\" + Defaults.CML.FusionBayesianNetworkFolderName + "\\" + NetworkSelectionBox.SelectedItem + ".xdsl"; string datasetDir = Properties.Settings.Default.CMLDirectory + "\\" + Defaults.CML.FusionFolderName + "\\" + Defaults.CML.FusionBayesianNetworkFolderName + "\\" + namebox.Text; double chunksizeinMS; double.TryParse(chunksizebox.Text, out chunksizeinMS); int tempsteps; int.TryParse(timestepsbox.Text, out tempsteps); bool isdynamic = tempsteps > 0 ? true : false; if (File.Exists(datasetDir) && ForceCheckBox.IsChecked == false) { // logTextBox.Text = "dataset exists, skip.\n"; logTextBox.Text += "\nData sheet exits, check force to overwrite"; // logTextBox.Text += handler.CMLTrainBayesianNetwork(networkrDir, datasetDir, isdynamic); return; } File.Delete(datasetDir); bool ishead = true; foreach (DatabaseSession session in SessionsBox.SelectedItems) { List <AnnoList> annoLists = new List <AnnoList>(); foreach (SchemeRoleAnnotator item in AnnotationSelectionBox.Items) { DatabaseRole role = DatabaseHandler.Roles.Find(r => r.Name == item.Role); DatabaseScheme scheme = DatabaseHandler.Schemes.Find(m => m.Name == item.Name); ObjectId annotatorID = DatabaseHandler.Annotators.Find(a => a.FullName == item.Annotator).Id; var builder = Builders <BsonDocument> .Filter; var filter = builder.Eq("scheme_id", scheme.Id) & builder.Eq("annotator_id", annotatorID) & builder.Eq("role_id", role.Id) & builder.Eq("session_id", session.Id); List <DatabaseAnnotation> list = DatabaseHandler.GetAnnotations(filter); foreach (DatabaseAnnotation anno in list) { AnnoList annolist = DatabaseHandler.LoadAnnoList(anno.Id); if (annolist.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS) { for (int i = 0; i < item.Classes; i++) { annolist.Scheme.Labels.Add(new AnnoScheme.Label("s" + (i + 1).ToString(), System.Windows.Media.Colors.Black)) ; } } annoLists.Add(annolist); logTextBox.Text = logTextBox.Text + "Session: " + session.Name + " Role: " + annolist.Meta.Role + " Scheme: " + annolist.Scheme.Name + "\n"; logTextBox.Focus(); logTextBox.CaretIndex = logTextBox.Text.Length; logTextBox.ScrollToEnd(); } } logTextBox.Text = logTextBox.Text + "----------------------------------\n"; if (rolecheckbox.IsChecked == true) { ExportFrameWiseAnnotations(chunksizeinMS, ';', "REST", datasetDir, annoLists, ishead, session.Name, tempsteps); } else { ExportFrameWiseAnnotationsRolesSeperated(chunksizeinMS, ';', "REST", datasetDir, annoLists, ishead, session.Name, tempsteps); } if (ishead) { ishead = false; } } string[] pairs = new string[AnnotationSelectionBox.Items.Count]; int s = 0; foreach (SchemeRoleAnnotator item in AnnotationSelectionBox.Items) { pairs[s] = item.Name + ":" + item.Annotator + ":" + item.Role + ":" + item.Classes; s++; } string cmlfolderpath = Properties.Settings.Default.CMLDirectory + "\\" + Defaults.CML.FusionFolderName + "\\" + Defaults.CML.FusionBayesianNetworkFolderName + "\\"; string trainingsetpath = cmlfolderpath + "training.set"; System.IO.File.WriteAllLines(trainingsetpath, pairs); logTextBox.Text += "\nCreating Data sheet successful\nHit train to train the network or use it in GenIE"; }
private void addNewAnnotationDatabase() { if (Time.TotalDuration > 0) { string annoScheme = DatabaseHandler.SelectScheme(); if (annoScheme == null) { return; } string role = DatabaseHandler.SelectRole(); if (role == null) { return; } AnnoScheme scheme = DatabaseHandler.GetAnnotationScheme(annoScheme); if (scheme == null) { return; } scheme.Labels.Add(new AnnoScheme.Label("GARBAGE", Colors.Black)); ObjectId annotatid = DatabaseHandler.GetObjectID(DatabaseDefinitionCollections.Annotators, "name", Properties.Settings.Default.MongoDBUser); string annotator = Properties.Settings.Default.MongoDBUser; // DatabaseHandler.FetchDBRef(DatabaseDefinitionCollections.Annotators, "fullname", annotatid); AnnoList annoList; if (DatabaseHandler.AnnotationExists(annotator, DatabaseHandler.SessionName, role, scheme.Name)) { DatabaseAnnotation annotation = new DatabaseAnnotation() { Annotator = annotator, Session = DatabaseHandler.SessionName, Role = role, Scheme = scheme.Name }; annoList = DatabaseHandler.LoadAnnoList(annotation, false); annoList.HasChanged = false; } else { annoList = new AnnoList(); annoList.Meta.Role = role; annoList.Meta.Annotator = annotator; string annotatorFullName = DatabaseHandler.GetUserInfo(annotator).Fullname; annoList.Meta.AnnotatorFullName = annotatorFullName; annoList.Scheme = scheme; annoList.Source.StoreToDatabase = true; annoList.Source.Database.Session = DatabaseHandler.SessionName; annoList.HasChanged = true; } addAnnoTier(annoList); control.annoListControl.editComboBox.SelectedIndex = 0; } else { MessageTools.Warning("Nothing to annotate, load some data first."); } }
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 = Properties.Settings.Default.ConvertToDiscreteClasses }; input["thresholds"] = new UserInputWindow.Input() { Label = "Upper thresholds (separated by ;)", DefaultValue = Properties.Settings.Default.ConvertToDiscreteThreshs }; input["offset"] = new UserInputWindow.Input() { Label = "Optional offset (s)", DefaultValue = Properties.Settings.Default.ConvertToDiscreteDelays }; 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) { Properties.Settings.Default.ConvertToDiscreteClasses = dialog.Result("labels"); Properties.Settings.Default.ConvertToDiscreteThreshs = dialog.Result("thresholds"); Properties.Settings.Default.ConvertToDiscreteDelays = dialog.Result("offset"); Properties.Settings.Default.Save(); 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 = ali.Score; 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.Unselect(); addAnnoTierFromList(discretevalues); Mouse.SetCursor(System.Windows.Input.Cursors.Arrow); } else { MessageBox.Show("Tier is already discrete"); } }
public static AnnoList LoadFromCSVFile(String filepath, double samplerate = 1, string type = "legacy", string filter = null) { AnnoList list = new AnnoList(); list.Source.File.Path = filepath; list.Scheme = new AnnoScheme(); try { StreamReader sr = new StreamReader(filepath, System.Text.Encoding.Default); string line = null; while ((line = sr.ReadLine()) != null) { if (type == "semicolon") { list.Scheme.Type = AnnoScheme.TYPE.FREE; string[] data = line.Split(';'); double start = Convert.ToDouble(data[0], CultureInfo.InvariantCulture); double duration = Convert.ToDouble(data[1]) - Convert.ToDouble(data[0], CultureInfo.InvariantCulture); string label = ""; string tier = ""; string meta = ""; double confidence = 1.0; if (data.Length > 2) { label = data[2]; } if (data.Length > 3) { if (data[3].Contains("#")) { tier = data[3]; tier = tier.Remove(0, 1); } else { bool isconfidence = double.TryParse(data[3], out confidence); } } if (data.Length > 4) { for (int i = 4; i < data.Length; i++) { meta += data[i] + ";"; } } AnnoListItem e = new AnnoListItem(start, duration, label, meta, Colors.Black, confidence); if (filter == null || tier == filter) { list.AddSorted(e); } } else if (type == "continuous") { list.Scheme.Type = AnnoScheme.TYPE.CONTINUOUS; list.Scheme.SampleRate = samplerate; string[] data = line.Split(';'); double start = Convert.ToDouble(data[0], CultureInfo.InvariantCulture); double score = double.NaN; string tier = ""; double confidence = 1.0; if (data.Length > 1) { double.TryParse(data[1], out score); } if (data.Length > 2) { bool isconfidence = double.TryParse(data[2], out confidence); } if (data.Length > 3) { list.Scheme.MinScore = double.Parse(data[3]); if (data.Length > 4) { list.Scheme.MaxScore = double.Parse(data[4]); } AnnoListItem e = new AnnoListItem(start, samplerate == 0 ? 0 : 1 / samplerate, score, "Range: " + list.Scheme.MinScore + "-" + list.Scheme.MaxScore, Colors.Black); list.AddSorted(e); } else { AnnoListItem e = new AnnoListItem(start, samplerate == 0 ? 0 : 1 / samplerate, score, "", Colors.Black, 1); if (filter == null || tier == filter) { list.AddSorted(e); } } } else if (type == "legacy") { list.Scheme.Type = AnnoScheme.TYPE.FREE; string[] data; data = line.Split(' '); if (data.Length < 2) { data = line.Split('\t'); } if (data.Length < 2) { data = line.Split(';'); } double start = Convert.ToDouble(data[0], CultureInfo.InvariantCulture); double duration = Convert.ToDouble(data[1], CultureInfo.InvariantCulture) - Convert.ToDouble(data[0], CultureInfo.InvariantCulture); string label = ""; string tier = ""; if (data.Length > 2) { label = data[2]; } if (data.Length > 3) { tier = data[3]; } for (int i = 4; i < data.Length; i++) { label += " " + data[i]; } AnnoListItem e = new AnnoListItem(start, duration, label, "", Colors.Black, 1); if (filter == null || tier == filter) { list.AddSorted(e); } } } sr.Close();; list.HasChanged = false; } catch { MessageBox.Show("An exception occured while reading annotation from '" + filepath + "'"); } return(list); }
public static AnnoList LoadFromEventFile(String filepath) { AnnoList list = new AnnoList(); try { XDocument doc = XDocument.Load(filepath); var events = doc.Descendants("event"); 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; } var state_attr = e.Attribute("state"); if (state_attr.Value.ToString().ToUpper() == "COMPLETED") { list.AddSorted(new AnnoListItem(start, duration, label, meta)); } } } catch (Exception ex) { MessageTools.Error(ex.ToString()); } return(list); }
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 { list.Scheme.Type = AnnoScheme.TYPE.FREE; } 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 = Colors.Orange; } 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 = Colors.LightBlue; } 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 = Colors.Black; 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", Colors.Black); list.Scheme.Labels.Add(garbage); } else if (list.Scheme.Type == AnnoScheme.TYPE.FREE) { } else if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS) { list.Scheme.SampleRate = double.Parse(scheme.Attributes["sr"].Value); list.Scheme.MinScore = double.Parse(scheme.Attributes["min"].Value); list.Scheme.MaxScore = double.Parse(scheme.Attributes["max"].Value); } if (File.Exists(filepath + "~")) { if (list.Source.File.Type == AnnoSource.FileSource.TYPE.ASCII) { StreamReader sr = new StreamReader(filepath + "~", System.Text.Encoding.Default); string line = null; double start = 0.0; while ((line = sr.ReadLine()) != null) { string[] data = line.Split(';'); if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS) { string value = data[0]; double confidence = Convert.ToDouble(data[1], CultureInfo.InvariantCulture); AnnoListItem e = new AnnoListItem(start, (1000.0 / list.Scheme.SampleRate) / 1000.0, value, "", Colors.Black, confidence); list.Add(e); start = start + (1000.0 / list.Scheme.SampleRate) / 1000.0; } 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); } } 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) { string value = binaryReader.ReadSingle().ToString(); double confidence = (double)binaryReader.ReadSingle(); AnnoListItem e = new AnnoListItem(start, (1000.0 / list.Scheme.SampleRate) / 1000.0, value, "", Colors.Black, confidence); list.Add(e); start = start + (1000.0 / list.Scheme.SampleRate) / 1000.0; } 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(); } } else { MessageBox.Show("Annotation data was not found, load scheme only from '" + filepath + "'"); } list.HasChanged = false; } catch (Exception e) { MessageBox.Show("An exception occured while reading annotation from '" + filepath + "'"); } return(list); }
private 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=\"" + Properties.Settings.Default.Annotator + "\"/>"); 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>"); } 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.Label + delimiter + e.Confidence.ToString("n2")); } } else if (Scheme.Type == AnnoScheme.TYPE.FREE) { foreach (AnnoListItem e in this) { if (e.Color != Scheme.MaxOrForeColor) { sw.WriteLine(e.Start.ToString("n2") + delimiter + e.Stop.ToString("n2") + delimiter + e.Label + delimiter + e.Confidence.ToString("n2")); } else { sw.WriteLine(e.Start.ToString("n2") + delimiter + e.Stop.ToString("n2") + delimiter + e.Label + delimiter + e.Confidence.ToString("n2") + 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.ToString("n2") + delimiter + e.Stop.ToString("n2") + delimiter + index + delimiter + e.Confidence.ToString("n2")); } else { sw.WriteLine(e.Start.ToString("n2") + delimiter + e.Stop.ToString("n2") + delimiter + -1 + delimiter + e.Confidence.ToString("n2")); } } } 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.Parse(e.Label)); 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); }
private void setAnnoList(AnnoList anno) { control.annoListControl.annoDataGrid.ItemsSource = anno; }
private void RMS_Click(object sender, RoutedEventArgs e) { Ok.IsEnabled = false; rms = rootMeanSquare(); }
public DatabaseSelectionWindow(List <string> strings, bool showadminbuttons, string title = "Select", string Collection = "none", bool allowEdit = false, AnnoList annoList = null) { InitializeComponent(); this.titlelabel.Content = title; this.collection = Collection; this.allowEdit = allowEdit; this.annoList = annoList; if (showadminbuttons) { this.Add.Visibility = Visibility.Visible; this.Delete.Visibility = Visibility.Visible; if (this.allowEdit == true) { this.Edit.Visibility = Visibility.Visible; } } else { this.Add.Visibility = Visibility.Hidden; this.Delete.Visibility = Visibility.Hidden; this.Edit.Visibility = Visibility.Hidden; } foreach (string session in strings) { DataBaseResultsBox.Items.Add(session); } mongo = new MongoClient(connectionString); if (strings.Count > 0) { DataBaseResultsBox.SelectedItem = strings[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); }
public static AnnoList[] LoadfromElanFile(String filepath) { AnnoList[] list = new AnnoList[1]; try { XmlDocument doc = new XmlDocument(); doc.Load(filepath); XmlNode time_order = doc.DocumentElement.ChildNodes[1]; 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())); } int numberoftracks = 0; foreach (XmlNode tier in doc.SelectNodes("//TIER")) { numberoftracks++; } list = new AnnoList[numberoftracks]; int i = 0; foreach (XmlNode tier in doc.SelectNodes("//TIER")) { string tierid; if (tier.Attributes.Count == 2) { tierid = tier.Attributes[1].Value.ToString(); } else { tierid = tier.Attributes[2].Value.ToString(); } list[i] = new AnnoList(); list[i].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; duration = end - start; list[i].AddSorted(new AnnoListItem(start, duration, label, "", Colors.Black)); list[i].Scheme.Name = tierid; //The tier is used as metainformation as well. Might be changed if thats relevant in the future } i++; } } catch (Exception ex) { MessageTools.Error(ex.ToString()); } return(list); }
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); }
public void ReloadAnnoTierFromDatabase(AnnoTier tier, bool loadBackup) { if (tier == null || tier.AnnoList == null) { return; } if (loadBackup && tier.AnnoList.Source.Database.DataBackupOID == AnnoSource.DatabaseSource.ZERO) { MessageTools.Warning("No backup exists"); return; } Action EmptyDelegate = delegate() { }; control.ShadowBoxText.Text = "Reloading Annotation"; control.ShadowBox.Visibility = Visibility.Visible; control.UpdateLayout(); control.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate); DatabaseAnnotation annotation = new DatabaseAnnotation(); annotation.Role = tier.AnnoList.Meta.Role; annotation.Scheme = tier.AnnoList.Scheme.Name; annotation.AnnotatorFullName = tier.AnnoList.Meta.AnnotatorFullName; annotation.Annotator = tier.AnnoList.Meta.Annotator; annotation.Session = DatabaseHandler.SessionName; AnnoList annoList = DatabaseHandler.LoadAnnoList(annotation, loadBackup); double maxdur = 0; if (annoList != null && annoList.Count > 0 && annoList.Scheme.Type == AnnoScheme.TYPE.DISCRETE || annoList.Scheme.Type == AnnoScheme.TYPE.FREE) { maxdur = annoList[annoList.Count - 1].Stop; setAnnoList(annoList); tier.Children.Clear(); tier.AnnoList.Clear(); tier.segments.Clear(); tier.AnnoList = annoList; foreach (AnnoListItem item in annoList) { tier.AddSegment(item); } tier.TimeRangeChanged(Time); updateTimeRange(maxdur); tier.AnnoList.HasChanged = false; } else if (annoList != null && annoList.Count > 0 && annoList.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS) { maxdur = annoList[annoList.Count - 1].Stop; setAnnoList(annoList); tier.AnnoList.Clear(); tier.AnnoList = annoList; tier.TimeRangeChanged(Time); updateTimeRange(maxdur); AnnoTier.Selected.TimeRangeChanged(MainHandler.Time); tier.AnnoList.HasChanged = false; } control.ShadowBox.Visibility = Visibility.Collapsed; }
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); }
public void loadProjectFile(string filepath) { clearWorkspace(); string workdir = Path.GetDirectoryName(filepath); XmlDocument doc = new XmlDocument(); try { doc.Load(filepath); foreach (XmlNode node in doc.SelectNodes("//media")) { string path = FileTools.GetAbsolutePath(node.InnerText, workdir); loadFile(path); } foreach (XmlNode node in doc.SelectNodes("//signal")) { Color background = Defaults.Colors.Background; Color foreground = Defaults.Colors.Foreground; if (node.Attributes["bg"] != null) { background = (Color)ColorConverter.ConvertFromString(node.Attributes["bg"].LastChild.Value); } if (node.Attributes["fg"] != null) { foreground = (Color)ColorConverter.ConvertFromString(node.Attributes["fg"].LastChild.Value); } string path = FileTools.GetAbsolutePath(node.InnerText, workdir); loadFile(path, foreground, background); } if (DatabaseHandler.IsConnected) { XmlNode node = doc.SelectSingleNode("//tiers"); if (node != null && node.Attributes["database"] != null) { DatabaseHandler.ChangeDatabase(node.Attributes["database"].LastChild.Value); } } foreach (XmlNode node in (doc.SelectNodes("//tier"))) { string path = node.InnerText; if (!Path.HasExtension(path)) { AnnoList annoList = DatabaseHandler.LoadAnnoList(path); if (annoList != null) { addAnnoTier(annoList); } else { MessageTools.Warning("Could not load annotation from database with id '" + node.InnerText + "'"); } } else { if (path == "") { path = node.Attributes["filepath"].LastChild.Value; } path = FileTools.GetAbsolutePath(path, workdir); loadFile(path); } } } catch (Exception e) { MessageTools.Error(e.ToString()); } }