public string CMLTrainBayesianNetwork(string netPath, string datasetpath, bool isdynamic) { string result = ""; string logPath = AppDomain.CurrentDomain.BaseDirectory + "\\cml-bayestrain.log"; if (File.Exists(logPath)) { File.Delete(logPath); } try { string options = (isdynamic ? "-dynamic " : "") + " -log \"" + logPath + "\""; string arguments = netPath + " " + datasetpath; Process process = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.WindowStyle = ProcessWindowStyle.Normal; startInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "bayesfusion.exe"; startInfo.Arguments = "--bayesnettrain " + options + " " + arguments; result += "\n-------------------------------------------\r\n" + startInfo.FileName + " " + startInfo.Arguments + "\n-------------------------------------------\r\n"; process.StartInfo = startInfo; process.Start(); process.WaitForExit(); result += File.ReadAllText(logPath); } catch (Exception ex) { MessageTools.Error(ex.ToString()); } return(result); }
public bool downloadDll(string name, bool isDependency) { string path = directory + name + ".dll"; if (!File.Exists(path)) { try { string url = "https://github.com/hcmlab/nova/blob/master/bin/" + name + ".dll?raw=true"; WebClient Client = new WebClient(); if (isDependency) { Client.DownloadFile(url, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "//" + name + ".dll"); } else { Client.DownloadFile(url, directory + "//" + name + ".dll"); }; } catch { MessageTools.Error("Can't download plugin, please check your internet connection."); return(false); } } return(true); }
private void clientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { try { Action EmptyDelegate = delegate() { }; string filename = ((System.Net.WebClient)(sender)).QueryString["file"]; string id_ = ((System.Net.WebClient)(sender)).QueryString["id"]; int id = Int32.Parse(id_); downloadsReceived[id] = e.BytesReceived; downloadsTotal[id] = e.TotalBytesToReceive; double bytesreceived = 0; double bytestotal = 0; for (int i = 0; i < downloadsTotal.Count; i++) { bytesreceived = bytesreceived + downloadsReceived[i]; bytestotal = bytestotal + downloadsTotal[i]; } double percent = ((double)bytesreceived / (double)bytestotal) * 100.0; control.navigator.Statusbar.Content = "Downloading " + lastdlfile + " (" + percent.ToString("F3") + "%)"; control.navigator.Statusbar.UpdateLayout(); control.navigator.Statusbar.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate); control.ShadowBox.Visibility = Visibility.Visible; control.ShadowBoxText.Text = "Downloading Files... Total progress: " + " (" + percent.ToString("F2") + "%)"; } catch (Exception ex) { MessageTools.Error(ex.ToString()); } }
private void reloadAnnoTier(string filename) { if (!File.Exists(filename)) { MessageTools.Error("Annotation file not found '" + filename + "'"); return; } AnnoList anno = AnnoList.LoadfromFile(filename); double maxdur = 0; maxdur = anno[anno.Count - 1].Stop; if (anno != null && AnnoTierStatic.Selected != null) { setAnnoList(anno); AnnoTierStatic.Selected.Children.Clear(); AnnoTierStatic.Selected.AnnoList.Clear(); AnnoTierStatic.Selected.segments.Clear(); AnnoTierStatic.Selected.AnnoList = anno; foreach (AnnoListItem item in anno) { AnnoTierStatic.Selected.addSegment(item); } AnnoTierStatic.Selected.TimeRangeChanged(MainHandler.Time); } updateTimeRange(maxdur); // if (maxdur > Properties.Settings.Default.DefaultZoominSeconds && Properties.Settings.Default.DefaultZoominSeconds != 0 && annos.Count != 0 && media_list.Medias.Count == 0) fixTimeRange(Properties.Settings.Default.DefaultZoominSeconds); }
private Signal loadAudioSignalFile(string filename, Color signalColor, Color backgroundColor) { if (!File.Exists(filename)) { MessageTools.Error("Audio file not found '" + filename + "'"); return(null); } Signal signal = null; try { signal = Signal.LoadAudioFile(filename); } catch (Exception e) { return(null); } if (signal != null && signal.loaded) { this.control.signalbar.Height = new GridLength(control.signalAndAnnoGrid.ActualHeight / 2 - 30); this.control.signalstatusbar.Visibility = Visibility.Visible; addSignalTrack(signal, signalColor, backgroundColor); } return(signal); }
private void loadCSVAnnoFile(string filename, double samplerate = 1, string type = "semicolon", string filter = null) { if (!File.Exists(filename)) { MessageTools.Error("Annotation file not found '" + filename + "'"); return; } AnnoList annoList = AnnoList.LoadFromCSVFile(filename, samplerate, type, filter); addAnnoTierFromList(annoList); }
private void loadStream(string filename, string color = "#FF000000", string background = "#FFF0F0F0") { if (!File.Exists(filename)) { MessageTools.Error("Stream file not found '" + filename + "'"); return; } Signal signal = Signal.LoadStreamFile(filename); signalCursor.signalLoaded = true; annoCursor.signalLoaded = true; if (signal != null && signal.loaded) { addSignal(signal, color, background); if (signal.meta_name == "face" || signal.meta_name == "skeleton") { if (control.videoskel.ColumnDefinitions.Count < 2 && mediaList.Medias.Count > 0) { ColumnDefinition split_column = new ColumnDefinition(); split_column.Width = new GridLength(1, GridUnitType.Auto); control.videoskel.ColumnDefinitions.Add(split_column); GridSplitter splitter = new GridSplitter(); splitter.ResizeDirection = GridResizeDirection.Columns; splitter.Width = 3; splitter.HorizontalAlignment = HorizontalAlignment.Stretch; splitter.VerticalAlignment = VerticalAlignment.Stretch; Grid.SetRowSpan(splitter, 1); //Grid.SetColumn(splitter, 0); Grid.SetColumn(splitter, control.videoskel.ColumnDefinitions.Count - 1); control.videoskel.Children.Add(splitter); ColumnDefinition column = new ColumnDefinition(); column.Width = new GridLength(1, GridUnitType.Star); control.videoskel.ColumnDefinitions.Add(column); } else if (control.videoskel.ColumnDefinitions.Count < 2) { ColumnDefinition columvideo = control.videoskel.ColumnDefinitions[0]; columvideo.Width = new GridLength(0, GridUnitType.Pixel); ColumnDefinition column = new ColumnDefinition(); column.Width = new GridLength(1, GridUnitType.Star); control.videoskel.ColumnDefinitions.Add(column); } control.pointcontrol.AddSignal(signal); visualizepoints = true; control.navigator.playButton.IsEnabled = true; } } }
private void loadAnnotation(string filename) { if (!File.Exists(filename)) { MessageTools.Error("Annotation file not found '" + filename + "'"); return; } AnnoList annoList = AnnoList.LoadfromFile(filename); handleAnnotation(annoList); }
private IMedia loadMediaFile(string filename, MediaType type) { if (!File.Exists(filename)) { MessageTools.Error("Media file not found '" + filename + "'"); return(null); } if (Mediabackend == MEDIABACKEND.MEDIAKIT) { try { MediaKit media = new MediaKit(filename, type); media.OnMediaMouseDown += OnMediaMouseDown; media.OnMediaMouseUp += OnMediaMouseUp; media.OnMediaMouseMove += OnMediaMouseMove; addMedia(media); return(media); } catch { return(null); //ignore the file } } else if (Mediabackend == MEDIABACKEND.MEDIA) { try { Media media = new Media(filename, type); media.OnMediaMouseDown += OnMediaMouseDown; media.OnMediaMouseUp += OnMediaMouseUp; media.OnMediaMouseMove += OnMediaMouseMove; addMedia(media); return(media); } catch { return(null); //ignore the file } } return(null); }
public bool ExportToCSV(string delimiter = ";") { string filePath = FileTools.SaveFileDialog(Source.File.Path != "" ? Source.File.Name : DefaultName(), ".csv", "Annotation(*.csv)|*.csv", ""); if (filePath == null) { return(false); } if (Scheme.Type == AnnoScheme.TYPE.CONTINUOUS) { try { StreamWriter sw = new StreamWriter(filePath, false, System.Text.Encoding.Default); foreach (AnnoListItem e in this) { sw.WriteLine(e.Start.ToString() + ";" + e.Score + ";" + e.Confidence); } sw.Close(); return(true); } catch (Exception ex) { MessageTools.Error(ex.ToString()); } } else { try { StreamWriter sw = new StreamWriter(filePath, false, System.Text.Encoding.Default); foreach (AnnoListItem e in this) { sw.WriteLine(e.Start.ToString() + delimiter + e.Stop.ToString() + delimiter + e.Label + delimiter + e.Confidence); } sw.Close(); return(true); } catch (Exception ex) { MessageTools.Error(ex.ToString()); } } return(false); }
public void loadProject(string filepath) { string workdir = Path.GetDirectoryName(filepath); XmlDocument doc = new XmlDocument(); try { doc.Load(filepath); foreach (XmlNode node in doc.SelectNodes("//media")) { bool isvideo = true; string path = node.InnerText; if (Path.GetExtension(path) == ".wav") { isvideo = false; } loadMedia(FileTools.GetAbsolutePath(path, workdir), isvideo); } foreach (XmlNode node in doc.SelectNodes("//signal")) { string background = node.Attributes["bg"].LastChild.Value; string foreground = node.Attributes["fg"].LastChild.Value; string path = node.InnerText; if (Path.GetExtension(path) == ".wav") { loadWav(FileTools.GetAbsolutePath(path, workdir), foreground, background); } else { loadStream(FileTools.GetAbsolutePath(path, workdir), foreground, background); } } foreach (XmlNode node in (doc.SelectNodes("//tier"))) { string path = node.InnerText; if (path == "") { path = node.Attributes["filepath"].LastChild.Value; } loadFileHandler(FileTools.GetAbsolutePath(path, workdir)); } } catch (Exception e) { MessageTools.Error(e.ToString()); } }
private void loadWav(string filename, string color = "#FF000000", string background = "#FFF0F0F0") { if (!File.Exists(filename)) { MessageTools.Error("Wav file not found '" + filename + "'"); return; } Signal signal = Signal.LoadWaveFile(filename); if (signal != null && signal.loaded) { addSignal(signal, color, background); } }
public static Signal LoadARFFFile(string filepath) { Signal signal = null; try { Signal.Type type = Signal.Type.FLOAT; uint dim = 0; double rate = 0; string[] lines = File.ReadAllLines(filepath); char[] delims = { ' ', '\t', ';', ',' }; string[] tokens = lines[0].Split(delims); dim = (uint)tokens.Length; string[] row = null; row = lines[0].Split(delims); double time1 = double.Parse(row[1]); row = lines[1].Split(delims); double time2 = double.Parse(row[1]); double step = time2 - time1; rate = 1000.0 / (1000.0 * step); uint number = (uint)lines.Length; uint bytes = Signal.TypeSize[(int)type]; if (dim > 0) { signal = new Signal(filepath, rate, 1, bytes, number, type); StreamReader fs_data = new StreamReader(filepath); LoadDataArff(signal, fs_data, dim - 1); fs_data.Close(); signal.ShowDim = 0; signal.loaded = true; } } catch (Exception e) { MessageTools.Error(e.ToString()); return(null); } return(signal); }
private void loadSignalFile(string filename, Color signalColor, Color backgroundColor) { if (!File.Exists(filename) || !File.Exists(filename + "~")) { MessageTools.Error("Stream file not found '" + filename + "'"); return; } Signal signal = null; signal = Signal.LoadStreamFile(filename); if (signal != null && signal.loaded) { if (signal.Meta.ContainsKey("name") && signal.Meta["name"] == "face") { if (signal.Meta.ContainsKey("type") && signal.Meta["type"] == "openface") { IMedia media = new Face(filename, signal, Face.FaceType.OPENFACE); addMedia(media); } else if (signal.Meta.ContainsKey("type") && signal.Meta["type"] == "kinect1") { IMedia media = new Face(filename, signal, Face.FaceType.KINECT1); addMedia(media); } else if (signal.Meta.ContainsKey("type") && signal.Meta["type"] == "kinect2") { IMedia media = new Face(filename, signal, Face.FaceType.KINECT2); addMedia(media); } } else if (signal.Meta.ContainsKey("name") && signal.Meta["name"] == "skeleton") { IMedia media = new Skeleton(filename, signal); addMedia(media); } //else //{ this.control.signalbar.Height = new GridLength(control.signalAndAnnoGrid.ActualHeight / 2 - 30); this.control.signalstatusbar.Visibility = Visibility.Visible; signalCursor.signalLoaded = true; annoCursor.signalLoaded = true; addSignalTrack(signal, signalColor, backgroundColor); //} } }
public static Signal LoadCSVFile(string filepath) { Signal signal = null; try { Type type = Type.UNDEF; uint dim = 0; double rate = 0; if (SelectDataType(filepath, ref type, ref rate)) { string[] lines = File.ReadAllLines(filepath); uint number = (uint)lines.Length; uint bytes = TypeSize[(int)type]; if (type != Type.UNDEF && rate > 0 && bytes > 0 && number > 0) { char[] delims = { ' ', '\t', ';', ',' }; string[] tokens = lines[0].Split(delims); dim = (uint)tokens.Length; if (dim > 0) { signal = new Signal(filepath, rate, dim, bytes, number, type); StreamReader fs_data = new StreamReader(filepath); LoadDataV2a(signal, fs_data, delims); fs_data.Close(); signal.minmax(); signal.loaded = true; } } } } catch (Exception e) { MessageTools.Error(e.ToString()); return(null); } return(signal); }
public AnnoTrigger(AnnoList annoList, PluginCaller trigger, Dictionary <string, object> args) { this.annoList = annoList; this.trigger = trigger; this.args = args; position = 0; currentOrNextItemIndex = annoList.Count == 0 ? -1 : 0; object result = trigger.call("open", args); if (result != null) { MessageTools.Error(result.ToString()); } }
public PluginCaller(string dllPath, string typeName) { isLoaded = true; dllName = Path.GetFileNameWithoutExtension(dllPath); directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\"; Directory.CreateDirectory(directory); if (!downloadDll(dllName, false)) { MessageTools.Error("Dll not found '" + dllName + ".dll'"); isLoaded = false; } else { Assembly asm = Assembly.LoadFile(directory + dllName + ".dll"); if (asm != null) { foreach (Type type in asm.GetExportedTypes()) { if (type.Name == typeName) { this.type = type; obj = Activator.CreateInstance(type); object result = call("dependencies", new Dictionary <string, object>()); if (result != null) { string[] dependencies = (string[])result; foreach (string dependency in dependencies) { if (!downloadDll(dependency, true)) { MessageTools.Error("Dll not found '" + dependency + ".dll'"); isLoaded = false; } } } break; } } } } }
private void httpGet(string URL, string db, string sessionid = "Default", string filename = "") { string fileName = filename; if (fileName.EndsWith(".stream%7E")) { fileName = fileName.Remove(fileName.Length - 3); fileName = fileName + "~"; } string localpath = Properties.Settings.Default.DatabaseDirectory + "\\" + db + "\\" + sessionid + "\\" + fileName; if (!File.Exists(localpath)) { try { WebClient client = new WebClient(); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(clientDownloadProgressChanged); client.DownloadFileCompleted += clientDownloadFileCompleted; client.QueryString.Add("file", localpath); client.QueryString.Add("id", numberOfParallelDownloads.ToString()); downloadsTotal.Add(0); downloadsReceived.Add(0); if (!localpath.EndsWith(".stream~")) { filesToDownload.Add(localpath); } numberOfParallelDownloads++; Directory.CreateDirectory(Properties.Settings.Default.DatabaseDirectory + "\\" + db + "\\" + sessionid); client.DownloadFileAsync(new Uri(URL), Properties.Settings.Default.DatabaseDirectory + "\\" + db + " \\" + sessionid + "\\" + fileName); } catch (Exception ex) { MessageTools.Error(ex.ToString()); } } else if (!localpath.EndsWith(".stream~") && !localpath.EndsWith(".stream%7E")) { loadFileHandler(localpath); } }
private bool parseTrainerFile(ref Trainer trainer, bool isTemplate) { XmlDocument doc = new XmlDocument(); try { doc.Load(trainer.Path); string[] tokens = trainer.Path.Split('\\'); trainer.Name = isTemplate ? Path.GetFileNameWithoutExtension(trainer.Path) : tokens[tokens.Length - 2] + " > " + Path.GetFileNameWithoutExtension(trainer.Path); trainer.LeftContext = "0"; trainer.RightContext = "0"; trainer.Balance = "none"; foreach (XmlNode node in doc.SelectNodes("//meta")) { var leftContext = node.Attributes["leftContext"]; if (leftContext != null) { trainer.LeftContext = leftContext.Value; } var rightContext = node.Attributes["rightContext"]; if (rightContext != null) { trainer.RightContext = rightContext.Value; } var balance = node.Attributes["balance"]; if (balance != null) { trainer.Balance = balance.Value; } } } catch (Exception e) { MessageTools.Error(e.ToString()); return(false); } return(true); }
private bool parseChainFile(ref Chain chain) { XmlDocument doc = new XmlDocument(); try { doc.Load(chain.Path); chain.Name = Path.GetFileNameWithoutExtension(chain.Path); foreach (XmlNode node in doc.SelectNodes("//meta")) { chain.FrameStep = node.Attributes["frameStep"].Value; var leftContext = node.Attributes["leftContext"]; if (leftContext != null) { chain.LeftContext = leftContext.Value; } else { chain.LeftContext = "0"; } var rightContext = node.Attributes["rightContext"]; if (rightContext != null) { chain.RightContext = rightContext.Value; } else { chain.RightContext = "0"; } } } catch (Exception e) { MessageTools.Error(e.ToString()); return(false); } return(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 string CallXMLPipe(string pipelinepath) { string result = ""; try { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.WindowStyle = ProcessWindowStyle.Normal; startInfo.FileName = "xmlpipe.exe"; startInfo.Arguments = pipelinepath; process.StartInfo = startInfo; process.Start(); // process.WaitForExit(); } catch (Exception ex) { MessageTools.Error(ex.ToString()); } return(result); }
public static bool SelectDataType(string filename, ref Signal.Type type, ref double rate) { SelectionBox box = new SelectionBox("Please select data type and sample rate (Hz) for:\r\n" + filename + "'", Signal.TypeName, "1", 9); box.ShowDialog(); box.Close(); if (box.DialogResult == true) { type = (Signal.Type)box.ComboBoxResult(); try { rate = double.Parse(box.TextFieldResult()); return(true); } catch (Exception e) { MessageTools.Error(e.ToString()); } } return(false); }
private void loadMedia(string filename, bool is_video, string url = null) { if (!File.Exists(filename)) { MessageTools.Error("Media file not found '" + filename + "'"); return; } double pos = MainHandler.Time.TimeFromPixel(signalCursor.X); IMedia media = mediaList.addMedia(filename, pos, url); control.mediaVideoControl.addMedia(media, is_video); control.navigator.playButton.IsEnabled = true; innomediaplaymode = false; noMediaPlayHandler(null); ColumnDefinition columvideo = control.videoskel.ColumnDefinitions[0]; columvideo.Width = new GridLength(1, GridUnitType.Star); DispatcherTimer _timer = new DispatcherTimer(); _timer.Interval = TimeSpan.FromMilliseconds(50); _timer.Tick += new EventHandler(delegate(object s, EventArgs a) { if (media.GetLength() > 0) { updateTimeRange(media.GetLength()); if (this.mediaList.Medias.Count == 1 && media.GetLength() > Properties.Settings.Default.DefaultZoominSeconds && Properties.Settings.Default.DefaultZoominSeconds != 0) { fixTimeRange(Properties.Settings.Default.DefaultZoominSeconds); } _timer.Stop(); } }); _timer.Start(); }
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 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 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 databaseLoad() { clearSession(); if (loadedDBmedia != null) { loadedDBmedia.Clear(); } if (filesToDownload != null) { filesToDownload.Clear(); } System.Collections.IList annotations = null; List <DatabaseMediaInfo> ci = null; DatabaseAnnoMainWindow dbhw = new DatabaseAnnoMainWindow(); try { dbhw.WindowStartupLocation = WindowStartupLocation.CenterScreen; dbhw.ShowDialog(); if (dbhw.DialogResult == true) { annotations = dbhw.Annotations(); loadedDBmedia = dbhw.Media(); ci = dbhw.MediaConnectionInfo(); control.databaseSaveSessionMenu.IsEnabled = true; control.databaseSaveSessionAndMarkAsFinishedMenu.IsEnabled = true; control.databaseCMLCompleteStepMenu.IsEnabled = true; control.databaseCMLTransferStepMenu.IsEnabled = true; control.databaseCMLExtractFeaturesMenu.IsEnabled = true; //This is just a UI thing. If a user does not have according rights in the mongodb he will not have acess anyway. We just dont want to show the ui here. if (dbhw.Authlevel() > 2) { control.databaseManageMenu.Visibility = Visibility.Visible; control.databaseCMLTransferStepMenu.Visibility = Visibility.Visible; } else { control.databaseManageMenu.Visibility = Visibility.Collapsed; control.databaseCMLTransferStepMenu.Visibility = Visibility.Collapsed; } } control.databaseSaveSessionMenu.IsEnabled = true; if (annotations != null) { Action EmptyDelegate = delegate() { }; control.ShadowBox.Visibility = Visibility.Visible; control.UpdateLayout(); control.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate); List <AnnoList> annoLists = DatabaseHandler.LoadFromDatabase(annotations, Properties.Settings.Default.DatabaseName, Properties.Settings.Default.LastSessionId, Properties.Settings.Default.MongoDBUser); control.navigator.Statusbar.Content = "Database Session: " + (Properties.Settings.Default.LastSessionId).Replace('_', '-'); try { if (annoLists != null) { foreach (AnnoList annoList in annoLists) { //annoList.FilePath = annoList.Role + "." + annoList.Scheme.Name + "." + annoList.AnnotatorFullName; handleAnnotation(annoList); } control.ShadowBox.Visibility = Visibility.Collapsed; //handle media if (loadedDBmedia.Count > 0) { for (int i = 0; i < loadedDBmedia.Count; i++) { foreach (DatabaseMediaInfo c in ci) { Properties.Settings.Default.DataServerConnectionType = c.connection; if (c.filename == loadedDBmedia[i].filename.ToString()) { if (c.connection == "sftp") { Properties.Settings.Default.DataServerConnectionType = "sftp"; SFTPDownloadFiles(c.ip, c.folder, Properties.Settings.Default.DatabaseName, Properties.Settings.Default.LastSessionId, c.filename, Properties.Settings.Default.DataServerLogin, Properties.Settings.Default.DataServerPass); } else if (ci[i].connection == "http" || ci[i].connection == "https" && ci[i].requiresauth == "false") { Properties.Settings.Default.DataServerConnectionType = "http"; httpGet(c.filepath, Properties.Settings.Default.DatabaseName, Properties.Settings.Default.LastSessionId, c.filename); } else if (ci[i].connection == "http" || ci[i].connection == "https" && ci[i].requiresauth == "true") { Properties.Settings.Default.DataServerConnectionType = "http"; //This has not been tested and probably needs rework. httpPost(c.filepath, c.filename, Properties.Settings.Default.DatabaseName, Properties.Settings.Default.DataServerLogin, Properties.Settings.Default.DataServerPass, Properties.Settings.Default.LastSessionId); } } } } } } DatabaseLoaded = true; } catch (TimeoutException e1) { MessageBox.Show("Make sure ip, login and password are correct", "Connection to database not possible"); } } } catch (Exception ex) { dbhw.Close(); MessageTools.Error(ex.ToString()); } }
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, ""); } }
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, ""); }