Informizely customer feedback surveys
By using the Aculab site, you agree with our use of cookies.

simple start transcription Sample

A simple inbound application that prompts the caller to say a few sentences. During the call, a local text file is written to that contains a transcription of the conversation.

Note, the results page is expected to respond with a status of 204 No Content.

Uses actions: Start Transcription, Play

    • {
          "actions" :
          [
              {
                  "start_transcription" :
                  {
                      "results_page" :
                      {
                          "url" : "TranscriptionResults",
                          "method" : "POST"
                      },
                      "id" : "0f705a8236c2b319.9834"
                  }
              }, 
              {
                  "play" :
                  {
                      "play_list" :
                      [
                          {
                              "text_to_say" : "Hello, this call is being transcribed. Please can you say the job title that you are applying for, and what interests you most about the position. Hang up when you have finished speaking."
                          }
                      ]
                  }
              }, 
              {
                  "sleep" :
                  {
                      "seconds" : 120
                  }
              }, 
              {
                  "play" : 
                  {
                      "play_list" : 
                      [
                          {
                              "text_to_say" : "Thank you, goodbye."
                          }
                      ]
                  }
              }
          ],
          "token": "my start transcription instance id",
          "api_version": "2.0"
      }
      
    • {
          [
          ],
          "token" : "Error for Action: xxxx  ActionIndex: xxxx  Result: xxxx"
      }
      
    • {
      }
      
    • Implementing this sample as an ASP.Net Web Form application:

      • // CSharp Wrapper sample for the Aculab Telephony REST API.
        //
        // Simple Start Transcription:
        // A simple application that starts a transcription, transcribing both inbound and outbound audio with
        // interim results, and then prompts the user for various spoken responses.
        
        using System;
        using System.Collections.Generic;
        using Aculab.Cloud.RestAPIWrapper;
        
        public partial class SimpleStartTranscription : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                // Unpack the request
                TelephonyRequest ourRequest = new TelephonyRequest(Request);
        
                // Setup the actions
                List<TelephonyAction> actions = new List<TelephonyAction>();
        
                // Start off the transcription
                // An id for this transcription, which is used by the results page to save the transcription to file
                var id = ourRequest.InstanceInfo.ApplicationInstanceId;
                var resultsPage = new WebPageRequest("TranscriptionResults.aspx");
                var startTranscriptionAction = new StartTranscription(resultsPage, id: id);
                actions.Add(startTranscriptionAction);
        
                // Start the conversation             
                var playAction = Play.SayText("Hello, this call is being transcribed. " +
                    "Please can you say the job title that you are applying for, and what interests " +
                    "you most about the position. Hang up when you have finished speaking.");
                actions.Add(playAction);
        
                // Wait for 2 minutes while audio is transcribed
                var sleepAction = new Sleep(120);
                actions.Add(sleepAction);
        
                // Note. A sleep is used here for simplicity. 
                // Instead, a record action could be started here that will terminate
                // after a period of silence.
                //
                // e.g. 
                // var recordAction = new Record()
                // {
                //     MillisecondsMaxSilence = 2000
                // };
                // actions.Add(recordAction);
        
                var lastPlay = Play.SayText("Thank you, goodbye.");
                actions.Add(lastPlay);
        
                // Respond
                String token = String.Format("my start transcription instance id");
                TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
                ourResponse.ToHttpResponse(Response);
            }
        }
        
        
      • // CSharp Wrapper sample for the Aculab Telephony REST API.
        //
        // Transcription Results:
        // A page that processes the results of a transcription and writes them to a file.
        
        using System;
        using System.Collections.Generic;
        using System.IO;
        using Aculab.Cloud.RestAPIWrapper;
        using System.Linq;
        using System.Net;
        
        public partial class TranscriptionResults : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                // Unpack the request
                TelephonyRequest ourRequest = new TelephonyRequest(Request);
                String token = ourRequest.InstanceInfo.Token;
                StartTranscriptionResult result = (StartTranscriptionResult)ourRequest.InstanceInfo.ActionResult;
        
                // Add your own code here to use the transcription result.
                // e.g. update a database, write to a log...
        
                // For now write it to a text file:
                string id = result.Id;
                string outputFolder = @"c:\test\RESTAPI\results";
                string outputFilename = string.Format(@"{0}\Transcription_{1}.txt", outputFolder, id);
        
                if (!Directory.Exists(outputFolder))
                {
                    Directory.CreateDirectory(outputFolder);
                }
        
                List<string> lines;
        
                // Format transcription results to show interim results, but replace them with the final result
                if (File.Exists(outputFilename))
                {
                    // Remove any interims results
                    lines = File.ReadAllLines(outputFilename).ToList();
                    lines = lines.Where(line => !line.StartsWith("---")).ToList();
                }
                else
                {
                    lines = new List<string>();
                }
                foreach (Phrase phrase in result.Transcription)
                {
                    if (phrase.Final)
                    {
                        switch (phrase.Direction)
                        {
                            case AudioDirection.Inbound:
                                lines.Add(string.Format("     caller: {0}", phrase.Alternatives[0].Text));
                                break;
                            case AudioDirection.Outbound:
                                lines.Add(string.Format("  agent:  {0}", phrase.Alternatives[0].Text));
                                break;
                            default:
                                lines.Add(string.Format("        : {0}", phrase.Alternatives[0].Text));
                                break;
                        }
                    }
                    else
                    {
                        lines.Add("---" + phrase.Alternatives[0].Text);
                    }
                }
                if (result.Completed)
                {
                    lines.Add("TRANSCRIPTION COMPLETED!");
                }
        
                // Alternative code that just formats raw transcription results
                /***
                lines.Add(string.Format("Result: Id {0}", result.Id));
                if (result.Completed)
                {
                    lines.Add(string.Format("Completed {0}", result.Completed));
                }
                foreach (Phrase phrase in result.Transcription)
                {
                    lines.Add(string.Format("Phrase:"));
                    var speech = phrase.Alternatives[0];
                    lines.Add(string.Format("  Alternative[0]: {0}", speech.Text));
                    lines.Add(string.Format("  Direction: {0}", phrase.Direction));
                    lines.Add(string.Format("  Final: {0}", phrase.Final));
                }
                ***/
        
                File.WriteAllLines(outputFilename, lines);
        
                Response.StatusCode = (int)HttpStatusCode.NoContent;
            }
        }
        
        
      • using System;
        using Aculab.Cloud.RestAPIWrapper;
        
        public partial class ErrorPage : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                // Unpack the request
                TelephonyRequest ourRequest = new TelephonyRequest(Request);
                ErrorResult result = ourRequest.InstanceInfo.ErrorResult;
        
                String token = String.Format("Action: {0}\nActionIndex: {1}\nResult: {2}",
                    result.Action, result.ActionIndex, result.Result);
        
                // Respond
                TelephonyResponse ourResponse = new TelephonyResponse(null, token);
                ourResponse.ToHttpResponse(Response);
            }
        }
        
        
      • using System;
        using Aculab.Cloud.RestAPIWrapper;
        
        public partial class FinalPage : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                // Unpack the request
                TelephonyRequest ourRequest = new TelephonyRequest(Request);
            }
        }
        
        
    • Implementing this sample as an ASP.Net Mvc application:

      • // ASP.NET Core MVC CSharp Wrapper sample for the Aculab Telephony REST API.
        //
        // Simple Start Transcription:
        // The first page of a simple application that prompts the caller to say a few sentences, transcribes the audio 
        // and writes the transcription results to a text file.
        // This acknowledges the end of audio being transcribed.
        using System;
        using System.Linq;
        using System.Collections.Generic;
        using Microsoft.AspNetCore.Mvc;
        using Aculab.Cloud.RestAPIWrapper;
        using System.IO;
        using System.Net;
        
        namespace Aculab.Cloud.RESTAPI.NETCoreCSharpSamples.Controllers
        {
            [Route("SimpleStartTranscription")]
            public class StartTranscriptionController : RESTSampleController
            {
                // Process the GET or POST request, set up the actions and construct the json response.
                [Route("FirstPage")]
                [HttpGet]
                [HttpPost]
                [ProducesResponseType(200)]
                [ProducesResponseType(400)]
                [ProducesResponseType(500)]
                public IActionResult SimpleStartTranscription()
                {
                    try
                    {
                        // Unpack the request
                        var telephonyRequest = new TelephonyRequest(Request);
        
                        // Setup the actions
                        List<TelephonyAction> actions = new List<TelephonyAction>();
        
                        // Start off the transcription
                        // An id for this transcription, which is used by the results page to save the transcription to file
                        var id = telephonyRequest.InstanceInfo.ApplicationInstanceId;
                        var resultsPage = new WebPageRequest("SimpleStartTranscription/TranscriptionResults");
                        var startTranscriptionAction = new StartTranscription(resultsPage, id: id);
                        actions.Add(startTranscriptionAction);
        
                        // Start the conversation             
                        var playAction = Play.SayText("Hello, this call is being transcribed. " +
                            "Please can you say the job title that you are applying for, and what interests " +
                            "you most about the position. Hang up when you have finished speaking.");
                        actions.Add(playAction);
        
                        // Wait for 2 minutes while audio is transcribed
                        var sleepAction = new Sleep(120);
                        actions.Add(sleepAction);
        
                        // Note. A sleep is used here for simplicity. 
                        // Instead, a record action could be started here that will terminate
                        // after a period of silence.
                        //
                        // e.g. 
                        // var recordAction = new Record()
                        // {
                        //     MillisecondsMaxSilence = 2000
                        // };
                        // actions.Add(recordAction);
        
                        var lastPlay = Play.SayText("Thank you, goodbye.");
                        actions.Add(lastPlay);
        
                        // Respond
                        String token = String.Format("my start transcription instance id");
                        TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
                        return ourResponse.ToJson(this);
                    }
                    catch (ArgumentException)
                    {
                        return BadRequest();
                    }
                    catch (Exception e)
                    {
                        return StatusCode((int)HttpStatusCode.InternalServerError, e.Message);
                    }
                }
        
                // Process the GET or POST request, extract the transcription results and write to a file
                [Route("TranscriptionResults")]
                [HttpGet]
                [HttpPost]
                [ProducesResponseType(200)]
                [ProducesResponseType(400)]
                [ProducesResponseType(500)]
                public IActionResult TranscriptionResults()
                {
                    // Unpack the request
                    var telephonyRequest = new TelephonyRequest(Request);
                    String token = telephonyRequest.InstanceInfo.Token;
                    StartTranscriptionResult result = (StartTranscriptionResult)telephonyRequest.InstanceInfo.ActionResult;
        
                    // Add your own code here to use the transcription result.
                    // e.g. update a database, write to a log...
        
                    // For now write it to a text file:
                    string id = result.Id;
                    string outputFolder = @"c:\test\RESTAPI\results";
                    string outputFilename = string.Format(@"{0}\Transcription_{1}.txt", outputFolder, id);
        
                    if (!Directory.Exists(outputFolder))
                    {
                        Directory.CreateDirectory(outputFolder);
                    }
        
                    // Try and make the output more meaningful
                    List<string> lines;
        
                    // Format transcription results to show interim results, but replace them with the final result
                    if (System.IO.File.Exists(outputFilename))
                    {
                        // Remove any interims results
                        lines = System.IO.File.ReadAllLines(outputFilename).ToList();
                        lines = lines.Where(line => !line.StartsWith("---")).ToList();
                    }
                    else
                    {
                        lines = new List<string>();
                    }
                    foreach (Phrase phrase in result.Transcription)
                    {
                        if (phrase.Final)
                        {
                            switch (phrase.Direction)
                            {
                                case AudioDirection.Inbound:
                                    lines.Add(string.Format("     caller: {0}", phrase.Alternatives[0].Text));
                                    break;
                                case AudioDirection.Outbound:
                                    lines.Add(string.Format("  agent:  {0}", phrase.Alternatives[0].Text));
                                    break;
                                default:
                                    lines.Add(string.Format("        : {0}", phrase.Alternatives[0].Text));
                                    break;
                            }
                        }
                        else
                        {
                            lines.Add("---" + phrase.Alternatives[0].Text);
                        }
                    }
                    if (result.Completed)
                    {
                        lines.Add("TRANSCRIPTION COMPLETED!");
                    }
        
                    // Alternative code that just formats raw transcription results
                    /***
                    lines.Add(string.Format("Result: Id {0}", result.Id));
                    if (result.Completed)
                    {
                        lines.Add(string.Format("Completed {0}", result.Completed));
                    }
                    foreach (Phrase phrase in result.Transcription)
                    {
                        lines.Add(string.Format("Phrase:"));
                        var speech = phrase.Alternatives[0];
                        lines.Add(string.Format("  Alternative[0]: {0}", speech.Text));
                        lines.Add(string.Format("  Direction: {0}", phrase.Direction));
                        lines.Add(string.Format("  Final: {0}", phrase.Final));
                    }
                    ***/
        
                    System.IO.File.WriteAllLines(outputFilename, lines);
        
                    return StatusCode((int)HttpStatusCode.NoContent);
                }
            }
        }
        
      • // ASP.NET Core MVC CSharp Wrapper sample for the Aculab Telephony REST API.
        //
        // Simple Start Transcription:
        // The first page of a simple application that prompts the caller to say a few sentences, transcribes the audio 
        // and writes the transcription results to a text file.
        // This acknowledges the end of audio being transcribed.
        using System;
        using System.Linq;
        using System.Collections.Generic;
        using Microsoft.AspNetCore.Mvc;
        using Aculab.Cloud.RestAPIWrapper;
        using System.IO;
        using System.Net;
        
        namespace Aculab.Cloud.RESTAPI.NETCoreCSharpSamples.Controllers
        }
        
      • // ASP.NET Core CSharp Wrapper sample for the Aculab Telephony REST API.
        
        using System;
        using Microsoft.AspNetCore.Mvc;
        using Aculab.Cloud.RestAPIWrapper;
        using System.Net;
        
        namespace Aculab.Cloud.RESTAPI.NETCoreCSharpSamples.Controllers
        {
            public class RESTSampleController : Controller
            {
                // Process the GET or POST request for the Error condition
                [Route("ErrorPage")]
                [HttpGet]
                [HttpPost]
                [ProducesResponseType(200)]
                [ProducesResponseType(400)]
                [ProducesResponseType(500)]
                public IActionResult ErrorPage()
                {
                    try
                    {
                        // Unpack the request
                        var telephonyRequest = new TelephonyRequest(Request);
                        ErrorResult result = telephonyRequest.InstanceInfo.ErrorResult;
        
                        String token = String.Format("Action: {0}\nActionIndex: {1}\nResult: {2}",
                            result.Action, result.ActionIndex, result.Result);
        
                        // Create response
                        TelephonyResponse ourResponse = new TelephonyResponse(null, token);
                        return ourResponse.ToJson(this);
                    }
                    catch (ArgumentException)
                    {
                        return BadRequest();
                    }
                    catch (Exception e)
                    {
                        return StatusCode((int)HttpStatusCode.InternalServerError, e.Message);
                    }
                }
            }
        }
        
      • // ASP.NET Core CSharp Wrapper sample for the Aculab Telephony REST API.
        
        using System;
        using Microsoft.AspNetCore.Mvc;
        using Aculab.Cloud.RestAPIWrapper;
        using System.Net;
        
        namespace Aculab.Cloud.RESTAPI.NETCoreCSharpSamples.Controllers
        {
            public class RESTSampleController : Controller
            {
                // Process the GET or POST request for the Final Page
                [Route("FinalPage")]
                [HttpGet]
                [HttpPost]
                [ProducesResponseType(200)]
                [ProducesResponseType(400)]
                [ProducesResponseType(500)]
                public IActionResult FinalPage()
                {
                    try
                    {
                        // Unpack the request
                        var telephonyRequest = new TelephonyRequest(Request);
                        String token = telephonyRequest.InstanceInfo.Token;
        
                        // Create response
                        // Only very limited actions can be returned here
                        TelephonyResponse ourResponse = new TelephonyResponse(null, token);
                        return ourResponse.ToJson(this);
                    }
                    catch (ArgumentException)
                    {
                        return BadRequest();
                    }
                    catch (Exception e)
                    {
                        return StatusCode((int)HttpStatusCode.InternalServerError, e.Message);
                    }
                }
            }
        }
        
  • Implemented as an ASP.Net Web Form:

    • ' Visual Basic Wrapper sample for the Aculab Telephony REST API.
      '
      ' Simple Transcription
      ' A simple application that prompts the user to say someting And then starts a transcription And then waits for 5 seconds of consecutive silence.
      Imports System.Collections.Generic
      Imports Aculab.Cloud.RestAPIWrapper
      
      Partial Class SimpleStartTranscription
          Inherits System.Web.UI.Page
      
          Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      
              ' Unpack the request
              Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
      
              ' Setup the actions
              Dim actions As List(Of TelephonyAction) = New List(Of TelephonyAction)
      
              ' Start off the transcription
              ' An id for this transcription, which Is used by the results page to save the transcription to file
              Dim id As String = ourRequest.InstanceInfo.ApplicationInstanceId
              Dim resultsPage As WebPageRequest = New WebPageRequest("TranscriptionResults.aspx")
              Dim startTranscriptionAction As StartTranscription = New StartTranscription(resultsPage, id:=id)
              actions.Add(startTranscriptionAction)
      
              ' Start the conversation             
              Dim playAction As Play = Play.SayText("Hello, this call is being transcribed. " +
                  "Please can you say the job title that you are applying for, and what interests " +
                  "you most about the position. Hang up when you have finished speaking.")
              actions.Add(playAction)
      
              ' Wait for 2 minutes while audio Is transcribed
              Dim sleepAction As Sleep = New Sleep(120)
              actions.Add(sleepAction)
      
              ' Note. A sleep Is used here for simplicity. 
              ' Instead, a record action could be started here that will terminate
              ' after a period of silence.
              '
              ' e.g. 
              ' Dim recordAction As Record = New Record(recordResultPage) With
              ' {
              '     .MillisecondsMaxSilence = 2000
              ' }
              ' actions.Add(recordAction)
      
              Dim lastPlay As Play = Play.SayText("Thank you, goodbye.")
              actions.Add(lastPlay)
      
              ' Respond
              Dim token As String = String.Format("my start transcription instance id")
              Dim ourResponse As TelephonyResponse = New TelephonyResponse(actions, token)
              ourResponse.ToHttpResponse(Response)
          End Sub
      End Class
      
      
    • ' Visual Basic Wrapper sample for the Aculab Telephony REST API.
      '
      ' Transcription Results:
      ' A page that processes the results of a transcription And writes them to a file.
      
      Imports System.Collections.Generic
      Imports System.Net
      Imports System.IO
      Imports System.Linq
      Imports Aculab.Cloud.RestAPIWrapper
      
      Partial Class TranscriptionResults
          Inherits System.Web.UI.Page
      
          Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      
              ' Unpack the request
              Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
              Dim token As String = ourRequest.InstanceInfo.Token
              Dim result As StartTranscriptionResult = ourRequest.InstanceInfo.ActionResult
      
              ' Add your own code here to use the transcription result.
              ' e.g. update a database, write to a log...
      
              ' For now write it to a text file:
              Dim id As String = result.Id
              Dim outputFolder As String = "c:\test\RESTAPI\results"
              Dim outputFilename As String = String.Format("{0}\Transcription_{1}.txt", outputFolder, id)
      
              If Not Directory.Exists(outputFolder) Then
                  Directory.CreateDirectory(outputFolder)
              End If
      
              Dim lines As List(Of String)
      
              ' Format transcription results to show interim results, but replace them with the final result
              If File.Exists(outputFilename) Then
                  ' Remove any interims results
                  lines = File.ReadAllLines(outputFilename).ToList()
                  lines = lines.Where(Function(line) Not line.StartsWith("---")).ToList()
              Else
                  lines = New List(Of String)
              End If
      
              For Each phrase As Phrase In result.Transcription
                  If phrase.Final Then
                      Select Case phrase.Direction
                          Case AudioDirection.Inbound
                              lines.Add(String.Format("     caller: {0}", phrase.Alternatives(0).Text))
                          Case AudioDirection.Outbound
                              lines.Add(String.Format("  agent:  {0}", phrase.Alternatives(0).Text))
                          Case Else
                              lines.Add(String.Format("        : {0}", phrase.Alternatives(0).Text))
                      End Select
                  Else
                      lines.Add("---" + phrase.Alternatives(0).Text)
                  End If
              Next
      
              If result.Completed Then
                  lines.Add("TRANSCRIPTION COMPLETED!")
              End If
      
              'Alternative code that just formats raw transcription results
              '
              'lines.Add(string.Format("Result: Id {0}", result.Id))
              'if result.Completed Then
              '    lines.Add(string.Format("Completed {0}", result.Completed))
              'End If
              'For Each phrase As Phrase In result.Transcription
              '    lines.Add(string.Format("Phrase:"))
              '    var speech = phrase.Alternatives(0)
              '    lines.Add(string.Format("  Alternative(0): {0}", speech.Text))
              '    lines.Add(string.Format("  Direction: {0}", phrase.Direction))
              '    lines.Add(string.Format("  Final: {0}", phrase.Final))
              'Next
      
              File.WriteAllLines(outputFilename, lines)
      
              Response.StatusCode = HttpStatusCode.NoContent
          End Sub
      End Class
      
      
    • ' Visual Basic Wrapper sample for the Aculab Telephony REST API.
      '
      ' A generic error page for all the samples.
      Imports Aculab.Cloud.RestAPIWrapper
      
      Partial Class ErrorPage
          Inherits System.Web.UI.Page
      
          Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      
              ' Unpack the request
              Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
              Dim result As ErrorResult = ourRequest.InstanceInfo.ErrorResult
      
              Dim token As String = String.Format("Action: {0}\nActionIndex: {1}\nResult: {2}", _
                  result.Action, result.ActionIndex, result.Result)
      
              ' Respond
              Dim ourResponse As TelephonyResponse = New TelephonyResponse(token)
              ourResponse.ToHttpResponse(Response)
          End Sub
      End Class
      
      
    • ' Visual Basic Wrapper sample for the Aculab Telephony REST API.
      '
      ' A generic final page for all the samples:
      Imports Aculab.Cloud.RestAPIWrapper
      
      Partial Class FinalPage
          Inherits System.Web.UI.Page
      
          Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      
              ' Unpack the request
              Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
      
              ' Do application tidying up
              ' ...
          End Sub
      End Class
      
      
  • Implemented as Java Servlets:

    • // Java Servlet sample for the Aculab Telephony REST API.
      //
      // Simple Play Encrypted:
      // A simple application that says some text and then plays a wav file to an answered inbound call.
      
      package com.aculab.telephonyrestapi.samples;
      
      import javax.servlet.http.*;
      import javax.servlet.ServletException;
      import java.io.IOException;
      import java.util.ArrayList;
      import java.util.List;
      
      import com.aculab.telephonyrestapi.*;
      
      public class SimpleStartTranscription extends HttpServlet
      {
          private static final long serialVersionUID = -3906337692740787588L;
      
          @Override
          public void doGet(HttpServletRequest request,
                            HttpServletResponse response)
              throws IOException, ServletException
          {
             	handleRequest(request, response);
          }
          
          @Override
          public void doPost(HttpServletRequest request,
                  HttpServletResponse response)
                          throws IOException, ServletException
          {
          	handleRequest(request, response);
          }
          
          private void handleRequest(HttpServletRequest request,
                                     HttpServletResponse response) throws IOException
          {
              // Unpack the request
              TelephonyRequest ourRequest = new TelephonyRequest(request);
      
              String callFrom = ourRequest.getInstanceInfo().getThisCall().getCallFrom();
              String app_inst_id = ourRequest.getInstanceInfo().getApplicationInstanceId();
      
              // Create the actions
              StartTranscription startTranscriptionAction = new StartTranscription(new WebPageRequest("TranscriptionResults"));
              startTranscriptionAction.setId(app_inst_id);
              Play hello_message = Play.sayText("Hello, this call is being transcribed. Please can you say the job title that you are applying for, and what interests you most about the position. Hang up when you have finished speaking.");
              Play goodbye_message = Play.sayText("Thank you, goodbye.");
      
              // Place the actions in a list
              List<TelephonyAction> actions = new ArrayList<TelephonyAction>();
              actions.add(startTranscriptionAction);
              actions.add(hello_message);
              actions.add(new Sleep(120)); // End the call after 2 minutes
              actions.add(goodbye_message);
      
              // Note. Rather than force call termination after 2 minutes, this
              // sample could be improved so that the call ends when the
              // caller finishes speaking (This can be achieved using the Record
              // action to terminate the call after detecting period of silence).
              // This improvement was deliberately not implemented to keep this
              // sample as simple as possible.
      
              // Respond
              String token = String.format("my start transcription instance id");
              TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
              ourResponse.setHttpServletResponse(response);
          }
      }
      
      
    • package com.aculab.telephonyrestapi.samples;
      
      import javax.servlet.http.*;
      
      import javax.servlet.ServletException;
      
      import java.io.BufferedWriter;
      import java.io.File;
      import java.io.FileWriter;
      import java.io.IOException;
      import java.nio.charset.Charset;
      import java.nio.file.Files;
      import java.util.ArrayList;
      import java.util.LinkedHashMap;
      import java.util.List;
      import java.util.Map.Entry;
      
      import com.aculab.telephonyrestapi.*;
      
      public class TranscriptionResults extends HttpServlet
      {
      	private static final long serialVersionUID = -6948346570255777073L;
      
      	@Override
          public void doGet(HttpServletRequest request,
                            HttpServletResponse response)
              throws IOException, ServletException
          {
             	handleRequest(request, response);
          }
          
          @Override
          public void doPost(HttpServletRequest request,
                  HttpServletResponse response)
                          throws IOException, ServletException
          {
          	handleRequest(request, response);
          }
          
          private void handleRequest(HttpServletRequest request,
                                     HttpServletResponse response) throws IOException
          {
              // Unpack the request
              TelephonyRequest ourRequest = new TelephonyRequest(request);
      
              // Get the result of the get input action
              StartTranscriptionResult result = (StartTranscriptionResult)ourRequest.getInstanceInfo().getActionResult();
              
              List<Phrase> phrases = result.getTranscription();
              String id = result.getId();
              String interim_prefix = "[interim]";
              
              // Find out the location of the temporary directory
              File temp = File.createTempFile("temp-file", ".tmp");
              String absolutePath = temp.getAbsolutePath();
              String tempFilePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator) + 1);
              temp.delete();
              
              List<String> transcription_entries = new ArrayList<>();
                      
              // Create the filename
      	    String filename = tempFilePath + "transcription_results_" + id + ".txt";
      	    
      	    // If the file already exists, copy the previous transcription data apart from
      	    // the interim data. 
      	    File fh = new File(filename);
              if (fh.exists())
              {
                  List<String> messageLines;
                  messageLines = Files.readAllLines(fh.toPath(), Charset.defaultCharset());
                  
                  for(String line : messageLines)
                  {
                  	if (!line.startsWith(interim_prefix))
                  	{
                  		line = line.replace(System.getProperty("line.separator"), "");
                  		line = line.trim();
                  		if (line.length() > 0)
                  		{
                  			transcription_entries.add(line);
                  		}
                  	}
                  }
              }
      
              //Append the new transcription data
              for (Phrase phrase : phrases)
              {
      	        String direction = phrase.getDirection();
      	        List<Speech> alternatives = phrase.getAlternatives();
      	        String prefix_string = "";
      
      	        if (direction == null)
      	        {
      	        	direction = "mixed";
      	        }
      
      	        if (phrase.getFinal() == false)
      	        {
      	            prefix_string += interim_prefix + " ";
      	        }
      	        prefix_string += "[" + direction + "]";
      
                  for (Speech alternative : alternatives)
                  {
                      transcription_entries.add(prefix_string + " " + alternative.getText());
                  }
              }
      
      	    // Copy the updated transcription to file (If the file already exists it will be
              // cleared and overwritten).
              //Example of what the file content may look like:
              //   [inbound] Hello, how are you
              //   [interim] [outbound] I'm nine tanks
              //   [interim] [outbound] I'm fine thanks
              BufferedWriter writer = new BufferedWriter(new FileWriter(filename, false)); //overwrites file
      
              for (String transcription_entry : transcription_entries)
              {
                  writer.write(transcription_entry);
                  writer.newLine();
              }
              writer.close();
      
              // Respond
              response.setStatus(HttpServletResponse.SC_NO_CONTENT);
          }
      }
      
      
    • // Java Servlet sample for the Aculab Telephony REST API.
      //
      
      package com.aculab.telephonyrestapi.samples;
      
      import javax.servlet.http.*;
      import javax.servlet.ServletException;
      import java.io.IOException;
      import java.util.ArrayList;
      import java.util.List;
      
      import com.aculab.telephonyrestapi.*;
      
      public class ErrorPage extends HttpServlet
      {
          private static final long serialVersionUID = -4842873371047361437L;
      
          @Override
          public void doGet(HttpServletRequest request,
                            HttpServletResponse response)
              throws IOException, ServletException
          {
             	handleRequest(request, response);
          }
          
          @Override
          public void doPost(HttpServletRequest request,
                  HttpServletResponse response)
                          throws IOException, ServletException
          {
          	handleRequest(request, response);
          }
          
          private void handleRequest(HttpServletRequest request,
                                     HttpServletResponse response) throws IOException
          {
              // Unpack the request
              TelephonyRequest ourRequest = new TelephonyRequest(request);
      
              ErrorResult result = ourRequest.getInstanceInfo().getErrorResult();
      
              String token = String.format("Action: %s\nActionIndex: %d\nResult: %s", result.getAction(), result.getActionIndex(), result.getResult());
              
              // Respond
              List<TelephonyAction> actions = new ArrayList<TelephonyAction>();
              TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
              ourResponse.setHttpServletResponse(response);
          }
      }
      
      
    • // Java Servlet sample for the Aculab Telephony REST API.
      //
      
      package com.aculab.telephonyrestapi.samples;
      
      import javax.servlet.http.*;
      import javax.servlet.ServletException;
      import java.io.IOException;
      import com.aculab.telephonyrestapi.*;
      
      public class FinalPage extends HttpServlet
      {
          private static final long serialVersionUID = 5940620014313056844L;
      
          @Override
          public void doGet(HttpServletRequest request,
                            HttpServletResponse response)
              throws IOException, ServletException
          {
             	handleRequest(request, response);
          }
          
          @Override
          public void doPost(HttpServletRequest request,
                  HttpServletResponse response)
                          throws IOException, ServletException
          {
          	handleRequest(request, response);
          }
          
          private void handleRequest(HttpServletRequest request,
                                     HttpServletResponse response) throws IOException
          {
              // Unpack the request
              TelephonyRequest ourRequest = new TelephonyRequest(request);
          }
      }
      
      
  • Implemented as a Flask web application:

    • @app.route('/SimpleStartTranscription', methods=['GET','POST'])
      def handle_SimpleStartTranscription():
      
          my_request = TelephonyRequest(request)
          app_inst_id = my_request.get_application_instance_id()
          print("SimpleStartTranscription: app_inst_id='{}'".format(app_inst_id))
      
          start_transcription_action = StartTranscription(WebPage(url='TranscriptionResults'))
          start_transcription_action.set_id(app_inst_id)
      
          list_of_actions = []
          list_of_actions.append(start_transcription_action)
          list_of_actions.append(Play(text_to_say='Hello, this call is being transcribed. Please can you say the job title that you are applying for, and what interests you most about the position. Hang up when you have finished speaking.'))
          list_of_actions.append(Sleep(120)) # End the call after 2 minutes
          list_of_actions.append(Play(text_to_say='Thank you, goodbye.'))
          
          # Note. Rather than force call termination after 2 minutes, this
          # sample could be improved so that the call ends when the
          # caller finishes speaking (This can be achieved using the Record
          # action to terminate the call after detecting period of silence).
          # This improvement was deliberately not implemented to keep this
          # sample as simple as possible.
          
          my_response = TelephonyResponse(list_of_actions, token='my start transcription instance id')
          
          return my_response.get_json()
      
      
    • @app.route('/TranscriptionResults', methods=['GET','POST'])
      def handle_TranscriptionResults():
      
          my_request = TelephonyRequest(request)
          action_result = my_request.get_action_result()
      
          transcription_result = action_result.get('result')
      
          phrases = transcription_result.get('transcription')
          id = transcription_result.get('id')
      
          interim_prefix = "[interim]"
      
          # Create the filename
          filename = tempfile.gettempdir() + "/transcription_results_" + id + ".txt"
      
          # If the file already exists, copy the previous transcription data apart from
          # the omit interim data.
          transcription_entries = []
          if os.path.isfile(filename):
              fh = open(filename, "r")
              for x in fh:
                  if not x.startswith(interim_prefix):
                      transcription_entries.append(x.rstrip())
              fh.close()
      
          # Append the new transcription data
          for phrase in phrases:
              direction = phrase.get('direction', 'mixed')
              alternatives = phrase.get('alternatives', []) 
      
              prefix_string = ""
              
              if phrase.get('final') == False:
                  prefix_string += interim_prefix + " "
                  
              prefix_string += "[" + direction + "]"
              
              for alternative in alternatives:
                  transcription_entries.append(prefix_string + " " + alternative.get('text'))
      
          # Copy the updated transcription to file (If the file already exists it will be cleared and overwritten)
          #   Example of what the file content may look like:
          #      [inbound] Hello, how are you
          #      [interim] [outbound] I'm nine tanks
          #      [interim] [outbound] I'm fine thanks
          fh = open(filename, "w")
          fh.write("\n".join(transcription_entries))
      
          # Return 'No content' Http Response code
          empty_json = '{}'.encode('utf-8')
          return empty_json, 204
      
    • @app.route('/ErrorPage', methods=['GET','POST'])
      def handle_ErrorPage():
          
          my_request = TelephonyRequest(request)
          token = my_request.get_token()
          app_inst_id = my_request.get_application_instance_id()
          error_result_dict = my_request.get_error_result()
          action_string = error_result_dict.get('action', "?")
          result_string = error_result_dict.get('result', "?")
          print("ErrorPage: app_inst_id='{}' token='{}' action='{}' result='{}'".format(app_inst_id, token, action_string, result_string))
          
          my_response = TelephonyResponse([Play(text_to_say='An error has occurred')])
          return my_response.get_json()
      
      
    • @app.route('/FinalPage', methods=['GET','POST'])
      def handle_FinalPage():
          # The FinalPage handler follows the guidelines on:
          # https://www.aculab.com/cloud/voice-and-fax-apis/rest-api/rest-api-version-2/writing-a-rest-application
          # The guidelines are:
          #   "Your final page should return an empty response, a 204 is preferable, but empty JSON is acceptable."
          my_request = TelephonyRequest(request)
          token = my_request.get_token()
          app_inst_id = my_request.get_application_instance_id()
          print("FinalPage: app_inst_id='{}' token='{}'".format(app_inst_id, token))
          empty_json = '{}'.encode('utf-8')
          return empty_json, 204
          
      
    • <?php
      header("Content-Type: application/json; charset=UTF-8");
      
      require __DIR__ . "/../../autoload.php";
      
      use \Aculab\TelephonyRestAPI\Play;
      use \Aculab\TelephonyRestAPI\Response;
      use \Aculab\TelephonyRestAPI\Sleep;
      use \Aculab\TelephonyRestAPI\StartTranscription;
      use \Aculab\TelephonyRestAPI\WebPageRequest;
      use \Aculab\TelephonyRestAPI\InstanceInfo;
      
      $info = InstanceInfo::getInstanceInfo();
      
      $response = new Response();
      $response->setToken('my start transcription instance id');
      
      $start = new StartTranscription(new WebPageRequest('TranscriptionResults.php', 'POST'));
      $start->setID($info->getApplicationInstanceId());
      
      $response->addAction($start);
      
      $play = new Play();
      $play->addText('Hello, this call is being transcribed. Please can you say the job title that you are applying for, and what interests you most about the position. Hang up when you have finished speaking.');
      $response->addAction($play);
      
      $response->addAction(new Sleep(120));
      
      $response->addAction(Play::sayText('Thank you, goodbye.'));
      
      print $response;
      
      
    • <?php
      require __DIR__ . "/../../autoload.php";
      use Aculab\TelephonyRestAPI\InstanceInfo;
      
      header("Content-Type: application/json; charset=UTF-8");
      http_response_code(204);
      
      $info = InstanceInfo::getInstanceInfo();
      
      $transcriptionResult = $info->getActionResult();
      
      $result = "";
      /* for each phrase, log the first speech alternative returned */
      foreach ($transcriptionResult->getTranscription() as $phrase) {
          $dir = $phrase->getDirection();
          $alternatives = $phrase->getAlternatives();
          $speech = array_shift($alternatives);
          if ($speech) {
              $text = $speech->getText();
              $confidence = $speech->getConfidence();
              $result .= "Direction: $dir, Text: $text, Confidence: $confidence" . PHP_EOL;
          }
      }
      
      if ($transcriptionResult->getCompleted()) {
          $result .= "Transcription completed" . PHP_EOL;
      }
      
      $result_file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "transcription_results_" . $transcriptionResult->getID() . ".txt";
      $f = fopen($result_file, "a");
      fwrite($f, $result);
      fclose($f);
      
      
    • <?php
      header("Content-Type: application/json; charset=UTF-8");
      
      require __DIR__ . "/../../autoload.php";
      
      use Aculab\TelephonyRestAPI\Play;
      use Aculab\TelephonyRestAPI\Response;
      use Aculab\TelephonyRestAPI\InstanceInfo;
      
      $info = InstanceInfo::getInstanceInfo();
      
      $error = $info->getErrorResult();
      $action = $error->getAction();
      $desc = $error->getResult();
      if (!is_null($action)) {
          error_log("Error from action \"$action\" with result:" . PHP_EOL . "$desc" . PHP_EOL);
      } else {
          error_log("Error result:" . PHP_EOL . "$desc" . PHP_EOL);
      }
      
      $response = new Response();
      $response->setToken('Error');
      
      $play = new Play();
      $play->addText('An error has occurred.');
      $response->addAction($play);
      
      print $response;
      
      
    • <?php
      require __DIR__ . "/../../autoload.php";
      
      http_response_code(204);
      header("Content-Type: application/json; charset=UTF-8");
      
      use Aculab\TelephonyRestAPI\InstanceInfo;
      
      $info = InstanceInfo::getInstanceInfo();
      $call = $info->getThisCallInfo();
      $callid = $call->getCallId();
      $duration = $call->getSecondsCallDuration();
      error_log("This call id: $callid" . PHP_EOL . "This call duration: $duration" . PHP_EOL);