-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathimage_loader.py
More file actions
75 lines (65 loc) · 2.65 KB
/
Copy pathimage_loader.py
File metadata and controls
75 lines (65 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import asyncio
import logging
from PySide6.QtCore import QThread, Signal
import aiohttp
logger = logging.getLogger(__name__)
class ImageLoader(QThread):
progress_updated = Signal(int, int, dict)
def __init__(
self,
image_urls,
image_manager,
iconified=False,
verify_ssl=True,
):
super().__init__()
self.image_urls = image_urls
self.image_manager = image_manager
self.iconified = iconified
self.verify_ssl = verify_ssl
async def fetch_image(self, session, image_rank, image_url):
try:
# Cache image on disk in worker thread, avoid creating GUI objects here
cache_path = await self.image_manager.cache_image_from_url(
session, image_url, self.iconified
)
if cache_path:
return {"rank": image_rank, "cache_path": cache_path, "iconified": self.iconified}
except Exception as e:
logger.warning(f"Error fetching image {image_url}: {e}")
raise
return None
async def decode_base64_image(self, image_rank, image_str):
try:
# Cache decoded image on disk in worker thread
cache_path = await self.image_manager.cache_image_from_base64(image_str, self.iconified)
if cache_path:
return {"rank": image_rank, "cache_path": cache_path, "iconified": self.iconified}
except Exception as e:
logger.warning(f"Error decoding base64 image : {e}")
raise
return None
async def load_images(self):
connector = aiohttp.TCPConnector(ssl=self.verify_ssl)
async with aiohttp.ClientSession(connector=connector) as session:
tasks = []
for image_rank, url in enumerate(self.image_urls):
if url:
if url.startswith(("http://", "https://")):
tasks.append(self.fetch_image(session, image_rank, url))
elif url.startswith("data:image"):
tasks.append(self.decode_base64_image(image_rank, url))
image_count = len(tasks)
for i, task in enumerate(asyncio.as_completed(tasks), 1):
try:
image_item = await task
except Exception as e:
image_item = None
logger.info(f"Image task failed: {e}")
finally:
self.progress_updated.emit(i, image_count, image_item)
def run(self):
try:
asyncio.run(self.load_images())
except Exception as e:
logger.warning(f"Error in image loading: {e}")