Python PPTX library issue - Replacing image in slides ('SlidePart' object has no attribute 'related_parts') - python

I use the PPTX library to automate the creation of a deck of slides on a weekly basis.
It was working really well until the last update of the library. As you can see below, I keep getting the following when updating the "image part" of the slides:
AttributeError: 'SlidePart' object has no attribute 'related_parts'
Here is my function for the image replacement:
def replace_img_slide(prs, slide_nbr, shape_nbr, img_path):
slide = prs.slides[slide_nbr]
img = slide.shapes[shape_nbr]
try:
imgPic = img._pic
except AttributeError:
raise AttributeError(
f"Error for slide: {slide_nbr}, shape: {shape_nbr}, path: {img_path}")
imgRID = imgPic.xpath('./p:blipFill/a:blip/#r:embed')[0]
imgPart = slide.part.related_parts[imgRID]
with open(img_path, 'rb') as f:
rImgBlob = f.read()
# replace
imgPart._blob = rImgBlob
return prs
I found some related subject and I understood that the "related_parts" is now obsolete in the new version of the library but I did not find how to solve it. Do you think you can help me with that please ?
Many thanks in advance for your help !

Just use part.related_part(imgRID) where you used to use part.related_parts[imgRID].
The latest version exposes that method (internally) rather than expose a dict-like object just to do that one job.

Related

'str' object has no attribute 'open' in python

I have created a simple streamlit app which has two option one is file upload another one is capturing image
while trying to open the uploaded file i am getting an error 'str' object has no attribute 'open' .
I am not sure why the issue is occurring kindly let me know how to solve this so that i can move forward
import streamlit as st
import numpy as np
import cv2
from PIL import Image
Image = st.sidebar.selectbox(
'Choose your method',
('Upload','Capture'))
if Image == 'Upload':
uploaded_file = st.file_uploader("HI",type=['jpg','png','jpeg'])
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image,width=300)
else:
file_image = st.camera_input(label = "Take a pic of you to be sketched out")
You have here two Image keywords, one of them is the Image library you imported from PIL, and the other is the return from your selectbox, which is a string.
Since the second one is declared later, it has overridden the first one, thus giving you this error when you try to call open.
I suggest renaming the second one to anything else and it should work properly.

Reading in-memory Avro file from S3: 'AttributeError:'

I'm trying to read Avro files stored in S3 by a vendor and write to a DW. See code below. (Was roughly working from this S/O thread.)
obj = obj.get()
raw_bytes = obj["Body"].read()
avro_bytes = io.BytesIO(raw_bytes)
reader = DataFileReader(avro_bytes, DatumReader())
The code is tripped up at the last line, where I get the error:
AttributeError: '_io.StringIO' object has no attribute 'mode'
That error comes from this spot in the source code, where DataFileReader is initialized.
def __init__(self, reader: IO[AnyStr], datum_reader: avro.io.DatumReader) -> None:
if "b" not in reader.mode:
warnings.warn(avro.errors.AvroWarning(f"Reader binary data from a reader {reader!r} that's opened for text"))
bytes_reader = getattr(reader, "buffer", reader)
I've tried using avro_bytes as StringIO as well to see if that would help, but it didn't.
Any ideas how to get past that AttributeError?
This is a bug in version 1.11.0 that has been fixed but a new version hasn't been released: https://issues.apache.org/jira/browse/AVRO-3252.
To resolve this, you can do one of the following:
Wait until the new version is released
Patch the call so that it doesn't do that check
Instead of using BytesIO you could make your own wrapper object that mimics BytesIO but has a mode attribute.

Python getting object has no attribute error but attribute exists in package documentation

I am trying to get the lat/lngs from a successful location search using the SearchControl class in ipyleaflet. Code is from the ipyleaflet documentation link. When I run the below example I get the error AttributeError: 'SearchControl' object has no attribute 'on_location_found'. I know the code as is wont get me what I need, but it was a starting point. Can anyone advise how I might be able to get the lat/lngs? New to this.
from ipyleaflet import Map, SearchControl
m = Map(center=[47, 2], zoom=5)
search = SearchControl(
position="topleft",
url='https://cartoradon.irsn.fr/commune.py/communes/search/FR/{s}?',
zoom=5
)
m.add_control(search)
def on_found(**kwargs):
# Print the result of the search (text, location etc)
print(kwargs)
search.on_location_found(on_found)
m

Django - AttributeError _committed

I have a form that saves an image, and everything is working fine, but I want to be able to crop the image. However, when I used Pillow to do this, I get a strange error that doesn't really give me much to go on.
Attribute error at /userprofile/addGame/
_committed
Looking further into the traceback, the following sections were highlighted:
I'm not really sure what this error means. I think it has something to do with the form.save(committed=False), and not being able to edit files after that point, but I'm not positive. I can edit the user after that line using form.user = request.user, so I think it's the fact that I'm trying to change the image getting uploaded that is part of the issue.
This is an old post but I recently experienced a similar problem.
The information in the question is somewhat incomplete but I had the same error.
Assuming the Error being
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/Image.py", line 627, in __getattr__
raise AttributeError(name)
AttributeError: _committed
So the root problem lies with using PIL (Pillow). The function :
image = Image.open(self.cleaned_data['image'])
We wrongly assume that the object image would continue to have the
instance of image throughout the function(clean_image in my case).
So in my code structure,
def clean_image(self):
if self.cleaned_data['image']:
try:
image = Image.open(self.cleaned_data['image'])
image.verify()
except IOError:
raise forms.ValidationError(_('The file is not an image'))
return image
The error mentioned above is thrown after we execute this code. It is so because
After several of the other PIL(pillow) functions we use, we need to
open the file again. Check this out in pillow documentation
As in the code above(last line),
return image
doesn't really return anything.
To fix it
Simply add ,
image = self.cleaned_data['image']
before the return image line.
Code looks like,
except IOError:
raise forms.ValidationError(_('The file is not an image'))
image = self.cleaned_data['image']
return image
I had faced the same issue trying to save a model with an ImageFileField. My requirement was to save an image from a zip object.
Using pillow gave me the AttributeError: _committed error. Following is what worked for me:
from django.core.files.images import ImageFile
zf = zipfile.ZipFile(zip_file, mode='r')
image_list = zf.infolist()
Model.objects.create(img=ImageFile(zipObj.open(image_list[0])),
file_name=image_list[0].filename.split("/")[-1].strip(),
...)

How to use TideSDK openFolderChooseDialog

I'm trying to use TideSDK and python tp get the user to select a folder from the hard drive. Everything works, but I have no idea how obtain which folder the user selected.
I can't seem to find documentation on what Ti.UI.UserWindow.openFolderChooseDialog returns and what kind of object the callback function uses. I just get errors that "window" in "onopen" in my code below is a None Type object when I try to print it out.
Is there any documentation on the proper use of the openFolderChooseDialog, what signature the callback needs to be and how to get the Folder/directory from the dialog?
My code:
def onopen(window):
Ti.App.stdout("------------------ Opening Dialog")
Ti.App.stdout(window)
def burndir():
try:
dir = Ti.UI.getCurrentWindow().openFolderChooserDialog(onopen)
Ti.App.stdout(dir)
except:
Ti.App.stderr("------ There was an error: ")
Ti.App.stderr(sys.exc_info()[0])
Ti.App.stderr(sys.exc_info()[1])
Ti.App.stderr(sys.exc_info()[2])
Any help is much appreciated
I found the answer in a Javascript Code example here:
https://github.com/appcelerator/titanium_developer/blob/master/Resources/perspectives/projects/js/projects.js#L1338
It appears that openFolderChooserDialog return nothing (a None object in Python). The callback function passes one argument which is a StaticBoundList (a Tuple object in Python) that contains all of the selected folders (in case of allowing multiple selections)
Here is the updated code:
def onopen(window):
if (len(window) > 0):
Ti.App.stdout("------------------ Opening Dialog")
Ti.App.stdout(window[0])
else:
Ti.App.stdout("------------------ Nothing Selected")
def burndir():
try:
Ti.UI.getCurrentWindow().openFolderChooserDialog(onopen)
except:
Ti.App.stderr("------ There was an error: ")
Ti.App.stderr(sys.exc_info()[0])
Ti.App.stderr(sys.exc_info()[1])
Ti.App.stderr(sys.exc_info()[2])
I hope this helps someone struggling to find the same documentation!

Categories

Resources