1+ import time
12import base64
23import httpx
4+ import logging
35from PIL import Image
46from io import BytesIO
7+ from fastapi import Request
8+ from lightllm .utils .log_utils import init_logger
9+
10+ logger = init_logger (__name__ )
511
612
713def image2base64 (img_str : str ):
@@ -13,17 +19,24 @@ def image2base64(img_str: str):
1319 return base64 .b64encode (buffer .getvalue ()).decode ("utf-8" )
1420
1521
16- async def fetch_image (url , timeout ):
17- async with httpx .AsyncClient () as client :
22+ async def fetch_image (url , request : Request , timeout , proxy = None ):
23+ logger .info (f"Begin to download image from url: { url } " )
24+ start_time = time .time ()
25+ async with httpx .AsyncClient (proxy = proxy ) as client :
1826 async with client .stream ("GET" , url , timeout = timeout ) as response :
1927 response .raise_for_status ()
2028 ans_bytes = []
21-
2229 async for chunk in response .aiter_bytes (chunk_size = 1024 * 1024 ):
30+ if request is not None and await request .is_disconnected ():
31+ await response .aclose ()
32+ raise Exception ("Request disconnected. User cancelled download." )
2333 ans_bytes .append (chunk )
2434 # 接收的数据不能大于128M
2535 if len (ans_bytes ) > 128 :
26- raise Exception ("image data is too big" )
36+ raise Exception (f"url { url } Image data is too big" )
2737
2838 content = b"" .join (ans_bytes )
29- return content
39+ end_time = time .time ()
40+ cost_time = end_time - start_time
41+ logger .info (f"Download url { url } image cost time: { cost_time } seconds" )
42+ return content
0 commit comments