How to fix 'FileNotFoundError' when using pyx.canvas.writeGSfile() in Python? - python-3.x

I would like to generate a jpeg or png file using the Pyx module. I found
pyx.canvas.writeGSfile() which I tried to use in the following code:
from pyx import *
def mark(x, y):
return path.circle(x, y, 0.1)
if __name__ == '__main__':
c = canvas.canvas()
# r = 70
f = trafo.scale(0.7, 1)
circle = path.circle(0, 0, 2)
a, b = circle.split([0, 2])
c.stroke(a, [style.linewidth.Thick, f])
d1 = f.apply(*circle.at(0.5*circle.arclen()))
d2 = f.apply(*circle.at(circle.arclen()))
c.fill(mark(*d1))
c.fill(mark(*d2))
c.writeGSfile('test.jpeg')
But it spits back the following error:
Traceback (most recent call last):
File "/Python/pyx/test.py", line 19, in <module>
c.writeGSfile('test.png')
File "\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pyx\canvas.py", line 474, in writeGSfile
p = config.Popen(cmd, stdin=config.PIPE)
File "\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pyx\config.py", line 218, in Popen
return subprocess.Popen(cmd, *args, **kwargs)
File "\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 997, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
I tried to debug but I'm having trouble understanding the processing.py section. Any ideas?

You need to have ghostscript installed (gs) to generate bitmap output.

Related

Unable to use Graphviz library in Python

Here is the code I try to execute:
from graphviz import Graph
# Instantiate a new Graph object
dot = Graph('Data Science Process', format='png')
# Add nodes
dot.node('A', 'Get Data')
dot.node('B', 'Clean, Prepare, & Manipulate Data')
dot.node('C', 'Train Model')
dot.node('D', 'Test Data')
dot.node('E', 'Improve')
# Connect these nodes
dot.edges(['AB', 'BC', 'CD', 'DE'])
# Save chart
#dot.render('data_science_flowchart', view=True)
The render function won't work, and I have not idea what is wrong. If commented out, the code works, but of course produces nothing. My goal is to make a visualization of the graph (PNG image, or PDF file). Just trying to plot a rudimentary flowchart in Python, I am open to using other libraries than graphviz: I am new to this, and tried graphviz after reading recommendations, tested a dozen scripts posted online, but none of them work, always resulting in the same error.
Here is the error:
$ py graph2.py
py graph2.py
Traceback (most recent call last):
File "C:\Users\vince\AppData\Local\Programs\Python\Python310\lib\site-packages\graphviz\backend\execute.py", line 81, in run_check
proc = subprocess.run(cmd, **kwargs)
File "C:\Users\vince\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 501, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\vince\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 966, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\vince\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1435, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\vince\graph2.py", line 17, in <module>
dot.render('data_science_flowchart', view=True)
File "C:\Users\vince\AppData\Local\Programs\Python\Python310\lib\site-packages\graphviz\_tools.py", line 171, in wrapper
return func(*args, **kwargs)
File "C:\Users\vince\AppData\Local\Programs\Python\Python310\lib\site-packages\graphviz\rendering.py", line 122, in render
rendered = self._render(*args, **kwargs)
File "C:\Users\vince\AppData\Local\Programs\Python\Python310\lib\site-packages\graphviz\_tools.py", line 171, in wrapper
return func(*args, **kwargs)
File "C:\Users\vince\AppData\Local\Programs\Python\Python310\lib\site-packages\graphviz\backend\rendering.py", line 324, in render
execute.run_check(cmd,
File "C:\Users\vince\AppData\Local\Programs\Python\Python310\lib\site-packages\graphviz\backend\execute.py", line 84, in run_check
raise ExecutableNotFound(cmd) from e
graphviz.backend.execute.ExecutableNotFound: failed to execute WindowsPath('dot'), make sure the Graphviz executables are on your systems' PATH

AttributeError: 'tuple' object has no attribute 'read' music21 .show()

i have been trying to show a score converted from krn file
import music21 as m
import os
test_data = "D:/Programming/DATA - SCIENCE/deep learning/music generation/data/test"
def load_krn_files(data_path):
# go through the whole files
songs = []
for path , subdirs,files in os.walk(data_path):
for file in files :
if file [-3:] == "krn":
song = m.converter.parse(os.path.join(path,file))
songs.append(song)
return songs
def preproccessing(data_path):
pass
#1 ) load the kern files and pars them
if __name__ == "__main__":
songs = load_krn_files(test_data)
print(f"loaded {len(songs)} songs.")
song = songs[0]
song.show()
but the method (show) return the following error
loaded 12 songs.
Traceback (most recent call last):
File "d:/Programming/DATA - SCIENCE/deep learning/music generation/scripts/preprocess.py", line 25, in
song.show()
File "C:\Users\ae504\AppData\Local\Programs\Python\Python38\lib\site-packages\music21\stream\base.py", line 334, in show
return super().show(fmt=fmt, app=app, **keywords) File "C:\Users\ae504\AppData\Local\Programs\Python\Python38\lib\site-packages\music21\base.py", line 2788, in show
return formatWriter.show(self,
File "C:\Users\ae504\AppData\Local\Programs\Python\Python38\lib\site-packages\music21\converter\subConverters.py", line 1114, in show
self.launch(returnedFilePath, fmt=fmt, app=app)
File "C:\Users\ae504\AppData\Local\Programs\Python\Python38\lib\site-packages\music21\converter\subConverters.py", line 197, in launch
subprocess.run(cmd, check=False, shell=shell)
File "C:\Users\ae504\AppData\Local\Programs\Python\Python38\lib\site-packages\run_init_.py", line 145, in new
process = cls.create_process(command, stdin, cwd=cwd, env=env, shell=shell)
File "C:\Users\ae504\AppData\Local\Programs\Python\Python38\lib\site-packages\run_init_.py", line 121, in create_process
shlex.split(command),
File "C:\Users\ae504\AppData\Local\Programs\Python\Python38\lib\shlex.py", line 311, in split
return list(lex)
File "C:\Users\ae504\AppData\Local\Programs\Python\Python38\lib\shlex.py", line 300, in next
token = self.get_token()
File "C:\Users\ae504\AppData\Local\Programs\Python\Python38\lib\shlex.py", line 109, in get_token
raw = self.read_token()
File "C:\Users\ae504\AppData\Local\Programs\Python\Python38\lib\shlex.py", line 140, in read_token
nextchar = self.instream.read(1)
AttributeError: 'tuple' object has no attribute 'read'

PythonPDF: FileNotFoundError: [WinError 2] The system cannot find the file specified

I am getting the below error trace when I am using PDFJinja's example for filling form fields in an existing PDF file.
Code Snippet:
dir_name = os.path.dirname("P:\\Project\\pdfjinja_services\\resources\\sample.pdf")
template_pdf_file = os.path.join(dir_name, 'sample.pdf')
template_pdf = PdfJinja(template_pdf_file, current_app.jinja_env)
print(type(template_pdf))
rendered_pdf = template_pdf({
'firstName': 'Faye',
'lastName': 'Valentine'
})
output_file = os.path.join(dir_name, 'output.pdf')
rendered_pdf.write(open(output_file, 'wb'))
Error:
Traceback (most recent call last):
File "P:\Professional\Python\CR\workspace\workspace-local\myplaybook\pdf_pdfjinja.py", line 10, in
rendered_pdf = template_pdf({
File "P:\Professional\Python\Softwares\python-3.9.6\lib\site-packages\pdfjinja.py", line 240, in call
filled = PdfFileReader(self.exec_pdftk(self.rendered))
File "P:\Professional\Python\Softwares\python-3.9.6\lib\site-packages\pdfjinja.py", line 212, in exec_pdftk
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
File "P:\Professional\Python\Softwares\python-3.9.6\lib\subprocess.py", line 951, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "P:\Professional\Python\Softwares\python-3.9.6\lib\subprocess.py", line 1420, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified
I am using python-3.9.6 and PDFJinja-1.1.0.
Please let me know if I am missing any other dependencies.
You are missing a binary (per update pdftk), or the binary is not in your search path.

Does `concurrent.futures.ProcessPoolExecutor()` have any restriction on number of processes?

I wrote a simple code using concurrent.futures.ProcessPoolExecutor() whihc you can see in below. I'm using Python 3.7.4 on Windows 10 (64 bit) on a Core-i7 laptop.
import time
import concurrent.futures
def f(x):
lo = 0
for i in range(x):
lo += i
return(lo)
n = 7
if __name__ == '__main__':
t1 = time.perf_counter()
with concurrent.futures.ProcessPoolExecutor() as executor:
Ans = [executor.submit(f, 10**7-i) for i in range(n)]
for f in concurrent.futures.as_completed(Ans):
print(f.result())
t2 = time.perf_counter()
print('completed at', t2-t1, 'seconds')
The variable n determines how many processes is going to execute. When I set n to 1, 2, 4, 7 everything work fine. For example the output for n=7 is
49999995000000
49999955000010
49999965000006
49999985000001
49999975000003
49999945000015
49999935000021
completed at 2.0607623 seconds
However for n=10 it gives the following error!
49999945000015
49999955000010
49999965000006
concurrent.futures.process._RemoteTraceback:
"""
Traceback (most recent call last):
File "E:\Python37\lib\multiprocessing\queues.py", line 236, in _feed
obj = _ForkingPickler.dumps(obj)
File "E:\Python37\lib\multiprocessing\reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function f at 0x00000285BFC4E0D8>: it's not the same object as __main__.f
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "e:/Python37/Python files/Parallel struggle/Python_20191219_parallel_3.py", line 23, in <module>
print(f.result())
File "E:\Python37\lib\concurrent\futures\_base.py", line 428, in result
return self.__get_result()
File "E:\Python37\lib\concurrent\futures\_base.py", line 384, in __get_result
raise self._exception
File "E:\Python37\lib\multiprocessing\queues.py", line 236, in _feed
obj = _ForkingPickler.dumps(obj)
File "E:\Python37\lib\multiprocessing\reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function f at 0x00000285BFC4E0D8>: it's not the same object as __main__.f
Why some of the processes get done if something is wrong with the code? And what has happened that an error comes up? And is it specific to python on windows? Is it about the number of CPUs?

OSError: [Errno 12] Cannot allocate memory pytesseract

I am facing an issue. I am running a python script which converts pdf to image using tesseract.
for filename in path_list:
print(filename)
pdfFile = wi(filename = filename, resolution = 300)
image = pdfFile.convert('jpeg')
imageBlobs = []
for img in image.sequence:
imgPage = wi(image = img)
imageBlobs.append(imgPage.make_blob('jpeg'))
extract = []
for imgBlob in imageBlobs:
image = Image.open(io.BytesIO(imgBlob))
text = pytesseract.image_to_string(image, lang = 'eng')
After extracting content from 11 pdfs I get the following error.
It's not the problem with the pdf file as when I give that particular pdf separately it extracted its content.
I am running the script on Ubuntu 16.04
Any help will be grateful.
Error: -
File "/home/steve/.local/lib/python3.5/site-packages/pytesseract/pytesseract.py", line 170 ,in run_tesseract
proc = subprocess.Popen(cmd_args, **subprocess_args())
File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.5/subprocess.py", line 1490, in _execute_child
restore_signals, start_new_session, preexec_fn)
OSError: [Errno 12] Cannot allocate memory
Traceback (most recent call last):
File "ocr_script.py", line 466, in <module>
gather_details(path_list)
File "ocr_script.py", line 45, in gather_details
discover_data('Indexing',discoveryPath,final_meta,start_time)
File "ocr_script.py", line 165, in discover_data
text = pytesseract.image_to_string(image, lang='eng')
File "/home/steve/.local/lib/python3.5/site
packages/pytesseract/pytesseract.py", line 294
, in image_to_string
return run_and_get_output(*args)
File "/home/steve/.local/lib/python3.5/site-
packages/pytesseract/pytesseract.py", line 202
, in run_and_get_output
run_tesseract(**kwargs)
File "/home/steve/.local/lib/python3.5/site-
packages/pytesseract/pytesseract.py", line 172
, in run_tesseract
raise TesseractNotFoundError()
pytesseract.pytesseract.TesseractNotFoundError: /usr/bin/tesseract is not
installed or it's
After further analysis and tweaks I came to conclusion that the problem was with my tesseract rather than OS.
Changes I did-
/etc/ImageMagic..(version )
Edit , policy.xml file
These are the parameters where I increased the memory.

Resources