Coverage for fastblocks / adapters / images / twicpics.py: 22%
166 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1"""TwicPics adapter for FastBlocks with real-time image optimization."""
3import asyncio
4from contextlib import suppress
5from typing import Any
6from urllib.parse import quote
7from uuid import UUID
9import httpx
10from pydantic import SecretStr
12from ._base import ImagesBase, ImagesBaseSettings
15class TwicPicsImagesSettings(ImagesBaseSettings):
16 """Settings for TwicPics adapter."""
18 # Required ACB 0.19.0+ metadata
19 MODULE_ID: UUID = UUID("01937d86-6f4c-8e5d-9a7b-c6d7e8f9a0b1") # Static UUID7
20 MODULE_STATUS: str = "stable"
22 # TwicPics configuration
23 domain: str = "" # Your TwicPics domain (e.g., "demo.twic.pics")
24 path_prefix: str = "" # Optional path prefix
25 api_key: SecretStr = SecretStr("") # For upload operations
27 # Image optimization defaults
28 default_quality: int = 85
29 default_format: str = "auto" # auto, webp, avif, jpeg, png
30 enable_placeholder: bool = True
31 placeholder_quality: int = 10
33 # Performance settings
34 enable_lazy_loading: bool = True
35 enable_progressive: bool = True
36 timeout: int = 30
39class TwicPicsImages(ImagesBase):
40 """TwicPics adapter with real-time image optimization."""
42 # Required ACB 0.19.0+ metadata
43 MODULE_ID: UUID = UUID("01937d86-6f4c-8e5d-9a7b-c6d7e8f9a0b1") # Static UUID7
44 MODULE_STATUS: str = "stable"
46 def __init__(self) -> None:
47 """Initialize TwicPics adapter."""
48 super().__init__()
49 self.settings: TwicPicsImagesSettings | None = None
50 self._client: httpx.AsyncClient | None = None
52 # Register with Oneiric resolver (fail gracefully if not supported)
53 with suppress(Exception):
54 depends.set(self)
56 async def _get_client(self) -> httpx.AsyncClient:
57 """Get or create HTTP client."""
58 if not self._client:
59 if not self.settings:
60 self.settings = TwicPicsImagesSettings()
62 headers = {}
63 if self.settings.api_key.get_secret_value():
64 headers["Authorization"] = (
65 f"Bearer {self.settings.api_key.get_secret_value()}"
66 )
68 self._client = httpx.AsyncClient(
69 timeout=self.settings.timeout, headers=headers
70 )
71 return self._client
73 async def upload_image(self, file_data: bytes, filename: str) -> str:
74 """Upload image to TwicPics (or return reference path)."""
75 # Note: TwicPics typically works with existing images via URL references
76 # For upload scenarios, you'd typically upload to your own storage
77 # and then reference through TwicPics. This is a simplified implementation.
79 if not self.settings:
80 self.settings = TwicPicsImagesSettings()
82 # For demo purposes, we'll create a reference based on filename
83 # In real implementation, you'd upload to your storage backend
84 # and return the path that TwicPics can access
86 # Clean filename for URL
87 clean_filename = quote(filename, safe=".-_")
89 # Return the path that will be used with TwicPics
90 if self.settings.path_prefix:
91 return f"{self.settings.path_prefix}/{clean_filename}"
92 return clean_filename
94 def _build_transform_parts(self, transformations: dict[str, Any]) -> list[str]:
95 """Build transformation parameter list for TwicPics."""
96 transform_parts = []
98 # Resize transformations
99 if "width" in transformations:
100 transform_parts.append(f"width={transformations['width']}")
101 if "height" in transformations:
102 transform_parts.append(f"height={transformations['height']}")
104 # Fit modes
105 if "fit" in transformations:
106 fit_mode = transformations["fit"]
107 resize_map = {"crop": "fill", "contain": "contain", "cover": "cover"}
108 resize_value = resize_map.get(fit_mode, fit_mode)
109 transform_parts.append(f"resize={resize_value}")
111 # Quality and format
112 transform_parts.append(
113 f"quality={transformations.get('quality', self.settings.default_quality if self.settings else 80)}"
114 )
115 output_format = transformations.get(
116 "format", self.settings.default_format if self.settings else "auto"
117 )
118 if output_format != "auto":
119 transform_parts.append(f"output={output_format}")
121 # Advanced effects
122 for effect in ("blur", "brightness", "contrast", "saturation", "rotate"):
123 if effect in transformations:
124 transform_parts.append(f"{effect}={transformations[effect]}")
126 # Focus point
127 if "focus" in transformations:
128 focus = transformations["focus"]
129 if isinstance(focus, dict) and "x" in focus and "y" in focus:
130 transform_parts.append(f"focus={focus['x']}x{focus['y']}")
131 elif isinstance(focus, str):
132 transform_parts.append(f"focus={focus}")
134 # Progressive JPEG
135 if (
136 self.settings
137 and self.settings.enable_progressive
138 and output_format
139 in (
140 "jpeg",
141 "jpg",
142 "auto",
143 )
144 ):
145 transform_parts.append("progressive=true")
147 return transform_parts
149 async def get_image_url(
150 self, image_id: str, transformations: dict[str, Any] | None = None
151 ) -> str:
152 """Generate TwicPics URL with real-time transformations."""
153 if not self.settings:
154 self.settings = TwicPicsImagesSettings()
156 base_url = f"https://{self.settings.domain}/{image_id}"
158 # Apply transformations if provided
159 if transformations:
160 transform_parts = self._build_transform_parts(transformations)
161 if transform_parts:
162 transform_string = "/".join(transform_parts)
163 return f"{base_url}?twic=v1/{transform_string}"
165 # Default optimizations
166 default_transforms = [
167 f"quality={self.settings.default_quality}",
168 f"output={self.settings.default_format}",
169 ]
170 if self.settings.enable_progressive:
171 default_transforms.append("progressive=true")
173 return f"{base_url}?twic=v1/{'/'.join(default_transforms)}"
175 def get_img_tag(self, image_id: str, alt: str, **attributes: Any) -> str:
176 """Generate img tag with TwicPics patterns and optimization."""
177 transformations = attributes.pop("transformations", {})
179 # Generate optimized URL
180 try:
181 loop = asyncio.get_event_loop()
182 url = loop.run_until_complete(self.get_image_url(image_id, transformations))
183 except RuntimeError:
184 loop = asyncio.new_event_loop()
185 asyncio.set_event_loop(loop)
186 url = loop.run_until_complete(self.get_image_url(image_id, transformations))
188 # Build base attributes
189 img_attrs = {"src": url, "alt": alt} | attributes
191 # Add TwicPics-specific optimizations
192 if self.settings and self.settings.enable_lazy_loading:
193 img_attrs["loading"] = "lazy"
195 # Add placeholder for better UX
196 if self.settings and self.settings.enable_placeholder:
197 placeholder_transforms = {
198 **transformations,
199 "quality": self.settings.placeholder_quality,
200 "width": 20, # Very small placeholder
201 }
202 with suppress(Exception): # Fallback to regular loading
203 placeholder_url = loop.run_until_complete(
204 self.get_image_url(image_id, placeholder_transforms)
205 )
206 # For TwicPics, you might use data-src for lazy loading
207 img_attrs["data-src"] = img_attrs["src"]
208 img_attrs["src"] = placeholder_url
209 img_attrs["class"] = (
210 f"{img_attrs.get('class', '')} twicpics-lazy".strip()
211 )
213 # Generate tag
214 attr_string = " ".join(
215 f'{k}="{v}"' for k, v in img_attrs.items() if v is not None
216 )
217 return f"<img {attr_string}>"
219 def get_responsive_img_tag(
220 self,
221 image_id: str,
222 alt: str,
223 breakpoints: dict[str, dict[str, Any]] | None = None,
224 **attributes: Any,
225 ) -> str:
226 """Generate responsive img tag with TwicPics breakpoint optimization."""
227 if not breakpoints:
228 # Default responsive breakpoints
229 breakpoints = {
230 "320w": {"width": 320},
231 "640w": {"width": 640},
232 "768w": {"width": 768},
233 "1024w": {"width": 1024},
234 "1280w": {"width": 1280},
235 "1536w": {"width": 1536},
236 }
238 base_transformations = attributes.pop("transformations", {})
240 # Generate srcset
241 srcset_parts = []
242 for descriptor, transforms in breakpoints.items():
243 combined_transforms = base_transformations | transforms
244 try:
245 loop = asyncio.get_event_loop()
246 url = loop.run_until_complete(
247 self.get_image_url(image_id, combined_transforms)
248 )
249 srcset_parts.append(f"{url} {descriptor}")
250 except Exception:
251 continue
253 # Default src (largest size)
254 default_transforms = {**base_transformations, "width": 1024}
255 try:
256 loop = asyncio.get_event_loop()
257 default_src = loop.run_until_complete(
258 self.get_image_url(image_id, default_transforms)
259 )
260 except RuntimeError:
261 loop = asyncio.new_event_loop()
262 asyncio.set_event_loop(loop)
263 default_src = loop.run_until_complete(
264 self.get_image_url(image_id, default_transforms)
265 )
267 # Build responsive img tag
268 img_attrs = {
269 "src": default_src,
270 "srcset": ", ".join(srcset_parts),
271 "alt": alt,
272 "sizes": attributes.pop("sizes", "(max-width: 768px) 100vw, 50vw"),
273 } | attributes
275 if self.settings and self.settings.enable_lazy_loading:
276 img_attrs["loading"] = "lazy"
278 attr_string = " ".join(
279 f'{k}="{v}"' for k, v in img_attrs.items() if v is not None
280 )
281 return f"<img {attr_string}>"
283 async def close(self) -> None:
284 """Close HTTP client."""
285 if self._client:
286 await self._client.aclose()
287 self._client = None
290# Template filter registration for FastBlocks
291def register_twicpics_filters(env: Any) -> None:
292 """Register TwicPics filters for Jinja2 templates."""
294 @env.filter("twic_url") # type: ignore[misc]
295 async def twic_url_filter(image_id: str, **transformations: Any) -> str:
296 """Template filter for TwicPics URLs."""
297 images = await depends.resolve("fastblocks", "images")
298 if isinstance(images, TwicPicsImages):
299 return await images.get_image_url(image_id, transformations)
300 return f"#{image_id}"
302 @env.filter("twic_img") # type: ignore[misc]
303 def twic_img_filter(image_id: str, alt: str = "", **attributes: Any) -> str:
304 """Template filter for TwicPics img tags."""
305 images = depends.get_sync("images")
306 if isinstance(images, TwicPicsImages):
307 return images.get_img_tag(image_id, alt, **attributes)
308 return f'<img src="#{image_id}" alt="{alt}">'
310 @env.global_("twicpics_responsive") # type: ignore[misc]
311 def twicpics_responsive(
312 image_id: str,
313 alt: str,
314 breakpoints: dict[str, dict[str, Any]] | None = None,
315 **attributes: Any,
316 ) -> str:
317 """Generate responsive image with TwicPics optimization."""
318 images = depends.get_sync("images")
319 if isinstance(images, TwicPicsImages):
320 return images.get_responsive_img_tag(
321 image_id, alt, breakpoints, **attributes
322 )
323 return f'<img src="#{image_id}" alt="{alt}">'
325 @env.filter("twic_placeholder") # type: ignore[misc]
326 async def twic_placeholder_filter(
327 image_id: str, width: int = 20, quality: int = 10
328 ) -> str:
329 """Generate ultra-low quality placeholder URL."""
330 images = await depends.resolve("fastblocks", "images")
331 if isinstance(images, TwicPicsImages):
332 return await images.get_image_url(
333 image_id, {"width": width, "quality": quality}
334 )
335 return f"#{image_id}"
338ImagesSettings = TwicPicsImagesSettings
339Images = TwicPicsImages
341depends.set(Images, "twicpics")
343# ACB 0.19.0+ compatibility
344__all__ = [
345 "TwicPicsImages",
346 "TwicPicsImagesSettings",
347 "register_twicpics_filters",
348 "Images",
349 "ImagesSettings",
350]