Getting this ONNXRuntimeError again and again. Please suggest - python-3.x

I am trying to run this code to remove background from my image but I keep getting an error. Please tell me what I am doing wrong
from rembg.bg import remove
import numpy as np
import io
from PIL import Image
input_path = 'crop.jpeg'
output_path = 'out.png'
f = np.fromfile(input_path)
result = remove(f)
img = Image.open(io.BytesIO(result)).convert("RGBA")
img.save(output_path)
*C:\Sauhard\Internships\TEST IMAGES>python -u "c:\Sauhard\Internships\TEST IMAGES\a.py"
Traceback (most recent call last):
File "c:\Sauhard\Internships\TEST IMAGES\a.py", line 10, in <module>
result = remove(f)
File "C:\Users\Sauhard Saini\AppData\Local\Programs\Python\Python39\lib\site-packages\rembg\bg.py", line 133, in remove
session = new_session("u2net")
File "C:\Users\Sauhard Saini\AppData\Local\Programs\Python\Python39\lib\site-packages\rembg\session_factory.py", line 60, in new_session
ort.InferenceSession(
File "C:\Users\Sauhard Saini\AppData\Local\Programs\Python\Python39\lib\site-packages\onnxruntime\capi\onnxruntime_inference_collection.py", line 347, in __init__
self._create_inference_session(providers, provider_options, disabled_optimizers)
File "C:\Users\Sauhard Saini\AppData\Local\Programs\Python\Python39\lib\site-packages\onnxruntime\capi\onnxruntime_inference_collection.py", line 395, in _create_inference_session
sess.initialize_session(providers, provider_options, disabled_optimizers)
RuntimeError: D:\a\_work\1\s\onnxruntime\core\session\provider_bridge_ort.cc:1029 onnxruntime::ProviderLibrary::Get [ONNXRuntimeError] : 1 : FAIL : LoadLibrary failed with error 126 "" when trying to load "C:\Users\Sauhard Saini\AppData\Local\Programs\Python\Python39\lib\site-packages\onnxruntime\capi\onnxruntime_providers_tensorrt.dll"*

This error is related to the generic graphics card driver provided with the Windows installation and happens mainly with AMD/ATI based solutions.
download and install the latest available version of the graphics card driver for your hardware at www.amd.com
Another option can be the installation of the "Visual C++ Redistributable Packages for Visual Studio".

Related

How to fix FileNotFoundError: [WinError 2] The system cannot find the file specified with AudioSegment.from_mp3()

I've been trying to find the position of spaces of audio silence in the audio of a video, but I can't get past just importing an audio file with pydub in python 3
I've already tried changing the directory that pydub is checking for ffmpeg to one within the project, and the file is in the directory I'm running the script from but it still seems to return the same error.
from moviepy import editor
from pydub import silence, AudioSegment
from pathlib import Path
import os
AudioSegment.converter = r"C:\\Users\\ratee\\PycharmProjects\\untitled\\ffmpeg\\bin\\ffmpeg.exe"
vid = editor.VideoFileClip("video.mp4")
print(AudioSegment.ffmpeg)
my_file = Path("audio.mp3")
if not my_file.is_file():
vid.audio.write_audiofile("audio.mp3")
audio = AudioSegment.from_mp3("audio.mp3")
print(audio)
I expect it to store the mp3 audio segment into the variable audi but it returns:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\pydevd.py", line 1741, in <module>
main()
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\pydevd.py", line 1735, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\pydevd.py", line 1135, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/ratee/PycharmProjects/untitled/fuc.py", line 12, in <module>
song = AudioSegment.from_mp3("audio.mp3")
File "C:\Users\ratee\PycharmProjects\untitled\venv\lib\site-packages\pydub\audio_segment.py", line 716, in from_mp3
return cls.from_file(file, 'mp3', parameters=parameters)
File "C:\Users\ratee\PycharmProjects\untitled\venv\lib\site-packages\pydub\audio_segment.py", line 665, in from_file
info = mediainfo_json(orig_file)
File "C:\Users\ratee\PycharmProjects\untitled\venv\lib\site-packages\pydub\utils.py", line 263, in mediainfo_json
res = Popen(command, stdin=stdin_parameter, stdout=PIPE, stderr=PIPE)
File "C:\Users\ratee\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 756, in __init__
restore_signals, start_new_session)
File "C:\Users\ratee\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 1155, in _execute_child
startupinfo)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\_pydev_bundle\pydev_monkey.py", line 452, in new_CreateProcess
return getattr(_subprocess, original_name)(app_name, patch_arg_str_win(cmd_line), *args)
FileNotFoundError: [WinError 2] The system cannot find the file specified
print(AudioSegment.ffmpeg)
returns as expected
C:\Users\ratee\PycharmProjects\untitled\ffmpeg\bin\ffmpeg.exe
print(my_file) returns
returns as expected
audio.mp3
and the code stops running at the point where I try to import audio
audio = AudioSegment.from_mp3("audio.mp3")
First part of the answer tries to reproduce OPs error for comparison reason. Thereafter finding a solution via update 1 and finally update 2. The folder-names x, y are used to shorten pathlengths.
Reproducing it threw me the following errors:
Error One:
c:\x\lib\site-packages\pydub\utils.py:165: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
c:\x\lib\site-packages\pydub\utils.py:193: RuntimeWarning: Couldn't find ffprobe or avprobe - defaulting to ffprobe, but may not work
warn("Couldn't find ffprobe or avprobe - defaulting to ffprobe, but may not work", RuntimeWarning)
Error Two:
Traceback (most recent call last):
File "C:\y\lol.py", line 16, in <module>
audi = AudioSegment.from_mp3("audio.mp3")
File "c:\x\lib\site-packages\pydub\audio_segment.py", line 716, in from_mp3
return cls.from_file(file, 'mp3', parameters=parameters)
File "c:\x\lib\site-packages\pydub\audio_segment.py", line 665, in from_file
info = mediainfo_json(orig_file)
File "c:\x\lib\site-packages\pydub\utils.py", line 263, in mediainfo_json
res = Popen(command, stdin=stdin_parameter, stdout=PIPE, stderr=PIPE)
File "c:\x\lib\subprocess.py", line 676, in __init__
restore_signals, start_new_session)
File "c:\x\lib\subprocess.py", line 957, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
The following code is to check if ffmpeg and ffprobe can be found:
AudioSegment.ffmpeg = os.getcwd()+"\\ffmpeg\\bin\\ffmpeg.exe"
print (AudioSegment.ffmpeg)
1) C:\y\ffmpeg\bin\ffmpeg.exe
And:
my_file = Path("audio.mp3")
print (my_file)
gives:
2) audio.mp3
Proposed solution:
Include the following specific codeline to specify where the ffmpeg is located:
pydub.AudioSegment.converter = r"C:\\path\\to\\ffmpeg.exe" where path\to\ is the actual path
And you should be fine.
Update 1:
You're raised error is due to the use of the filename at "my_file" and not "filepath" as required by AudioSegment.from_mp3(my_file). By providing the filepath this fixes the raised [WinError2] issue.
When you run below script the AttributeError: 'WindowsPath' object has no attribute 'read' error occurs. The error is related to pathlib and should have be been fixed in pydub 0.22 version as discussed here at github. I've raised the issue at Github.
The file.read() issue raised is python version related (2.7 vs. 3.5) because its nolonger in its build-in library. Therefore the .read() triggers the AttributeError: 'WindowsPath' object has no attribute 'read' error.
from pydub import silence, AudioSegment
from pathlib import Path
import os, sys
print (sys.version)
#AudioSegment.ffmpeg = os.getcwd()+"\\ffmpeg\\bin\\ffmpeg.exe"
AudioSegment.converter = r"C:\\x\\build\\win\\64\\ffmpeg.exe"
AudioSegment.ffprobe = r"C:\\x\\build\\win\\64\\ffprobe.exe"
#print (AudioSegment.converter)
#print (AudioSegment.ffprobe)
my_file = Path("C:\\y\\audio.mp3")
print ('ID1 : %s' % my_file)
audio = AudioSegment.from_mp3(my_file) # solves ***[WinError2]*** issue.
Update 2:
As update 1 solves a platform version issue update 2 solves the issue in error one and two at the same time if solution 1 in update 1 doesn't solve it yet.
Include in your script directly after the import statements the following lines:
mypaths = os.getenv('PATH').split(';') # replace 'PATH' by 'your search path' if needed.
for i in mypaths:
if i.find('python'):
print(i)
The printout shows you whether you have included the location of FFmpeg files or not. If not you need to reboot windows due to the fact the windows environment paths are not updated while you are currently in a python environment/editor.
In my case after reboot c:\y\FFmpeg\ showed up under 'PATH' and all warnings in error one and two were gone.
I met with the same problem.
pydub.AudioSegment.converter = os.getcwd()+ "\\ffmpeg.exe"
pydub.AudioSegment.ffprobe = os.getcwd()+ "\\ffprobe.exe"
sound = pydub.AudioSegment.from_mp3(os.getcwd()+"\\sample.mp3")
And everything is OK
I encountered the same problem but apparently even after adding ffmpeg path it still gives the same error. I tried this in Linux without extra commands like AudioSegment.converter = 'path\to\ffmpeg' it works fine, the problem is with Windows IDEs (pycharm, spyder, etc). Try running script directly from your prompt(anaconda, cmd, etc.) in windows. It should work.
Refrence: https://github.com/jiaaro/pydub/issues/319

ImportError: cannot import name '_ni_support' -- Using cx-freeze with scipy

I have used cx-freeze to make an executable file from my python 3 script. The issue is that apparently cx-freeze is having a hard time importing scipy scripts. I had to resolve other issues previously, e.g. adding the tcl library files manually. Anyway, my setup files is below:
from cx_Freeze import setup, Executable
import os
os.environ['TCL_LIBRARY'] = "C:\\Users\\Gobryas\\AppData\\Local\\Continuum\\anaconda3\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\Users\\Gobryas\\AppData\\Local\\Continuum\\anaconda3\\tcl\\tk8.6"
additional_mods = ['numpy.core._methods', 'numpy.lib.format']
setup(name = "Curve Characterization" ,
options = {'build_exe': {'includes': additional_mods}},
version = "0.1" ,
description = "" ,
executables = [Executable("curvCharLite.py")])
This is the error that I get:
ImportError: cannot import name '_ni_support'
Full details
Traceback (most recent call last):
File "C:\Users\Gobryas\AppData\Local\Continuum\anaconda3\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 14, in run
module.run()
File "C:\Users\Gobryas\AppData\Local\Continuum\anaconda3\lib\site-packages\cx_Freeze\initscripts\Console.py", line 26, in run
exec(code, m.__dict__)
File "curvCharLite.py", line 21, in <module>
File "c:\users\Gobryas\documents\mo\project 1\ruptures\ruptures\__init__.py", line 8, in <module>
from .detection import (Binseg, BottomUp, Dynp, Omp, OmpK, Pelt, Window,
File "c:\users\Gobryas\documents\mo\project 1\ruptures\ruptures\detection\__init__.py", line 51, in <module>
from .window import Window
File "c:\users\Gobryas\documents\mo\project 1\ruptures\ruptures\detection\window.py", line 112, in <module>
from scipy.signal import argrelmax
File "C:\Users\Gobryas\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\signal\__init__.py", line 311, in <module>
from ._savitzky_golay import savgol_coeffs, savgol_filter
File "C:\Users\Gobryas\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\signal\_savitzky_golay.py", line 6, in <module>
from scipy.ndimage import convolve1d
File "C:\Users\Gobryas\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\ndimage\__init__.py", line 161, in <module>
from .filters import *
File "C:\Users\Gobryas\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\ndimage\filters.py", line 35, in <module>
from . import _ni_support
ImportError: cannot import name '_ni_support'
PS 1: There is a similar issue asked here, but no helpful answer really.
PS 2: I'm using scipy 1.1.0, cx-freeze 5.1.1, and python 3.6.5
So, I think I found a solution for this problem inspired by the post by #fepzzz.
Looks like there are bad conflicts between cx-freeze and scipy which can be avoided as follows. I needed to modify the include_files build option as below:
import os
import scipy
includefiles_list=[]
scipy_path = os.path.dirname(scipy.__file__)
includefiles_list.append(scipy_path)
build_options = dict(packages=['matplotlib'], #this line solves an issue w/ matplotlib
include_files=includefiles_list, #this line is for scipy issue
includes=['matplotlib.backends.backend_qt5agg']) #this line solves another issue w/ matplotlib
Hope this helps others.

win32com module not found

I am trying to get pyttsx3 up and running on my computer. I did pip install pyttsx3 and pip install pypiwin32 I can see both of them in my python directory.
I type this code in to test it:
import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()
This is what comes out:
Traceback (most recent call last):
File "C:\Users\Danny\AppData\Local\Programs\Python\Python36\lib\site-packages\pyttsx3__init__.py", line 44, in init
eng = _activeEngines[driverName]
File "C:\Users\Danny\AppData\Local\Programs\Python\Python36\lib\weakref.py", line 131, in getitem
o = self.datakey
KeyError: None
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Danny\Desktop\python text to speech.py", line 9, in
engine = pyttsx3.init()
File "C:\Users\Danny\AppData\Local\Programs\Python\Python36\lib\site-packages\pyttsx3__init__.py", line 46, in init
eng = Engine(driverName, debug)
File "C:\Users\Danny\AppData\Local\Programs\Python\Python36\lib\site-packages\pyttsx3\engine.py", line 52, in init
self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
File "C:\Users\Danny\AppData\Local\Programs\Python\Python36\lib\site-packages\pyttsx3\driver.py", line 77, in init
self._driver = self._module.buildDriver(weakref.proxy(self))
File "C:\Users\Danny\AppData\Local\Programs\Python\Python36\lib\site-packages\pyttsx3\drivers\sapi5.py", line 22, in buildDriver
return SAPI5Driver(proxy)
File "C:\Users\Danny\AppData\Local\Programs\Python\Python36\lib\site-packages\pyttsx3\drivers\sapi5.py", line 41, in init
self.setProperty('voice', self.getProperty('voice'))
File "C:\Users\Danny\AppData\Local\Programs\Python\Python36\lib\site-packages\pyttsx3\drivers\sapi5.py", line 83, in setProperty
self._tts.Voice = token
File "C:\Users\Danny\AppData\Local\Programs\Python\Python36\lib\site-packages\win32com\client\dynamic.py", line 549, in setattr
self.oleobj.Invoke(entry.dispid, 0, invoke_type, 0, value)
pywintypes.com_error: (-2147352573, 'Member not found.', None, None)
I tried the same thing on another computer that already had both installed, and got the same output. Any idea what is going on with the win32com? I have no experience with it and am pretty lost. Thanks.
Ok, so I found the answer looking at other problems that were related to the win32com module. Basically what you need to do is navigate to your python scripts folder (in my case: C:\Users\Danny\AppData\Local\Programs\Python\Python36\Scripts) and run pywin32_postinstall. Upon running that script, it works perfectly!
Cheers!

RuntimeError: Failed to open TrueType font in matplotlib.backends_pdf in python 3.6.1

This code produces a pdf with matplotlib.
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages('test.pdf') as pdf:
plt.plot([1,4,3])
pdf.savefig()
On my desktop it works fine, but on my laptop it produces the following messages:
Traceback (most recent call last):
File "test.py", line 9, in <module>
pdf.savefig()
File "C:\Users\Georg\Anaconda3\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2426, in __exit__
self.close()
File "C:\Users\Georg\Anaconda3\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2433, in close
self._file.close()
File "C:\Users\Georg\Anaconda3\lib\site-packages\matplotlib\backends\backend_pdf.py", line 547, in close
self.writeFonts()
File "C:\Users\Georg\Anaconda3\lib\site-packages\matplotlib\backends\backend_pdf.py", line 650, in writeFonts
fonts[Fx] = self.embedTTF(realpath, chars[1])
File "C:\Users\Georg\Anaconda3\lib\site-packages\matplotlib\backends\backend_pdf.py", line 1124, in embedTTF
return embedTTFType3(font, characters, descriptor)
File "C:\Users\Georg\Anaconda3\lib\site-packages\matplotlib\backends\backend_pdf.py", line 910, in embedTTFType3
filename.encode(sys.getfilesystemencoding()), glyph_ids)
RuntimeError: Failed to open TrueType font
On both systems I run Python 3.6.1 :: Anaconda 4.4.0 (64-bit). The same code ran fine with python 3.5.1 on both systems. OS is Windows 10 Pro and Windows 10 Home.
I have no idea where to look to find a possible installation difference.
I have same problem.
Thanks guys from https://github.com/matplotlib/matplotlib/issues/7937
Using the example from the link above, I found a font with which I have correctly saved the pdf.
I add 2 strings and all works. For your code it's look as
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
plt.rcParams['pdf.fonttype'] = 42
plt.rcParams['font.family'] = 'Calibri'
with PdfPages('test.pdf') as pdf:
plt.plot([1,4,3])
pdf.savefig()

Unable to use print_control_identifiers() for my desktop application in pywinauto

Hi I am unable to use the "print_control_identifiers()" for my desktop application.
I am using a) Python 3.5.3 (32 bit since my application I am automating is 32 bit)
b) Pywinauto 0.6.2.
My simple code is as follows:
`from pywinauto import Application
app = Application(backend="uia")
app = Application().start(r"C:\Program Files (x86)\Trane\TRACE 3D Plus\TRACE™ 3D Plus.exe")
app['TRACE™ 3D Plus'].print_control_identifiers()`
When I run the above command, I got the following in command prompt:
Traceback (most recent call last):
File "D:\Python\lib\site-packages\pywinauto\application.py", line 243, in __re
solve_control
criteria)
File "D:\Python\lib\site-packages\pywinauto\timings.py", line 424, in wait_until_passes
raise err
pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "inspect.py", line 4, in <module>
app['TRACE\u2122 3D Plus'].print_control_identifiers()
File "D:\Python\lib\site-packages\pywinauto\application.py", line 573, in prin
t_control_identifiers
this_ctrl = self.__resolve_control(self.criteria)[-1]
File "D:\Python\lib\site-packages\pywinauto\application.py", line 246, in __re
solve_control
raise e.original_exception
File "D:\Python\lib\site-packages\pywinauto\timings.py", line 402, in wait_unt
il_passes
func_val = func(*args)
File "D:\Python\lib\site-packages\pywinauto\application.py", line 188, in __ge
t_ctrl
dialog = self.backend.generic_wrapper_class(findwindows.find_element(**crite
ria[0]))
File "D:\Python\lib\site-packages\pywinauto\findwindows.py", line 84, in find_
element
elements = find_elements(**kwargs)
File "D:\Python\lib\site-packages\pywinauto\findwindows.py", line 294, in find
_elements
elements = findbestmatch.find_best_control_matches(best_match, wrapped_elems
)
File "D:\Python\lib\site-packages\pywinauto\findbestmatch.py", line 534, in fi
nd_best_control_matches
raise MatchError(items = name_control_map.keys(), tofind = search_text)
pywinauto.findbestmatch.MatchError: Could not find 'TRACE\u2122 3D Plus' in 'dic
t_keys([])'
Can anyone tell me what the problem is and what I could do to resolve it ?
Thanks in advance !
Replace these commands
app = Application(backend="uia")
app = Application().start(r"C:\Program Files (x86)\Trane\TRACE 3D Plus\TRACE™ 3D Plus.exe")
with this one:
app = Application(backend="uia").start(r'"C:\Program Files (x86)\Trane\TRACE 3D Plus\TRACE™ 3D Plus.exe"')
Because you re-create app object with default backend="win32" if not using any argument. If it's hard to understand, I'd recommend to get a Python course first. Basic Python programming skills is necessary here to understand what's going on.

Resources