Read image bytes from local /tmp cache or remote URL.
(url: str)
| 169 | |
| 170 | |
| 171 | async def retrieve_image_data(url: str) -> Optional[bytes]: |
| 172 | """Read image bytes from local /tmp cache or remote URL.""" |
| 173 | file_cache = getattr(generation_handler, "file_cache", None) |
| 174 | try: |
| 175 | if "/tmp/" in url and file_cache: |
| 176 | path = urlparse(url).path |
| 177 | filename = path.split("/tmp/")[-1] |
| 178 | local_file_path = file_cache.cache_dir / filename |
| 179 | |
| 180 | if local_file_path.exists() and local_file_path.is_file(): |
| 181 | data = local_file_path.read_bytes() |
| 182 | if data: |
| 183 | return data |
| 184 | except Exception as exc: |
| 185 | debug_logger.log_warning(f"[CONTEXT] 本地缓存读取失败: {str(exc)}") |
| 186 | |
| 187 | proxy_url = None |
| 188 | try: |
| 189 | if file_cache and hasattr(file_cache, "_resolve_download_proxy"): |
| 190 | proxy_url = await file_cache._resolve_download_proxy("image") |
| 191 | except Exception as exc: |
| 192 | debug_logger.log_warning(f"[CONTEXT] 图片下载代理解析失败: {str(exc)}") |
| 193 | |
| 194 | try: |
| 195 | async with AsyncSession() as session: |
| 196 | response = await session.get( |
| 197 | url, |
| 198 | timeout=60, |
| 199 | proxies={"http": proxy_url, "https": proxy_url} if proxy_url else None, |
| 200 | headers={ |
| 201 | "Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8", |
| 202 | "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", |
| 203 | "Accept-Encoding": "gzip, deflate, br", |
| 204 | "Connection": "keep-alive", |
| 205 | "Referer": "https://labs.google/", |
| 206 | }, |
| 207 | impersonate="chrome120", |
| 208 | verify=False, |
| 209 | ) |
| 210 | if response.status_code == 200 and response.content: |
| 211 | return response.content |
| 212 | debug_logger.log_warning( |
| 213 | f"[CONTEXT] 图片下载失败,状态码: {response.status_code}" |
| 214 | ) |
| 215 | except Exception as exc: |
| 216 | debug_logger.log_error(f"[CONTEXT] 图片下载异常: {str(exc)}") |
| 217 | |
| 218 | return None |
| 219 | |
| 220 | |
| 221 | async def _load_image_bytes_from_uri(uri: str) -> bytes: |
no test coverage detected