Un programme pour apprendre ses tables de multiplications

En primaire on commence à apprendre ses tables de multiplications. Bien sûr on se sert des parents pour les réciter avant le contrôle. Cependant, les parents ça passe leurs temps à faire des commentaires. Alors pourquoi ne pas utiliser la machine pour les réciter sans jugement ?

C’est d’autant plus facile aujourd’hui avec la multitude de langages de haut niveau disponibles. Par exemple en python on peut tartiner un programme vite fait bien fait comme cela :

import random

maxcount = 10
count = maxcount

while count != 0:
    a = random.randint(2, 9)
    b = random.randint(2, 9)
    
    res = input(f"{a} x {b} = ")
    if (int(res) != int(a*b)):
        print(f"NAN! C'était {a*b}")
        count = maxcount
    else:
        print("Bien")
        count = count - 1
    print(f"Encore {count} multiplications à trouver")

print("BRAVO \o/")Langage du code : PHP (php)

Le programme fonctionne plutôt bien, on peut ensuite l’améliorer et ajouter des défis.

Réponse parlée

Là, il faut un clavier pour répondre, ça suppose de savoir s’en servir. Et c’est plus long pour répondre. Si on veut faire un programme basé sur la vitesse et qui évite d’avoir à connaître l’usage du clavier on peut essayer de passer par la reconnaissance vocale avec la bibliothèque open-source Vosk par exemple. Ce logiciel a l’avantage de pouvoir s’utiliser hors ligne.

L’installation de vosk est d’une simplicité biblique :

$ sudo python3 -m pip install vosk
[sudo] Mot de passe de fabien :        
Collecting vosk
  Downloading vosk-0.3.45-py3-none-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (7.2 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 7.2/7.2 MB 22.7 MB/s eta 0:00:00
Collecting tqdm
  Downloading tqdm-4.65.0-py3-none-any.whl (77 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 77.1/77.1 KB 13.6 MB/s eta 0:00:00
Requirement already satisfied: requests in /usr/lib/python3/dist-packages (from vosk) (2.25.1)
Collecting websockets
  Downloading websockets-11.0.3-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (129 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 129.9/129.9 KB 6.6 MB/s eta 0:00:00
Collecting cffi>=1.0
  Downloading cffi-1.15.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (441 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 441.8/441.8 KB 11.6 MB/s eta 0:00:00
Collecting srt
  Downloading srt-3.5.3.tar.gz (28 kB)
  Preparing metadata (setup.py) ... done
Collecting pycparser
  Downloading pycparser-2.21-py2.py3-none-any.whl (118 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 118.7/118.7 KB 8.2 MB/s eta 0:00:00
Building wheels for collected packages: srt
  Building wheel for srt (setup.py) ... done
  Created wheel for srt: filename=srt-3.5.3-py3-none-any.whl size=22445 sha256=5d6b0eded4562ad3cdb720ee5932cf7a7c377a463690f0cfef649372d3501355
  Stored in directory: /root/.cache/pip/wheels/d7/31/a1/18e1e7e8bfdafd19e6803d7eb919b563dd11de380e4304e332
Successfully built srt
Installing collected packages: websockets, tqdm, srt, pycparser, cffi, vosk
Successfully installed cffi-1.15.1 pycparser-2.21 srt-3.5.3 tqdm-4.65.0 vosk-0.3.45 websockets-11.0.3
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
Langage du code : JavaScript (javascript)

On pourra ensuite essayer de convertir un échantillon de voix lisant ’42’ :

$ vosk-transcriber -l fr -i vosk/quarante-deux.mp3 -o quarante-deux.txt
vosk-model-small-fr-0.22.zip: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 40.3M/40.3M [00:02<00:00, 20.8MB/s] 
LOG (VoskAPI:ReadDataFiles():model.cc:213) Decoding params beam=13 max-active=7000 lattice-beam=4
LOG (VoskAPI:ReadDataFiles():model.cc:216) Silence phones 1:2:3:4:5:6:7:8:9:10
LOG (VoskAPI:RemoveOrphanNodes():nnet-nnet.cc:948) Removed 0 orphan nodes.
LOG (VoskAPI:RemoveOrphanComponents():nnet-nnet.cc:847) Removing 0 orphan components.
LOG (VoskAPI:ReadDataFiles():model.cc:248) Loading i-vector extractor from /home/fabien/.cache/vosk/vosk-model-small-fr-0.22/ivector/final.ie
LOG (VoskAPI:ComputeDerivedVars():ivector-extractor.cc:183) Computing derived variables for iVector extractor
LOG (VoskAPI:ComputeDerivedVars():ivector-extractor.cc:204) Done.
LOG (VoskAPI:ReadDataFiles():model.cc:282) Loading HCL and G from /home/fabien/.cache/vosk/vosk-model-small-fr-0.22/graph/HCLr.fst /home/fabien/.cache/vosk/vosk-model-small-fr-0.22/graph/Gr.fst
LOG (VoskAPI:ReadDataFiles():model.cc:308) Loading winfo /home/fabien/.cache/vosk/vosk-model-small-fr-0.22/graph/phones/word_boundary.int
INFO:root:Recognizing vosk/quarante-deux.mp3
INFO:root:{'partial': 'quarante-deux'}
INFO:root:{'partial': 'quarante-deux'}
INFO:root:{'partial': 'quarante-deux'}
INFO:root:{'partial': 'quarante-deux'}
INFO:root:{'partial': 'quarante-deux'}
INFO:root:{'partial': 'quarante-deux'}
INFO:root:{'partial': 'quarante-deux'}
INFO:root:File quarante-deux.txt processing complete
INFO:root:Execution time: 0.766 sec; xRT 0.426

$ cat quarante-deux.txt 
quarante-deux
Langage du code : JavaScript (javascript)

Bon pour le «offline» c’est pas tout à fait ça puisqu’il faut quand même télécharger le modèle pour la langue (ici ‘-l fr’ pour français). Mais, une fois téléchargé il n’y a plus à y revenir.

Testé sur d’autre échantillons ça marche relativement bien. Il nous reste quelque problèmes:

  • Nous avons utilisé un échantillon sonore enregistré. Notre objectif est de pouvoir «écouter» la réponse sans avoir à utiliser le clavier.
  • Le résultat est donné en texte, il va donc falloir le convertir en nombre.

test_microphone.py

Le projet Vosk propose un script en python pour tester son microphone. Ce script transcrit en temps réel le texte reconnue.

On peut reprendre le script et modifier la boucle d’affichage du texte pour convertir en nombre le texte reconnue puis vérifier que le calcul est bon.

Ça tombe bien car en python il y a un module qui fait la conversion texte en nombre : text2num

Text2num

Convertir un texte en un nombre est chose facile avec text2num:

$ sudo python3 -m pip install text2num
Collecting text2num
  Downloading text2num-2.5.0.tar.gz (38 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: text2num
  Building wheel for text2num (setup.py) ... done
  Created wheel for text2num: filename=text2num-2.5.0-py3-none-any.whl size=58681 sha256=fd5ff29e88655c69c08cee37608129ffd7fbbed2cc96ef59ddc9ce4b77443bda
  Stored in directory: /root/.cache/pip/wheels/49/b2/af/5db9aefd179867bbae782e4e1aefa78490377f561b4c97f34e
Successfully built text2num
Installing collected packages: text2num
Successfully installed text2num-2.5.0
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
Langage du code : JavaScript (javascript)

L’utilisation se fait de la manière suivante (dans une console ipython):

In [2]: from text_to_num import text2num

In [3]: text2num("quarante-deux", "fr")
Out[3]: 42
Langage du code : JavaScript (javascript)

Il reste à ajouter le module json de python pour convertir la sortie texte et nous avons notre squelette de programme de récitation des multiplications :

            rec = KaldiRecognizer(model, args.samplerate)
            count = MAX_OPERATION_NB 
            while count != 0:
                print(f"Courage, plus que {count} opérations")
                a = random.randint(2, 9)
                b = random.randint(2, 9)
                print(f"Combien font {a} x {b} ?")
                while True:
                    data = q.get()
                    if rec.AcceptWaveform(data):
                        res = rec.Result()
                        textvalue = json.loads(res).get("text", None)
                        if textvalue is not None:
                            response = my_text_2_num(textvalue)
                            if textvalue.strip() == "":
                                print("alors ?")
                            elif response < 0:
                                print(f"J'ai pas compris ({textvalue})")
                            else:
                                print(f"(Ta réponse «{textvalue}» -> {response})")
                                if response == a * b:
                                    print("Bien")
                                    count -= 1
                                    break
                                else:
                                    print("Raté")
                                    count = MAX_OPERATION_NB
                                    breakLangage du code : PHP (php)

Le script quick & dirty est disponible sur mon dépot github. Le système fonctionne étonnamment bien, même avec un vieux lenovo Thinkpad T430.

Maintenant que le principe est validé on va pouvoir «gamifier» tout ça et faire de super jeux 🙂

Mais c’est une autre histoire.

Ce contenu a été publié dans Non classé, avec comme mot(s)-clé(s) , , , . Vous pouvez le mettre en favoris avec ce permalien.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *