I am having trouble with the streamlit I am using a Chromebook and cant keep to insert images - python

from PIL import Image
import requests
import streamlit as st
from streamlit_lottie import st_lottie
#find more emojis at the link he set line 4 will show how your website would be layedout for users to see
st.set_page_config(page_title="My Webpage", page_icon=":tada:", layout="wide")
def load_lottieurl(url):
r =requests.get(url)
if r.status_code != 200:
return None
return r.json()
#lottie files are for animation to be put on your webiste (pip install requests)(pip install streamlit-lottie)(pip install pillow)
lottie_coding = load_lottieurl("https://assets7.lottiefiles.com/packages/lf20_2znxgjyt.json")
img_william = Image.open("images\william.png")
img_tacos = Image.open("images\tacos.png")
#header section / st.container will organize the code it will work fine without
with st.container():
st.subheader("hello i am william and this is my first website made by python header :wave:")
st.title("this would be were the title would go ")
st.write("this would be a small paragraph you wold write this area")
#st.write is for small paragrahps / st.title is to start the paragraps )
# what i am doing with the 3 lines and quotes on line 15 and that i am diving space on the website
with st.container():
st.write("---")
left_column, right_column = st.columns(2)
with left_column:
st.header("this will be the column for the left side ")
st.write('##')
st.write(
"""
i am currently doing what the tutotial is telling me to do even though i am quite cofnused:
- i will master this and i will understtand the concepts of making a website with this framework
- i will be great i bless god for changing how i act and i am as a person
- i know allot of people do not want to see me win but god does and thats all i need
- rome was not built in a day and they will say the samething about my journey
i am confused but if i keep puttingand effort in everyday i will master this in jesues name
"
""
)
i am having difficulty uploading images to python I am using the framework called streamlit and i have been following a tutorial on how to make my own website and when i do what he does to upload the image it tells me in the terminal that no such file in the directory i have made a file for the images that includes the code in the same file so i am very confused please help i am also using a chromebook

if images folder is in the working directory and you want to display the images, all you need is the code below.
st.image("images/william.png")
st.image("images/tacos.png")
but displaying image with PIL, you can do the following
img_william = Image.open("images/william.png")
img_tacos = Image.open("images/tacos.png")
st.image(img_william)
st.image(img_tacos)
Then apply this last method:
right click on your images folder and copy full path.
from pathlib import Path
SCR_DIR = 'C:\\users\\Desktop\\images' # Edit 'C:\\users\\Desktop\\images' with the coppied path you made at the first step. But maintain \\ when editting
img_william = Image.open(Path(SRC_DIR, "william.png"))
img_tacos = Image.open(Path(SRC_DIR, "tacos.png"))
st.image(img_william)
st.image(img_tacos)
Your scr_dir hould be something like
SCR_DIR = 'C:\\user\\My files\\Webpage\\images'
I am pretty sure you are missing something out.

Related

Replacing a word with another word, and replacing an image with another image in a PDF file through python, is this possible?

I need to replace a K words with K other words for every PDF file I have within a certain path file location and on top of this I need to replace every logo with another logo. I have around 1000 PDF files, and so I do not want to use Adobe Acrobat and edit 1 file at a time. How can I start this?
Replacing words seems at least doable as long as there is a decent PDF reader one can access through Python ( Note I want to do this task in Python ), however replacing an image might be more difficult. I will most likely have to find the dimension of the current image and resize the image being used to replace the current image dynamically, whilst the program runs through these PDF files.
Hi, so I've written down some code regarding this:
from pikepdf import Pdf, PdfImage, Name
import os
import glob
from PIL import Image
import zlib
example = Pdf.open(r'...\Likelihood.pdf')
PagesWithImages = []
ImageCodesForPages = []
# Grab all the pages and all the images in every page.
for i in example.pages:
if len(list(i.images.keys())) >= 1:
PagesWithImages.append(i)
ImageCodesForPages.append(list(i.images.keys()))
pdfImages = []
for i,j in zip(PagesWithImages, ImageCodesForPages):
for x in j:
pdfImages.append(i.images[x])
# Replace every single page using random image, ensure that the dimensions remain the same?
for i in pdfImages:
pdfimage = PdfImage(i)
rawimage = pdfimage.obj
im = Image.open(r'...\panda.jpg')
pillowimage = pdfimage.as_pil_image()
print(pillowimage.height)
print(pillowimage.width)
im = im.resize((pillowimage.width, pillowimage.height))
im.show()
rawimage.write(zlib.compress(im.tobytes()), filter=Name("/FlateDecode"))
rawimage.ColorSpace = Name("/DeviceRGB")
So just one problem, it doesn't actually replace anything. If you're wondering why and how I wrote this code I actually got it from this documentation:
https://buildmedia.readthedocs.org/media/pdf/pikepdf/latest/pikepdf.pdf
Start at Page 53
I essentially put all the pdfImages into a list, as 1 page can have multiple images. In conjunction with this, the last for loop essentially tries to replace all these images whilst maintaining the same width and height size. Also note, the file path names I changed here and it definitely is not the issue.
Again Thank You
I have figured out what I was doing wrong. So for anyone that wants to actually replace an image with another image in place on a PDF file what you do is:
from pikepdf import Pdf, PdfImage, Name
from PIL import Image
import zlib
example = Pdf.open(filepath, allow_overwriting_input=True)
PagesWithImages = []
ImageCodesForPages = []
# Grab all the pages and all the images in every page.
for i in example.pages:
imagelists = list(i.images.keys())
if len(imagelists) >= 1:
for x in imagelists:
rawimage = i.images[x]
pdfimage = PdfImage(rawimage)
rawimage = pdfimage.obj
pillowimage = pdfimage.as_pil_image()
im = Image.open(imagePath)
im = im.resize((pillowimage.width, pillowimage.height))
rawimage.write(zlib.compress(im.tobytes()), filter=Name("/FlateDecode"))
rawimage.ColorSpace = Name("/DeviceRGB")
rawimage.Width, rawimage.Height = pillowimage.width, pillowimage.height
example.save()
Essentially, I changed the arguements in the first line, such that I specify that I can overwrite. In conjunction, I also added the last line which actually allows me to save.

Saving image of every python execution in a folder with a serial number as file name

I am a beginner in Python and would like to execute a code which saves an image into particular directory.
The thing is, I would like to save image with a serial number so that I can have many images(each execution gives one image) in the directory.
plt.savefig('Images/Imageplot.png') ## Image saved to particular folder
About the serial number, you can use the uuid library to generate a random and unique id for an image. See more here: https://www.geeksforgeeks.org/generating-random-ids-using-uuid-python/
To save images, it is a bit more complicated. It requires you to import the os library.
Here is an example:
import os
UPLOADED_FILE_DIR_PATH = os.path.join(os.path.dirname(__file__), "static", "uploaded-images")
my_file_path = os.path.join(UPLOADED_FILE_DIR_PATH, my_filename)
image_file.save(my_file_path)
This is a block of code I used previously for my website, so it may not apply for you, depending on your situation. I personnaly like that method, but if you are unsatisfied, take a look at this for more options: https://towardsdatascience.com/loading-and-saving-images-in-python-ba5a1f5058fb

Music21 - cannot display rests

I'm cutting up sections of sheet music into snippets on the beat. I'm using music21 and LilyPond to convert the output into a png. There's a very specific issue though where I get no display of a snippet only containing a rest. If the rest is being displayed with note then it shows fine.. but if the bar consists of a rest and nothing else the image is blank. My guess would be the program doesn't know where to place the rest when there's no context to wether a bass clef - stave is being used.. but I did attempt to providing placement information to the rest through Style.absoluteY module but no joy. If anybody could provide a bit of insight that'd be cool! Cheers
n = note.Note("C4")
r = note.Rest()
ss = stream.Stream()
ss.append(n)
ss.append(r)
ss.show("lily")
When I use the above code I get an output of image of 1/4 note and 1/4 rest
Then, when I use the below code I get an output of blank white box, where there should be a single 1/4 rest
r = note.Rest()
ss = stream.Stream()
ss.append(r)
ss.show("lily")
Lilypond interface is not so strong, so better would be to install MuseScore
add-apt-repository ppa:mscore-ubuntu/mscore3-stable
apt update
apt install musescore3
pip uninstall music21
pip install music21
output:

Python PPTX: Adding Entire Slide from Another Presentation

It seems this issue was brought up and requested back in 2015 but I cannot find any updates on it. I'm trying to copy an entire slide (including its text and images) from another presentation into my working presentation by doing something like the following:
prs = Presentation('CurrentPresentation.pptx')
prs1 = Presentation('OtherPresentation.pptx')
# Wanted_Slide = prs1.slides[0]
New_Slide = prs.slides.add_slide(prs1.slide_layout[0])
But all this does is add a totally blank slide (with the wanted slide's background) with slide layout 0, which totally makes sense. I know that's not the right way to do it. I tried the below and it did add a slide, but it was just a duplicate one of what was already in the prs presentation (I guess I found a way to duplicate a slide already in the presentation inadvertently):
def Add_Slide(self):
xml_slides = prs.slides._sldIdLst
xml_slides1 = prs1.slides._sldIdLst
slides = list(xml_slides)
slides1 = list(xml_slides1)
xml_slides.append(slides1[0])
The above code is a manipulation of a slide delete method I found online.
Or does anyone have any sort of recommendation on how to completely copy a slide and all of its contents over to a working presentation?
I apologize if no developments have been made and this post is a rehash. Thank you in advance.
There's an issue in the library's repo that has some code to do this, but it's rough, it doesn't work for all cases.
from pptx.parts.chart import ChartPart
from pptx.parts.embeddedpackage import EmbeddedXlsxPart
from pptx import Presentation
import copy
def _get_blank_slide_layout(pres):
layout_items_count = [len(layout.placeholders) for layout in pres.slide_layouts]
min_items = min(layout_items_count)
blank_layout_id = layout_items_count.index(min_items)
return pres.slide_layouts[blank_layout_id]
def move_slide(pres1, pres, index):
"""Duplicate the slide with the given index in pres1 and "moves" it into pres.
Adds slide to the end of the presentation"""
source = pres1.slides[index]
blank_slide_layout = _get_blank_slide_layout(pres)
dest = pres.slides.add_slide(blank_slide_layout)
for shape in source.shapes:
newel = copy.deepcopy(shape.element)
dest.shapes._spTree.insert_element_before(newel, 'p:extLst')
for key, value in source.part.rels.items():
# Make sure we don't copy a notesSlide relation as that won't exist
if "notesSlide" not in value.reltype:
target = value._target
# if the relationship was a chart, we need to duplicate the embedded chart part and xlsx
if "chart" in value.reltype:
partname = target.package.next_partname(
ChartPart.partname_template)
xlsx_blob = target.chart_workbook.xlsx_part.blob
target = ChartPart(partname, target.content_type,
copy.deepcopy(target._element), package=target.package)
target.chart_workbook.xlsx_part = EmbeddedXlsxPart.new(
xlsx_blob, target.package)
dest.part.rels.add_relationship(value.reltype, target,value.rId)
This function is an alteration of what is on the github comments at the location cited above. It works well for me, haven't tested it with charts or anything. It's slightly altered from what was posted on the site, because there was the rough example noted by the original answer, and there was a more thorough answer for duplicating within a presentation. Figured I'd post since it took me a while to get this all put together.
This solution has mainly worked with one exception. After copying the slide over to the destination presentation when I open the destination presentation I get the following warning:
PowerPoint couldn't read some content in xxx.pptx and removed it. Please check your presentation to see if the rest of it looks ok.
The rest of the presentation does look fine and after saving and reopening the warning goes away. Do you know of a way to make it so this warning doesn't appear or if there is a way to resolve it with Python (saving/closing again?).

Issue writing temp images to temp pdf in pyramid with reportlabs

I am using python 3, with pyramid and reportlabs to generate dynamic pdfs.
I am having a issue writing images in to a pdf. I am using Reportlab in a web to generate a pdf with images, by my images are not stored locally, they are on a remote server. I am downloading them locally into a temp directory ( they are saving, I have checked) When i go to add the images to the pdf, they space is allocating but image is not showing up.
Here is my relevant code (simplified):
# creates pdf in memory
doc = SimpleDocTemplate(pdfName, pagesize=A4)
elements = []
for item in model['items']:
# image goes here:
if item['IMAGENAME']:
response = getImageFromRemoteServer(item['IMAGENAME'])
dir_filename = directory + item['IMAGENAME']
if response.status_code == 200:
with open(dir_filename, 'wb') as f:
for chunk in response.iter_content():
f.write(chunk)
questions.append(Image(dir_filename, width=2*inch, height=2*inch))
# create and save the pdf
doc.build(elements,canvasmaker=NumberedCanvas)
I have followed the user guide here https://www.reportlab.com/docs/reportlab-userguide.pdf and have tried the above way, plus embedded images (as the user guide says in the paragraph section) and putting the image in the table.
I also looked here: and it did not help me.
My question is really, what is the right what to download an image and put in a pdf?
EDIT: fixed code indentation
EDIT 2:
Answered, I was finally about to get the images in the PDF. I am not sure what was the trigger to get it to work. The only thing that know I change was now I am using urllib to do the request and before i was not. Here is the my working code (simplified for the question only, this is more abstracted and encapsulated in my code.):
doc = SimpleDocTemplate(pdfName, pagesize=A4)
# array of elements in the pdf
elements = []
for question in model['questions']:
# image goes here:
if question['IMAGEFILE']:
filename = question['IMAGEFILE']
dir_filename = directory + filename
url = get_url(settings, filename)
response = urllib.request.urlopen(url)
raw_data = response.read()
f = open(dir_filename, 'wb')
f.write(raw_data)
f.close()
response.close()
myImage = Image(dir_filename)
myImage.drawHeight = 2* inch
myImage.drawWidth = 2* inch
myImage.hAlign = "LEFT"
elements.append(myImage)
# create and save the pdf
doc.build(elements)
Make your code independent from where the files come from. Separate file/resource retrieval from document generation. Ensure that your toolset is working with local files. Encapsulate the code to load files in a loader class or function. The encapsulation is what matters. Noticed this again this week while looking at thumbor loader classes.
If that works, you know reportlab, PIL and your application basically work.
Then make your code work with remote files using URI like http://path/to/remote/files.
Afterwards you can switch from using your fileloader or your httploader depending on environment or use case.
Another option to go would be to make your code work with local files using URI like file://path/to/file
This way the only thing that changes when switching from local to remote is the URL. Probably you need a python library supporting this. requests library is well suited for downloading things, most probably it supports URL scheme file:// as well.
Most probably the lazy parameter was responsible that your first code sample did not render the images. Triggering reportlab PDF rendering outside of the context managers for temporary files could have lead to this behaviour.
reportlab.platypus.flowables.py (using version 3.1.8)
class Image(Flowable):
"""an image (digital picture). Formats supported by PIL/Java 1.4 (the Python/Java Imaging Library
are supported. At the present time images as flowables are always centered horozontally
in the frame. We allow for two kinds of lazyness to allow for many images in a document
which could lead to file handle starvation.
lazy=1 don't open image until required.
lazy=2 open image when required then shut it.
"""
_fixedWidth = 1
_fixedHeight = 1
def __init__(self, filename, width=None, height=None, kind='direct', mask="auto", lazy=1):
"""If size to draw at not specified, get it from the image."""
self.hAlign = 'CENTER'
self._mask = mask
fp = hasattr(filename,'read')
if fp:
self._file = filename
self.filename = repr(filename)
...
The last three lines of the code example tell you that you can pass an object that has a read method. This is exactly what a call to urllib.request.urlopen(url) returns. Using that memory buffer you create an instance of Image. No need to have write access to filesystem, no need to delete these files after PDF rendering. Applying our new knowledge to improve code readability. Since your use-case includes retrieval of remote resources using memory buffers that support python file API could be a much cleaner approach to assemble your PDF files.
from contextlib import closing
import urllib.request
doc = SimpleDocTemplate(pdfName, pagesize=A4)
# array of elements in the pdf
elements = []
for question in model['questions']:
# download image and create Image from file-like object
if question['IMAGEFILE']:
filename = question['IMAGEFILE']
image_url = get_url(settings, filename)
with closing(urllib.request.urlopen(image_url)) as image_file:
myImage = Image(image_file, width=2*inch, height=2*inch)
myImage.hAlign = "LEFT"
elements.append(myImage)
# create and save the pdf
doc.build(elements)
References
Coding with context managers

Categories

Resources