1
0
Fork 0
mirror of https://github.com/ldericher/fftcgtool synced 2025-01-15 23:03:00 +00:00
fftcgtool/fftcg/imageloader.py

73 lines
1.8 KiB
Python
Raw Normal View History

2021-08-04 01:39:19 +00:00
import io
import logging
import queue
2021-08-04 01:41:14 +00:00
import threading
2021-08-04 01:39:19 +00:00
import requests
2021-08-04 01:41:14 +00:00
from PIL import Image
2021-08-04 01:39:19 +00:00
class ImageLoader(threading.Thread):
def __init__(self, url_queue, resolution, language):
2021-08-04 01:39:19 +00:00
threading.Thread.__init__(self)
self.__queue = url_queue
2021-08-04 01:39:19 +00:00
self.__resolution = resolution
self.__language = language
self.__images = {}
def run(self) -> None:
logger = logging.getLogger(__name__)
2021-08-04 16:36:23 +00:00
2021-08-04 01:39:19 +00:00
while not self.__queue.empty():
# take next url
url = self.__queue.get()
2021-08-04 01:39:19 +00:00
# fetch image (retry on fail)
2021-08-04 01:39:19 +00:00
while True:
logger.info(f"downloading image {url}")
2021-08-04 01:39:19 +00:00
try:
res = requests.get(url)
2021-08-04 01:39:19 +00:00
image = Image.open(io.BytesIO(res.content))
2021-08-04 18:15:38 +00:00
# unify images
2021-08-04 01:39:19 +00:00
image.convert("RGB")
image = image.resize(self.__resolution, Image.BICUBIC)
break
except:
pass
# put image in correct position
self.__images[url] = image
2021-08-04 01:39:19 +00:00
# image is processed
self.__queue.task_done()
@classmethod
def load(cls, urls, resolution, language, num_threads):
url_queue = queue.Queue()
for url in urls:
url_queue.put(url)
2021-08-04 01:39:19 +00:00
2021-08-04 16:36:23 +00:00
loaders = []
2021-08-04 01:39:19 +00:00
for _ in range(num_threads):
loader = cls(url_queue, resolution, language)
2021-08-04 16:36:23 +00:00
loaders.append(loader)
loader.start()
url_queue.join()
2021-08-04 16:36:23 +00:00
# stitch all "images" dicts together
2021-08-04 16:36:23 +00:00
images = {}
for loader in loaders:
images = {**images, **loader.images}
2021-08-04 01:39:19 +00:00
2021-08-04 18:15:38 +00:00
# sort images to match the initial "cards" list
images = [images[url] for url in urls]
2021-08-04 18:15:38 +00:00
2021-08-04 16:36:23 +00:00
return images
2021-08-04 01:39:19 +00:00
2021-08-04 16:36:23 +00:00
@property
def images(self):
2021-08-04 01:39:19 +00:00
return self.__images