Skip to content

Commit

Permalink
Recommendations: Quick fix to load images frmo URLs (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
janezd authored Jun 25, 2024
1 parent 2390f5b commit a51551a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
40 changes: 32 additions & 8 deletions orangecontrib/pumice/widgets/owrecommendation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os.path
from typing import Optional
import urllib.request, urllib.error, urllib.parse

import numpy as np

Expand Down Expand Up @@ -29,6 +30,32 @@ def height(text, font=None, bold=False):
return height


# TODO
# This is a horrible quick patch because I realised that using URL's of iamges
# in data.pumice.si broke this widget. This must be done properly and
# asynchronously.
class ImageStore(dict):
def __getitem__(self, url):
if url not in self:
if url.startswith("http"):
try:
scheme, path = url.split("://", 1)
url = f'{scheme}://{urllib.parse.quote(path)}'
headers = {'User-Agent': 'Mozilla/5.0'}
request = urllib.request.Request(url, headers=headers)
data = urllib.request.urlopen(request).read()
except urllib.error.URLError:
return None
elif os.path.exists(url):
data = open(url, "rb").read()
else:
return None
pixmap = QPixmap()
pixmap.loadFromData(data)
self[url] = pixmap.scaled(150, 200, Qt.AspectRatioMode.KeepAspectRatio)
return super().__getitem__(url)


class PersonDelegate(QItemDelegate):
def paint(self, painter, option, index):
painter.save()
Expand Down Expand Up @@ -339,6 +366,8 @@ def __init__(self):
images (list of QPixmap): images
"""
super().__init__()
self.image_store = ImageStore()

self.network: Network = None
self.data: Table = None
self.choices = None
Expand Down Expand Up @@ -592,16 +621,11 @@ def set_images(self):
return

image_origin = self.image_column.attributes.get("origin", ".")

self.images = []
for img_name in self.data.get_column(self.image_column):
img_name = os.path.join(image_origin, img_name)
if os.path.exists(img_name):
self.images.append(
QPixmap(img_name)
.scaled(150, 200, Qt.AspectRatioMode.KeepAspectRatio))
else:
self.images.append(None)
if not img_name.startswith("http"):
img_name = os.path.join(image_origin, img_name)
self.images.append(self.image_store[img_name])

def get_friends(self):
if not self.is_valid:
Expand Down
3 changes: 2 additions & 1 deletion orangecontrib/pumice/widgets/tests/test_owrecommendation.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,8 +490,9 @@ def test_update_page_sets_model(self):
w.rec_model.set_data.assert_called()

@patch("os.path.exists", new=lambda x: bool(ord(x[-1]) % 2))
@patch("builtins.open")
@patch("orangecontrib.pumice.widgets.owrecommendation.QPixmap")
def test_set_images(self, _):
def test_set_images(self, *_):
w = self.widget

w.image_column = None
Expand Down

0 comments on commit a51551a

Please sign in to comment.