Search code examples
pythoncsvscopenameerror

NameError: free variable 'csv' referenced before assignment in enclosing scope


I'm new in Python and it might be a noob question, I've tried to google and search for the solution but I failed to understand, please be kind and if anyone could guide me through this?

I'm trying to callback my function in another function :

import csv
#import other libraries

#.......................................

def suara():
    fs = 44100  
    seconds = 2  
    myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
    print("Memulai: Silahkan berbicara sekarang!")
    sd.wait()  
    print("Selesai")
    write((os.path.join('data', 'recordings', 'test', '0_login.wav')), fs, myrecording)

    CREATE_CSV_FILES = True

    # Defines the names of the CSV files
    TRAIN_CSV_FILE = "train.csv"
    TEST_CSV_FILE = "test.csv"

    def extractWavFeatures(soundFilesFolder, csvFileName):
        print("The features of the files in the folder "+soundFilesFolder+" will be saved to "+csvFileName)
        header = 'filename chroma_stft rmse spectral_centroid spectral_bandwidth rolloff zero_crossing_rate'
        for i in range(1, 21):
            header += f' mfcc{i}'
        header += ' label'
        header = header.split()
        print('CSV Header: ', header)
        file = open(csvFileName, 'w', newline='')
        #with file:
        writer = csv.writer(file)
        writer.writerow(header)
        genres = '1 2 3 4 5 6 7 8 9 0'.split()
        for filename in os.listdir(soundFilesFolder):
            number = f'{soundFilesFolder}/{filename}'
            # print(number)
            y, sr = librosa.load(number, mono=True, duration=30)
            # remove leading and trailing silence
            y, index = librosa.effects.trim(y)
            chroma_stft = librosa.feature.chroma_stft(y=y, sr=sr)
            rmse = librosa.feature.rms(y=y)
            spec_cent = librosa.feature.spectral_centroid(y=y, sr=sr)
            spec_bw = librosa.feature.spectral_bandwidth(y=y, sr=sr)
            rolloff = librosa.feature.spectral_rolloff(y=y, sr=sr)
            zcr = librosa.feature.zero_crossing_rate(y)
            mfcc = librosa.feature.mfcc(y=y, sr=sr)
            to_append = f'{filename} {np.mean(chroma_stft)} {np.mean(rmse)} {np.mean(spec_cent)} {np.mean(spec_bw)} {np.mean(rolloff)} {np.mean(zcr)}'
            for e in mfcc:
                to_append += f' {np.mean(e)}'
            writer.writerow(to_append.split())
        file.close()
        print("End of extractWavFeatures")

#........................................................

I tried to call back this function in here :

def access(option):
    global name
    if(option=="login"):
        name = input("Masukkan ID: ")
        password = input("Masukkan Password: ")
        login(name,password)
    else:
        suara()
        
def begin():
    global option
    print("="*45)
    print(" |  Selamat datang  |")
    print("-"*45)
    print("Ketik 'login' jika anda ingin membuka pintu via nama dan password")
    print("Ketik 'suara' jika anda inin membuka pintu via suara")
    print("="*45)
    option = input("slahkan masukkan (login/suara): ")
    if(option!="login" and option!="suara"):
        begin()
        
begin()
access(option)

But I got the following error :

(cloning2) C:\Users\thosiba\speaker-recognition>C:/Users/thosiba/Anaconda3/envs/cloning2/python.exe c:/Users/thosiba/speaker-recognition/login2.py
=============================================
 |  Selamat datang  |
---------------------------------------------
Ketik 'login' jika anda ingin membuka pintu via nama dan password
Ketik 'suara' jika anda inin membuka pintu via suara
=============================================
slahkan masukkan (login/suara): suara
Memulai: Silahkan berbicara sekarang!
Selesai
The features of the files in the folder C:/Users/thosiba/speaker-recognition/data/recordings/train will be saved to train.csv
CSV Header:  ['filename', 'chroma_stft', 'rmse', 'spectral_centroid', 'spectral_bandwidth', 'rolloff', 'zero_crossing_rate', 'mfcc1', 'mfcc2', 'mfcc3', 'mfcc4', 'mfcc5', 'mfcc6', 'mfcc7', 'mfcc8', 'mfcc9', 'mfcc10', 'mfcc11', 'mfcc12', 'mfcc13', 'mfcc14', 'mfcc15', 'mfcc16', 'mfcc17', 'mfcc18', 'mfcc19', 'mfcc20', 'label']      
Traceback (most recent call last):
  File "c:/Users/thosiba/speaker-recognition/login2.py", line 236, in <module>
    access(option)
  File "c:/Users/thosiba/speaker-recognition/login2.py", line 221, in access
    suara()
  File "c:/Users/thosiba/speaker-recognition/login2.py", line 79, in suara
    extractWavFeatures("C:/Users/thosiba/speaker-recognition/data/recordings/train", TRAIN_CSV_FILE)
  File "c:/Users/thosiba/speaker-recognition/login2.py", line 55, in extractWavFeatures
    writer = csv.writer(file)
NameError: free variable 'csv' referenced before assignment in enclosing scope

I'm pretty sure it's related to calling the function or marking it down as global but I really don't understand how to work around it in this case. I'm sorry for the long question because I don't know how to explain better.


Solution

  • If you're naming a variable csv anywhere in your file (even below the line of the error), that would cause this error. Try changing the name of that variable to something else.