Multiple Identical Text_input in streamlit

Hello Team,
I’m trying to call the function pronunciation_assessment_from_microphone() but after assesing for the first time it is displaying like this.

After the user enter the input and speaks the entered text.

It should ask for the next time but it is exiting

import azure.cognitiveservices.speech as speechsdk
import sys
import streamlit as st
import time

def pronunciation_assessment_from_microphone():
“”"“performs one-shot pronunciation assessment asynchronously with input from microphone.”""

config = speechsdk.SpeechConfig(subscription="", region="")

# The pronunciation assessment service has a longer default end silence timeout (5 seconds) than normal STT
# as the pronunciation assessment is widely used in education scenario where kids have longer break in reading.
# You can adjust the end silence timeout based on your real scenario.
config.set_property(speechsdk.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs, "3000")

reference_text = ""
# create pronunciation assessment config, set grading system, granularity and if enable miscue based on your requirement.
pronunciation_config = speechsdk.PronunciationAssessmentConfig(reference_text=reference_text,
                                                               grading_system=speechsdk.PronunciationAssessmentGradingSystem.HundredMark,
                                                               granularity=speechsdk.PronunciationAssessmentGranularity.Phoneme,
                                                               enable_miscue=True)
st.markdown("###  Reading Fluency Check")
recognizer = speechsdk.SpeechRecognizer(speech_config=config)
while True:
    # Receives reference text from console input.
    st.success('Enter reference text you want to assess, or enter stop to exit.')

    try:
        reference_text = st.text_input("Enter your text","")
        if reference_text == "stop":
            st.success('Entered stop to exit')
            sys.exit(0)
    except EOFError:
        break

    pronunciation_config.reference_text = reference_text
    pronunciation_config.apply_to(recognizer)

    # Starts recognizing.
    st.success('Read out "{}" for pronunciation assessment ...'.format(reference_text))

    # Note: Since recognize_once() returns only a single utterance, it is suitable only for single
    # shot evaluation.
    # For long-running multi-utterance pronunciation evaluation, use start_continuous_recognition() instead.
    result = recognizer.recognize_once_async().get()

    # Check the result
    if result.reason == speechsdk.ResultReason.RecognizedSpeech:
        st.success('Recognized: {}'.format(result.text))
        st.success('  Pronunciation Assessment Result:')

        pronunciation_result = speechsdk.PronunciationAssessmentResult(result)
        
        st.info(st.info('Accuracy Score : {}'.format(pronunciation_result.accuracy_score)))
        st.info(st.info('Pronunciation Score : {}'.format(pronunciation_result.pronunciation_score)))
        st.info(st.info('Completeness Score : {}'.format(pronunciation_result.completeness_score)))
        st.info(st.info('Fluency Score : {}'.format(pronunciation_result.fluency_score)))
        
    
        st.success('  Word-level details:')
        for idx, word in enumerate(pronunciation_result.words):
            st.info('    {}: word: {}, accuracy score: {}, error type: {};'.format(
                idx + 1, word.word, word.accuracy_score, word.error_type
            ))
    elif result.reason == speechsdk.ResultReason.NoMatch:
        st.warning("No speech could be recognized")
    elif result.reason == speechsdk.ResultReason.Canceled:
        cancellation_details = result.cancellation_details
        st.error("Speech Recognition canceled: {}".format(cancellation_details.reason))
        if cancellation_details.reason == speechsdk.CancellationReason.Error:
            st.error("Error details: {}".format(cancellation_details.error_details))

start=st.sidebar.checkbox(“Start”)
if start:
pronunciation_assessment_from_microphone()
time.sleep(10)

can you help me

1 Like

@benlindsay @Marc

I don’t have my computer nearby, so I can’t replicate your problem right now, but I think the bestvway you could get help frome or anyone else would be to reduce it down even further to an MVP (Minimum Viable…Problem?) to show the smallest amount of code that reproduces the main problem you’re seeing. In general that’s good practice for getting help on forums like this or Stack Overflow. Also getting the code formatted into a properly indented code block would help. I know it’s tough to figure out the right syntax for that stuff though

1 Like

@bhargav you’re putting multiple text_input fields with the same label on the page since it’s in a while loop. In that case you must supply a new key for each instance. Looks like the key could be a randomly generated number to allow multiple instances of the widget to co-exist. On the other hand, try this:

txt_widget = st.empty()
while True:
    # Receives reference text from console input.
    st.success('Enter reference text you want to assess, or enter stop to exit.')

    try:
        reference_text = txt_widget.text_input("Enter your text","")
        if reference_text == "stop":
            st.success('Entered stop to exit')
            sys.exit(0)
    except EOFError:
        break
1 Like

The error remains the same

Hi @bhargav,

I moved your question to its own topic so we can work up a new solution here for you! Feel free to adjust change the title I made.

Can you post the code you used to get this error?

If you created a function that calls text_input with the same parameters, then I would suspect that you need to add in some random-ness to your function by generating a random number and passing that to the key parameter in your text_input.

Hard to say exactly though as I would need to see a bit more about your code to know for sure.

Happy Streamlit-ing!
Marisa

Hello @Marisa_Smith

Hi @bhargav,

I saw that you have made another post about this same topic so I merged them here (that way there is no confusion on which thread to use).

@asehmi I think is on the right track with the random number generator and that (as you see above) was my gut reaction too. First, you will need to import random as a package. Check out their docs here.

Then, each time your function runs that creates the text_input your will need to generate a random number and insert it as a string to the key parameter

import random as ran

# these lines go inside your function/while loop

#generates a random number on a uniform distribution between 1-10
random = ran.uniform(1,10) 

txt = st.text_input("Enter your text", key = "{}".format(random))

I’m not :100: sure how this will affect your use of the inputted text though. You will need to run some tests on this to make sure you’re not losing info from your user.

As @benlindsay alluded to the best thing would be to mock up a Minimum Working Example that reproduced this error with the least amount of code and minimum number of packages to reproduce. (LOL @ @benlindsay clever use of MVP).

Also, why do you need to have your text input in this while loop? Can you explain a bit about why that is? There may be a way to simplify this for you!

Happy Streamlit-ing!
Marisa

Thanks @Marisa_Smith @benlindsay @asehmi

As you asked me why do you need to have your text input in this while loop?

what to do if it needs to run only once and display output and exit

Hi @bhargav (@Marisa_Smith @benlindsay),

I think the code below achieves what you’re trying to do. In your code, my opinion is that it’s not good practice to use infinite loops and sys.exit(). I recommend staying within the natural execution flow of Streamlit. It might take a little effort getting used to, but your programs will end up being much simpler to write – I promise :slight_smile:

Hope it helps, and good luck with your efforts.

import streamlit as st
import time

def check_fluency(text):
    my_info = st.empty()
    my_bar = st.progress(0)
    my_info.info('Checking fluency...')
    for percent_complete in range(25):
        time.sleep(0.1)
        my_bar.progress(percent_complete + 1)
    my_info.empty()
    my_bar.empty()

def main():
    """performs one-shot pronunciation assessment asynchronously with input from microphone."""
    st.title('Reading Fluency Check')
    # Receives reference text from console input.
    text_widget = st.empty()
    ref_text = text_widget.text_input('Enter text (stop to exit)', '')
    if ref_text == 'stop':
        text_widget.empty()
        st.info('Thank you!')
    elif ref_text != '':
        # Starts recognizing.
        check_fluency(ref_text)
        st.success(f'\U0001f4E2 Reading out "{ref_text}" for your pronunciation assessment ...')

if __name__ == '__main__':
    main()

text_input_demo

1 Like