|
| 1 | +from os import getenv |
| 2 | + |
| 3 | +import azure.cognitiveservices.speech as speechsdk |
| 4 | +import streamlit as st |
| 5 | +from dotenv import load_dotenv |
| 6 | + |
| 7 | +load_dotenv() |
| 8 | + |
| 9 | +with st.sidebar: |
| 10 | + service_type = st.selectbox( |
| 11 | + label="Service type", |
| 12 | + options=[ |
| 13 | + "Local", |
| 14 | + "Azure", |
| 15 | + ], |
| 16 | + ) |
| 17 | + if service_type == "Azure": |
| 18 | + azure_ai_services_api_key = st.text_input( |
| 19 | + label="AZURE_AI_SERVICES_API_KEY", |
| 20 | + key="AZURE_AI_SERVICES_API_KEY", |
| 21 | + type="password", |
| 22 | + ) |
| 23 | + azure_ai_speech_region = st.text_input( |
| 24 | + label="AZURE_AI_SPEECH_REGION", |
| 25 | + value=getenv("AZURE_AI_SPEECH_REGION"), |
| 26 | + key="AZURE_AI_SPEECH_REGION", |
| 27 | + type="default", |
| 28 | + ) |
| 29 | + if service_type == "Local": |
| 30 | + host = st.text_input( |
| 31 | + label="Host", |
| 32 | + value="ws://localhost:5000", |
| 33 | + key="host", |
| 34 | + type="default", |
| 35 | + ) |
| 36 | + "[Azure Portal](https://portal.azure.com/)" |
| 37 | + "[View the source code](https://github.com/ks6088ts-labs/workshop-azure-openai/blob/main/apps/99_streamlit_examples/pages/13_Azure_AI_Speech.py)" |
| 38 | + "[Speech to text containers with Docker](https://learn.microsoft.com/azure/ai-services/speech-service/speech-container-stt?tabs=container&pivots=programming-language-python)" |
| 39 | + |
| 40 | + |
| 41 | +def is_configured(): |
| 42 | + if service_type == "Azure": |
| 43 | + return azure_ai_services_api_key and azure_ai_speech_region |
| 44 | + if service_type == "Local": |
| 45 | + return host != "" |
| 46 | + return False |
| 47 | + |
| 48 | + |
| 49 | +def get_speech_config(): |
| 50 | + if service_type == "Azure": |
| 51 | + return speechsdk.SpeechConfig( |
| 52 | + subscription=azure_ai_services_api_key, |
| 53 | + region=azure_ai_speech_region, |
| 54 | + ) |
| 55 | + if service_type == "Local": |
| 56 | + return speechsdk.SpeechConfig( |
| 57 | + endpoint=host, |
| 58 | + ) |
| 59 | + |
| 60 | + |
| 61 | +def from_mic(): |
| 62 | + speech_recognizer = speechsdk.SpeechRecognizer( |
| 63 | + speech_config=get_speech_config(), |
| 64 | + ) |
| 65 | + |
| 66 | + print("Speak into your microphone.") |
| 67 | + speech_recognition_result = speech_recognizer.recognize_once_async().get() |
| 68 | + print(speech_recognition_result.text) |
| 69 | + |
| 70 | + |
| 71 | +st.title("Azure AI Speech Services") |
| 72 | + |
| 73 | +if not is_configured(): |
| 74 | + st.warning("Please fill in the required fields at the sidebar.") |
| 75 | + |
| 76 | +st.info("Transcribe your speech.") |
| 77 | + |
| 78 | +if st.button("Transcribe", disabled=not is_configured()): |
| 79 | + from_mic() |
0 commit comments