Path error with Tesseract - python-2.7

I thought I'd got Tesseract to work on my Win 7 machine:
from PIL import Image
import pytesseract
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'
tessdata_dir_config = '--tessdata-dir "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata"'
myFile = r"D:\temp\OCR\rightness_of_rendering.tif"
print(pytesseract.image_to_string(Image.open(myFile)))
tesseract.exe is located in C:\Program Files (x86)\Tesseract-OCR\tesseract.exe
eng.traineddata is located in C:\Program Files (x86)\Tesseract-OCR\tessdata
The error I get is
D:\LearnPython>D:\LearnPython\ocr_test.py
Traceback (most recent call last):
File "D:\LearnPython\ocr_test.py", line 14, in <module>
print(pytesseract.image_to_string(Image.open(myFile)))
File "C:\Python27\lib\site-packages\pytesseract\pytesseract.py", line 125, in
image_to_string
raise TesseractError(status, errors)
pytesseract.pytesseract.TesseractError: (1, u'Error opening data file \\Program
Files (x86)\\Tesseract-OCR\\eng.traineddata')
D:\LearnPython>
Which is one directory up, so I'm a little confused as how to set that up so it'll work properly.

From pytesseract github page
tessdata_dir_config = '--tessdata-dir "<replace_with_your_tessdata_dir_path>"'
# Example config: '--tessdata-dir "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata"'
# It's important to add double quotes around the dir path.
pytesseract.image_to_string(image, lang='chi_sim', config=tessdata_dir_config)
Note that you need to provide config=tessdata_dir_config into your image_to_string call
So if you're using eng data it would be
print(pytesseract.image_to_string(Image.open(myFile), lang='eng', config=tessdata_dir_config))

Related

How to close several folders in window 7 using Python

I seeking a way to close 20 open sub directories in window 7 using this python code. i want to close only those sub directories and not other open directories:
import os,sys,re
day = '2.1'
rootdir = r'G:\desktop'
for rootdir, dirs, files in os.walk(rootdir):
for subdir in dirs:
dayFolder = os.path.join(rootdir, subdir)
match = re.search('2022.January$',dayFolder)
if match:
os.close(os.path.join(dayFolder,day))
after i run it i get an error:
Traceback (most recent call last):
File "G:\desktop\y\general\test1.py", line 21, in <module>
os.close(os.path.join(dayFolder,day)) # close folder path
TypeError: an integer is required
>>>
update:
"close the sub directories" - i mean like clicking on the close button

OpenVino Model Optimizer Error when converting TensorFlow model

I have created a custom image classification .pb model file using the python scripts in the TensorFlow for Poets 2 repo (https://github.com/googlecodelabs/tensorflow-for-poets-2).
I tried converting it to Intermediate Representation using the OpenVino Model Optimizer using the below scripts:
python mo_tf.py --input_model retrained_graph.pb
python mo_tf.py --input_model retrained_graph.pb --mean_values [127.5,127.5,127.5] --input Mul
In both cases this is what happened:
Model Optimizer arguments:
Common parameters:
- Path to the Input Model: C:\Program Files (x86)\IntelSWTools\openvino_2019.3.379\deployment_tools\model_optimizer\retrained_graph.pb
- Path for generated IR: C:\Program Files (x86)\IntelSWTools\openvino_2019.3.379\deployment_tools\model_optimizer\.
- IR output name: retrained_graph
- Log level: ERROR
- Batch: Not specified, inherited from the model
- Input layers: Not specified, inherited from the model
- Output layers: Not specified, inherited from the model
- Input shapes: Not specified, inherited from the model
- Mean values: Not specified
- Scale values: Not specified
- Scale factor: Not specified
- Precision of IR: FP32
- Enable fusing: True
- Enable grouped convolutions fusing: True
- Move mean values to preprocess section: False
- Reverse input channels: False
TensorFlow specific parameters:
- Input model in text protobuf format: False
- Path to model dump for TensorBoard: None
- List of shared libraries with TensorFlow custom layers implementation: None
- Update the configuration file with input/output node names: None
- Use configuration file used to generate the model with Object Detection API: None
- Operations to offload: None
- Patterns to offload: None
- Use the config file: None
Model Optimizer version: 2019.3.0-408-gac8584cb7
[ ERROR ] -------------------------------------------------
[ ERROR ] ----------------- INTERNAL ERROR ----------------
[ ERROR ] Unexpected exception happened.
[ ERROR ] Please contact Model Optimizer developers and forward the following information:
[ ERROR ] local variable 'new_attrs' referenced before assignment
[ ERROR ] Traceback (most recent call last):
File "C:\Program Files (x86)\IntelSWTools\openvino_2019.3.379\deployment_tools\model_optimizer\mo\front\extractor.py", line 608, in extract_node_attrs
supported, new_attrs = extractor(Node(graph, node))
File "C:\Program Files (x86)\IntelSWTools\openvino_2019.3.379\deployment_tools\model_optimizer\mo\pipeline\tf.py", line 132, in <lambda>
extract_node_attrs(graph, lambda node: tf_op_extractor(node, check_for_duplicates(tf_op_extractors)))
File "C:\Program Files (x86)\IntelSWTools\openvino_2019.3.379\deployment_tools\model_optimizer\mo\front\tf\extractor.py", line 109, in tf_op_extractor
attrs = tf_op_extractors[op](node)
File "C:\Program Files (x86)\IntelSWTools\openvino_2019.3.379\deployment_tools\model_optimizer\mo\front\tf\extractor.py", line 65, in <lambda>
return lambda node: pb_extractor(node.pb)
File "C:\Program Files (x86)\IntelSWTools\openvino_2019.3.379\deployment_tools\model_optimizer\mo\front\tf\extractors\const.py", line 31, in tf_const_ext
result['value'] = tf_tensor_content(pb_tensor.dtype, result['shape'], pb_tensor)
File "C:\Program Files (x86)\IntelSWTools\openvino_2019.3.379\deployment_tools\model_optimizer\mo\front\tf\extractors\utils.py", line 76, in tf_tensor_content
dtype=type_helper[0]),
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files (x86)\IntelSWTools\openvino_2019.3.379\deployment_tools\model_optimizer\mo\main.py", line 298, in main
return driver(argv)
File "C:\Program Files (x86)\IntelSWTools\openvino_2019.3.379\deployment_tools\model_optimizer\mo\main.py", line 247, in driver
is_binary=not argv.input_model_is_text)
File "C:\Program Files (x86)\IntelSWTools\openvino_2019.3.379\deployment_tools\model_optimizer\mo\pipeline\tf.py", line 132, in tf2nx
extract_node_attrs(graph, lambda node: tf_op_extractor(node, check_for_duplicates(tf_op_extractors)))
File "C:\Program Files (x86)\IntelSWTools\openvino_2019.3.379\deployment_tools\model_optimizer\mo\front\extractor.py", line 614, in extract_node_attrs
new_attrs['name'] if 'name' in new_attrs else '<UNKNOWN>',
UnboundLocalError: local variable 'new_attrs' referenced before assignment
[ ERROR ] ---------------- END OF BUG REPORT --------------
[ ERROR ] -------------------------------------------------
Does anyone know how to fix it?
Eventually I found a solution that worked for me.
I checked the OpenVino Toolkit documentation and found this (02/03/2020)
Under 'Supported Topologies' there is a list with the topologies that work with the OpenVino model optimizer. When you create a model using TensorFlow for Poets 2, you need make sure you choose an architecture that is supported by the model optimizer.

cx_Freeze: 'The system cannot find the file specified' error during build [win10] [PyQt4] [python2.7]

I'm trying to create a .exe file from a python script (which use PyQt4 GUI and matplotlib). I'm using cx_Freeze version 5.1.1 for 64-bit windows with the following setup.py:
import cx_Freeze
import sys
import matplotlib
base = "Win32GUI"
includes = ["atexit"]
buildOptions = dict(
#create_shared_zip=False,
#append_script_to_exe=True,
includes=includes
)
executables = [cx_Freeze.Executable(script = "main.py", base = base)] # icon = "chart32.jpg")]
cx_Freeze.setup(
name= "1ChPlotGUI",
options = dict(build_exe=buildOptions), # {"build_exe": {"packages": ["matplotlib"], "include_files":["chart32.jpg"]}},
version = "0.01",
description = "1 Channel Plotting app with GUI",
executables = executables
)
after running
python setup.py build
in the cmd from the position of
C:\Users\Us.Er\Pyth-examples\Qt\UI-examples\ChannelplotGUI-to-exe
I have something like this:
running build
running build_exe
copying c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-
packages\cx_Freeze\bases\Win32GUI.exe -> build\exe.win-amd64-2.7\main.exe
copying
c:\users\Us.Er\appdata\local\enthought\canopy\user\scripts\python27.dll ->
build\exe.win-amd64-2.7\python27.dll
Traceback (most recent call last):
File "setup.py", line 23, in <module>
executables = executables
File "c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-packages\cx_Freeze\dist.py", line 349, in setup
distutils.core.setup(**attrs)
File "C:\Users\Us.Er\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\distutils\core.py", line 151, in setup
dist.run_commands()
File "C:\Users\Us.Er\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\distutils\dist.py", line 953, in run_commands
self.run_command(cmd)
File "C:\Users\Us.Er\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\distutils\dist.py", line 972, in run_command
cmd_obj.run()
File "C:\Users\Us.Er\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\distutils\command\build.py", line 127, in run
self.run_command(cmd_name)
File "C:\Users\Us.Er\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\distutils\cmd.py", line 326, in run_command
self.distribution.run_command(command)
File "C:\Users\Us.Er\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\distutils\dist.py", line 972, in run_command
cmd_obj.run()
File "c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-packages\cx_Freeze\dist.py", line 219, in run
freezer.Freeze()
File "c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-packages\cx_Freeze\freezer.py", line 626, in Freeze
self._FreezeExecutable(executable)
File "c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-packages\cx_Freeze\freezer.py", line 232, in _FreezeExecutable
self._AddVersionResource(exe)
File "c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-packages\cx_Freeze\freezer.py", line 172, in _AddVersionResource
stamp(fileName, versionInfo)
File "c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-packages\win32\lib\win32verstamp.py", line 159, in stamp
h = BeginUpdateResource(pathname, 0)
pywintypes.error: (2, 'BeginUpdateResource', 'The system cannot find the file specified.')
What is the possible solution for above problem?
EDIT
To be clear: I don't want to add any icon for now. I am happy with just a simple, working .exe
I have added the target in this way:
executables = [cx_Freeze.Executable(script = "main.py", base = base, targetName="main.exe")]
I have tried to add
targetDir = "C:\Users\Us.Er\Pyth-examples\Qt\UI-examples\ChannelplotGUI-to-exe"
anyway, the return is:
TypeError: __init__() got an unexpected keyword argument 'targetDir'
The main problem is as before - the error with last lines as:
h = BeginUpdateResource(pathname, 0)
pywintypes.error: (2, 'BeginUpdateResource', 'The system cannot find the file specified.')
In my case the issue was solved by changing
'build_exe': 'build_folder'
to
'build_exe': './/build_folder'
This is because open(pathname) would work on the pathname='build_folder\\executable.exe', allowing the code to advance during the check at the begginning of the stamp method, but BeginUpdateResource(pathname, 0) would only work on './/build_folder\\executable.exe'
Solution
options = {
'build_exe': {
'build_exe': './/build'
}
}
Note: .//build here, build is the folder name where you want to build your project.
Thanks to help of user jpeg I managed to successfully freeze the script.
To eliminate the problem with path I have added a line print(pathname) in win32verstamp.py before line 159.
The print statement worked fine showing the relative path to the newly made .exe file.
Despite showing the correct path, the error was still present. I went to the stamp() definition in win32verstamp.py and found a try - except block, and have inserted print(pathname) over there.
The part is:
def stamp(pathname, options):
# For some reason, the API functions report success if the file is open
# but doesnt work! Try and open the file for writing, just to see if it is
# likely the stamp will work!
#print("Current path is " + pathname)
try:
f = open(pathname, "a+b")
f.close()
print("Possible to open" + pathname) #<---line added
except IOError, why:
print "WARNING: File %s could not be opened - %s" % (pathname, why)r code here
....
Since that the freeze was possible. (Not sure why tho, I'm happy to add some info if explanation is known)
I had the same issue tying to freeze my PyQt5 app (using python 3.7 under windows 10) with the following message :
h = BeginUpdateResource(pathname, 0)
pywintypes.error: (2, 'BeginUpdateResource', 'Le fichier spécifié est introuvable.')
So I choose to use cx_freeze Sample provided as a first step.
(This samples are availables after cx_freeze installation under MyVENVpath\Lib\site-packages\cx_Freeze\samples)
The very basic PyQt5 exemple was working, but my case was way more complex as I used several sub Python class I have developed.
I honestly don't really understand why but I was able to make it work So here is all modifications I have performed :
In setup.py identify sub python files
add my personnal packages and class like this :
include = ["PyQt5", "PySerial", "myclass1", "myclass2", "myclass3", "PandasModel"]
packages = ["PySerial", "myclass1", "myclass2", "myclass3", "PandasModel", "pandas","math"]
Use relative path in setup.py
executables = [cx_Freeze.Executable(os.getcwd() + r'\..\..\MyFileName.py', base=base)]
include_files = [(os.getcwd() + r'\..\..\CalibrationTool.ui', r'Inputs\GUI\CalibrationTool.ui')
The reason for "...." is to jump two directories higher level, as my python.exe is in sub folders VENV\Script\
Add python Files containing "Myclass1" at same level as setup.py.
Even if in my application, class files are in a subfolder Input\Packages\Myclass1File.py, I had to copy-paste it at the same level as setup.py. This way the include and package line of setup.py work and was able to generate the executable.
Last but not least,the terminal command
I have no idea why but the only command who did suceed was:
to use full path to the python.exe and full path to the setup.py with the "build" at the end.
cmd:>C:\Folder1\Folder2\MyVENV\Scripts\python.exe D:\Folder1\Folder2\setup.py build
This finaly created the executable in a build folder under C:\Folder1\Folder2\MyVENV\Scripts\

Creating a small python program with cx_Freeze and pyGTK

I'm writing a small test-program that using python 2.7 and pygtk.
I will use Glade too
I need freeze this with cx_freeze.
This is my little program:
import gtk
win = gtk.Window()
win.connect("delete-event", gtk.main_quit)
win.show_all()
gtk.main()
And this is my setup:
from cx_Freeze import setup, Executable
import os, site, sys
## Get the site-package folder, not everybody will install
## Python into C:\PythonXX
site_dir = site.getsitepackages()[1]
include_dll_path = os.path.join(site_dir, "gnome")
## Collect the list of missing dll when cx_freeze builds the app
missing_dll = ['libgtk-win32-2.0-0.dll',
'libgdk-win32-2.0-0.dll',
'libatk-1.0-0.dll',
'libcairo-gobject-2.dll',
'libgdk_pixbuf-2.0-0.dll',
'libjpeg-8.dll',
'libpango-1.0-0.dll',
'libpangocairo-1.0-0.dll',
'libpangoft2-1.0-0.dll',
'libpangowin32-1.0-0.dll'
# 'libgnutls-26.dll',
# 'libgcrypt-11.dll',
# 'libp11-kit-0.dll'
]
## We also need to add the glade folder, cx_freeze will walk
## into it and copy all the necessary files
glade_path = os.path.join(site_dir, "gtk-2.0\\runtime\include\libglade-2.0\\")
glade_folder = 'glade'
# glade_folder = os.path.join(site_dir, "gtk-2.0\\")
# glade_folder += "runtime\include\libglade-2.0\glade"
## We need to add all the libraries too (for themes, etc..)
gtk_libs = ['etc', 'lib', 'share']
## Create the list of includes as cx_freeze likes
include_files = []
for dll in missing_dll:
include_files.append((os.path.join(include_dll_path, dll), dll))
## Let's add glade folder and files
include_files.append((glade_path, glade_folder))
## Let's add gtk libraries folders and files
for lib in gtk_libs:
include_files.append((os.path.join(include_dll_path, lib), lib))
base = None
## Lets not open the console while running the app
if sys.platform == "win32":
base = "Win32GUI"
executables = [
Executable("hello.py",
base=base
)
]
buildOptions = dict(
compressed=False,
includes=["gi"],
packages=["gi"],
include_files=include_files
)
setup(
name="test_gtk3_app",
author="my name",
version="1.0",
description="GTK 3 test",
options=dict(build_exe=buildOptions),
executables=executables
)
I run this command:
python setup_fr.py build
So, a folder called "build" is created with various files and directories. But, when I run the program "hello.exe", this error occurs:
Traceback (most recent call last): File "C:\Python27\lib\site-packages\cx_freeze-4.3.3-py2.7-win32.egg\cx_Freeze\initscripts\Console.py", line 27, in <module>
exec(code, m.__dict__) File "hello.py", line 1, in <module> File "C:\Python27\lib\site-packages\gtk-2.0\gtk\__init__.py", line 30, in <module>
import gobject as _gobject File "C:\Python27\lib\site-packages\gobject\__init__.py", line 26, in <module>
from glib import spawn_async, idle_add, timeout_add, timeout_add_seconds, \ File "C:\Python27\lib\site-packages\glib\__init__.py", line 22, in <module>
from glib._glib import * File "ExtensionLoader_glib__glib.py", line 22, in <module> File "ExtensionLoader_glib__glib.py", line 14, in __bootstrap__ ImportError: DLL load failed: Could not find the specified module.
I've looked at the "Build" folder to see if missing something related to gobject and found the "gobject._gobject.pyd" "libcairo-gobject-2.dll" and "GObject-2.0.typelib" files. I do not know exactly which file is still missing.
Can anyone help me figure out what is wrong?
Go to the gnome dir, which by itself is in the site-packages dir and manually copy all the .dll files (not the nested one) from this dir to your build/your-application-dir/ dir.
And it will work.

Creating a single executable .exe from Python script that uses PuLP

I have been struggling with this for a while. I have used py2exe and cx_freeze to package everything. I am using a 32 bit machine and Everything works fine and the interface opens up and everything just that I know the entire puLP package is not being copied correctly into the package. I know this because the solver does not work. Inside both library zips in the packages created by py2exe and cx_freeze, there are only .pyc files included where PuLP has cbc.exe and other file types that make the solver work.
Is there any work around this? I have tried copying the actual PuLP package into the library.zip as well as into the dist folder and that didn't work.
Here is the setup I used for py2exe:
import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["pulp"],
"icon": "icon.ico",
"include_files": ["icon.ico","cbc.exe","cbc-32","cbc-64","cbc-osx-64","CoinMP.dll"]}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup( name = "my_app",
version = "0.1",
options = {"build_exe": build_exe_options},
executables = [Executable("my_app.py", base=base)])
I received the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "Tkinter.pyc", line 1470, in __call__
File "my_app.py", line 796, in <lambda>
File "my_app.py", line 467, in branchAndBound
File "pulp\pulp.pyc", line 1619, in solve
AttributeError: 'NoneType' object has no attribute 'actualSolve'
EDIT
I tried to change the paths to cbc.exe and CoinMP.dll but that didn't really work either. I am probably missing something.
I changed the following inside solvers.py in the PuLP package:
try:
coinMP_path = config.get("locations", "CoinMPPath").split(', ')
except configparser.Error:
coinMP_path = ['/Users/al/Desktop/my_app/build/exe.win32-2.7']
try:
cbc_path = config.get("locations", "CbcPath")
except configparser.Error:
cbc_path = '/Users/al/Desktop/my_app/build/exe.win32-2.7'
try:
pulp_cbc_path = config.get("locations", "PulpCbcPath")
except configparser.Error:
pulp_cbc_path = '/Users/al/Desktop/my_app/build/exe.win32-2.7'
What am I missing or doing wrong?