/// <summary> /// Returns information about a transcription job. To see the status of the job, check /// the <code>Status</code> field. If the status is <code>COMPLETE</code>, the job is /// finished and you can find the results at the location specified in the <code>TranscriptionFileUri</code> /// field. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetTranscriptionJob service method.</param> /// /// <returns>The response from the GetTranscriptionJob 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.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> /// <exception cref="Amazon.TranscribeService.Model.NotFoundException"> /// We can't find the requested job. Check the job name and try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-2017-10-26/GetTranscriptionJob">REST API Reference for GetTranscriptionJob Operation</seealso> public virtual GetTranscriptionJobResponse GetTranscriptionJob(GetTranscriptionJobRequest request) { var marshaller = new GetTranscriptionJobRequestMarshaller(); var unmarshaller = GetTranscriptionJobResponseUnmarshaller.Instance; return(Invoke <GetTranscriptionJobRequest, GetTranscriptionJobResponse>(request, marshaller, unmarshaller)); }
/// <summary> /// Initiates the asynchronous execution of the GetTranscriptionJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetTranscriptionJob 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/GetTranscriptionJob">REST API Reference for GetTranscriptionJob Operation</seealso> public virtual Task <GetTranscriptionJobResponse> GetTranscriptionJobAsync(GetTranscriptionJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetTranscriptionJobRequestMarshaller(); var unmarshaller = GetTranscriptionJobResponseUnmarshaller.Instance; return(InvokeAsync <GetTranscriptionJobRequest, GetTranscriptionJobResponse>(request, marshaller, unmarshaller, cancellationToken)); }
/// <summary> /// Initiates the asynchronous execution of the GetTranscriptionJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetTranscriptionJob 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 EndGetTranscriptionJob /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-2017-10-26/GetTranscriptionJob">REST API Reference for GetTranscriptionJob Operation</seealso> public virtual IAsyncResult BeginGetTranscriptionJob(GetTranscriptionJobRequest request, AsyncCallback callback, object state) { var marshaller = GetTranscriptionJobRequestMarshaller.Instance; var unmarshaller = GetTranscriptionJobResponseUnmarshaller.Instance; return(BeginInvoke <GetTranscriptionJobRequest>(request, marshaller, unmarshaller, callback, state)); }
/// <summary> /// Initiates the asynchronous execution of the GetTranscriptionJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetTranscriptionJob 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/GetTranscriptionJob">REST API Reference for GetTranscriptionJob Operation</seealso> public virtual Task <GetTranscriptionJobResponse> GetTranscriptionJobAsync(GetTranscriptionJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetTranscriptionJobRequestMarshaller.Instance; options.ResponseUnmarshaller = GetTranscriptionJobResponseUnmarshaller.Instance; return(InvokeAsync <GetTranscriptionJobResponse>(request, options, cancellationToken)); }
/// <summary> /// Returns information about a transcription job. To see the status of the job, check /// the <code>TranscriptionJobStatus</code> field. If the status is <code>COMPLETED</code>, /// the job is finished and you can find the results at the location specified in the /// <code>TranscriptionFileUri</code> field. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetTranscriptionJob service method.</param> /// /// <returns>The response from the GetTranscriptionJob 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.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> /// <exception cref="Amazon.TranscribeService.Model.NotFoundException"> /// We can't find the requested resource. Check the name and try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-2017-10-26/GetTranscriptionJob">REST API Reference for GetTranscriptionJob Operation</seealso> public virtual GetTranscriptionJobResponse GetTranscriptionJob(GetTranscriptionJobRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetTranscriptionJobRequestMarshaller.Instance; options.ResponseUnmarshaller = GetTranscriptionJobResponseUnmarshaller.Instance; return(Invoke <GetTranscriptionJobResponse>(request, options)); }
/// <summary> /// Initiates the asynchronous execution of the GetTranscriptionJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetTranscriptionJob 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 EndGetTranscriptionJob /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-2017-10-26/GetTranscriptionJob">REST API Reference for GetTranscriptionJob Operation</seealso> public virtual IAsyncResult BeginGetTranscriptionJob(GetTranscriptionJobRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetTranscriptionJobRequestMarshaller.Instance; options.ResponseUnmarshaller = GetTranscriptionJobResponseUnmarshaller.Instance; return(BeginInvoke(request, options, callback, state)); }
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 } } }
private void HandleOutput(GetTranscriptionJobRequest request) { var waiterConfig = new WaiterConfiguration { MaxAttempts = MaxWaitAttempts, GetNextDelayInSeconds = (_) => WaitIntervalSeconds }; switch (ParameterSetName) { case LifecycleStateParamSet: response = client.Waiters.ForTranscriptionJob(request, waiterConfig, WaitForLifecycleState).Execute(); break; case Default: response = client.GetTranscriptionJob(request).GetAwaiter().GetResult(); break; } WriteOutput(response, response.TranscriptionJob); }
protected override void ProcessRecord() { base.ProcessRecord(); GetTranscriptionJobRequest request; try { request = new GetTranscriptionJobRequest { TranscriptionJobId = TranscriptionJobId, OpcRequestId = OpcRequestId }; HandleOutput(request); FinishProcessing(response); } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
public async Task <State> ProcessCompletedTranscribeJobsAsync(State state, ILambdaContext context) { var request = new GetTranscriptionJobRequest { TranscriptionJobName = state.TranscriptionJobName }; context.Logger.LogLine($"Processing transcription job completion: {state.TranscriptionJobName}"); var response = await this._transcribeClient.GetTranscriptionJobAsync(request); context.Logger.LogLine($"... Download transcript"); var transcript = await _httpClient.GetStringAsync(response.TranscriptionJob.Transcript.TranscriptFileUri); context.Logger.LogLine("... Uploading transcript to S3 bucket"); await _s3Client.PutObjectAsync(new PutObjectRequest { BucketName = Utilites.BUCKET, Key = Utilites.GetTranscriptKey(state.Id), ContentBody = transcript }); return(state); }
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); }
private async void BeginTranscription_Click(object sender, RoutedEventArgs e) { this._ctlBeginTranscription.IsEnabled = false; try { this._ctlStatusLog.Text = ""; this._ctlTranscription.Text = ""; var filepath = this._ctlFilepath.Text; if (string.IsNullOrEmpty(filepath)) { MessageBox.Show($"An mp4 file must be selected first before transcribing", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (!System.IO.File.Exists(filepath)) { MessageBox.Show($"File {filepath} does not exist", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } var s3Key = System.IO.Path.GetFileName(filepath); var s3Bucket = _ctlS3Bucket.Text; var chain = new CredentialProfileStoreChain(); AWSCredentials credentials; if (!chain.TryGetAWSCredentials(this._ctlProfile.Text, out credentials)) { MessageBox.Show($"Profile {this._ctlProfile.Text} was not found", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } var region = RegionEndpoint.GetBySystemName(this._ctlRegion.Text); var transcriptionJobName = $"{s3Key}-{Guid.NewGuid().ToString()}"; using (var s3Client = new AmazonS3Client(credentials, region)) using (var transcribeClient = new AmazonTranscribeServiceClient(credentials, region)) using (var httpClient = new HttpClient()) // Http Client to download the transcription once complete { AppendStatusLine("Ensuring S3 bucket exists"); await s3Client.PutBucketAsync(s3Bucket); var transferUtility = new TransferUtility(s3Client); AppendStatusLine("Starting upload"); var uploadRequest = new TransferUtilityUploadRequest { FilePath = filepath, BucketName = s3Bucket, Key = s3Key }; uploadRequest.UploadProgressEvent += ProgressUploadStatus; await transferUtility.UploadAsync(uploadRequest); var mediaFileUri = $"https://s3.{region.SystemName}.amazonaws.com/{s3Bucket}/{s3Key}"; AppendStatusLine($"Upload Complete to: {mediaFileUri}"); await transcribeClient.StartTranscriptionJobAsync(new StartTranscriptionJobRequest { LanguageCode = LanguageCode.EnUS, Media = new Media { MediaFileUri = mediaFileUri }, MediaFormat = MediaFormat.Mp4, TranscriptionJobName = transcriptionJobName }); AppendStatusLine($"Started transcription job: {transcriptionJobName}"); GetTranscriptionJobRequest request = new GetTranscriptionJobRequest { TranscriptionJobName = transcriptionJobName }; GetTranscriptionJobResponse response = null; do { AppendStatusLine($"... {DateTime.Now} Waiting for transcription job to complete"); await Task.Delay(TimeSpan.FromSeconds(2)); response = await transcribeClient.GetTranscriptionJobAsync(request); } while (response.TranscriptionJob.TranscriptionJobStatus == TranscriptionJobStatus.IN_PROGRESS); if (response.TranscriptionJob.TranscriptionJobStatus == TranscriptionJobStatus.FAILED) { AppendStatusLine($"Transcription job failed: {response.TranscriptionJob.FailureReason}"); return; } AppendStatusLine("Job Done"); var transcriptionDocument = await httpClient.GetStringAsync(response.TranscriptionJob.Transcript.TranscriptFileUri); var root = JsonConvert.DeserializeObject(transcriptionDocument) as JObject; var sb = new StringBuilder(); foreach (JObject transcriptionNode in root["results"]["transcripts"]) { if (sb.Length != 0) { sb.AppendLine("\n\n"); } sb.Append(transcriptionNode["transcript"]); } this._ctlTranscription.Text = sb.ToString(); } } catch (Exception ex) { AppendStatusLine($"Unknown error: {ex.Message}"); } finally { this._ctlBeginTranscription.IsEnabled = true; } }
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); } }