Skip to content

Instantly share code, notes, and snippets.

@typedrat
Created June 4, 2012 18:15
Show Gist options
  • Save typedrat/2869958 to your computer and use it in GitHub Desktop.
Save typedrat/2869958 to your computer and use it in GitHub Desktop.
Wolfram Omega is an attempt to voice control the Wolfram|Alpha API. It sort of works, sometimes. It is Mac only. Deps: nokogiri (nokogiri.org), speech2text (https://github.com/taf2/speech2text), coreaudio (https://github.com/nagachika/ruby-coreaudio)
require 'coreaudio'
require 'speech'
require 'nokogiri'
require 'open-uri'
require 'uri'
require 'tempfile'
Signal.trap("INT") do
puts "Terminating..."
buf.stop
$stdout.puts "done."
exit
end
ApiKey = '' #Put thy Wolfram|Alpha API key here.
$dev = CoreAudio.default_input_device
buf = $dev.input_buffer(1024)
def speak(text)
IO.popen(["say"], "w") {|pipe| pipe.puts text}
end
def wolfram_alpha(question)
doc = Nokogiri::XML(
open(
URI.escape(
"http://api.wolframalpha.com/v2/query?appid=#{ApiKey}&input=#{question}&format=plaintext"
)
)
)
answer = doc.xpath "/queryresult/pod[@primary]"
return answer.text.strip
end
current_file = ""
def start_recording
# create temp file, begin recording sound.
$current_file = Tempfile.new ['wolfram_omega', '.wav']
$dev = CoreAudio.default_input_device
$wav = CoreAudio::AudioFile.new($current_file.path, :write, :format => :wav,
:rate => $dev.nominal_rate,
:channels => $dev.input_stream.channels)
end
def stop_recording
# stop recording, dictate text, and speak answer.
$wav.close
$current_file.close
audio = Speech::AudioToText.new $current_file.path
begin
question = audio.to_text["hypotheses"][0][0]
rescue NoMethodError => e
puts "No hypothesis..."
end
answer = wolfram_alpha question
speak answer
end
buf.start;
puts "^C to quit."
$stdout.flush
writing = false
loop do
w = buf.read(4096)
if writing
$wav.write w
end
if w.rms > 400 && writing == false
puts "Got question!"
writing = true
start_recording
elsif w.rms < 400 && writing == true
writing = false
stop_recording
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment