// thinkbeforecoding

Speaking computers for more fun !

I didn't try it on mono, but it should also work with some tweaking, see details here

Xmas is a good time to surprise kids, and what's more fun than a talking computer ?!

Hello world !

Nothing's easier, and this kind of Hello World will appeal them to programming in a flash :

#r "System.Speech"
open System.Speech.Synthesis

let synt = new SpeechSynthesizer()
let say s = synt.Speak(s: string)

say "Hello world !" 

Of course, if you're french like me, it'll say this with an awful french accent - something like hélo ouorld !

But you can select a different voice if available by providing hints:

open System.Globalization
let english = CultureInfo.GetCultureInfo("en-US")

synt.SelectVoiceByHints(VoiceGender.NotSet, VoiceAge.NotSet, 1, english)
say "Hello world !"

Far better !

Can you beat it ?

Now, a talking fizz buzz, up to 100 ! Can you beat it ?

[1 .. 100]
|> List.map (fun n -> 
    match n%3, n%5 with
    | 0, 0 -> "FizzBuzz"
    | 0, _ -> "Fizz"
    | _, 0 -> "Buzz"
    | _ -> string n )
|> List.iter say

Even harder !

Now with a recognizer, we can wait for voice user input.

The problem with the Grammar API is that it's totally mutable and not really DSL oriented. Let's correct that :

open System.Speech.Recognition

type Grammar =
    | Phrase of text:string * result: string
    | Lst of Grammar list
    | Alt of Grammar list
    | Repeat of min: int * max: int * Grammar


let rec build = function
    | Phrase (text, result) -> 
        // Just build the a single phrase
        GrammarBuilder(SemanticResultValue(text,result))

    | Lst grammars -> 
        // Append parts of grammars one after the other
        let builder = GrammarBuilder()
        grammars
        |> List.map build
        |> List.iter builder.Append
        builder

    | Alt alternatives -> 
        // Create alternatives
        let choices =
            alternatives
            |> List.map build 
            |> List.toArray
        GrammarBuilder(Choices())

    | Repeat(min, max, grammar) -> 
        // Repeat a part of the grammar
        GrammarBuilder(build grammar, min, max)

This is not a full DSL for speach recognition, you can look at all the GrammarBuilder methods to add more possibilities.. Even here, I'll use only Phrase and Alt.

Now, we need a recognizer and wire the grammar with functions that will be called when a part of the grammar is recognized or rejected. It is mandatory to set grammar's culture to the recognizer's culture. There's usually a single recognizer installed by default on your system and it uses installed system's culture. In my case, it'll be french.

let recog = new SpeechRecognizer()

let recognize grammar recognized rejected  = 
    let builder = build grammar
    builder.Culture <- recog.RecognizerInfo.Culture
    printfn "%A" recog.RecognizerInfo.Culture
    recog.LoadGrammar(Grammar builder)
    
    recog.SpeechRecognized |> Event.add (fun e -> recognized e.Result.Text (string e.Result.Semantics.Value))
    recog.SpeechRecognitionRejected |> Event.add (fun e -> rejected ())
    recog.Enabled

We can then use this to create a little Christmass quizz thanks to the FSharp.Data FreeBase Type Provider !

We'll use free base to find a list of Actors who plaid Santa in movies.

For this, install the FSharp.Data NuGet:

nuget install FSharp.Data -o packages -x

The dll should be in .\packages\FSharp.Data\lib et40\FSharp.Data.dll

#r @"packages\FSharp.Data\lib\net40\FSharp.Data.dll"
open FSharp.Data

let fb =FreebaseData.GetDataContext()

Let's build the grammar

let santaActorsFilms =
    fb.``Arts and Entertainment``
      .Film
      .``Film characters``
      .IndividualsAZ.S
      .``Santa Claus``
      .``Portrayed in films``
    |> Seq.map (fun c -> c.Actor.Name, c.Film.Name)
    |> Seq.toList

let santaActorsGrammar =
    santaActorsFilms
    |> List.map (fun (actor,film) -> Phrase(actor, film))
    |> Alt

Here is the function to call when an actor is recognized.

I tried to pass a discriminated union as a value, but even if the API uses an object, the documentation states that it has to be a bool, an int or a string. I used only strings here.

let recognized text value =
    say (sprintf "True ! %s was Santa in %s" text value)

Here is the function when the speech could not be matched with the grammar.

It is also possible to get the audio of the text in this case. I decided to ignore it due to time constraints.

let rejected () = say "No, Not a Santa !"

Now, let's run it !!

recognize santaActorsGrammar recognized rejected

At this point the speech recognition configuration should appear if it's the first time you use it.

Once done you should be able to try the quizz !

If your OS culture is not english, don't hesitate to use a local accent for actor's name !

Conlusion

I hope you had fun with this API, and that you'll want to tweak it for your own demo !

The full code - using FSharp.Formatting - is on my gist

Happy Christmass !

espace de noms System
val synt: obj
val say: s: 'a -> 'b
val s: 'a
Multiple items
val string: value: 'T -> string

--------------------
type string = System.String
espace de noms System.Globalization
val english: CultureInfo
Multiple items
type CultureInfo = interface ICloneable interface IFormatProvider new: culture: int -> unit + 3 surcharges member ClearCachedData: unit -> unit member Clone: unit -> obj member Equals: value: obj -> bool member GetConsoleFallbackUICulture: unit -> CultureInfo member GetFormat: formatType: Type -> obj member GetHashCode: unit -> int member ToString: unit -> string ...
<summary>Provides information about a specific culture (called a locale for unmanaged code development). The information includes the names for the culture, the writing system, the calendar used, the sort order of strings, and formatting for dates and numbers.</summary>

--------------------
CultureInfo(culture: int) : CultureInfo
CultureInfo(name: string) : CultureInfo
CultureInfo(culture: int, useUserOverride: bool) : CultureInfo
CultureInfo(name: string, useUserOverride: bool) : CultureInfo
CultureInfo.GetCultureInfo(name: string) : CultureInfo
CultureInfo.GetCultureInfo(culture: int) : CultureInfo
CultureInfo.GetCultureInfo(name: string, altName: string) : CultureInfo
CultureInfo.GetCultureInfo(name: string, predefinedOnly: bool) : CultureInfo
Multiple items
module List de Microsoft.FSharp.Collections

--------------------
type List<'T> = | op_Nil | op_ColonColon of Head: 'T * Tail: 'T list interface IReadOnlyList<'T> interface IReadOnlyCollection<'T> interface IEnumerable interface IEnumerable<'T> member GetReverseIndex: rank: int * offset: int -> int member GetSlice: startIndex: int option * endIndex: int option -> 'T list static member Cons: head: 'T * tail: 'T list -> 'T list member Head: 'T member IsEmpty: bool member Item: index: int -> 'T with get ...
val map: mapping: ('T -> 'U) -> list: 'T list -> 'U list
val n: int
val iter: action: ('T -> unit) -> list: 'T list -> unit
type Grammar = | Phrase of text: string * result: string | Lst of Grammar list | Alt of Grammar list | Repeat of min: int * max: int * Grammar
type 'T list = List<'T>
val min: e1: 'T -> e2: 'T -> 'T (requires comparison)
Multiple items
val int: value: 'T -> int (requires member op_Explicit)

--------------------
type int = int32

--------------------
type int<'Measure> = int
val max: e1: 'T -> e2: 'T -> 'T (requires comparison)
val build: _arg1: Grammar -> 'a
cas d'union Grammar.Phrase: text: string * result: string -> Grammar
val text: string
val result: string
cas d'union Grammar.Lst: Grammar list -> Grammar
val grammars: Grammar list
val builder: 'a
cas d'union Grammar.Alt: Grammar list -> Grammar
val alternatives: Grammar list
val choices: 'a array
val toArray: list: 'T list -> 'T array
cas d'union Grammar.Repeat: min: int * max: int * Grammar -> Grammar
val min: int
val max: int
val grammar: Grammar
val recog: obj
val recognize: grammar: Grammar -> recognized: ('a -> string -> unit) -> rejected: (unit -> unit) -> 'b
val recognized: ('a -> string -> unit)
val rejected: (unit -> unit)
val builder: obj
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
Multiple items
module Event de Microsoft.FSharp.Control

--------------------
type Event<'T> = new: unit -> Event<'T> member Trigger: arg: 'T -> unit member Publish: IEvent<'T>

--------------------
type Event<'Delegate,'Args (requires delegate and 'Delegate :> Delegate and reference type and 'Delegate: not null)> = new: unit -> Event<'Delegate,'Args> member Trigger: sender: objnull * args: 'Args -> unit member Publish: IEvent<'Delegate,'Args>

--------------------
new: unit -> Event<'T>

--------------------
new: unit -> Event<'Delegate,'Args>
val add: callback: ('T -> unit) -> sourceEvent: IEvent<'Del,'T> -> unit (requires delegate and 'Del :> System.Delegate and 'Del: not null)
val e: obj
val e: 'a
Multiple items
espace de noms FSharp

--------------------
espace de noms Microsoft.FSharp
espace de noms Microsoft.FSharp.Data
val fb: 'a
val santaActorsFilms: (string * string) list
module Seq de Microsoft.FSharp.Collections
val map: mapping: ('T -> 'U) -> source: 'T seq -> 'U seq
val c: 'a
val toList: source: 'T seq -> 'T list
val santaActorsGrammar: Grammar
val actor: string
val film: string
val recognized: text: string -> value: string -> 'a
val value: string
val sprintf: format: Printf.StringFormat<'T> -> 'T
val rejected: unit -> 'a