Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
if else repeating
#1
Hello,

Something i never understood if why with an if and else statement there is that repeat effect.
Inside the try except the voice is saying "le fruit a été ajouté dans le panier" if its fraise or pomme word and saying "le légume a été ajouté au panier" if its a vegetable.
Why is it jumping to the else if there is no vegetable?

from speech_recognition import Recognizer, Microphone
from gtts import gTTS
import subprocess

recognizer = Recognizer()

# On enregistre le son

with Microphone() as source:
    print("Réglage du bruit ambiant... Patientez...")
    recognizer.adjust_for_ambient_noise(source)
    print("Vous pouvez parler...")
    recorded_audio = recognizer.listen(source)
    print("Enregistrement terminé !")
    
# Reconnaissance de l'audio

try:
    print("Reconnaissance du texte...")
    text = recognizer.recognize_google(
            recorded_audio, 
            language="fr-FR"
        )
    print("Vous avez dit : {}".format(text))
    hotword= ["pomme","fraise"]
    for h in hotword:
        if h in text:
            tts = gTTS(u"le fruit a été ajouté dans le panier", lang="fr")
            tts.save('out.mp3')
            cmd = ['mpg321', '-q', 'out.mp3']
            subprocess.call(cmd)
        else:
            tts = gTTS(u"le légume a été ajouté au panier", lang="fr")
            tts.save('out.mp3')
            cmd = ['mpg321', '-q', 'out.mp3']
            subprocess.call(cmd)
except Exception as ex:
    print(ex)
Thank you
Reply
#2
(Jul-09-2022, 03:39 PM)Frankduc Wrote: the voice is saying "le fruit a été ajouté dans le panier" if its fraise or pomme word and saying "le légume a été ajouté au panier" if its a vegetable.
This is not what the code does. The code says "le fruit a été ajouté dans le panier" for every hotword that is found in the text and it says "le légume a été ajouté au panier" for every hotword that is not found in the text. The code does not know about fruits and vegetables.
Reply
#3
i solve the problem this way but there must be a way not to repeat all the code so many times:

if "pomme" in text:
        tts = gTTS(u"le fruit a été ajouté dans le panier", lang="fr")
        tts.save('out.mp3')
        cmd = ['mpg321', '-q', 'out.mp3']
        subprocess.call(cmd)
    if "fraise" in text:
        tts = gTTS(u"le fruit a été ajouté dans le panier", lang="fr")
        tts.save('out.mp3')
        cmd = ['mpg321', '-q', 'out.mp3']
        subprocess.call(cmd)
...
I thought the h in hotword was looping everyword in the list and if h == text (so "pomme" in list = the word text when = "pomme" than it excute the script?
Reply
#4
You seem to have a hard time with code that needs to remember something. In your example you need to rember if you found one of the hotwords in the text. If a hotword was found you perform one action, else you perform another. The important thing is to evaluate the condition first, the perform the action. In your first example the evaluation and performing action were intertwined.
    # This is the search
    found_word = None
    for h in hotword:
        if h in text:
            found_word = h
            break

    # Perform the action based on search result
    if found_word
        tts = gTTS(u"le fruit a été ajouté dans le panier", lang="fr")
        tts.save('out.mp3')
        cmd = ['mpg321', '-q', 'out.mp3']
        subprocess.call(cmd)
    else:
        tts = gTTS(u"le légume a été ajouté au panier", lang="fr")
        tts.save('out.mp3')
        cmd = ['mpg321', '-q', 'out.mp3']
This is kind of ugly, so Python has a shorthand.
def contains(string, substrings):
    if any(s in string for s in substrings):
        print(f"{string} contains one of these {substrings}")
    else:
        print(f"{string} does not contain any of these {substrings}")

contains("blast", ["first", "last"])
contains("blast", ["begin", "end"])
Functionally this is identical to:
def contains(string, substrings):
    found = False
    for s in substrings:
        if s in string:
            found = True
            break
    if found:
        print(f"{string} contains one of these {substrings}")
    else:
        print(f"{string} does not contain any of these {substrings}")

contains("blast", ["first", "last"])
contains("blast", ["begin", "end"])
Another way to solve your particular problem is to use sets. You have a set of words and a set of hotwords. If the insersection of words and hotwords is not empty, that means one of the hotwords is in words.
if set(words).intersection(set(hotwords)):
    # do found stuff
else:
    # do not found stuff
Frankduc likes this post
Reply
#5
In the last case it always jump to the else. Even if i say a word in the list:
Tomate is a fruit but it reply it is a vegetable (else) .

from speech_recognition import Recognizer, Microphone
from gtts import gTTS
import subprocess

recognizer = Recognizer()

# On enregistre le son

with Microphone() as source:
    print("Dite un fruit ou un légume dans le microphone")
    print("Réglage du bruit ambiant... Patientez...")
    recognizer.adjust_for_ambient_noise(source)
    print("Vous pouvez parler...")
    recorded_audio = recognizer.listen(source)
    print("Enregistrement terminé !")
    
# Reconnaissance de l'audio

try:
    print("Reconnaissance du texte...")
    text = recognizer.recognize_google(
            recorded_audio, 
            language="fr-FR"
        )
    print("Vous avez dit : {}".format(text))
    words = text
    hotword = ["fraise", "pomme","tomate"]
    if set(words).intersection(set(hotword)):
        tts = gTTS(u"le fruit a été ajouté dans le panier", lang="fr")
        tts.save('out.mp3')
        cmd = ['mpg321', '-q', 'out.mp3']
        subprocess.call(cmd)
    else:
        tts = gTTS(u"le légume a été ajouté au panier", lang="fr")
        tts.save('out.mp3')
        cmd = ['mpg321', '-q', 'out.mp3']
        subprocess.call(cmd)
   

except Exception as ex:
    print(ex)
for the function i dont get where the blast is coming from and what is the use of contains.

from speech_recognition import Recognizer, Microphone
from gtts import gTTS
import subprocess

recognizer = Recognizer()

# On enregistre le son

with Microphone() as source:
    print("Dite un fruit ou un légume dans le microphone")
    print("Réglage du bruit ambiant... Patientez...")
    recognizer.adjust_for_ambient_noise(source)
    print("Vous pouvez parler...")
    recorded_audio = recognizer.listen(source)
    print("Enregistrement terminé !")
    
# Reconnaissance de l'audio

try:
    print("Reconnaissance du texte...")
    text = recognizer.recognize_google(
            recorded_audio, 
            language="fr-FR"
        )
    print("Vous avez dit : {}".format(text))
    words = text
    hotword = ["fraise", "pomme","tomate"]
    def contains(string, substrings):
        found = False
    for s in substrings:
        if s in string:
            found = True
            break
        if found:
            tts = gTTS(u"le fruit a été ajouté dans le panier", lang="fr")
            tts.save('out.mp3')
            cmd = ['mpg321', '-q', 'out.mp3']
            subprocess.call(cmd)
        else:
            tts = gTTS(u"le légume a été ajouté au panier", lang="fr")
            tts.save('out.mp3')
            cmd = ['mpg321', '-q', 'out.mp3']
            subprocess.call(cmd)
        
contains("blast", ["text"])
contains("blast", ["fraise", "pomme","tomate"])
  except Exception as ex:
    print(ex)
Reply
#6
The set() approach will only find matching words if there are matches to be found. "tomato" does not match "Tomato", nor does it match "tomatoes" or "I like that with tomato please". Verify that "words" is a list of words and not a string that contains words.

My "any" example finds substrings in a word, not words in a list. It is not directly applicable to your problem, but it does a nice job demonstrating how "any" works.
Reply
#7
I cant figure out why it is not working.

Dite un fruit ou un légume dans le microphone
Réglage du bruit ambiant... Patientez...
Vous pouvez parler...
Enregistrement terminé !
Reconnaissance du texte...
Vous avez dit : pomme <-----i said the word pomme it is correctly written like in the list:

from speech_recognition import Recognizer, Microphone
from gtts import gTTS
import subprocess

recognizer = Recognizer()

# On enregistre le son

with Microphone() as source:
    print("Dite un fruit ou un légume dans le microphone")
    print("Réglage du bruit ambiant... Patientez...")
    recognizer.adjust_for_ambient_noise(source)
    print("Vous pouvez parler...")
    recorded_audio = recognizer.listen(source)
    print("Enregistrement terminé !")
    
# Reconnaissance de l'audio

try:
    print("Reconnaissance du texte...")
    text = recognizer.recognize_google(
            recorded_audio, 
            language="fr-FR"
        )
    print("Vous avez dit : {}".format(text))
    words = text
    hotword = ["fraise", "pomme","tomate"]
    if set(words).intersection(set(hotword)):
        tts = gTTS(u"le fruit a été ajouté dans le panier", lang="fr")
        tts.save('out.mp3')
        cmd = ['mpg321', '-q', 'out.mp3']
        subprocess.call(cmd)
    else:
        tts = gTTS(u"le légume a été ajouté au panier", lang="fr")
        tts.save('out.mp3')
        cmd = ['mpg321', '-q', 'out.mp3']
        subprocess.call(cmd)
   

except Exception as ex:
    print(ex)
Quote: Verify that "words" is a list of words and not a string that contains words.

I am not sure what you meant by string that contains words.
Reply
#8
Do you understand the difference between a list of strings and a single string?
Reply
#9
the list of strings: hotword = ["fraise", "pomme","tomate"]
a single string : a = "Hello"

the variable text is a string?
I mean it returned a string, the string pomme. But i cant confirm it was under the form of a string.

it becomes a string representation here: print("Vous avez dit : {}".format(text))

does it sees a string here: if set(words).intersection(set(hotword)):

i am not sure

Also i am trying to rerun the program so the user can tell another phrase after 15 seconds. It has been changed for phrase but it doesnt seems to recognize phrases.

from speech_recognition import Recognizer, Microphone
from gtts import gTTS
import subprocess
import time

recognizer = Recognizer()

# On enregistre le son

with Microphone() as source:
    print("Dite un fruit ou un légume dans le microphone")
    print("Réglage du bruit ambiant... Patientez...")
    recognizer.adjust_for_ambient_noise(source)
    print("Vous pouvez parler...")
    recorded_audio = recognizer.listen(source)
    print("Enregistrement terminé !")
    
# Reconnaissance de l'audio
while(True):
    try:
        print("Reconnaissance du texte...")
        text = recognizer.recognize_google(
                recorded_audio, 
                language="fr-FR"
            )
        print("Vous avez dit : {}".format(text))
        def speech():
            tts = gTTS(u"La lumière de l’entrée est allumé", lang="fr")
            tts.save('out.mp3')
            cmd = ['mpg321', '-q', 'out.mp3']
            subprocess.call(cmd)
            
        def speech2():
            tts = gTTS(u"La lumière de l’entrée est fermé", lang="fr")
            tts.save('out.mp3')
            cmd = ['mpg321', '-q', 'out.mp3']
            subprocess.call(cmd)
        
        found_word = None
        hotword = ["Ouvrir la lumière de l’entrée", "Allumer la lumière de l’entrée"]
        for h in hotword:
            if h in text:
                found_word = h
                break
     

        if found_word:
            speech()
        else:
            speech2()
        time.sleep(15)
        
    except Exception as ex:
        print(ex)
        
Reply
#10
A list of words is ["Vous", "avez", "dit", "pomme"]. A string of words is "Vous avez dit : pomme". You can use set intersection to find "pomme" in a list of words. You cannot use it to find the substring "pomme" in a longer string (a string of words).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why is 2/3 not just .666 repeating? DocFro 4 714 Dec-12-2023, 09:09 AM
Last Post: buran
  repeating a user_input astral_travel 17 2,316 Oct-26-2022, 04:15 PM
Last Post: astral_travel
  matching a repeating string Skaperen 2 1,258 Jun-23-2022, 10:34 PM
Last Post: Skaperen
  Random Number Repeating Tzenesh 5 4,062 Jan-13-2021, 10:00 PM
Last Post: deanhystad
  factorial, repeating Aldiyar 4 2,816 Sep-01-2020, 05:22 PM
Last Post: DPaul
  number repeating twice in loop JonnyEnglish 3 3,322 Nov-24-2019, 09:23 AM
Last Post: ThomasL
  Repeating equations Tbot100 2 3,286 May-29-2019, 02:38 AM
Last Post: heiner55
  First non-repeating char and some errors. blackknite 1 2,284 Jan-06-2019, 02:19 PM
Last Post: stullis
  repeating for loop Kaldesyvon 5 3,867 Dec-06-2018, 08:00 PM
Last Post: ichabod801
  Repeating same number in sequence Rudinirudini 6 4,254 Oct-28-2018, 07:44 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020