''' Created By Lewis Kamau Kimaru https://towardsdev.com/building-a-voice-assistant-using-openai-api-and-flask-by-chatgpt-9f90a430b242 https://github.com/prathmeshChaudhari05/Voice-Assistant-Flask August 2023 ''' from flask import Flask, render_template, request, redirect, url_for, send_from_directory from playsound import playsound import speech_recognition as sr from pyngrok import ngrok from gtts import gTTS import openai import os app = Flask(__name__) # Set your ngrok authtoken ngrok.set_auth_token("2UAhCqf5zP0cCgJzeadNANkbIqx_7ZJvhkDSNWccqMX2hyxXP") #ngrok.set_auth_token("2S6xeFEoSVFWr2egtDRcqgeUtSx_2juefHFkEW6nGbpRHS37W") #ngrok.set_auth_token("2UAmdjHdAFV9x84TdyEknIfNhYk_4Ye8n4YK7ZhfCMob3yPBh") #ngrok.set_auth_token("2UAqm26HuWiWvQjzK58xYufSGpy_6tStKSyLLyR9f7pcezh6R") #ngrok.set_auth_token("2UGQqzZoI3bx7SSk8H4wuFC3iaC_2WniWyNAsW5fd2rFyKVq1") #ngrok.set_auth_token("2UISOtStHwytO70NQK38dFhS1at_5opQaXnoQCKeyhEe4qfT2") # Set up OpenAI API credentials openai.api_key = 'YOUR_API_KEY' html_content = """ Voice Assistant

Voice Assistant

""" @app.route('/') def home(): return html_content def handle_form(): r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") audio = r.listen(source) try: result = r.recognize_google(audio) print("result2:") print(r.recognize_google(audio, show_all=True)) response = openai.Completion.create( engine="davinci", prompt=result, max_tokens=60, n=1, stop=None, temperature=0.5, ) if response.choices: tts = gTTS(text=response.choices[0].text, lang='en') else: tts = gTTS(text="I'm sorry, I didn't understand what you said", lang='en') filename = 'response.mp3' tts.save(filename) playsound(filename) os.remove(filename) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e)) return html_content @app.route('/', methods=['POST']) def submit_textarea(): return handle_form() ngrok_tunnel = ngrok.connect(7860) public_url = ngrok_tunnel.public_url print('\nPublic URL✅:', public_url) print("\nFlask APP starting .......\n")