pythonvisual-studio-codeimportdependencies

Why does running Python import fails on first run but works on subsequent ones (noisereduce package)?


Working with VS Code and Jupyter notebook extension (among others), in a virtual environment that is properly activated.
I am trying to run the following import:

import noisereduce

The first time I run the code, this error is shown:

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_2444\169068538.py in <module>
----> 1 import noisereduce

c:\Users\Username\miniconda3\envs\adsml\lib\site-packages\noisereduce\__init__.py in <module>
----> 1 from noisereduce.noisereduce import reduce_noise

c:\Users\Username\miniconda3\envs\adsml\lib\site-packages\noisereduce\noisereduce.py in <module>
----> 1 from noisereduce.spectralgate.stationary import SpectralGateStationary
      2 from noisereduce.spectralgate.nonstationary import SpectralGateNonStationary
      3 
      4 try:
      5     import torch

c:\Users\Username\miniconda3\envs\adsml\lib\site-packages\noisereduce\spectralgate\__init__.py in <module>
      1 from .nonstationary import SpectralGateNonStationary
      2 from .stationary import SpectralGateStationary
----> 3 from .streamed_torch_gate import StreamedTorchGate

c:\Users\Username\miniconda3\envs\adsml\lib\site-packages\noisereduce\spectralgate\streamed_torch_gate.py in <module>
----> 1 import torch
      2 from noisereduce.spectralgate.base import SpectralGate
      3 from noisereduce.torchgate import TorchGate as TG
      4 import numpy as np
      5 

ModuleNotFoundError: No module named 'torch'

But then, running it again works, until I restart the kernel, or reload window, or close/reopen VS Code.
Why is that? Should I try to manually install torch on this venv?

Edit
This [ugly hack] works:

try:
    import noisereduce
except:
    import noisereduce  # must run twice

Edit 2
Versions

python      3.9.16
noisereduce 3.0.0
VSCode      1.84.2

Solution

  • Seems that is some issue of the 3.0.0 version. From the noisereduce github: https://github.com/timsainb/noisereduce/issues/96

    The owner suggets to use the patch-torch-dependency branch.