public async Task <ActionResult <Video> > PostVideo(URLDTO URL)
        {
            Video  newVideo;
            String videoId;

            try
            {
                videoId  = YouTubeHelper.GetVideoIdFromURL(URL.URL);
                newVideo = YouTubeHelper.GetVideoFromId(videoId);
            }
            catch {
                return(BadRequest("Invalid YouTube URL"));
            }
            _context.Video.Add(newVideo);
            await _context.SaveChangesAsync();

            TranscriptionsController transcriptionsController = new TranscriptionsController(new scriberContext());
            List <Transcription>     transcriptions           = YouTubeHelper.GetTranscriptions(videoId);

            Task addCaptions = Task.Run(async() =>
            {
                for (int i = 0; i < transcriptions.Count; i++)
                {
                    // Get the transcription objects form transcriptions and assign VideoId to id, the primary key of the newly inserted video
                    Transcription transcription = transcriptions.ElementAt(i);
                    transcription.VideoId       = newVideo.VideoId;
                    // Add this transcription to the database
                    await transcriptionsController.PostTranscription(transcription);
                    Console.WriteLine("inserting transcription" + i);
                }
            });


            return(CreatedAtAction("GetVideo", new { id = newVideo.VideoId }, newVideo));
        }
Exemplo n.º 2
0
        /// <summary>
        /// This method is called when the Transcribe button is clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            // If we have an active sequence
            if (cbSequences.SelectedIndex >= 0)
            {
                ISequence seq = _sequences[cbSequences.SelectedIndex];

                // Determine the sequence type (DNA vs. RNA)
                ISequence result = null, proteinResult = null;
                if (seq.Alphabet == Alphabets.DNA)
                {
                    result        = Transcription.Transcribe(seq);
                    proteinResult = ProteinTranslation.Translate(result);
                }
                else if (seq.Alphabet == Alphabets.RNA)
                {
                    result = Transcription.ReverseTranscribe(seq);
                }

                // Set the result.
                targetSequenceText.Text = (result != null)
                    ? GetString(result)
                    : string.Empty;

                // Translate the protein result
                proteinTextBox.Text = (proteinResult != null)
                    ? GetString(proteinResult)
                    : string.Empty;
            }
            else
            {
                // Reset the fields.
                targetSequenceText.Text = string.Empty;
            }
        }
Exemplo n.º 3
0
        private Transcription ObtenerTranscripcionRealizada(int id, string login)
        {
            Transcription transcripcion = baseDatosResource.ObtenerTranscripcion(id, login);

            // Flujo Alternativo A
            if (transcripcion == null)
            {
                throw new TranscripcionNoEncontradaException();
            }

            // Flujo Alternativo B
            if (transcripcion.Estado == (int)TipoEstadoTranscripcion.PENDIENTE ||
                transcripcion.Estado == (int)TipoEstadoTranscripcion.EN_PROGRESO)
            {
                throw new TranscripcionPendienteException();
            }

            // Flujo Alternativo C
            if (transcripcion.Estado == (int)TipoEstadoTranscripcion.ERROR)
            {
                throw new TranscripcionErroneaException();
            }

            return(transcripcion);
        }
Exemplo n.º 4
0
        public async Task <ActionResult <Transcription> > PostTranscription(Transcription transcription)
        {
            _context.Transcription.Add(transcription);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetTranscription", new { id = transcription.TranscriptionId }, transcription));
        }
Exemplo n.º 5
0
        public static bool Export(Transcription transcription, Stream output)
        {
            using (StreamWriter sw = new StreamWriter(output))
            {
                int cntr = 1;
                foreach (var p in transcription.EnumerateParagraphs())
                {
                    sw.WriteLine(cntr.ToString());
                    string b = p.Begin.ToString(SRTdateformat);
                    string e = p.End.ToString(SRTdateformat);
                    if (string.IsNullOrWhiteSpace(p.Phonetics))
                    {
                        sw.WriteLine(string.Format("{0} --> {1}", b, e));
                    }
                    else
                    {
                        sw.WriteLine(string.Format("{0} --> {1} {2}", b, e, string.Join(" ", p.Phonetics.Split('\n').Select(ph => ph.Trim())))); //position data.. remove new lines
                    }
                    foreach (var l in p.Text.Split('\n').Select(l => l.Trim()))
                    {
                        if (!string.IsNullOrEmpty(l))
                        {
                            sw.WriteLine(l);
                        }
                    }

                    sw.WriteLine();
                    cntr++;
                }
            }

            return(true);
        }
        public async Task <ActionResult <Video> > PostVideo(URLDTO URL)
        {
            String videoId  = YoutubeHelper.GetVideoIdFromURL(URL.URL);
            Video  newVideo = YoutubeHelper.GetVideoFromId(videoId);


            _context.Video.Add(newVideo);
            await _context.SaveChangesAsync();

            TranscriptionsController transcriptionsController = new TranscriptionsController(new youtubeContext());
            List <Transcription>     transcriptions           = YoutubeHelper.GetTranscriptions(videoId);

            //Go through each transaction and insert it into the database by calling PostTransactions()

            Task addCaptions = Task.Run(async() =>
            {
                for (int i = 0; i < transcriptions.Count; i++)
                {
                    Transcription transcription = transcriptions.ElementAt(i);
                    transcription.VideoId       = newVideo.VideoId;

                    await transcriptionsController.PostTranscription(transcription);
                    Console.WriteLine("inserting transcription" + i);
                }
            });

            return(CreatedAtAction("GetVideo", new { id = newVideo.VideoId }, newVideo));
        }
Exemplo n.º 7
0
        public ActionResult Index()
        {
            VoiceBase voice = new VoiceBase();

            voice.Say("Welcome to my Tropo Web API.");

            Say timeout = new Say(
                VALUE("Sorry, I did not hear anything. Please call back."),
                EVENT("timeout")
                );

            Say say = new Say(VALUE("Please leave a message"), ARRAY(timeout));

            Choices choices = new Choices(TERMINATOR("#"));

            Transcription transcription = new Transcription(
                ID("1234"),
                URL("mailto:[email protected]")
                );

            voice.Record(
                ATTEMPTS(3),
                BARGEIN(false),
                METHOD("POST"),
                REQUIRED(true),
                INSTANCE(say),
                NAME("foo"),
                URL("http://openovate.com/globe.php"),
                FORMAT(Format.WAV),
                INSTANCE(choices),
                INSTANCE(transcription)
                );

            return(Content(voice.Render().ToString(), "application/json"));
        }
Exemplo n.º 8
0
        public void ValidateDnaProteinTranslationWithOffset()
        {
            // Get Node values from XML.
            string alphabetName = _utilityObj._xmlUtil.GetTextValue(Constants.SimpleDnaAlphabetNode,
                                                                    Constants.AlphabetNameNode);
            string expectedSeq = _utilityObj._xmlUtil.GetTextValue(Constants.TranscribeNode,
                                                                   Constants.DnaSequence);
            string expectedProtein = _utilityObj._xmlUtil.GetTextValue(Constants.TranslationNode,
                                                                       Constants.AminoAcidForOffsetTwelve);
            string expectedOffset = _utilityObj._xmlUtil.GetTextValue(Constants.CodonsNode,
                                                                      Constants.OffsetVaule1);
            ISequence seq = new Sequence(Utility.GetAlphabet(alphabetName), expectedSeq);

            // Transcription of DNA Sequence.
            ISequence transcribe = Transcription.Transcribe(seq);

            // Protein Translation by passing offset value.
            ISequence proteinTranslation = new Sequence(Alphabets.RNA, transcribe.ToString());
            ISequence protein            = ProteinTranslation.Translate(proteinTranslation,
                                                                        Convert.ToInt32(expectedOffset, null));

            // Validate Protein Translation.
            Assert.AreEqual(protein.ToString(), expectedProtein);
            ApplicationLog.WriteLine(
                "Translation P1: Protein translation validation is completed successfully.");
        }
Exemplo n.º 9
0
        /// <summary>
        /// Translate the coding sequence of a transcript
        /// </summary>
        /// <param name="transcript"></param>
        /// <returns></returns>
        public static ISequence OneFrameTranslation(ISequence dnaSequence, bool mitochondrial)
        {
            ISequence rnaSequence = Transcription.Transcribe(dnaSequence);
            ISequence proteinSequence;

            if (!mitochondrial)
            {
                proteinSequence = ProteinTranslation.Translate(rnaSequence);
            }
            else
            {
                List <byte> aminoAcidSequence = new List <byte>();
                for (int codonNum = 0; codonNum < (int)(rnaSequence.Count / 3); codonNum++)
                {
                    // Check for start codon, and add 'M' if so
                    if (aminoAcidSequence.Count == 0 &&
                        CodonsVertebrateMitochondrial.START_CODONS.Contains(
                            new string(dnaSequence.GetSubSequence(codonNum * 3, GeneModel.CODON_SIZE).Select(bp => (char)bp).ToArray())))
                    {
                        aminoAcidSequence.Add((byte)CodonsVertebrateMitochondrial.DEFAULT_START_AA);
                        continue;
                    }
                    aminoAcidSequence.Add(CodonsVertebrateMitochondrial.TryLookup(rnaSequence, codonNum * 3, out byte aa) ? aa : (byte)'X');
                }
                proteinSequence = new Sequence(Alphabets.AmbiguousProtein, aminoAcidSequence.ToArray());
            }
            return(proteinSequence);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Get Amino Acids Using Ambiguous DNA Codons.
        /// </summary>
        /// <param name="firstPos">First position.</param>
        /// <param name="secondPos">Second position.</param>
        /// <param name="thirdPos">Third position.</param>
        /// <returns>Returns list of bytes.</returns>
        private static IList <byte> GetAminoAcidsUsingAmbigiousDNACodons(byte firstPos, byte secondPos, byte thirdPos)
        {
            IList <byte>   aminoAcids = new List <byte>();
            HashSet <byte> firstBasicSymbols;

            DnaAlphabet.Instance.TryGetBasicSymbols(firstPos, out firstBasicSymbols);
            HashSet <byte> secondBasicSymbols;

            DnaAlphabet.Instance.TryGetBasicSymbols(secondPos, out secondBasicSymbols);
            HashSet <byte> thirdBasicSymbols;

            DnaAlphabet.Instance.TryGetBasicSymbols(thirdPos, out thirdBasicSymbols);

            foreach (byte firstPosAlphabet in firstBasicSymbols)
            {
                byte firstPosNucleotide = Transcription.GetRnaComplement(firstPosAlphabet);
                foreach (byte secondPosAlphabet in secondBasicSymbols)
                {
                    byte secondPosNucleotide = Transcription.GetRnaComplement(secondPosAlphabet);
                    foreach (byte thirdPosAlphabet in thirdBasicSymbols)
                    {
                        aminoAcids.Add(Codons.Lookup(firstPosNucleotide, secondPosNucleotide, Transcription.GetRnaComplement(thirdPosAlphabet)));
                    }
                }
            }

            return(aminoAcids);
        }
Exemplo n.º 11
0
        public async Task <IActionResult> PutTranscription(int id, Transcription transcription)
        {
            if (id != transcription.TranscriptionId)
            {
                return(BadRequest());
            }

            _context.Entry(transcription).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TranscriptionExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Exemplo n.º 12
0
        public void ValidateLookupWithDnaSequence()
        {
            string alphabetName = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleDnaAlphabetNode, Constants.AlphabetNameNode);
            string expectedSeq = _utilityObj._xmlUtil.GetTextValue(
                Constants.TranscribeNode, Constants.DnaSequence);
            string expectedAminoAcid = _utilityObj._xmlUtil.GetTextValue(
                Constants.CodonsNode, Constants.DnaSeqAminoAcid);
            string expectedOffset = _utilityObj._xmlUtil.GetTextValue(
                Constants.CodonsNode, Constants.OffsetVaule);

            ISequence seq = new Sequence(Utility.GetAlphabet(alphabetName), expectedSeq);

            // Transcribe DNA to RNA.
            ISequence transcribe = Transcription.Transcribe(seq);

            // Validate Codons lookup method.
            AminoAcid aminoAcid = Codons.Lookup(transcribe, Convert.ToInt32(expectedOffset, null));

            // Validate amino acids for a given sequence.
            Assert.AreEqual(aminoAcid.Name.ToString((IFormatProvider)null), expectedAminoAcid);
            ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                   "Translation P1: Amino Acid {0} is expected.", aminoAcid));
            ApplicationLog.WriteLine(
                "Translation P1: Amino Acid validation for a given sequence was completed successfully.");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // Create a new instance of the Tropo object.
            Tropo tropo = new Tropo();

            // Create a transcription object to use with recording.
            Transcription trancription = new Transcription();

            trancription.Uri         = "mailto:[email protected]";
            trancription.EmailFormat = "omit";

            // Set up grammar for recording.
            Choices choices = new Choices();

            choices.Value      = "[10 DIGITS]";
            choices.Terminator = "#";

            // Construct a prompt to use with the recording.
            Say say = new Say();

            say.Value = "Please say your account number";

            // Use the record() method to set up a recording.
            tropo.Record(3, false, true, choices, AudioFormat.Wav, 10, 60, Method.Post, null, true, say, 5, trancription, null, "http://somehost.com/record.aspx");

            // Hangup when finished.
            tropo.Hangup();

            // Render the JSON for Tropo to consume.
            Response.Write(tropo.RenderJSON());
        }
Exemplo n.º 14
0
        public static List <Transcription> GetTranscriptions(String videoId)
        {
            String subtitleLink = GetTranscriptionLink(videoId);

            // Use XmlDocument to load the subtitle XML.
            XmlDocument doc = new XmlDocument();

            doc.Load(subtitleLink);
            XmlNode root = doc.ChildNodes[1];

            // Go through each tag and look for start time and phrase.
            List <Transcription> transcriptions = new List <Transcription>();

            if (root.HasChildNodes)
            {
                for (int i = 0; i < root.ChildNodes.Count; i++)
                {
                    // Decode HTTP characters to text
                    // e.g. &#39; -> '
                    String phrase = root.ChildNodes[i].InnerText;
                    phrase = HttpUtility.HtmlDecode(phrase);

                    Transcription transcription = new Transcription
                    {
                        StartTime = (int)Convert.ToDouble(root.ChildNodes[i].Attributes["start"].Value),
                        Phrase    = phrase
                    };

                    transcriptions.Add(transcription);
                }
            }
            return(transcriptions);
        }
Exemplo n.º 15
0
        public void ValidateDnaProteinTranslation()
        {
            // Get Node values from XML.
            string alphabetName = utilityObj.xmlUtil.GetTextValue(
                Constants.SimpleDnaAlphabetNode, Constants.AlphabetNameNode);
            string expectedSeq = utilityObj.xmlUtil.GetTextValue(
                Constants.TranscribeNode, Constants.DnaSequence);
            string expectedProtein = utilityObj.xmlUtil.GetTextValue(
                Constants.TranslationNode, Constants.AminoAcidForSixCharsV2);
            ISequence transcribe = null;

            var seq = new Sequence(Utility.GetAlphabet(alphabetName), expectedSeq);

            // Transcription of DNA Sequence.
            transcribe = Transcription.Transcribe(seq);

            // Protein Translation.
            ISequence proteinTranslation = new Sequence(Alphabets.RNA,
                                                        new string(transcribe.Select(a => (char)a).ToArray()));
            ISequence protein = ProteinTranslation.Translate(proteinTranslation);

            // Validate Protein Translation.
            Assert.AreEqual(expectedProtein, new string(protein.Select(a => (char)a).ToArray()));
            ApplicationLog.WriteLine(
                "Translation P1: Protein translation validation is completed successfully.");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // Create a new instance of the Tropo object.
            Tropo tropo = new Tropo();

            // Create a transcription object to use with recording.
            Transcription trancription = new Transcription();

            trancription.Url         = "mailto:[email protected]";
            trancription.EmailFormat = "omit";
            trancription.Id          = "asyncUploadNULL";

            // Set up grammar for recording.
            Choices choices = new Choices();

            choices.Value      = "[10 DIGITS]";
            choices.Terminator = "#";

            // Construct a prompt to use with the recording.
            Say say = new Say();

            say.Value = "Please say your account number";
            //say.Value = "Fourscore and seven years ago our fathers brought forth, on this continent, a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal.Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived, and so dedicated, can long endure. We are met on a great battle - field of that war.We have come to dedicate a portion of that field, as a final resting-place for those who here gave their lives, that that nation might live.It is altogether fitting and proper that we should do this.But, in a larger sense, we cannot dedicate, we cannot consecrate—we cannot hallow—this ground.The brave men, living and dead, who struggled here, have consecrated it far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced.It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they here gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom, and that government of the people, by the people, for the people, shall not perish from the earth.";
            tropo.Call("+8613466549249");
            // Use the record() method to set up a recording.
            //tropo.Record(3, false, true, choices, AudioFormat.Wav, 10, 600, Method.Post, null, true, say, 15, trancription, null, "http://54.88.99.156:9080/FileUpload/uploadFile");
            tropo.Record(3, null, null, null, null, choices, say, AudioFormat.Wav, 10, 600, Method.Post, "whname", true, trancription, "http://54.88.99.156:9080/FileUpload/uploadFile", null, null, 15, 5, null, "none");
            tropo.On("continue", "TropoResult.aspx", new Say("This is a on say in record"));
            // Hangup when finished.
            //tropo.Hangup();

            HttpContext.Current.Trace.Warn("learn trace of dot net" + DateTime.Now.ToString());

            tropo.RenderJSON(Response);
        }
        private void ScrollToItem(TranscriptionElement elm)
        {
            if (_scrollViewer == null)
                return;

            listbox.SelectedItem = elm;
            listbox.ScrollIntoView(listbox.Items[listbox.SelectedIndex]);
            if (elm == Transcription.Last())
            {
                _scrollViewer.ScrollToBottom();
            }
            else
            {
                var all = listbox.VisualFindChildren<Element>();
                var visible = all.Where(itm => listbox.VisualIsVisibleChild(itm));

                Action scroll = new Action(() =>
                    {
                        all = listbox.VisualFindChildren<Element>();
                        visible = all.Where(itm => listbox.VisualIsVisibleChild(itm));
                        var element = all.First(itm => itm.ValueElement == elm);
                        var position = element.TransformToAncestor(_scrollViewer).Transform(new Point(0, element.ActualHeight));
                        _scrollViewer.ScrollToVerticalOffset(position.Y);
                        _scrollViewer.UpdateLayout();
                    });

                if (visible.Any(itm => itm.ValueElement == elm))
                    _scrollViewer.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, scroll);
            }
        }
Exemplo n.º 18
0
        public static List <Transcription> GetTranscriptions(String videoId)
        {
            String subtitleLink = GetTranscriptionLink(videoId);

            XmlDocument doc = new XmlDocument();

            doc.Load(subtitleLink);
            XmlNode root = doc.ChildNodes[1];

            List <Transcription> transcriptions = new List <Transcription>();

            if (root.HasChildNodes)
            {
                for (int i = 0; i < root.ChildNodes.Count; i++)
                {
                    String phrase = root.ChildNodes[i].InnerText;
                    phrase = HttpUtility.HtmlDecode(phrase);
                    Transcription transcription = new Transcription
                    {
                        StartTime = (int)Convert.ToDouble(root.ChildNodes[i].Attributes["start"].Value),
                        Phrase    = phrase
                    };
                    transcription.Add(transcription);
                }
            }
            return(transcriptions);
        }
Exemplo n.º 19
0
 public static void AddTranscription(DBContext context, Transcription transcription, string userId)
 {
     transcription.CreatedById        = userId;
     transcription.CreatedOn          = DateTime.Now;
     transcription.TranscriptionState = TranscriptionState.AwaitingApproval;
     context.Transcriptions.Add(transcription);
 }
Exemplo n.º 20
0
        public void ValidateSingleSymbolDnaReverseTranscribe()
        {
            // Get Node values from XML.
            string alphabetName = utilityObj.xmlUtil.GetTextValue(
                Constants.SimpleDnaAlphabetNode, Constants.AlphabetNameNode);
            string expectedSeq = utilityObj.xmlUtil.GetTextValue(
                Constants.TranscribeNode, Constants.DnaSymbol);
            string expectedTranscribe = utilityObj.xmlUtil.GetTextValue(
                Constants.TranscribeNode, Constants.DnaSymbolRevTranscribe);
            ISequence transcribe = null;

            var seq = new Sequence(Utility.GetAlphabet(alphabetName), expectedSeq);

            // Reverse Transcribe DNA Symbol.
            transcribe = Transcription.Transcribe(seq);

            ISequence revTranscribe = Transcription.ReverseTranscribe(transcribe);

            // Validate Single DNA Symbol Reverse transcribe.
            Assert.AreEqual(new string(revTranscribe.Select(a => (char)a).ToArray()), expectedTranscribe);
            ApplicationLog.WriteLine(string.Format(null,
                                                   "Translation P1: Reverse Transcribe {0} is expected.", revTranscribe));
            ApplicationLog.WriteLine(
                "Translation P1: Reverse Transcribe of Single DNA Symbol was validate successfully.");
        }
Exemplo n.º 21
0
        public async Task SaveAudioFileAsync(Stream stream, string boundary, long instanceId, long campaignId, long importNumber)
        {
            Transcription transcription = new Transcription();

            await transactionService.CommitAsync(new[] { TransactionContextScope.Main }, async() =>
            {
                using (var memoryStream = new MemoryStream())
                {
                    await stream.CopyToAsync(memoryStream);
                    transcription.AudioId = await labelingAudioService.SaveAudioFileAsync(memoryStream, boundary, instanceId, campaignId);
                    if (transcription.AudioId == 0)
                    {
                        return;
                    }

                    if (labelingModuleConfiguration.DeepSpeechControl.IsEnabled)
                    {
                        var result = await GetDeepSpeechTranscription(memoryStream, boundary);
                        transcription.DeepSpeechTranscription = result.Transcript;
                        transcription.MetricsId = await SaveTranscriptionMetrics(result.Score);
                    }

                    transcription.ImportNumber = importNumber == 0 ? null : (long?)importNumber;

                    await transcriptionRepository.AddAsync(transcription);
                    return;
                }
            });
        }
Exemplo n.º 22
0
        public string ObtenerTextoTranscripcionRealizada(int id, string login)
        {
            Transcription transcripcion   = ObtenerTranscripcionRealizada(id, login);
            string        textoTranscrito = ObtenerFicheroTranscritoTxt(transcripcion);

            return(textoTranscrito);
        }
Exemplo n.º 23
0
        public void ProcesarTranscripcion(Transcription transcripcion)
        {
            TipoEstadoTranscripcion nuevoEstadoTranscripcion = TipoEstadoTranscripcion.EN_PROGRESO;
            string mensajeError = "";

            try
            {
                string nombreFichero = ObtenerNombreFicheroMp3(transcripcion);

                Byte[] ficheroMp3 = ficherosResource.ObtenerFicheroMp3(nombreFichero);

                string textoTranscrito = new INVOXMedicalMock().TranscribirFicheroMp3(transcripcion.LoginUsuario, ficheroMp3);

                string nombreFicheroTranscrito = ObtenerNombreFicheroTranscritoTxt(transcripcion.Id);

                ficherosResource.GrabarFicheroTextoTranscrito(nombreFicheroTranscrito, textoTranscrito);

                nuevoEstadoTranscripcion = TipoEstadoTranscripcion.REALIZADA;
            }
            catch (Exception ex)
            {
                nuevoEstadoTranscripcion = TipoEstadoTranscripcion.ERROR;
                mensajeError             = ex.Message;

                logger.Error(ex, ex.Message);
            }
            finally
            {
                transcripcion.Estado = (int)nuevoEstadoTranscripcion;
                transcripcion.FechaHoraTranscripcion = DateTime.Now;
                transcripcion.MensajeError           = mensajeError;
                baseDatosResource.ActualizarTranscripcion(transcripcion);
            }
        }
Exemplo n.º 24
0
        public Transcription GetTranscription(bool useOrtoTP, bool removeNonPhonemes)
        {
            Transcription tr = new Transcription();

            GetTranscription(useOrtoTP, removeNonPhonemes, tr);
            return(tr);
        }
Exemplo n.º 25
0
        public Transcription ObtenerSiguienteTranscripcionPendiente()
        {
            bloqueo.EnterWriteLock();

            Transcription transcripcion = null;

            try
            {
                transcripcion = transcripciones
                                .FindAll(x => x.Estado == (int)TipoEstadoTranscripcion.PENDIENTE)
                                .OrderBy(x => x.FechaHoraRecepcion)
                                .FirstOrDefault();

                if (transcripcion != null)
                {
                    transcripcion.Estado = (int)TipoEstadoTranscripcion.EN_PROGRESO;
                }

                return(transcripcion);
            }
            finally
            {
                bloqueo.ExitWriteLock();
            }
        }
Exemplo n.º 26
0
        public async Task <ActionResult <Video> > PostVideo([FromBody] URLDTO data)
        {
            String videoURL;
            String videoId;
            Video  video;

            try
            {
                // Constructing the video object from our helper function
                videoURL = data.URL;
                videoId  = YouTubeHelper.GetVideoIdFromURL(videoURL);
                video    = YouTubeHelper.GetVideoInfo(videoId);
            } catch {
                return(BadRequest("Invalid YouTube URL"));
            }

            // Determine if we can get transcriptions from YouTube
            if (!YouTubeHelper.CanGetTranscriptions(videoId))
            {
                return(BadRequest("Subtitle does not exist on YouTube, failed to add video"));
            }

            if (VideoExists(video.VideoTitle))
            {
                return(BadRequest("Video already exists in the database"));
            }

            // Add this video object to the database
            _context.Video.Add(video);
            await _context.SaveChangesAsync();

            // Get the primary key of the newly created video record
            int id = video.VideoId;

            // This is needed because context are NOT thread safe, therefore we create another context for the following task.
            // We will be using this to insert transcriptions into the database on a seperate thread
            // So that it doesn't block the API.
            scriberContext           tempContext = new scriberContext();
            TranscriptionsController transcriptionsController = new TranscriptionsController(tempContext);

            // This will be executed in the background.
            Task addCaptions = Task.Run(async() =>
            {
                List <Transcription> transcriptions = new List <Transcription>();
                transcriptions = YouTubeHelper.GetTranscriptions(videoId);

                for (int i = 0; i < transcriptions.Count; i++)
                {
                    // Get the transcription objects form transcriptions and assign VideoId to id, the primary key of the newly inserted video
                    Transcription transcription = transcriptions.ElementAt(i);
                    transcription.VideoId       = id;
                    // Add this transcription to the database
                    await transcriptionsController.PostTranscription(transcription);
                }
            });

            // Return success code and the info on the video object
            return(CreatedAtAction("GetVideo", new { id = video.VideoId }, video));
        }
Exemplo n.º 27
0
        public async Task <ActionResult <Video> > PostVideo([FromBody] Urldto data)
        {
            String videoUrl;
            String youtubeId;
            Video  video;

            try
            {
                // Construct a video using YoutubeHelper's function
                videoUrl  = data.Url;
                youtubeId = YouTubeHelper.GetYouTubeIdFromUrl(videoUrl);
                video     = YouTubeHelper.GetVideoInfo(youtubeId);
            }
            catch
            {
                return(BadRequest("Invalid YouTube URL"));
            }

            // Determine whether its transcription is available on YouTube
            //if (!YouTubeHelper.CanGetTranscriptions(youtubeId))
            //{
            //    return BadRequest("Subtitle does not exist on YouTube, failed to add video");
            //}

            // Add this video to the database
            _context.Video.Add(video);
            await _context.SaveChangesAsync();

            // Get the primary key of the newly created video
            int id = video.VideoId;

            // Insert transcriptions into the database on using a different context
            //  GuessContext tempContext = new GuessContext();
            TranscriptionsController transcriptionsController = new TranscriptionsController(_context);
            //LeaderBoardsController lbController = new LeaderBoardsController(_context);

            // This will be executed in the background on a separate thread
            // Task addCaptions = Task.Run(async () =>
            //{
            List <Transcription> transcriptions = new List <Transcription>();

            transcriptions = YouTubeHelper.GetTranscriptions(youtubeId);

            for (int i = 0; i < transcriptions.Count; i++)
            {
                // Get the transcription objects form transcriptions
                Transcription transcription = transcriptions.ElementAt(i);
                //  Assign the transcription's VideoId to the id of the newly inserted video
                transcription.VideoId = id;
                transcription.Video   = video;
                // Add the transcription to the database
                await transcriptionsController.PostTranscription(transcription);
            }
            //});
            // await Task.Yield();

            // Return Video and a success code
            return(CreatedAtAction("GetVideo", new { id = video.VideoId }, video));
        }
Exemplo n.º 28
0
 private void CountErrorRates(ref Transcription transcription)
 {
     if (transcription.MetricsId.HasValue)
     {
         transcription.Metrics.WordErrorRate = StringDistance.CountWordErrorRate(transcription.AgentTranscription, transcription.DeepSpeechTranscription);
         transcription.Metrics.CharErrorRate = StringDistance.CountCharErrorRate(transcription.AgentTranscription, transcription.DeepSpeechTranscription);
     }
 }
Exemplo n.º 29
0
 public TranscripcionDTO(Transcription transcripcion)
 {
     this.Id                 = transcripcion.Id;
     this.FechaRecepcion     = transcripcion.FechaHoraRecepcion.ToShortDateString();
     this.NombreFicheroMp3   = transcripcion.NombreArchivo;
     this.Estado             = ((TipoEstadoTranscripcion)Enum.ToObject(typeof(TipoEstadoTranscripcion), transcripcion.Estado)).ToString();
     this.FechaTranscripcion = (transcripcion.FechaHoraTranscripcion != null) ? ((DateTime)transcripcion.FechaHoraTranscripcion).ToShortDateString() : "";
 }
        public async Task <ActionResult <Video> > PostVideo([FromBody] URLDTO data)
        {
            Video  video;
            String videoURL;
            String videoId;
            Video  checkVideo = await _videoRepository.GetVideoByURL(data.URL);

            if (checkVideo != null)
            {
                return(CreatedAtAction("GetVideo", new { id = checkVideo.VideoId }, checkVideo));
            }
            try
            {
                // Constructing the video object from our helper function
                videoURL = data.URL;
                videoId  = YouTubeHelper.GetVideoIdFromURL(videoURL);
                video    = YouTubeHelper.GetVideoInfo(videoId);
            }
            catch
            {
                return(BadRequest("Invalid YouTube URL"));
            }

            // Add this video object to the database
            await _videoRepository.AddVideo(video);

            // Get video for videoId
            Video newVideo = await _videoRepository.GetVideoByURL(data.URL);

            // Get the primary key of the newly created video record
            //video = _videoRepository.GetVideoByID
            int id = newVideo.VideoId;


            ITranscriptionsRepository transcriptionsRepository = new TranscriptionsRepository();
            TranscriptionsController  transcriptionsController = new TranscriptionsController(transcriptionsRepository);

            // This will be executed in the background.
            Task addCaptions = Task.Run(async() =>
            {
                // Get a list of captions from YouTubeHelper
                List <Transcription> transcriptions = new List <Transcription>();
                transcriptions = YouTubeHelper.GetTranscriptions(videoId);

                for (int i = 0; i < transcriptions.Count; i++)
                {
                    // Get the transcription objects form transcriptions and assign VideoId to id, the primary key of the newly inserted video
                    Transcription transcription = transcriptions.ElementAt(i);
                    transcription.VideoId       = id;
                    // Add this transcription to the database
                    await transcriptionsController.PostTranscription(transcription);
                }
            });

            // Return success code and the info on the video object
            return(CreatedAtAction("GetVideo", new { id = video.VideoId }, video));
        }
Exemplo n.º 31
0
 public static bool Import(Stream input, Transcription storage)
 {
     if (input is FileStream)
     {
         storage.Add(new TranscriptionParagraph());
         storage.MediaURI = ((FileStream)input).Name;
         return true;
     }
     return false;
 }
Exemplo n.º 32
0
        public static bool Export(Transcription data, Stream output)
        {
            bool exc = true;
            try
            {
                Transcription.SerializeV1(output, data, false);
            }
            catch
            {
                exc = false;
            }

            return exc;
        }
Exemplo n.º 33
0
        public static bool Import(Stream input, Transcription storage)
        {
            XDocument doc = XDocument.Load(input);
            var root = doc.Element("NanovoidSegmentation");

            var mediums = root.Elements("Medium").ToArray();

            XElement medium = null;
            if (mediums.Length > 1)
            {
                SelectFile sf = new SelectFile(mediums.Select(m => m.Attribute("url") != null ? Path.GetFileName(m.Attribute("url").Value) : "name not specified").ToList());
                sf.Title = "Select Medium";
                if (sf.ShowDialog() == true)
                {
                    medium = mediums[sf.SelectedIndex];
                }
                else return false;
            }
            else
                medium = mediums.First();

            var segmentations = medium.Elements("Segmentation").ToArray();

            XElement segmentation = null;
            if (segmentations.Length > 1)
            {
                var lst = segmentations.Select(s => string.Join(" ", s.Attributes().Select(a => a.Name + ":" + a.Value))).ToList();
                SelectFile sf = new SelectFile(lst);
                sf.Title = "Select segmentation";
                if (sf.ShowDialog() == true)
                {
                    segmentation = segmentations[sf.SelectedIndex];
                }
                else return false;
            }
            else
                segmentation = segmentations.First();

            TimeSpan unitlen = new TimeSpan((long)(TimeSpan.FromSeconds(1).Ticks * XmlConvert.ToDouble(segmentation.Attribute("tres").Value)));
            //segmentations.Elements("Segment");

            Transcription tr = storage;
            TranscriptionChapter ch = new TranscriptionChapter();
            ch.Text = segmentation.Attribute("type").Value;

            TranscriptionSection sec = new TranscriptionSection();
            sec.Text = segmentation.Attribute("label").Value;

            tr.MediaURI = medium.Attribute("url")!=null?medium.Attribute("url").Value:"";

            var idss = segmentation.Element("Identities");
            if (idss != null)
            {
                var ids = idss.Elements("Id");
                if (ids != null && ids.Count() > 0)
                {
                    var speakers = ids.Select(i => new Speaker() { ID = XmlConvert.ToInt32(i.Attribute("id").Value), Surname = i.Attribute("label").Value });
                    tr.Speakers = new SpeakerCollection(speakers);
                }
            }

            var segments = segmentation.Element("Segments").Elements("Segment");

            var paragraphs = MakeParagraphs(segments, unitlen);

            foreach (var p in paragraphs)
                sec.Add(p);

            ch.Add(sec);
            tr.Add(ch);

               tr.AssingSpeakersByID(); //added in newer version

            return true;
        }
Exemplo n.º 34
0
 public override void Revert(Transcription trans)
 {
     trans.RemoveAt(ChangeTranscriptionIndex);
 }
Exemplo n.º 35
0
 public abstract void Revert(Transcription trans);
Exemplo n.º 36
0
 public override void Revert(Transcription trans)
 {
     ((TranscriptionParagraph)trans[ChangeTranscriptionIndex]).Language = OldLanguage;
 }
Exemplo n.º 37
0
 public override void Revert(Transcription trans)
 {
     ((TranscriptionParagraph)trans[ChangeTranscriptionIndex]).DataAttributes = OldAttributes;
 }
Exemplo n.º 38
0
 public override void Revert(Transcription trans)
 {
     trans.Insert(ChangeTranscriptionIndex, ChangedElement);
 }
Exemplo n.º 39
0
 public override void Revert(Transcription trans)
 {
     ((TranscriptionParagraph)trans[ChangeTranscriptionIndex]).Speaker = OldSpeaker;
 }
Exemplo n.º 40
0
 public override void Revert(Transcription trans)
 {
     trans[ChangeTranscriptionIndex] = ChangedElement;
 }
Exemplo n.º 41
0
 public override void Revert(Transcription trans)
 {
     trans[ChangeTranscriptionIndex].Text = _oldtstring;
 }
Exemplo n.º 42
0
 public override void Revert(Transcription trans)
 {
     trans[ChangeTranscriptionIndex].Begin = Oldtime;
 }
Exemplo n.º 43
0
 public static bool Import(Stream input,Transcription storage)
 {
     Transcription.Deserialize(input,storage);
     return true;
 }
Exemplo n.º 44
0
        public void ExecuteExport(Transcription data, string destfile = null)
        {
            if (destfile == null)
            {
                SaveFileDialog sf = new SaveFileDialog();

                sf.CheckPathExists = true;
                sf.Filter = _mask;

                if (sf.ShowDialog() == true)
                {
                    destfile = sf.FileName;
                }

            }

            try
            {
                if (Isassembly)
                {
                    _exportDelegate.Invoke(data, File.Create(destfile));
                }
                else
                {
                    string tempFolder = FilePaths.TempDirectory;
                    string inputfile = System.IO.Path.Combine(tempFolder, System.IO.Path.GetRandomFileName()) + ".trsx";
                    string tempFile = destfile;

                    data.Serialize(inputfile, true);

                    ProcessStartInfo psi = new ProcessStartInfo();

                    psi.FileName = Path.Combine(FilePaths.GetReadPath(FilePaths.PluginsPath), _fileName);
                    psi.Arguments = string.Format(_parameters, "\"" + inputfile + "\"", "\"" + tempFile + "\"", "\"" + tempFolder + "\"");

                    Process p = new Process();
                    p.StartInfo = psi;

                    p.Start();
                    p.WaitForExit();
                    File.Delete(inputfile);
                }
            }
            catch
            {
                MessageBox.Show(Properties.Strings.MessageBoxExportError, Properties.Strings.MessageBoxErrorCaption, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }