I'm building a tiny Python 2.7.9 script that takes a list of JPEG images as an input and outputs a PDF file. I'm googling for hours but can't find a solution:
I tried pypdf, but it says I don't have PIL installed although i have.
I tried Reportlab, but the page size is bigger than the image itself and I couldn't find a way to fix it. I also find it hard...
I tried img2pdf, but couldn't understand how to use it
I'm really tired of all these libraries, and I'm looking for a good solution.
Good means:
As pythonic as possible
fit page size to image size
Support big amount of images (maybe even 500)
Easy enough
If you can help with with the modules I already tried/code examples it would be awesome.
Also, if you have experience with a module I would be glad if you could share it.
Edit:
As suggested in the comments, I decided to give another chance to img2pdf. I'm using the following code from the official GitHub README:
import img2pdf
pdf_bytes = img2pdf('test.jpg', dpi=150)
But it throws an exception:
`TypeError: 'module' object is not callable
Do someone knows how to use img2pdf as a module to several images?`
Nothing in the GitHub code suggests to me that this module is callable. It's possible that's a mistake in the readme; they have meant for the example to use the convert function. Try this instead:
import img2pdf
pdf_bytes = img2pdf.convert(('test.jpg',), dpi=150, x=None, y=None)
In the source code, this function requires positional arguments x and y:
def convert(images, dpi, x, y, title=None, author=None, creator=None, producer=None,
creationdate=None, moddate=None, subject=None, keywords=None,
colorspace=None, verbose=False):
But as long as you provide the dpi argument, it's set up with a default case that makes it look (to me, at least) like both x and y were intended to be optional arguments:
if not x and not y:
pdf_x, pdf_y = 72.0*width/ndpi[0], 72.0*height/ndpi[1]
The package you got on PIP isn't necessarily identical to the code on GitHub, though. You could try it without supplying x and y as arguments to convert as well—or even better, find the source file on your own machine and check it out yourself.
Related
I want to replicate the code here, and I get the following error while running in Google Colab?
ImportError: cannot import name 'zero_gradients' from
'torch.autograd.gradcheck'
(/usr/local/lib/python3.7/dist-packages/torch/autograd/gradcheck.py)
Can someone help me with how to solve this?
This seems like it's using a very old version of PyTorch, the function itself is not available anymore. However, if you look at this commit, you will see the implementation of zero_gradients. What it does is simply zero out the gradient of the input:
def zero_gradients(i):
for t in iter_gradients(i):
t.zero_()
Then zero_gradients(x) should be the same as x.zero_grad(), which is the current API, assuming x is a nn.Module!
Or it's just:
if x.grad is not None:
x.grad.zero_()
I am using PyObjC bindings to try to get a spoken sound file from phonemes.
I figured out that I can turn speech into sound as follows:
import AppKit
ss = AppKit.NSSpeechSynthesizer.alloc().init()
ss.setVoice_('com.apple.speech.synthesis.voice.Alex')
ss.startSpeakingString_toURL_("Hello", AppKit.NSURL.fileURLWithPath_("hello.aiff"))
# then wait until ve.isSpeaking() returns False
Next for greater control I'd like to turn the text first into phonemes, and then speak them.
phonemes = ss.phonemesFromText_("Hello")
But now I'm stuck, because I know from the docs that to get startSpeakingString to accept phonemes as input, you first need to set NSSpeechSynthesizer.SpeechPropertyKey.Mode to "phoneme". And I think I'm supposed to use setObject_forProperty_error_ to set that.
There are two things I don't understand:
Where is NSSpeechSynthesizer.SpeechPropertyKey.Mode in PyObjC? I grepped the entire PyObjC directory and SpeechPropertyKey is not mentioned anywhere.
How do I use setObject_forProperty_error_ to set it? I think based on the docs that the first argument is the value to set (although it's called just "an object", so True in this case?), and the second is the key (would be phoneme in this case?), and finally there is an error callback. But I'm not sure how I'd pass those arguments in Python.
Where is NSSpeechSynthesizer.SpeechPropertyKey.Mode in PyObjC?
Nowhere.
How do I use setObject_forProperty_error_ to set it?
ss.setObject_forProperty_error_("PHON", "inpt", None)
"PHON" is the same as NSSpeechSynthesizer.SpeechPropertyKey.Mode.phoneme
"inpt" is the same as NSSpeechSynthesizer.SpeechPropertyKey.inputMode
It seems these are not defined anywhere in PyObjC, but I found them by firing up XCode and writing a short Swift snippet:
import Foundation
import AppKit
let synth = NSSpeechSynthesizer()
let x = NSSpeechSynthesizer.SpeechPropertyKey.Mode.phoneme
let y = NSSpeechSynthesizer.SpeechPropertyKey.inputMode
Now looking at x and y in the debugger show that they are the strings mentioned above.
As for how to call setObject_forProperty_error_, I simply tried passing in those strings and None as the error handler, and that worked.
I'm trying to read the help on what various things do as I'm reading through code. I'm getting a bit lost in how to determine which module a function comes from. Here is my current example:
import quandl
import numpy as np
import matplotlib.pyplot as plt
amzn = quandl.get("WIKI/AMZN", start_date="2018-01-01", end_date="2019-01-01")
amzn_daily_close = amzn[['Adj. Close']]
amzn_daily_log_returns = np.log(amzn_daily_close.pct_change()+1)
monthly = amzn.resample('BM').apply(lambda x: x[-1])
So given this block of code, I can do help (quandl.get) to see information about that and help (np.log) to see what that does. But when I get to amzn.resample, where is that resample coming from? What should I be entering to see some help information on the resample stuff?
Look at the docstring of quandl.get method to get the help message about the return object. This will contain a statement as returns x-object. Googling about x-object will give you more info on this.
Alternatively, you can do this. To identify what is the object you can do the below.
amzn_type = type(amzn)
This gives the monthly object type. Googling for this type value will give you more insights about that object.Example -
a = 10
print(type(a))
The above code returns <class 'int'> output. Googling about int class in python3 will be helpful.
Inspection
You can 'inspect' the method to find the implementation:
import inspect
print(inspect.getfile(amzn.resample))
# /opt/miniconda/envs/stackoverflow/lib/python3.6/site-packages/pandas/core/generic.py
IDE
Or you can use a good IDE (e.g. PyCharm or IntelliJ) which supports you with some neat features:
Generally, these modules should be documented somewhere. They are usually "packaged" and made available on Python Package Index (pypi). You can search there for your package name and find the quandl page. That may have a link to the projects home page with more documentation.
I keep trying to run this function:
def flipPic():
#Set up source picture
barbf=getMediaPath("barbara.jpg")
barb=makePicture(barbf)
#Now, for the mirroring
mirrorPoint=219
for X in range(0,mirrorPoint):
for Y in range(0,291):
pleft=getPixel(barb,X,Y)
pright=getPixel(barb,Y,mirrorPoint + mirrorPoint - 1 - X)
setColor(pright,(getColor(pleft)))
show(barb)
return(barb)
However, an error comes up on this line:
barb=makePicture(barbf)
It says:
Inappropriate argument value (of correct type).
An error occurred attempting to pass an argument to a function.
I'm not sure what the issue is as it is written the same way that is in my textbook.
I am still learning how to program in python, is there something I doing wrong?
I'm not sure what library you are using but this is a simple call in Pillow. The commands are these:
out = im.transpose(Image.FLIP_LEFT_RIGHT)
out = im.transpose(Image.FLIP_TOP_BOTTOM)
Taken from this chapter in the docs.
I'm currently trying to access Math functions such as DeltaR from rootpy, but I'm not sure how this is done. I've seen nothing in the documentation or in any examples. The C++ equivalent would be something like:
double dR = ROOT::Math::VectorUtil::DeltaR((jets)[i],(partons)[i]);
But I'm unable to find a rootpy or even pyroot equivalent that'll work. If I try in pyroot with
import ROOT as r
r.Math.VectorUtil.DeltaR(jets[i],partons[i])
I get the error:
AttributeError: type object 'ROOT::Math' has no attribute 'VectorUtil'
When it quite clearly should, unless I don't understand correctly what it means by 'Attribute'. Anyway, I don't want to ask pyroot questions here :) I just put this down to a quirk in the way that pyroot handles such things, which is why I thought I'd give rootpy a try. I'm not sure if this is possible however.
Cheers,
Joseph
The functions from ROOT::Math::VectorUtil are in libGenVector which is loaded automatically in neither CINT nor PyROOT. Manually loading it (like you probably do in your root_logon.C) makes the functions available, e.g.
import ROOT as r
r.gSystem.Load('libGenVector')
# ...
r.Math.VectorUtil.DeltaR(jets[i],partons[i])
If jets and partons are TLorentzVectors then you should be able to do:
from ROOT import *
dR = jet.DeltaR(parton)