Sunday, 7 February 2021

python speech recognition + duckduckgo instant answer api

#ask a question through microphone
#computer translate to text, and query on duckduckgo
#computer receive response from duckduckgo and speaks result
PS C:\Users\bob\python-speech> python main.py
Ask me any question?
say something!
You said: Banff National Park
Banff National Park is Canada's oldest national park, established in 1885. Located in Alberta's Rocky Mountains, 110–180 kilometres west of Calgary, Banff encompasses 6,641 square kilometres of mountainous terrain, with many glaciers and ice fields, dense coniferous forest, and alpine landscapes. The Icefields Parkway extends from Lake Louise, connecting to Jasper National Park in the north. Provincial forests and Yoho National Park are neighbours to the west, while Kootenay National Park is located to the south and Kananaskis Country to the southeast. The main commercial centre of the park is the town of Banff, in the Bow River valley. The Canadian Pacific Railway was instrumental in Banff's early years, building the Banff Springs Hotel and Chateau Lake Louise, and attracting tourists through extensive advertising. In the early 20th century, roads were built in Banff, at times by war internees from World War I, and through Great Depression-era public works projects.

import time
import speech_recognition as sr
import pyttsx3
import requests
import json

def speak(audioString):
    print(audioString)

    engine = pyttsx3.init()
    engine.say(audioString)
    engine.runAndWait()

def recordAudio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("say something!")
        #r.adjust_for_ambient_noise(source)
        audio = r.listen(source)

        try:
            data = r.recognize_google(audio)
            print("You said: " + data)

        except sr.UnknownValueError:
            return "Couldn't understand audio"

        except sr.RequestError as e:
            return "couldn't request results; {0}" + format(e)

        return data


speak("Ask me any question?")

data = recordAudio()

res = requests.get("https://api.duckduckgo.com",
             params={"q": data,
                     "format": "json",
                     "pretty": "1"})

answer = json.loads( res.content)

reply = answer["Abstract"] + answer["Answer"]

speak(reply)
"""
if reply:
    speak(reply)
elif reply == "":
    speak("I did't find answer")
"""

reference:

duckduckgo instant answer api

No comments:

Post a Comment