Convert pdf to jpg using python 2.7- an error - python-2.7

I try to find a simple python code that convert hundred of pdf files to jpg files to the same folder where the pdf files located. I use this code from Python Wand converts from PDF to JPG background is incorrect
from wand.image import Image
from wand.color import Color
import os, os.path, sys
def pdf2jpg(source_file, target_file, dest_width, dest_height):
RESOLUTION = 300
ret = True
try:
with Image(filename=source_file, resolution=(RESOLUTION,RESOLUTION)) as img:
img.background_color = Color('white')
img_width = img.width
ratio = dest_width / img_width
img.resize(dest_width, int(ratio * img.height))
img.format = 'jpeg'
img.save(filename = target_file)
except Exception as e:
ret = False
return ret
if __name__ == "__main__":
source_file = r"C:\Users\yaron.KAYAMOT\Desktop\aaa.pdf"
target_file = r"C:\Users\yaron.KAYAMOT\Desktop\aaa.jpg"
ret = pdf2jpg(source_file, target_file, 1895, 1080)
but i get an error:
ImportError: MagickWand shared library not found.
You probably had not installed ImageMagick library.
Try to install:
http://docs.wand-py.org/en/latest/guide/install.html#install-imagemagick-on-windows
>>>
but i do have module MagickWand in the hard disk as shown in the cmd :
UPDATE:
when i try to pip install in the cmd "wand" module i get:
so,i do have this module. When i try to pip install imagemagick \ ImageMagick i get:

You're importing from wand module.
You probably haven't installed bindings for Python.
pip install Wand
See the details here: http://docs.wand-py.org/en/0.4.2/
Also try to do the following:
pip search pythonmagick
or something like that. Try to install all required packages.
This may help you.

Related

Kernel restarts when compressing tif file using PIL in Anaconda

I'm trying to compress a bunch of tiff files with the pillow package. However, when I'm executing the code in python3.7.13 in Spyder IDE within the Anaconda3 environment, the Kernel restarts in the line in which the tiff file should be compressed. I tried different compression methods (e.g. "group4", "zlib", "deflate", etc..).
I also tried other packages like libtiff and tifffile, but the same problem occurs here as well.
import os
import glob
from PIL import Image, TiffTags
from IPython.display import display
import numpy as np
images = [file for file in os.listdir("C:/Home/Slicer/tif") if file.endswith('tif')]
#search for alle the images in the path
for image in images:
img_name = str(image)
img = Image.open("C:/Home/Slicer/tif/"+img_name)
print(img_name + str(img))
display(img)
#save tiff file with new name
img.save("C:/Home/Slicer/tif/" + "compressed" + img_name, compression="tiff_lzw")
Console output

AttributeError: 'module' object has no attribute 'fsdecode'; PYTHON 2.7; mac os X

I have found a script in PYTHON. Need to run it to cut images' sizes.
Why this error occurs and How to fix it?
(Python 2.7 installed+ installed PIL for current script+ Imaging 1.1.7; Mac OS)
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import argparse
import os
from PIL import Image
parser = argparse.ArgumentParser()
parser.add_argument('--image_dir', help='Directory of images to resize')
args = parser.parse_args()
image_dir = os.getcwd() + "/" + args.image_dir
for f in os.listdir(image_dir):
filename = os.fsdecode(f)
image = Image.open(image_dir + '/' + filename)
print(image_dir + '/' + filename)
height, width = image.size
if width > 1000:
resize_amt = 1000 / width
new_height = int(round(height * resize_amt))
image = image.resize((new_height, 1000))
image.save(os.getcwd() + "/" + image_dir + "/" + filename)
After I've fixed all issues this text occurs in Terminal:
Oleksandrs-MacBook-Air: jaskier$ python resize.py --image_dir=/Images/
Traceback (most recent call last):
File "resize.py", line 16, in
filename = os.fsdecode(f)
AttributeError: 'module' object has no attribute 'fsdecode'
There is a Hugh difference between Python 2.7(native for Mac OS) and Python 3+(should install with terminal or https://www.python.org/download/releases/3.0/
Terminal:
pip3 install Pillow
It will help to make dependencies between PIL and Python3... (moreover check Python3 in folder:
/Library/Frameworks/Python.framework/Versions/3.6/bin/
The pip3 should be also there if you've done all correctly.
After this steps now I have some code errors, but none of modules errors. I hope it will help someone.

ImportError with nltk_train

I am trying to get my ways around with nltk-trainer (https://github.com/japerk/nltk-trainer). I managed to train Dutch taggers and chunkers with the commands (directly in Anaconda console):
python train_tagger.py conll2002 --fileids ned.train --classifier IIS --filename ~/nltk_data/taggers/conll2002_ned_IIS.pickle
python train_chunker.py conll2002 --fileids ned.train --classifier NaiveBayes --filename ~/nltk_data/chunkers/conll2002_ned_NaiveBayes.pickle
Then I run a little script to test the tagger and the chunker:
import nltk
from nltk.corpus import conll2002
# Loading training pickles
tokenizer = nltk.data.load('tokenizers/punkt/dutch.pickle')
tagger = nltk.data.load('taggers/conll2002_ned_IIS.pickle')
chunker = nltk.data.load('chunkers/conll2002_ned_NaiveBayes.pickle')
# Testing
test_sents = conll2002.tagged_sents(fileids="ned.testb")[0:1000]
print "tagger accuracy on test-set: " + str(tagger.evaluate(test_sents))
test_sents = conll2002.chunked_sents(fileids="ned.testb")[0:1000]
print "tagger accuracy on test-set: " + str(chunker.evaluate(test_sents))
This works fine from the nltk-trainer-master folder, but when I move the script elsewhere, I get an import error:
ImportError: No module named nltk_trainer.chunking.chunkers
How can I make this work outside the nltk-trainer-master folder, without copying the nltk_trainer folder?
(Python 2.7, nltk 3.2.1)

python + wx & uno to fill libreoffice using ubuntu 14.04

I collected user data using a wx python gui and than I used uno to fill this data into an openoffice document under ubuntu 10.xx
user + my-script ( +empty document ) --> prefilled document
After upgrading to ubuntu 14.04 uno doesn't work with python 2.7 anymore and now we have libreoffice instead of openoffice in ubuntu. when I try to run my python2.7 code, it says:
ImportError: No module named uno
How could I bring it back to work?
what I tried:
installed https://pypi.python.org/pypi/unotools v0.3.3
sudo apt-get install libreoffice-script-provider-python
converted the code to python3 and got uno importable, but wx is not importable in python3 :-/
ImportError: No module named 'wx'
googled and read python3 only works with wx phoenix
so tried to install: http://wxpython.org/Phoenix/snapshot-builds/
but wasn't able to get it to run with python3
is there a way to get the uno bridge to work with py2.7 under ubuntu 14.04?
Or how to get wx to run with py3?
what else could I try?
Create a python macro in LibreOffice that will do the work of inserting the data into LibreOffice and then in your python 2.7 code envoke the macro.
As the macro is running from with LibreOffice it will use python3.
Here is an example of how to envoke a LibreOffice macro from the command line:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
##
# a python script to run a libreoffice python macro externally
# NOTE: for this to run start libreoffice in the following manner
# soffice "--accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp;" --writer --norestore
# OR
# nohup soffice "--accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp;" --writer --norestore &
#
import uno
from com.sun.star.connection import NoConnectException
from com.sun.star.uno import RuntimeException
from com.sun.star.uno import Exception
from com.sun.star.lang import IllegalArgumentException
def uno_directmacro(*args):
localContext = uno.getComponentContext()
localsmgr = localContext.ServiceManager
resolver = localsmgr.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
try:
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
except NoConnectException as e:
print ("LibreOffice is not running or not listening on the port given - ("+e.Message+")")
return
msp = ctx.getValueByName("/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory")
sp = msp.createScriptProvider("")
scriptx = sp.getScript('vnd.sun.star.script:directmacro.py$directmacro?language=Python&location=user')
try:
scriptx.invoke((), (), ())
except IllegalArgumentException as e:
print ("The command given is invalid ( "+ e.Message+ ")")
return
except RuntimeException as e:
print("An unknown error occurred: " + e.Message)
return
except Exception as e:
print ("Script error ( "+ e.Message+ ")")
print(e)
return
return(None)
uno_directmacro()
And this is the corresponding macro code within LibreOffice called "directmacro.py" and stored in the User area for libreOffice macros (which would normally be $HOME/.config/libreoffice/4/user/Scripts/python :
#!/usr/bin/python
from com.sun.star.awt.MessageBoxButtons import BUTTONS_OK, BUTTONS_OK_CANCEL, BUTTONS_YES_NO, BUTTONS_YES_NO_CANCEL, BUTTONS_RETRY_CANCEL, BUTTONS_ABORT_IGNORE_RETRY
from com.sun.star.awt.MessageBoxButtons import DEFAULT_BUTTON_OK, DEFAULT_BUTTON_CANCEL, DEFAULT_BUTTON_RETRY, DEFAULT_BUTTON_YES, DEFAULT_BUTTON_NO, DEFAULT_BUTTON_IGNORE
from com.sun.star.awt.MessageBoxType import MESSAGEBOX, INFOBOX, WARNINGBOX, ERRORBOX, QUERYBOX
def directmacro(*args):
import socket, time
class FontSlant():
from com.sun.star.awt.FontSlant import (NONE, ITALIC,)
#get the doc from the scripting context which is made available to all scripts
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
text = model.Text
tRange = text.End
cursor = desktop.getCurrentComponent().getCurrentController().getViewCursor()
doc = XSCRIPTCONTEXT.getDocument()
parentwindow = doc.CurrentController.Frame.ContainerWindow
# your cannot insert simple text and text into a table with the same method
# so we have to know if we are in a table or not.
# oTable and oCurCell will be null if we are not in a table
oTable = cursor.TextTable
oCurCell = cursor.Cell
insert_text = "This is text inserted into a LibreOffice Document\ndirectly from a macro called externally"
Text_Italic = FontSlant.ITALIC
Text_None = FontSlant.NONE
cursor.CharPosture=Text_Italic
if oCurCell == None: # Are we inserting into a table or not?
text.insertString(cursor, insert_text, 0)
else:
cell = oTable.getCellByName(oCurCell.CellName)
cell.insertString(cursor, insert_text, False)
cursor.CharPosture=Text_None
return None
You will of course need to adapt the code to either accept data as arguments, read it from a file or whatever.
Ideally I would say use python 3, because python 2 is becoming outdated. The switch requires quite a bit of new coding changes, but better sooner than later. So I tried:
sudo pip3 install -U --pre \
-f http://wxpython.org/Phoenix/snapshot-builds/ \
wxPython_Phoenix
However this gave me errors, and I didn't want to spend the next couple of days working through them. Probably the pre-release versions are not ready for prime time yet.
So instead, what I recommend is to switch to AOO for now. See https://stackoverflow.com/a/27980255/5100564 for instructions. AOO does not have all the latest features that LO has, but it is a good solid Office product.
Apparently it is also possible to rebuild LibreOffice with python 2 using this script: https://gist.github.com/hbrunn/6f4a007a6ff7f75c0f8b

pywin32 and pyttsx error, trouble combining the two

i have pywin32 in my site packages and my pyttsx is in a separate folder. Is this the reason why i am getting the following error?
import win32api, sys, os
ImportError: DLL load failed: The specified module could not be found
The code is as follows,
import pyttsx
def onStart(name):
print 'starting', name
def onWord(name, location, length):
print 'word', name, location, length
def onEnd(name, completed):
print 'finishing', name, completed
engine = pyttsx.init()
engine.connect('started-utterance', onStart)
engine.connect('started-word', onWord)
engine.connect('finished-utterance', onEnd)
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()
from here, http://pyttsx.readthedocs.org/en/latest/engine.html#examples
My pywin32 is from here,
http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/
for Py 2.7
The problem was that the file
pywintypes27.dll
was not in the right directory. It had to be in
'C:\Windows\System32'
#CristiFati
Use the pyttsx3 module instead . It supports both python3 and python2.
To install:
pip install pyttsx3.
It automatically installs those win32 and other dependencies.