1212 - torch
1313 - transformers
1414 - Pillow (PIL)
15- - requests
15+ - httpx (already in repo dependencies)
1616
1717Resources:
1818 - Paper: https://arxiv.org/abs/2010.11929
4040from typing import Any
4141
4242try :
43- import requests
43+ import httpx
4444 import torch
4545 from PIL import Image
4646 from transformers import ViTForImageClassification , ViTImageProcessor
4747except ImportError as e :
4848 print (f"Error: Missing required dependency: { e .name } " )
49- print ("Install dependencies: pip install torch transformers pillow requests " )
49+ print ("Install dependencies: pip install torch transformers pillow httpx " )
5050 sys .exit (1 )
5151
5252
@@ -62,8 +62,8 @@ def load_image(image_source: str | Path, timeout: int = 10) -> Image.Image:
6262 PIL Image object
6363
6464 Raises:
65- TimeoutError: If request times out
66- ConnectionError: If URL is unreachable
65+ TimeoutError: If request times out
66+ ConnectionError: If URL is unreachable
6767 FileNotFoundError: If local file doesn't exist
6868 IOError: If image cannot be opened
6969
@@ -79,16 +79,17 @@ def load_image(image_source: str | Path, timeout: int = 10) -> Image.Image:
7979 ("http://" , "https://" )
8080 ):
8181 try :
82- response = requests .get (str (image_source ), timeout = timeout )
83- response .raise_for_status ()
84- return Image .open (BytesIO (response .content )).convert ("RGB" )
85- except requests .exceptions .Timeout :
82+ with httpx .Client (timeout = timeout ) as client :
83+ response = client .get (str (image_source ))
84+ response .raise_for_status ()
85+ return Image .open (BytesIO (response .content )).convert ("RGB" )
86+ except httpx .TimeoutException :
8687 msg = (
8788 f"Request timed out after { timeout } seconds. "
8889 "Try increasing the timeout parameter."
8990 )
9091 raise TimeoutError (msg )
91- except requests . exceptions . RequestException as e :
92+ except httpx . HTTPError as e :
9293 msg = f"Failed to download image from URL: { e } "
9394 raise ConnectionError (msg ) from e
9495 else :
0 commit comments