Module "Word" not found on custom class

Question:

I have a script1.py that is trying to call a custom class named Word.py that is in the same folder as the custom class. The directory is like this:

main/
├─ folder1/
│  ├─ __init__.py
│  ├─ script1.py
│  ├─ Word.py
├─ folder2/
│  ├─ __init__.py
│  ├─ script2.py
├─ __init__.py
├─ main.py
├─ __init__.py

On script1.py, I try to do the following:

import wave
import json

from vosk import Model, KaldiRecognizer, SetLogLevel
**from .Word import Word as custom_Word** 

model_path = "models/vosk-model-en-us-0.21"
audio_filename = "audio/speech_recognition_systems.wav"

model = Model(model_path)
wf = wave.open(audio_filename, "rb")
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True)

# get the list of JSON dictionaries
results = []
# recognize speech using vosk model
while True:
    data = wf.readframes(4000)
    if len(data) == 0:
        break
    if rec.AcceptWaveform(data):
        part_result = json.loads(rec.Result())
        results.append(part_result)
part_result = json.loads(rec.FinalResult())
results.append(part_result)

# convert list of JSON dictionaries to list of 'Word' objects
list_of_Words = []
for sentence in results:
    if len(sentence) == 1:
        # sometimes there are bugs in recognition 
        # and it returns an empty dictionary
        # {'text': ''}
        continue
    for obj in sentence['result']:
       

       **# Here You need to call custom_Word only**

 
        w = **custom_Word(obj)**  # create custom Word object
        list_of_Words.append(w)  # and add it to list

wf.close()  # close audiofile

# output to the screen
for word in list_of_words:
    print(word.to_string())

I get the error no module named "Word" found.

The issue is that I’ve tried in another folder before with the script calling the class side by side and it worked. But now it doesn’t.

I followed this tutorial that uses the class Word.py this way if you need further info: https://towardsdatascience.com/speech-recognition-with-timestamps-934ede4234b2

If anyone can point me in the right direction it would be great, thanks in advance.

The custom class is the following:

class Word:
    # A class representing a word from the JSON format for vosk speech recognition API 

    def __init__(self, dict):
        '''
        Parameters:
          dict (dict) dictionary from JSON, containing:
            conf (float): degree of confidence, from 0 to 1
            end (float): end time of the pronouncing the word, in seconds
            start (float): start time of the pronouncing the word, in seconds
            word (str): recognized word
        '''

        self.conf = dict["conf"]
        self.end = dict["end"]
        self.start = dict["start"]
        self.word = dict["word"]

    def to_string(self):
        ''' Returns a string describing this instance '''
        # return "{:20} from {:.2f} sec to {:.2f} sec, confidence is {:.2f}%".format(
        
        return "{:.2f} - {:.2f}n{:20}".format(
            # self.word, self.start, self.end, self.conf*100)
            self.start, self.end, self.word)

EDIT: After @LietKynes posted an answer, I realized you also need, when instantiating the custom class, call the name that you defined the import as , in my case, custom_Word. I added what I changed to the question in bold.

Asked By: kanjas

||

Answers:

For python modules (.py files) that are being in a package (in a directory that has __init__.py file), the modules should use relative import to import from other modules in the same package:

from .Word import Word as custom_Word
Answered By: LietKynes

Hello all import words as custom_Word worked for me 🙂

Answered By: Yanet G. Bustamante
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.