public async Task ExecuteAsync(WorkerJobHelper <AIJob> jobHelper)
        {
            S3Locator inputFile;

            if (!jobHelper.JobInput.TryGet <S3Locator>(nameof(inputFile), out inputFile))
            {
                throw new Exception("Invalid or missing input file.");
            }

            string mediaFileUrl;

            if (!string.IsNullOrWhiteSpace(inputFile.HttpEndpoint))
            {
                mediaFileUrl = inputFile.HttpEndpoint;
            }
            else
            {
                var bucketLocation = await inputFile.GetBucketLocationAsync();

                var s3SubDomain = !string.IsNullOrWhiteSpace(bucketLocation) ? $"s3-{bucketLocation}" : "s3";
                mediaFileUrl = $"https://{s3SubDomain}.amazonaws.com/{inputFile.AwsS3Bucket}/{inputFile.AwsS3Key}";
            }

            string mediaFormat;

            if (mediaFileUrl.EndsWith("mp3", StringComparison.OrdinalIgnoreCase))
            {
                mediaFormat = "mp3";
            }
            else if (mediaFileUrl.EndsWith("mp4", StringComparison.OrdinalIgnoreCase))
            {
                mediaFormat = "mp4";
            }
            else if (mediaFileUrl.EndsWith("wav", StringComparison.OrdinalIgnoreCase))
            {
                mediaFormat = "wav";
            }
            else if (mediaFileUrl.EndsWith("flac", StringComparison.OrdinalIgnoreCase))
            {
                mediaFormat = "flac";
            }
            else
            {
                throw new Exception($"Unable to determine media format from input file '{mediaFileUrl}'");
            }

            var transcribeParameters = new StartTranscriptionJobRequest
            {
                TranscriptionJobName = "TranscriptionJob-" + jobHelper.JobAssignmentId.Substring(jobHelper.JobAssignmentId.LastIndexOf("/") + 1),
                LanguageCode         = "en-US",
                Media = new Media {
                    MediaFileUri = mediaFileUrl
                },
                MediaFormat      = mediaFormat,
                OutputBucketName = jobHelper.Request.GetRequiredContextVariable("ServiceOutputBucket")
            };

            using (var transcribeService = new AmazonTranscribeServiceClient())
                await transcribeService.StartTranscriptionJobAsync(transcribeParameters);
        }
Esempio n. 2
0
        /// <summary>
        /// Starts an asynchronous job to transcribe speech to text.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the StartTranscriptionJob service method.</param>
        ///
        /// <returns>The response from the StartTranscriptionJob service method, as returned by TranscribeService.</returns>
        /// <exception cref="Amazon.TranscribeService.Model.BadRequestException">
        /// There is a problem with one of the input fields. Check the S3 bucket name, make sure
        /// that the job name is not a duplicate, and confirm that you are using the correct file
        /// format. Then resend your request.
        /// </exception>
        /// <exception cref="Amazon.TranscribeService.Model.ConflictException">
        /// The <code>JobName</code> field is a duplicate of a previously entered job name. Resend
        /// your request with a different name.
        /// </exception>
        /// <exception cref="Amazon.TranscribeService.Model.InternalFailureException">
        /// There was an internal error. Check the error message and try your request again.
        /// </exception>
        /// <exception cref="Amazon.TranscribeService.Model.LimitExceededException">
        /// Either you have sent too many requests or your input file is longer than 2 hours.
        /// Wait before you resend your request, or use a smaller file and resend the request.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-2017-10-26/StartTranscriptionJob">REST API Reference for StartTranscriptionJob Operation</seealso>
        public virtual StartTranscriptionJobResponse StartTranscriptionJob(StartTranscriptionJobRequest request)
        {
            var marshaller   = new StartTranscriptionJobRequestMarshaller();
            var unmarshaller = StartTranscriptionJobResponseUnmarshaller.Instance;

            return(Invoke <StartTranscriptionJobRequest, StartTranscriptionJobResponse>(request, marshaller, unmarshaller));
        }
        /// <summary>
        /// Initiates the asynchronous execution of the StartTranscriptionJob operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the StartTranscriptionJob operation on AmazonTranscribeServiceClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartTranscriptionJob
        ///         operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-2017-10-26/StartTranscriptionJob">REST API Reference for StartTranscriptionJob Operation</seealso>
        public virtual IAsyncResult BeginStartTranscriptionJob(StartTranscriptionJobRequest request, AsyncCallback callback, object state)
        {
            var marshaller   = StartTranscriptionJobRequestMarshaller.Instance;
            var unmarshaller = StartTranscriptionJobResponseUnmarshaller.Instance;

            return(BeginInvoke <StartTranscriptionJobRequest>(request, marshaller, unmarshaller,
                                                              callback, state));
        }
        /// <summary>
        /// Starts an asynchronous job to transcribe speech to text.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the StartTranscriptionJob service method.</param>
        ///
        /// <returns>The response from the StartTranscriptionJob service method, as returned by TranscribeService.</returns>
        /// <exception cref="Amazon.TranscribeService.Model.BadRequestException">
        /// Your request didn't pass one or more validation tests. For example, if the transcription
        /// you're trying to delete doesn't exist or if it is in a non-terminal state (for example,
        /// it's "in progress"). See the exception <code>Message</code> field for more information.
        /// </exception>
        /// <exception cref="Amazon.TranscribeService.Model.ConflictException">
        /// When you are using the <code>StartTranscriptionJob</code> operation, the <code>JobName</code>
        /// field is a duplicate of a previously entered job name. Resend your request with a
        /// different name.
        ///
        ///
        /// <para>
        /// When you are using the <code>UpdateVocabulary</code> operation, there are two jobs
        /// running at the same time. Resend the second request later.
        /// </para>
        /// </exception>
        /// <exception cref="Amazon.TranscribeService.Model.InternalFailureException">
        /// There was an internal error. Check the error message and try your request again.
        /// </exception>
        /// <exception cref="Amazon.TranscribeService.Model.LimitExceededException">
        /// Either you have sent too many requests or your input file is too long. Wait before
        /// you resend your request, or use a smaller file and resend the request.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-2017-10-26/StartTranscriptionJob">REST API Reference for StartTranscriptionJob Operation</seealso>
        public virtual StartTranscriptionJobResponse StartTranscriptionJob(StartTranscriptionJobRequest request)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = StartTranscriptionJobRequestMarshaller.Instance;
            options.ResponseUnmarshaller = StartTranscriptionJobResponseUnmarshaller.Instance;

            return(Invoke <StartTranscriptionJobResponse>(request, options));
        }
        /// <summary>
        /// Initiates the asynchronous execution of the StartTranscriptionJob operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the StartTranscriptionJob operation on AmazonTranscribeServiceClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartTranscriptionJob
        ///         operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-2017-10-26/StartTranscriptionJob">REST API Reference for StartTranscriptionJob Operation</seealso>
        public virtual IAsyncResult BeginStartTranscriptionJob(StartTranscriptionJobRequest request, AsyncCallback callback, object state)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = StartTranscriptionJobRequestMarshaller.Instance;
            options.ResponseUnmarshaller = StartTranscriptionJobResponseUnmarshaller.Instance;

            return(BeginInvoke(request, options, callback, state));
        }
Esempio n. 6
0
        private async Task ProcessTranscribe(string bucket, string key)
        {
            Settings settings = new Settings();

            settings.ShowSpeakerLabels = true;
            settings.MaxSpeakerLabels  = 2;
            settings.VocabularyName    = "Vocab";

            Media media = new Media();

            media.MediaFileUri = string.Format("https://s3.us-east-2.amazonaws.com/{0}/{1}", bucket, key);
            CancellationToken token = new CancellationToken();


            StartTranscriptionJobRequest startRequest = new StartTranscriptionJobRequest();

            startRequest.LanguageCode         = LanguageCode.EnUS;
            startRequest.Settings             = settings;
            startRequest.Media                = media;
            startRequest.MediaFormat          = MediaFormat.Mp3;
            startRequest.TranscriptionJobName = Guid.NewGuid().ToString();

            StartTranscriptionJobResponse response = await transClient.StartTranscriptionJobAsync(startRequest, token);


            GetTranscriptionJobRequest request = new GetTranscriptionJobRequest();

            request.TranscriptionJobName = startRequest.TranscriptionJobName;

            bool isComplete = false;

            while (!isComplete)
            {
                GetTranscriptionJobResponse response2 = await transClient.GetTranscriptionJobAsync(request);

                if (response2.TranscriptionJob.TranscriptionJobStatus == TranscriptionJobStatus.COMPLETED)
                {
                    //we need to DL the file to S3
                    isComplete = true;

                    WriteFileToS3(response2.TranscriptionJob.Transcript.TranscriptFileUri, startRequest.TranscriptionJobName);
                }
                else if (response2.TranscriptionJob.TranscriptionJobStatus == TranscriptionJobStatus.FAILED)
                {
                    isComplete = true;
                    //need to log the error.
                }
                else
                {
                    System.Threading.Thread.Sleep(5000);//wait 5 seconds and check again
                    //not done yet
                }
            }
        }
Esempio n. 7
0
        public async Task <State> StartTranscribeAsync(State state, ILambdaContext context)
        {
            context.Logger.LogLine($"Starting transcribe {state.VideoName}, S3 location {state.S3Url}");
            var request = new StartTranscriptionJobRequest
            {
                TranscriptionJobName = $"{state.VideoName.Replace(" ", "")}-{Guid.NewGuid().ToString()}",
                LanguageCode         = LanguageCode.EnUS,
                MediaFormat          = MediaFormat.Mp4,
                Media = new Media
                {
                    MediaFileUri = state.S3Url
                }
            };

            var response = await _transcribeClient.StartTranscriptionJobAsync(request);

            state.TranscriptionJobName = request.TranscriptionJobName;
            context.Logger.LogLine($"Transcribe initiated, job name: {response.TranscriptionJob.TranscriptionJobName}");
            return(state);
        }
        private async Task <TranscriptionJob> StartTranscriptionJob(string jobName, string mediaFileUri, string fileExt)
        {
            var transcriptionRequest = new StartTranscriptionJobRequest()
            {
                LanguageCode = "en-US",
                Media        = new Media()
                {
                    MediaFileUri = mediaFileUri
                },
                MediaFormat          = fileExt,
                TranscriptionJobName = jobName,
                Settings             = new Settings()
                {
                    MaxSpeakerLabels  = MAX_SPEAKER_LABELS,
                    ShowSpeakerLabels = true
                },
            };

            Console.WriteLine($"Start Transcription job: {DateTime.Now}");
            var getTranscribeResponse = await config.AzTranscribeClient.StartTranscriptionJobAsync(transcriptionRequest);

            return(getTranscribeResponse?.TranscriptionJob);
        }
Esempio n. 9
0
        public async Task <SpeechRecognitionResult> ParseSpeectToText(string[] args)
        {
            if (string.IsNullOrEmpty(args[0]))
            {
                return(null);
            }

            var uploadDetails = await _amazonUploaderService.UploadBase64Wav(args[0]);

            if (string.IsNullOrEmpty(uploadDetails.FileRoute))
            {
                return(null);
            }

            var transciptionJobName = "Transcribe_" + uploadDetails.FileRoute;
            var request             = new StartTranscriptionJobRequest()
            {
                Media = new Media()
                {
                    MediaFileUri = "https://s3." + uploadDetails.BucketRegion + ".amazonaws.com/" + uploadDetails.BucketName + "/" + uploadDetails.FileRoute
                },
                LanguageCode         = new LanguageCode(LanguageCode.EnUS),
                MediaFormat          = new MediaFormat("Wav"),
                TranscriptionJobName = transciptionJobName
            };

            try
            {
                var res = await _amazonTranscribeService.StartTranscriptionJobAsync(request);

                var jobComplete = false;
                GetTranscriptionJobResponse jobRes = null;
                while (!jobComplete)
                {
                    jobRes = await _amazonTranscribeService.GetTranscriptionJobAsync(new GetTranscriptionJobRequest()
                    {
                        TranscriptionJobName = transciptionJobName
                    });

                    if (jobRes != null && jobRes.TranscriptionJob.TranscriptionJobStatus !=
                        TranscriptionJobStatus.COMPLETED)
                    {
                        System.Threading.Thread.Sleep(5000);
                    }
                    else
                    {
                        jobComplete = true;
                    }
                }

                var jsonRes = "";
                using (var client = _httpProxyClientService.CreateHttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var response = client
                                   .GetAsync(jobRes.TranscriptionJob.Transcript.TranscriptFileUri).Result;

                    if (!response.IsSuccessStatusCode)
                    {
                        return(null);
                    }
                    jsonRes = response.Content.ReadAsStringAsync().Result;
                }

                // Once done delete the file
                await _amazonUploaderService.DeleteFile(uploadDetails.FileRoute);

                return(new SpeechRecognitionResult()
                {
                    StatusCode = 200,
                    JSONResult = jsonRes
                });
            }
            catch (AmazonTranscribeServiceException ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }

            return(null);
        }
        /// <summary>
        /// Initiates the asynchronous execution of the StartTranscriptionJob operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the StartTranscriptionJob operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-2017-10-26/StartTranscriptionJob">REST API Reference for StartTranscriptionJob Operation</seealso>
        public virtual Task <StartTranscriptionJobResponse> StartTranscriptionJobAsync(StartTranscriptionJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = StartTranscriptionJobRequestMarshaller.Instance;
            options.ResponseUnmarshaller = StartTranscriptionJobResponseUnmarshaller.Instance;

            return(InvokeAsync <StartTranscriptionJobResponse>(request, options, cancellationToken));
        }
Esempio n. 11
0
        internal static async Task ProcessJobAssignmentAsync(AwsAiServiceWorkerRequest @event)
        {
            var resourceManager = @event.GetAwsV4ResourceManager();
            var table           = new DynamoDbTable(@event.StageVariables["TableName"]);
            var jobAssignmentId = @event.JobAssignmentId;

            try
            {
                // 1. Setting job assignment status to RUNNING
                await UpdateJobAssignmentStatusAsync(resourceManager, table, jobAssignmentId, "RUNNING", null);

                // 2. Retrieving WorkflowJob
                var job = await RetrieveJobAsync(resourceManager, table, jobAssignmentId);

                // 3. Retrieve JobProfile
                var jobProfile = await RetrieveJobProfileAsync(resourceManager, job);

                // 4. Retrieve job inputParameters
                var jobInput = job.JobInput;

                // 5. Check if we support jobProfile and if we have required parameters in jobInput
                ValidateJobProfile(jobProfile, jobInput);

                S3Locator inputFile;
                if (!jobInput.TryGet <S3Locator>(nameof(inputFile), out inputFile))
                {
                    throw new Exception("Invalid or missing input file.");
                }

                S3Locator outputLocation;
                if (!jobInput.TryGet <S3Locator>(nameof(outputLocation), out outputLocation))
                {
                    throw new Exception("Invalid or missing output location.");
                }

                switch (jobProfile.Name)
                {
                case JOB_PROFILE_TRANSCRIBE_AUDIO:
                    string mediaFileUrl;
                    if (!string.IsNullOrWhiteSpace(inputFile.HttpEndpoint))
                    {
                        mediaFileUrl = inputFile.HttpEndpoint;
                    }
                    else
                    {
                        var bucketLocation = await inputFile.GetBucketLocationAsync();

                        var s3SubDomain = !string.IsNullOrWhiteSpace(bucketLocation) ? $"s3-{bucketLocation}" : "s3";
                        mediaFileUrl = $"https://{s3SubDomain}.amazonaws.com/{inputFile.AwsS3Bucket}/{inputFile.AwsS3Key}";
                    }

                    string mediaFormat;
                    if (mediaFileUrl.EndsWith("mp3", StringComparison.OrdinalIgnoreCase))
                    {
                        mediaFormat = "mp3";
                    }
                    else if (mediaFileUrl.EndsWith("mp4", StringComparison.OrdinalIgnoreCase))
                    {
                        mediaFormat = "mp4";
                    }
                    else if (mediaFileUrl.EndsWith("wav", StringComparison.OrdinalIgnoreCase))
                    {
                        mediaFormat = "wav";
                    }
                    else if (mediaFileUrl.EndsWith("flac", StringComparison.OrdinalIgnoreCase))
                    {
                        mediaFormat = "flac";
                    }
                    else
                    {
                        throw new Exception($"Unable to determine media format from input file '{mediaFileUrl}'");
                    }

                    var transcribeParameters = new StartTranscriptionJobRequest
                    {
                        TranscriptionJobName = "TranscriptionJob-" + jobAssignmentId.Substring(jobAssignmentId.LastIndexOf("/") + 1),
                        LanguageCode         = "en-US",
                        Media = new Media {
                            MediaFileUri = mediaFileUrl
                        },
                        MediaFormat      = mediaFormat,
                        OutputBucketName = @event.StageVariables["ServiceOutputBucket"]
                    };

                    var transcribeService = new AmazonTranscribeServiceClient();

                    var startJobResponse = await transcribeService.StartTranscriptionJobAsync(transcribeParameters);

                    Logger.Debug(startJobResponse.ToMcmaJson().ToString());
                    break;

                case JOB_PROFILE_TRANSLATE_TEXT:
                    var s3Bucket = inputFile.AwsS3Bucket;
                    var s3Key    = inputFile.AwsS3Key;

                    GetObjectResponse s3Object;
                    try
                    {
                        s3Object = await inputFile.GetAsync();
                    }
                    catch (Exception error)
                    {
                        throw new Exception($"Unable to read file in bucket '{s3Bucket}' with key '{s3Key}'.", error);
                    }

                    var inputText = await new StreamReader(s3Object.ResponseStream).ReadToEndAsync();

                    var translateParameters = new TranslateTextRequest
                    {
                        SourceLanguageCode = jobInput.TryGet("sourceLanguageCode", out string srcLanguageCode) ? srcLanguageCode : "auto",
                        TargetLanguageCode = jobInput.Get <string>("targetLanguageCode"),
                        Text = inputText
                    };

                    var translateService  = new AmazonTranslateClient();
                    var translateResponse = await translateService.TranslateTextAsync(translateParameters);

                    var s3Params = new PutObjectRequest
                    {
                        BucketName  = outputLocation.AwsS3Bucket,
                        Key         = (!string.IsNullOrWhiteSpace(outputLocation.AwsS3KeyPrefix) ? outputLocation.AwsS3Key : string.Empty) + Guid.NewGuid() + ".txt",
                        ContentBody = translateResponse.TranslatedText
                    };

                    var outputS3 = await outputLocation.GetClientAsync();

                    await outputS3.PutObjectAsync(s3Params);

                    var jobOutput = new JobParameterBag();
                    jobOutput["outputFile"] = new S3Locator
                    {
                        AwsS3Bucket = s3Params.BucketName,
                        AwsS3Key    = s3Params.Key
                    };

                    Logger.Debug("Updating job assignment");
                    await UpdateJobAssignmentWithOutputAsync(table, jobAssignmentId, jobOutput);
                    await UpdateJobAssignmentStatusAsync(resourceManager, table, jobAssignmentId, "COMPLETED");

                    break;

                case JOB_PROFILE_DETECT_CELEBRITIES:
                    var randomBytes = new byte[16];
                    new Random().NextBytes(randomBytes);
                    var clientToken = randomBytes.HexEncode();

                    var base64JobId = Encoding.UTF8.GetBytes(jobAssignmentId).HexEncode();

                    var rekoParams = new StartCelebrityRecognitionRequest
                    {
                        Video = new Video
                        {
                            S3Object = new Amazon.Rekognition.Model.S3Object
                            {
                                Bucket = inputFile.AwsS3Bucket,
                                Name   = inputFile.AwsS3Key
                            }
                        },
                        ClientRequestToken  = clientToken,
                        JobTag              = base64JobId,
                        NotificationChannel = new NotificationChannel
                        {
                            RoleArn     = REKO_SNS_ROLE_ARN,
                            SNSTopicArn = SNS_TOPIC_ARN
                        }
                    };

                    var rekognitionClient             = new AmazonRekognitionClient();
                    var startCelebRecognitionResponse = await rekognitionClient.StartCelebrityRecognitionAsync(rekoParams);

                    Logger.Debug(startCelebRecognitionResponse.ToMcmaJson().ToString());
                    break;
                }
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);

                try
                {
                    await UpdateJobAssignmentStatusAsync(resourceManager, table, jobAssignmentId, "FAILED", ex.ToString());
                }
                catch (Exception innerEx)
                {
                    Logger.Exception(innerEx);
                }
            }
        }
Esempio n. 12
0
        public string GetTranscriptURL()
        {
            string result = string.Empty;

            try
            {
                AmazonTranscribeServiceClient client = new AmazonTranscribeServiceClient(ConfigurationManager.AppSettings["AmazonAccessKey"],
                                                                                         ConfigurationManager.AppSettings["AmazonSecretAccessKey"],
                                                                                         RegionEndpoint.EUWest1);

                if (client != null)
                {
                    string url = String.Format(ConfigurationManager.AppSettings["AmazonBucketURL"],
                                               ConfigurationManager.AppSettings["AmazonBucketName"],
                                               keyName);

                    Media media = new Media();
                    StartTranscriptionJobResponse transcriptionJobResponse = null;
                    GetTranscriptionJobResponse   checkJob = null;

                    media.MediaFileUri = url;



                    StartTranscriptionJobRequest transcriptionJobRequest = new StartTranscriptionJobRequest();
                    string name = Guid.NewGuid().ToString();
                    transcriptionJobRequest.TranscriptionJobName = name;
                    transcriptionJobRequest.MediaFormat          = "wav";
                    transcriptionJobRequest.Media        = media;
                    transcriptionJobRequest.LanguageCode = "en-US";

                    GetTranscriptionJobRequest getTranscriptionJobRequest = new GetTranscriptionJobRequest();
                    getTranscriptionJobRequest.TranscriptionJobName = name;

                    bool finished = false;
                    transcriptionJobResponse = client.StartTranscriptionJob(transcriptionJobRequest);

                    while (!finished)
                    {
                        checkJob = client.GetTranscriptionJob(getTranscriptionJobRequest);

                        if (checkJob != null)
                        {
                            if (!checkJob.TranscriptionJob.TranscriptionJobStatus.Value.Contains("IN_PROGRESS"))
                            {
                                finished = true;
                            }

                            Thread.Sleep(1000);
                        }
                    }


                    result = checkJob.TranscriptionJob.Transcript.TranscriptFileUri;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(result);
        }
Esempio n. 13
0
        private async Task Transcribe(string filePath)
        {
            var   fileNameWithExtension = Path.GetFileName(filePath);
            var   hash      = (DateTime.Now.Ticks);
            var   jobName   = "Test_" + fileNameWithExtension + "_" + hash;
            var   bucketref = "https://s3." + _bucketRegion + ".amazonaws.com/" + _bucketName + "/" + fileNameWithExtension;
            Media fileref   = new Media {
                MediaFileUri = bucketref
            };
            var fileInfoContainer = CheckValidityAndReturnFileInfo(filePath).GetEnumerator();

            fileInfoContainer.MoveNext();
            var filetype = fileInfoContainer.Current.Key;
            var bitrate  = fileInfoContainer.Current.Value;

            //TODO standardize a way to define / figure out the file properties
            var request = new StartTranscriptionJobRequest
            {
                TranscriptionJobName = jobName,
                LanguageCode         = "en-US",
                MediaSampleRateHertz = bitrate,
                MediaFormat          = filetype,
                Media = fileref
            };

            //initial request to service
            await _atClient.StartTranscriptionJobAsync(request);

            //generate polling request to check in on service
            var pollingreq = new GetTranscriptionJobRequest
            {
                TranscriptionJobName = request.TranscriptionJobName
            };

            //status of request
            string status;

            do
            {
                //check the request
                var step = await _atClient.GetTranscriptionJobAsync(pollingreq);

                //generate new status
                status = step.TranscriptionJob.TranscriptionJobStatus.Value;
                //sleep for 5 seconds before trying again
                Thread.Sleep(10000);
                //check if the transcription job failed for any reason
                if (status == "FAILED")
                {
                    Environment.Exit(0);
                }
            } while (status != "COMPLETED"); //run until complete

            //Check the request one more time to get final updated info
            var final = await _atClient.GetTranscriptionJobAsync(pollingreq);

            //Generate an Http client to use to GET the JSON data from the URI
            using (var temp = new HttpClient())
            {
                var location = final.TranscriptionJob.Transcript.TranscriptFileUri;
                var msg      = await temp.GetAsync(location);

                var responseBody = await msg.Content.ReadAsStringAsync();

                //Newtonsoft Parsing body
                var data  = JObject.Parse(responseBody);
                var query = (string)data["results"]["transcripts"][0]["transcript"];

                if (!Directory.Exists(TranscriptDestination))
                {
                    Directory.CreateDirectory(TranscriptDestination);
                }

                if (File.Exists(TranscriptDestination + "aws_" + Path.GetFileNameWithoutExtension(filePath) + ".txt"))
                {
                    File.Delete(TranscriptDestination + "aws_" + Path.GetFileNameWithoutExtension(filePath) + ".txt");
                }
                File.WriteAllText((TranscriptDestination + "aws_" + Path.GetFileNameWithoutExtension(filePath) + ".txt"), query);
            }
        }
        public async static Task <string> TranscribeDemo(IAmazonTranscribeService transcribeClient, string lauguageCode, string mediaUri)
        {
            string result = null;
            Media  media  = new Media()
            {
                MediaFileUri = mediaUri
            };

            StartTranscriptionJobRequest transcriptionRequest = new StartTranscriptionJobRequest()
            {
                TranscriptionJobName = DateTime.Now.Millisecond.ToString(),
                Media            = media,
                MediaFormat      = MediaFormat.Wav.ToString(),
                LanguageCode     = lauguageCode,
                OutputBucketName = "reinvent-indiamazones"
            };

            try
            {
                Task <StartTranscriptionJobResponse> transcriptionTask     = transcribeClient.StartTranscriptionJobAsync(transcriptionRequest);
                StartTranscriptionJobResponse        transcriptionResponse = await transcriptionTask;
                TranscriptionJob transcriptionJob = transcriptionResponse.TranscriptionJob;

                bool loop = true;
                while (loop == true)
                {
                    if (transcriptionResponse.TranscriptionJob.TranscriptionJobStatus == TranscriptionJobStatus.IN_PROGRESS)
                    {
                        Console.WriteLine(transcriptionResponse.TranscriptionJob.TranscriptionJobName);
                        Console.WriteLine(transcriptionResponse.TranscriptionJob.TranscriptionJobStatus);
                        if (transcriptionResponse.TranscriptionJob.Transcript != null)
                        {
                            Console.WriteLine(transcriptionResponse.TranscriptionJob.Transcript.TranscriptFileUri);
                        }
                        Thread.Sleep(3000);
                    }
                    else if (transcriptionResponse.TranscriptionJob.TranscriptionJobStatus == TranscriptionJobStatus.COMPLETED)
                    {
                        Console.Write("Transcription job completed.");
                        DateTime completionTime = transcriptionJob.CompletionTime;
                        result = transcriptionJob.Transcript.TranscriptFileUri;

                        loop = false;
                    }
                    else
                    {
                        Console.WriteLine(transcriptionResponse.TranscriptionJob.TranscriptionJobStatus);
                        result = string.Empty;

                        loop = false;
                    }
                }

                result = transcriptionResponse.TranscriptionJob.Transcript.TranscriptFileUri;
            }
            catch (AmazonTranscribeServiceException transcribeException)
            {
                Console.WriteLine(transcribeException.Message, transcribeException.InnerException);
            }

            return(result);
        }