I tried installing pyotherside from the ubuntu repos (packages qml-module-io-thp-pyotherside and pyotherside) as well as from the git repo.
But in when importing it in Python3 I keep getting ImportError: No module named 'pyotherside'.
Any knows why? What is the path where I should find pyotherside installed?
OS: Ubuntu 16.04.2
PyOtherSide is a library that uses the python code from QML and not vice versa, in your project you must the qml file and the python file. To run the program you must execute the qml, for example:
{your directory}
├── imageprovider.py
└── imageprovider.qml
imageprovider.py
import pyotherside
import math
def render(image_id, requested_size):
print('image_id: "{image_id}", size: {requested_size}'.format(**locals()))
# width and height will be -1 if not set in QML
if requested_size == (-1, -1):
requested_size = (300, 300)
width, height = requested_size
# center for circle
cx, cy = width/2, 10
pixels = []
for y in range(height):
for x in range(width):
pixels.extend(reversed([
255, # alpha
int(10 + 10 * ((x - y * 0.5) % 20)), # red
20 + 10 * (y % 20), # green
int(255 * abs(math.sin(0.3*math.sqrt((cx-x)**2 + (cy-y)**2)))) # blue
]))
return bytearray(pixels), (width, height), pyotherside.format_argb32
pyotherside.set_image_provider(render)
imageprovider.qml
import QtQuick 2.0
import io.thp.pyotherside 1.5
Image {
id: image
width: 300
height: 300
Python {
Component.onCompleted: {
// Add the directory of this .qml file to the search path
addImportPath(Qt.resolvedUrl('.'));
importModule('imageprovider', function () {
image.source = 'image://python/image-id-passed-from-qml';
});
}
onError: console.log('Python error: ' + traceback)
}
}
You open a terminal run:
qmlscene {your directory}/imageprovider.qml
Related
I am trying to implement a Django ImageField class function for resizing images however I am not certain where this function accepts my new image dimensions
Running on Linux and Python 3.7
I've had a look at this documentation, but can't quite make sense of it:
https://docs.djangoproject.com/en/1.11/_modules/django/db/models/fields/files/#ImageField
I'd really appreciate it if someone can show me an example of how to use this function.
EDIT
I haven't successfully managed to resize my image dimensions yet, which is what i am trying to achieve. How may I resize this image before I save it given it is being fetched by ImageField (I found the update_dimensions_fields class function for ImageField however i cant figure out how to use it)
class Posts(models.Model):
title = models.CharField(max_length=200, blank=True)
body = models.TextField(blank=True)
created_at = models.DateTimeField(default=datetime.datetime.now)
post_image = models.ImageField(upload_to=get_image_path, blank=True, null=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
# I would like to use the function beneath to resize my images before I save them to my database
self.post_image.update_dimension_fields(self, instance, force=False, *args, **kwargs)
super().save(*args, **kwargs) # Call the "real" save() method.
class Meta:
verbose_name_plural = "Posts"
You could use the django-resized library. It resizes images when uploaded and stores them for you.
Usage
from django_resized import ResizedImageField
class Posts(models.Model):
title = models.CharField(max_length=200, blank=True)
body = models.TextField(blank=True)
created_at = models.DateTimeField(default=datetime.datetime.now)
post_image = ResizedImageField(size=[500, 300], upload_to=get_image_path, blank=True, null=True)
def __str__(self):
return self.title
Options
size - max width and height, for example [640, 480]
crop - resize and crop. ['top', 'left'] - top left corner, ['middle', -
'center'] is center cropping, ['bottom', 'right'] - crop right bottom corner.
quality - quality of resized image 1..100
keep_meta - keep EXIF and other meta data, default True
force_format - force the format of the resized image, available formats are the one supported by pillow, default to None
**
This will work
**First of all install "PIL Fork" using 'pip install pillow
from PIL import Image
def __str__(self):
return self.title
def save(self, *args, **kwargs):
super(Posts, self).save(*args, **kwargs)
imag = Image.open(self.post_image.path)
if imag.width > 400 or imag.height> 300:
output_size = (400, 300)
imag.thumbnail(output_size)
imag.save(self.post_image.path)
class Meta:
verbose_name_plural = "Posts"
You can use this method to resize the image before saving it: (you need pip install pillow)
import os
from io import BytesIO
from PIL import Image as PilImage
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import InMemoryUploadedFile, TemporaryUploadedFile
def resize_uploaded_image(image, max_width, max_height):
size = (max_width, max_height)
# Uploaded file is in memory
if isinstance(image, InMemoryUploadedFile):
memory_image = BytesIO(image.read())
pil_image = PilImage.open(memory_image)
img_format = os.path.splitext(image.name)[1][1:].upper()
img_format = 'JPEG' if img_format == 'JPG' else img_format
if pil_image.width > max_width or pil_image.height > max_height:
pil_image.thumbnail(size)
new_image = BytesIO()
pil_image.save(new_image, format=img_format)
new_image = ContentFile(new_image.getvalue())
return InMemoryUploadedFile(new_image, None, image.name, image.content_type, None, None)
# Uploaded file is in disk
elif isinstance(image, TemporaryUploadedFile):
path = image.temporary_file_path()
pil_image = PilImage.open(path)
if pil_image.width > max_width or pil_image.height > max_height:
pil_image.thumbnail(size)
pil_image.save(path)
image.size = os.stat(path).st_size
return image
Then use it in the clean method of the image field in your form:
class ImageForm(forms.Form):
IMAGE_WIDTH = 450
IMAGE_HEIGHT = 450
image = forms.ImageField()
def clean_image(self):
image = self.cleaned_data.get('image')
image = resize_uploaded_image(image, self.IMAGE_WIDTH, self.IMAGE_HEIGHT)
return image
To understand how the resize_uploaded_image method works, you may read about how Django handles uploaded files in the docs, here and here.
You can use the django-imagekit library.
Installation
Install Pillow. (If you're using an ImageField in Django,
you should have already done this.)
pip install django-imagekit
Add 'imagekit' to your INSTALLED_APPS list in your project's settings.py
Models.py
from django.db import models
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
class Profile(models.Model):
avatar = models.ImageField(upload_to='avatars')
avatar_thumbnail = ImageSpecField(source='avatar',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
Pay attention to the source attribute of ImageSpecField which directs to the actual image field (avatar in this case) as ImageSpecField are virtual in nature, you can read more about it here
Using in your template
<img src="{{ profile.avatar_thumbnail.url }}" />
I'm trying to use a julia function from a streamlit app. Created a toy example to test the interaction, simply returning a matrix from a julia functions based on a single parameter to specify the value of the diagonal elements.
Will also note at the outset that both julia_import_method = "api_compiled_false" and julia_import_method = "main_include" works when importing the function in Spyder IDE (rather than at the command line to launch the streamlit app via streamlit run streamlit_julia_test.py).
My project directory looks like:
├── my_project_directory
│ ├── julia_test.jl
│ └── streamlit_julia_test.py
The julia function is in julia_test.jl and just simply returns a matrix with diagonals specified by the v parameter:
function get_matrix_from_julia(v::Int)
m=[v 0
0 v]
return m
end
The streamlit app is streamlit_julia_test.py and is defined as:
import os
from io import BytesIO
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import streamlit as st
# options:
# main_include
# api_compiled_false
# dont_import_julia
julia_import_method = "api_compiled_false"
if julia_import_method == "main_include":
# works in Spyder IDE
import julia
from julia import Main
Main.include("julia_test.jl")
elif julia_import_method == "api_compiled_false":
# works in Spyder IDE
from julia.api import Julia
jl = Julia(compiled_modules=False)
this_dir = os.getcwd()
julia_test_path = """include(\""""+ this_dir + """/julia_test.jl\"""" +")"""
print(julia_test_path)
jl.eval(julia_test_path)
get_matrix_from_julia = jl.eval("get_matrix_from_julia")
elif julia_import_method == "dont_import_julia":
print("Not importing ")
else:
ValueError("Not handling this case:" + julia_import_method)
st.header('Using Julia in Streamlit App Example')
st.text("Using Method:" + julia_import_method)
matrix_element = st.selectbox('Set Matrix Diagonal to:', [1,2,3])
matrix_numpy = np.array([[matrix_element,0],[0,matrix_element]])
col1, col2 = st.columns([4,4])
with col1:
fig, ax = plt.subplots(figsize=(5,5))
sns.heatmap(matrix_numpy, ax = ax, cmap="Blues",annot=True)
ax.set_title('Matrix Using Python Numpy')
buf = BytesIO()
fig.savefig(buf, format="png")
st.image(buf)
with col2:
if julia_import_method == "dont_import_julia":
matrix_julia = matrix_numpy
else:
matrix_julia = get_matrix_from_julia(matrix_element)
fig, ax = plt.subplots(figsize=(5,5))
sns.heatmap(matrix_julia, ax = ax, cmap="Blues",annot=True)
ax.set_title('Matrix from External Julia Script')
buf = BytesIO()
fig.savefig(buf, format="png")
st.image(buf)
If the app were working correctly, it would look like this (which can be reproduced by setting the julia_import_method = "dont_import_julia" on line 13):
Testing
When I try julia_import_method = "main_include", I get the well known error:
julia.core.UnsupportedPythonError: It seems your Julia and PyJulia setup are not supported.
Julia executable:
julia
Python interpreter and libpython used by PyCall.jl:
/Users/myusername/opt/anaconda3/bin/python3
/Users/myusername/opt/anaconda3/lib/libpython3.9.dylib
Python interpreter used to import PyJulia and its libpython.
/Users/myusername/opt/anaconda3/bin/python
/Users/myusername/opt/anaconda3/lib/libpython3.9.dylib
Your Python interpreter "/Users/myusername/opt/anaconda3/bin/python"
is statically linked to libpython. Currently, PyJulia does not fully
support such Python interpreter.
The easiest workaround is to pass `compiled_modules=False` to `Julia`
constructor. To do so, first *reboot* your Python REPL (if this happened
inside an interactive session) and then evaluate:
>>> from julia.api import Julia
>>> jl = Julia(compiled_modules=False)
Another workaround is to run your Python script with `python-jl`
command bundled in PyJulia. You can simply do:
$ python-jl PATH/TO/YOUR/SCRIPT.py
See `python-jl --help` for more information.
For more information, see:
https://pyjulia.readthedocs.io/en/latest/troubleshooting.html
As suggested, when I set julia_import_method = "api_compiled_false", I get a seg fault:
include("my_project_directory/julia_test.jl")
2022-04-03 10:23:13.406 Traceback (most recent call last):
File "/Users/myusername/opt/anaconda3/lib/python3.9/site-packages/streamlit/script_runner.py", line 430, in _run_script
exec(code, module.__dict__)
File "my_project_directory/streamlit_julia_test.py", line 25, in <module>
jl = Julia(compiled_modules=False)
File "/Users/myusername/.local/lib/python3.9/site-packages/julia/core.py", line 502, in __init__
if not self.api.was_initialized: # = jl_is_initialized()
File "/Users/myusername/.local/lib/python3.9/site-packages/julia/libjulia.py", line 114, in __getattr__
return getattr(self.libjulia, name)
File "/Users/myusername/opt/anaconda3/lib/python3.9/ctypes/__init__.py", line 395, in __getattr__
func = self.__getitem__(name)
File "/Users/myuserame/opt/anaconda3/lib/python3.9/ctypes/__init__.py", line 400, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: dlsym(0x21b8e5840, was_initialized): symbol not found
signal (11): Segmentation fault: 11
in expression starting at none:0
Allocations: 35278345 (Pool: 35267101; Big: 11244); GC: 36
zsh: segmentation fault streamlit run streamlit_julia_test.py
I've also tried the alternative recommendation provided in the PyJulia response message regarding the use of:
python-jl my_project_directory/streamlit_julia_test.py
But I get this error when running the python-jl command:
INTEL MKL ERROR: dlopen(/Users/myusername/opt/anaconda3/lib/libmkl_intel_thread.1.dylib, 0x0009): Library not loaded: #rpath/libiomp5.dylib
Referenced from: /Users/myusername/opt/anaconda3/lib/libmkl_intel_thread.1.dylib
Reason: tried: '/Applications/Julia-1.7.app/Contents/Resources/julia/bin/../lib/libiomp5.dylib' (no such file), '/usr/local/lib/libiomp5.dylib' (no such file), '/usr/lib/libiomp5.dylib' (no such file).
Intel MKL FATAL ERROR: Cannot load libmkl_intel_thread.1.dylib.
So I'm stuck, thanks in advance for a modified reproducible example or instructions for the following system specs!
System specs:
Mac OS Monterey 12.2.1 (Chip - Mac M1 Pro)
Python 3.9.7
Julia 1.7.2
PyJulia 0.5.8.dev
Streamlit 1.7.0
yes we can use it streamlit_julia_test.py NumPy for instance
I have some difficulties to apply a css file to my dash app when using cx_freeze. If I run python app.py the layout is properly applied, however not if I am executing the .exe generated by cx_freeze. Then the default html layout is displayed. The css and the image appear in the same directory where the .exe is located.
This is how my setup.py looks like.
from setuptools import find_packages
from cx_Freeze import setup, Executable
options = {
'build_exe': {
'includes': [
'cx_Logging', 'idna', 'idna.idnadata'
],
'packages': [
'asyncio', 'flask', 'jinja2', 'dash', 'plotly', 'waitress'
],
'excludes': ['tkinter'],
'include_files': [
'assets/logo.jpg', 'assets/style.css'
],
}
}
executables = [
Executable('server.py',
base='console',
targetName='dash_app.exe')
]
setup(
name='BI_Report',
packages=find_packages(),
version='0.0.1',
description='rig',
executables=executables,
options=options
)
To load the external files I use a helper function as suggested here:
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
app = dash.Dash(__name__,
assets_folder=find_data_file('assets/'))
I am using:
Python 3.7.6
dash 1.9.1
cx-freeze 6.1
Any help much appreciated!
I try to create an exe file with pyinstaller (in Python 3.6) from a script that is using pdfminer modules but the created exe file is huge, around 240 MB. In contrast, when using pyinstaller in Python 2.7 with a similar script the created exe file is only around 10 MB.
What is it that I am doing wrong?
I create the exe file with the following command: pyinstaller.exe --onefile {filename/path}
My code:
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
...
def convert_pdf_to_txt(path):
rsrcmgr = PDFResourceManager()
retstr = io.StringIO()
#codec = 'windows-1250'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, laparams=laparams)
fp = open(path, 'rb')
# reply = s.get(path, stream=True, verify= False)
# fp = StringIO()
# fp.write(reply.content)
# fp.seek(0)
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos = set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password, caching=caching, check_extractable=True):
interpreter.process_page(page)
text = retstr.getvalue()
fp.close()
device.close()
retstr.close()
return text
...
I found the following solution:
Created a virtual environment
Via pip installed only the packages needed (i.e. pdfminer and pyinstaller).
The result in now an exe file that is only 7.8 MB.
I try to change the color of an button icon at runtime. If I have the svg as xml its easy to do. Is it possible to load the xml text representation from an resource file?
Solved: Yes it's possible:
#!/usr/bin/env python
import sip
try:
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
except ValueError, e:
log.error(e)
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtSvg import *
import sys
import resources_rc
if __name__ == '__main__':
app = QApplication(sys.argv)
f = QFile(":/icons/icons/svg/draw-freehand.svg")
if f.open(QFile.ReadOnly | QFile.Text):
textStream = QTextStream(f)
svgData = textStream.readAll()
f.close()
svg = QSvgRenderer(QByteArray(svgData))
qim = QImage(32, 32, QImage.Format_ARGB32)
qim.fill(0)
painter = QPainter()
painter.begin(qim)
svg.render(painter)
painter.end()
qim.save('test2.png')
You can read the SVG source code from QRC into a QString and do string manipulation from there:
Reading from and writing to file in The Qt Resource System (qt 5.0.2)