clearfetch 1.0.0__tar.gz → 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clearfetch
3
- Version: 1.0.0
4
- Summary: Official Python SDK for ClearFetch (clearfetch.dev) - Unblocked Web & Anti-Bot Markdown/JSON Extraction for AI Agents.
3
+ Version: 1.1.0
4
+ Summary: Official Python SDK for ClearFetch (clearfetch.dev) - Unblocked Web, Anti-Bot Markdown/JSON Extraction, and Web Screenshot API for AI Agents.
5
5
  Author-email: ClearFetch Team <support@clearfetch.dev>
6
- License: MIT
6
+ License-Expression: MIT
7
7
  Project-URL: Homepage, https://clearfetch.dev
8
8
  Project-URL: Documentation, https://clearfetch.dev/docs
9
- Project-URL: Repository, https://github.com/clearfetch/clearfetch-python
10
- Keywords: clearfetch,web-scraper,anti-bot,cloudflare-turnstile,datadome,ai-agent,llm,langchain,llamaindex,rag
9
+ Project-URL: Repository, https://github.com/zenkdom/clearfetch
10
+ Keywords: clearfetch,web-scraper,web-screenshot,screenshot-api,anti-bot,cloudflare-turnstile,datadome,ai-agent,llm,langchain,llamaindex,rag
11
11
  Classifier: Development Status :: 5 - Production/Stable
12
12
  Classifier: Intended Audience :: Developers
13
- Classifier: License :: OSI Approved :: MIT License
14
13
  Classifier: Programming Language :: Python :: 3
15
14
  Classifier: Programming Language :: Python :: 3.9
16
15
  Classifier: Programming Language :: Python :: 3.10
@@ -110,7 +109,25 @@ print(result.data)
110
109
 
111
110
  ---
112
111
 
113
- ### 4. LangChain Integration
112
+ ### 4. Capture Website Screenshots (Full-Page, Dark Mode, Mobile, Element Crop)
113
+
114
+ ```python
115
+ shot = client.screenshot(
116
+ url="https://linear.app/pricing",
117
+ format="png",
118
+ full_page=True,
119
+ dark_mode=True,
120
+ block_ads=True,
121
+ device_scale_factor=2.0,
122
+ output_path="linear_pricing.png"
123
+ )
124
+
125
+ print(f"Captured {shot.width}x{shot.height} ({shot.size_bytes} bytes)")
126
+ ```
127
+
128
+ ---
129
+
130
+ ### 5. LangChain Integration
114
131
 
115
132
  ```python
116
133
  from clearfetch import ClearFetchLoader
@@ -126,7 +143,7 @@ print(docs[0].page_content)
126
143
 
127
144
  ---
128
145
 
129
- ### 5. CLI Terminal Usage
146
+ ### 6. CLI Terminal Usage
130
147
 
131
148
  ```bash
132
149
  # Export your key
@@ -137,6 +154,9 @@ clearfetch read https://example.com
137
154
 
138
155
  # Live search and bundle
139
156
  clearfetch search "Autonomous AI agents" --limit 3
157
+
158
+ # Capture a full-page dark-mode screenshot
159
+ clearfetch screenshot https://example.com --full-page --dark-mode --output page.png
140
160
  ```
141
161
 
142
162
  ---
@@ -79,7 +79,25 @@ print(result.data)
79
79
 
80
80
  ---
81
81
 
82
- ### 4. LangChain Integration
82
+ ### 4. Capture Website Screenshots (Full-Page, Dark Mode, Mobile, Element Crop)
83
+
84
+ ```python
85
+ shot = client.screenshot(
86
+ url="https://linear.app/pricing",
87
+ format="png",
88
+ full_page=True,
89
+ dark_mode=True,
90
+ block_ads=True,
91
+ device_scale_factor=2.0,
92
+ output_path="linear_pricing.png"
93
+ )
94
+
95
+ print(f"Captured {shot.width}x{shot.height} ({shot.size_bytes} bytes)")
96
+ ```
97
+
98
+ ---
99
+
100
+ ### 5. LangChain Integration
83
101
 
84
102
  ```python
85
103
  from clearfetch import ClearFetchLoader
@@ -95,7 +113,7 @@ print(docs[0].page_content)
95
113
 
96
114
  ---
97
115
 
98
- ### 5. CLI Terminal Usage
116
+ ### 6. CLI Terminal Usage
99
117
 
100
118
  ```bash
101
119
  # Export your key
@@ -106,6 +124,9 @@ clearfetch read https://example.com
106
124
 
107
125
  # Live search and bundle
108
126
  clearfetch search "Autonomous AI agents" --limit 3
127
+
128
+ # Capture a full-page dark-mode screenshot
129
+ clearfetch screenshot https://example.com --full-page --dark-mode --output page.png
109
130
  ```
110
131
 
111
132
  ---
@@ -1,9 +1,18 @@
1
1
  from clearfetch.client import ClearFetch, AsyncClearFetch, ClearFetchError
2
- from clearfetch.types import ReadResult, ExtractResult, SearchResult, SearchItem, UsageResult, Metadata
2
+ from clearfetch.types import (
3
+ ReadResult,
4
+ ExtractResult,
5
+ SearchResult,
6
+ SearchItem,
7
+ ScreenshotResult,
8
+ ScreenshotMetadata,
9
+ UsageResult,
10
+ Metadata,
11
+ )
3
12
  from clearfetch.integrations.langchain import ClearFetchLoader
4
13
  from clearfetch.integrations.llamaindex import ClearFetchReader
5
14
 
6
- __version__ = "1.0.0"
15
+ __version__ = "1.1.0"
7
16
 
8
17
  __all__ = [
9
18
  "ClearFetch",
@@ -13,6 +22,8 @@ __all__ = [
13
22
  "ExtractResult",
14
23
  "SearchResult",
15
24
  "SearchItem",
25
+ "ScreenshotResult",
26
+ "ScreenshotMetadata",
16
27
  "UsageResult",
17
28
  "Metadata",
18
29
  "ClearFetchLoader",
@@ -30,6 +30,18 @@ def main():
30
30
  search_parser.add_argument("query", help="Search query string")
31
31
  search_parser.add_argument("--limit", type=int, default=5, help="Number of results (1-10)")
32
32
 
33
+ # Screenshot command
34
+ shot_parser = subparsers.add_parser("screenshot", help="Capture a PNG, JPEG, or WebP webpage screenshot")
35
+ shot_parser.add_argument("url", help="Target URL to capture")
36
+ shot_parser.add_argument("--format", choices=["png", "jpeg", "webp"], default="png", help="Output image format")
37
+ shot_parser.add_argument("--full-page", action="store_true", help="Capture full scrollable page height")
38
+ shot_parser.add_argument("--dark-mode", action="store_true", help="Emulate dark color scheme")
39
+ shot_parser.add_argument("--mobile", action="store_true", help="Emulate mobile viewport and touch events")
40
+ shot_parser.add_argument("--width", type=int, default=1440, help="Viewport width in pixels")
41
+ shot_parser.add_argument("--height", type=int, default=900, help="Viewport height in pixels")
42
+ shot_parser.add_argument("--selector", help="Optional CSS selector to crop tightly around an element")
43
+ shot_parser.add_argument("--output", "-o", default="screenshot.png", help="Output file path")
44
+
33
45
  # Usage command
34
46
  subparsers.add_parser("usage", help="Check remaining credits and plan details")
35
47
 
@@ -59,6 +71,21 @@ def main():
59
71
  print(f"{item.snippet}\n")
60
72
  print("-" * 50)
61
73
 
74
+ elif args.command == "screenshot":
75
+ result = client.screenshot(
76
+ url=args.url,
77
+ format=args.format,
78
+ full_page=args.full_page,
79
+ dark_mode=args.dark_mode,
80
+ is_mobile=args.mobile,
81
+ width=args.width,
82
+ height=args.height,
83
+ selector=args.selector,
84
+ output_path=args.output,
85
+ )
86
+ print(f"Saved {result.format.upper()} screenshot ({result.width}x{result.height}, {result.size_bytes} bytes) -> {args.output}")
87
+ print(f"--- Metadata: status={result.metadata.status_code}, latency={result.metadata.latency_ms}ms, credits={result.metadata.credits_used} ---", file=sys.stderr)
88
+
62
89
  elif args.command == "usage":
63
90
  result = client.get_usage()
64
91
  print(f"Plan Tier: {result.plan_tier}")
@@ -1,7 +1,85 @@
1
1
  import os
2
2
  import httpx
3
3
  from typing import Dict, Any, Optional, List
4
- from clearfetch.types import ReadResult, ExtractResult, SearchResult, SearchItem, UsageResult, Metadata
4
+ from clearfetch.types import (
5
+ ReadResult,
6
+ ExtractResult,
7
+ SearchResult,
8
+ SearchItem,
9
+ ScreenshotResult,
10
+ ScreenshotMetadata,
11
+ UsageResult,
12
+ Metadata,
13
+ )
14
+
15
+
16
+ def _build_screenshot_payload(
17
+ url: str,
18
+ format: str = "png",
19
+ quality: int = 85,
20
+ full_page: bool = False,
21
+ width: int = 1440,
22
+ height: int = 900,
23
+ device_scale_factor: float = 1.0,
24
+ is_mobile: bool = False,
25
+ dark_mode: bool = False,
26
+ block_ads: bool = True,
27
+ omit_background: bool = False,
28
+ selector: Optional[str] = None,
29
+ wait_for_selector: Optional[str] = None,
30
+ hide_selectors: Optional[List[str]] = None,
31
+ delay_ms: int = 400,
32
+ timeout: int = 45,
33
+ stealth: str = "auto",
34
+ max_age: int = 0,
35
+ ) -> Dict[str, Any]:
36
+ payload: Dict[str, Any] = {
37
+ "url": url,
38
+ "format": format,
39
+ "quality": quality,
40
+ "full_page": full_page,
41
+ "width": width,
42
+ "height": height,
43
+ "device_scale_factor": device_scale_factor,
44
+ "is_mobile": is_mobile,
45
+ "dark_mode": dark_mode,
46
+ "block_ads": block_ads,
47
+ "omit_background": omit_background,
48
+ "delay_ms": delay_ms,
49
+ "timeout": timeout,
50
+ "stealth": stealth,
51
+ "max_age": max_age,
52
+ "response_type": "json",
53
+ }
54
+ if selector:
55
+ payload["selector"] = selector
56
+ if wait_for_selector:
57
+ payload["wait_for_selector"] = wait_for_selector
58
+ if hide_selectors:
59
+ payload["hide_selectors"] = hide_selectors
60
+ return payload
61
+
62
+
63
+ def _parse_screenshot_result(data: Dict[str, Any], output_path: Optional[str] = None) -> ScreenshotResult:
64
+ meta = data["metadata"]
65
+ result = ScreenshotResult(
66
+ success=data["success"],
67
+ url=data["url"],
68
+ final_url=data.get("final_url", data["url"]),
69
+ page_title=data.get("page_title", ""),
70
+ format=data["format"],
71
+ mime_type=data["mime_type"],
72
+ width=data["width"],
73
+ height=data["height"],
74
+ full_page=data["full_page"],
75
+ size_bytes=data["size_bytes"],
76
+ image_base64=data["image_base64"],
77
+ data_uri=data["data_uri"],
78
+ metadata=ScreenshotMetadata(**meta),
79
+ )
80
+ if output_path:
81
+ result.save(output_path)
82
+ return result
5
83
 
6
84
  class ClearFetchError(Exception):
7
85
  """Base exception for ClearFetch API errors."""
@@ -30,7 +108,7 @@ class ClearFetch:
30
108
  self._headers = {
31
109
  "Authorization": f"Bearer {self.api_key}",
32
110
  "Content-Type": "application/json",
33
- "User-Agent": "ClearFetch-Python-SDK/1.0.0"
111
+ "User-Agent": "ClearFetch-Python-SDK/1.1.0"
34
112
  }
35
113
 
36
114
  def _handle_response(self, response: httpx.Response) -> Dict[str, Any]:
@@ -146,6 +224,58 @@ class ClearFetch:
146
224
  credits_used=data["credits_used"]
147
225
  )
148
226
 
227
+ def screenshot(
228
+ self,
229
+ url: str,
230
+ format: str = "png",
231
+ quality: int = 85,
232
+ full_page: bool = False,
233
+ width: int = 1440,
234
+ height: int = 900,
235
+ device_scale_factor: float = 1.0,
236
+ is_mobile: bool = False,
237
+ dark_mode: bool = False,
238
+ block_ads: bool = True,
239
+ omit_background: bool = False,
240
+ selector: Optional[str] = None,
241
+ wait_for_selector: Optional[str] = None,
242
+ hide_selectors: Optional[List[str]] = None,
243
+ delay_ms: int = 400,
244
+ timeout: int = 45,
245
+ stealth: str = "auto",
246
+ max_age: int = 0,
247
+ output_path: Optional[str] = None,
248
+ ) -> ScreenshotResult:
249
+ """Captures a full-page, mobile, dark-mode, or element screenshot (PNG/JPEG/WebP)."""
250
+ payload = _build_screenshot_payload(
251
+ url=url,
252
+ format=format,
253
+ quality=quality,
254
+ full_page=full_page,
255
+ width=width,
256
+ height=height,
257
+ device_scale_factor=device_scale_factor,
258
+ is_mobile=is_mobile,
259
+ dark_mode=dark_mode,
260
+ block_ads=block_ads,
261
+ omit_background=omit_background,
262
+ selector=selector,
263
+ wait_for_selector=wait_for_selector,
264
+ hide_selectors=hide_selectors,
265
+ delay_ms=delay_ms,
266
+ timeout=timeout,
267
+ stealth=stealth,
268
+ max_age=max_age,
269
+ )
270
+ with httpx.Client(timeout=self.timeout) as client:
271
+ resp = client.post(
272
+ f"{self.base_url}/v1/screenshot",
273
+ headers=self._headers,
274
+ json=payload,
275
+ )
276
+ data = self._handle_response(resp)
277
+ return _parse_screenshot_result(data, output_path=output_path)
278
+
149
279
  def get_usage(self) -> UsageResult:
150
280
  """Retrieves account balance and recent telemetry logs."""
151
281
  with httpx.Client(timeout=self.timeout) as client:
@@ -180,7 +310,7 @@ class AsyncClearFetch:
180
310
  self._headers = {
181
311
  "Authorization": f"Bearer {self.api_key}",
182
312
  "Content-Type": "application/json",
183
- "User-Agent": "ClearFetch-Python-AsyncSDK/1.0.0"
313
+ "User-Agent": "ClearFetch-Python-AsyncSDK/1.1.0"
184
314
  }
185
315
 
186
316
  def _handle_response(self, response: httpx.Response) -> Dict[str, Any]:
@@ -293,6 +423,58 @@ class AsyncClearFetch:
293
423
  credits_used=data["credits_used"]
294
424
  )
295
425
 
426
+ async def screenshot(
427
+ self,
428
+ url: str,
429
+ format: str = "png",
430
+ quality: int = 85,
431
+ full_page: bool = False,
432
+ width: int = 1440,
433
+ height: int = 900,
434
+ device_scale_factor: float = 1.0,
435
+ is_mobile: bool = False,
436
+ dark_mode: bool = False,
437
+ block_ads: bool = True,
438
+ omit_background: bool = False,
439
+ selector: Optional[str] = None,
440
+ wait_for_selector: Optional[str] = None,
441
+ hide_selectors: Optional[List[str]] = None,
442
+ delay_ms: int = 400,
443
+ timeout: int = 45,
444
+ stealth: str = "auto",
445
+ max_age: int = 0,
446
+ output_path: Optional[str] = None,
447
+ ) -> ScreenshotResult:
448
+ """Asynchronously captures a website screenshot (PNG/JPEG/WebP)."""
449
+ payload = _build_screenshot_payload(
450
+ url=url,
451
+ format=format,
452
+ quality=quality,
453
+ full_page=full_page,
454
+ width=width,
455
+ height=height,
456
+ device_scale_factor=device_scale_factor,
457
+ is_mobile=is_mobile,
458
+ dark_mode=dark_mode,
459
+ block_ads=block_ads,
460
+ omit_background=omit_background,
461
+ selector=selector,
462
+ wait_for_selector=wait_for_selector,
463
+ hide_selectors=hide_selectors,
464
+ delay_ms=delay_ms,
465
+ timeout=timeout,
466
+ stealth=stealth,
467
+ max_age=max_age,
468
+ )
469
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
470
+ resp = await client.post(
471
+ f"{self.base_url}/v1/screenshot",
472
+ headers=self._headers,
473
+ json=payload,
474
+ )
475
+ data = self._handle_response(resp)
476
+ return _parse_screenshot_result(data, output_path=output_path)
477
+
296
478
  async def get_usage(self) -> UsageResult:
297
479
  async with httpx.AsyncClient(timeout=self.timeout) as client:
298
480
  resp = await client.get(f"{self.base_url}/v1/usage", headers=self._headers)
@@ -19,7 +19,7 @@ class ClearFetchLoader:
19
19
  try:
20
20
  from langchain_core.documents import Document
21
21
  except ImportError:
22
- # Fallback mock Document class if langchain_core is not installed
22
+ # Fallback lightweight Document container if langchain_core is not installed
23
23
  from dataclasses import dataclass
24
24
  @dataclass
25
25
  class Document:
@@ -1,3 +1,4 @@
1
+ import base64
1
2
  from typing import List, Dict, Any, Optional
2
3
  from dataclasses import dataclass
3
4
 
@@ -44,6 +45,42 @@ class SearchResult:
44
45
  total_estimated_tokens: int
45
46
  credits_used: int
46
47
 
48
+ @dataclass
49
+ class ScreenshotMetadata:
50
+ status_code: int
51
+ cached: bool
52
+ stealth_used: bool
53
+ latency_ms: int
54
+ credits_used: int
55
+
56
+
57
+ @dataclass
58
+ class ScreenshotResult:
59
+ success: bool
60
+ url: str
61
+ final_url: str
62
+ page_title: str
63
+ format: str
64
+ mime_type: str
65
+ width: int
66
+ height: int
67
+ full_page: bool
68
+ size_bytes: int
69
+ image_base64: str
70
+ data_uri: str
71
+ metadata: ScreenshotMetadata
72
+
73
+ @property
74
+ def image_bytes(self) -> bytes:
75
+ return base64.b64decode(self.image_base64)
76
+
77
+ def save(self, path: str) -> str:
78
+ """Writes decoded screenshot image bytes to disk and returns the saved path."""
79
+ with open(path, "wb") as f:
80
+ f.write(self.image_bytes)
81
+ return path
82
+
83
+
47
84
  @dataclass
48
85
  class UsageResult:
49
86
  credits_balance: int
@@ -1,16 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clearfetch
3
- Version: 1.0.0
4
- Summary: Official Python SDK for ClearFetch (clearfetch.dev) - Unblocked Web & Anti-Bot Markdown/JSON Extraction for AI Agents.
3
+ Version: 1.1.0
4
+ Summary: Official Python SDK for ClearFetch (clearfetch.dev) - Unblocked Web, Anti-Bot Markdown/JSON Extraction, and Web Screenshot API for AI Agents.
5
5
  Author-email: ClearFetch Team <support@clearfetch.dev>
6
- License: MIT
6
+ License-Expression: MIT
7
7
  Project-URL: Homepage, https://clearfetch.dev
8
8
  Project-URL: Documentation, https://clearfetch.dev/docs
9
- Project-URL: Repository, https://github.com/clearfetch/clearfetch-python
10
- Keywords: clearfetch,web-scraper,anti-bot,cloudflare-turnstile,datadome,ai-agent,llm,langchain,llamaindex,rag
9
+ Project-URL: Repository, https://github.com/zenkdom/clearfetch
10
+ Keywords: clearfetch,web-scraper,web-screenshot,screenshot-api,anti-bot,cloudflare-turnstile,datadome,ai-agent,llm,langchain,llamaindex,rag
11
11
  Classifier: Development Status :: 5 - Production/Stable
12
12
  Classifier: Intended Audience :: Developers
13
- Classifier: License :: OSI Approved :: MIT License
14
13
  Classifier: Programming Language :: Python :: 3
15
14
  Classifier: Programming Language :: Python :: 3.9
16
15
  Classifier: Programming Language :: Python :: 3.10
@@ -110,7 +109,25 @@ print(result.data)
110
109
 
111
110
  ---
112
111
 
113
- ### 4. LangChain Integration
112
+ ### 4. Capture Website Screenshots (Full-Page, Dark Mode, Mobile, Element Crop)
113
+
114
+ ```python
115
+ shot = client.screenshot(
116
+ url="https://linear.app/pricing",
117
+ format="png",
118
+ full_page=True,
119
+ dark_mode=True,
120
+ block_ads=True,
121
+ device_scale_factor=2.0,
122
+ output_path="linear_pricing.png"
123
+ )
124
+
125
+ print(f"Captured {shot.width}x{shot.height} ({shot.size_bytes} bytes)")
126
+ ```
127
+
128
+ ---
129
+
130
+ ### 5. LangChain Integration
114
131
 
115
132
  ```python
116
133
  from clearfetch import ClearFetchLoader
@@ -126,7 +143,7 @@ print(docs[0].page_content)
126
143
 
127
144
  ---
128
145
 
129
- ### 5. CLI Terminal Usage
146
+ ### 6. CLI Terminal Usage
130
147
 
131
148
  ```bash
132
149
  # Export your key
@@ -137,6 +154,9 @@ clearfetch read https://example.com
137
154
 
138
155
  # Live search and bundle
139
156
  clearfetch search "Autonomous AI agents" --limit 3
157
+
158
+ # Capture a full-page dark-mode screenshot
159
+ clearfetch screenshot https://example.com --full-page --dark-mode --output page.png
140
160
  ```
141
161
 
142
162
  ---
@@ -12,4 +12,5 @@ clearfetch.egg-info/requires.txt
12
12
  clearfetch.egg-info/top_level.txt
13
13
  clearfetch/integrations/__init__.py
14
14
  clearfetch/integrations/langchain.py
15
- clearfetch/integrations/llamaindex.py
15
+ clearfetch/integrations/llamaindex.py
16
+ tests/test_sdk.py
@@ -4,17 +4,19 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "clearfetch"
7
- version = "1.0.0"
8
- description = "Official Python SDK for ClearFetch (clearfetch.dev) - Unblocked Web & Anti-Bot Markdown/JSON Extraction for AI Agents."
7
+ version = "1.1.0"
8
+ description = "Official Python SDK for ClearFetch (clearfetch.dev) - Unblocked Web, Anti-Bot Markdown/JSON Extraction, and Web Screenshot API for AI Agents."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
11
- license = { text = "MIT" }
11
+ license = "MIT"
12
12
  authors = [
13
13
  { name = "ClearFetch Team", email = "support@clearfetch.dev" }
14
14
  ]
15
15
  keywords = [
16
16
  "clearfetch",
17
17
  "web-scraper",
18
+ "web-screenshot",
19
+ "screenshot-api",
18
20
  "anti-bot",
19
21
  "cloudflare-turnstile",
20
22
  "datadome",
@@ -27,7 +29,6 @@ keywords = [
27
29
  classifiers = [
28
30
  "Development Status :: 5 - Production/Stable",
29
31
  "Intended Audience :: Developers",
30
- "License :: OSI Approved :: MIT License",
31
32
  "Programming Language :: Python :: 3",
32
33
  "Programming Language :: Python :: 3.9",
33
34
  "Programming Language :: Python :: 3.10",
@@ -48,7 +49,10 @@ all = ["langchain-core>=0.1.0", "llama-index-core>=0.10.0"]
48
49
  [project.urls]
49
50
  Homepage = "https://clearfetch.dev"
50
51
  Documentation = "https://clearfetch.dev/docs"
51
- Repository = "https://github.com/clearfetch/clearfetch-python"
52
+ Repository = "https://github.com/zenkdom/clearfetch"
52
53
 
53
54
  [project.scripts]
54
55
  clearfetch = "clearfetch.cli:main"
56
+
57
+ [tool.pytest.ini_options]
58
+ pythonpath = ["."]
@@ -0,0 +1,181 @@
1
+ import base64
2
+ import pytest
3
+ import httpx
4
+ from unittest.mock import patch
5
+ from clearfetch import ClearFetch, AsyncClearFetch
6
+ from clearfetch.types import (
7
+ Metadata,
8
+ ReadResult,
9
+ ExtractResult,
10
+ SearchItem,
11
+ SearchResult,
12
+ ScreenshotMetadata,
13
+ ScreenshotResult,
14
+ UsageResult,
15
+ )
16
+ from clearfetch.client import ClearFetchError
17
+
18
+ def test_client_init_requires_key():
19
+ with pytest.raises(ValueError, match="ClearFetch API key must be provided"):
20
+ ClearFetch(api_key=None)
21
+
22
+ def test_client_init_with_key():
23
+ client = ClearFetch(api_key="cf_live_test12345", base_url="https://api.clearfetch.dev/")
24
+ assert client.api_key == "cf_live_test12345"
25
+ assert client.base_url == "https://api.clearfetch.dev"
26
+ assert client._headers["Authorization"] == "Bearer cf_live_test12345"
27
+
28
+ def test_async_client_init_with_key():
29
+ async_client = AsyncClearFetch(api_key="cf_live_async12345")
30
+ assert async_client.api_key == "cf_live_async12345"
31
+ assert async_client.base_url == "https://api.clearfetch.dev"
32
+
33
+ def test_types_dataclasses():
34
+ meta = Metadata(
35
+ status_code=200,
36
+ cached=False,
37
+ stealth_used=True,
38
+ estimated_tokens=500,
39
+ latency_ms=120,
40
+ credits_used=1
41
+ )
42
+ read_res = ReadResult(
43
+ success=True,
44
+ url="https://example.com",
45
+ title="Example",
46
+ description="Desc",
47
+ markdown="# Content",
48
+ links=["https://example.com/about"],
49
+ metadata=meta
50
+ )
51
+ assert read_res.success is True
52
+ assert read_res.metadata.stealth_used is True
53
+
54
+ def test_error_class():
55
+ err = ClearFetchError("Unauthorized", status_code=401, details={"detail": "Bad Key"})
56
+ assert err.status_code == 401
57
+ assert err.details == {"detail": "Bad Key"}
58
+ assert str(err) == "Unauthorized"
59
+
60
+
61
+ def test_screenshot_result_and_save(tmp_path):
62
+ raw = b"\x89PNG\r\n\x1a\nfake"
63
+ b64 = base64.b64encode(raw).decode("utf-8")
64
+ meta = ScreenshotMetadata(
65
+ status_code=200,
66
+ cached=False,
67
+ stealth_used=True,
68
+ latency_ms=820,
69
+ credits_used=3,
70
+ )
71
+ res = ScreenshotResult(
72
+ success=True,
73
+ url="https://example.com",
74
+ final_url="https://example.com/",
75
+ page_title="Example",
76
+ format="png",
77
+ mime_type="image/png",
78
+ width=1440,
79
+ height=900,
80
+ full_page=True,
81
+ size_bytes=len(raw),
82
+ image_base64=b64,
83
+ data_uri=f"data:image/png;base64,{b64}",
84
+ metadata=meta,
85
+ )
86
+ assert res.image_bytes == raw
87
+ out_file = tmp_path / "shot.png"
88
+ res.save(str(out_file))
89
+ assert out_file.read_bytes() == raw
90
+
91
+
92
+ def test_sync_screenshot_client_call(tmp_path):
93
+ raw = b"\x89PNG\r\n\x1a\nfake-sync"
94
+ b64 = base64.b64encode(raw).decode("utf-8")
95
+ mock_payload = {
96
+ "success": True,
97
+ "url": "https://example.com",
98
+ "final_url": "https://example.com/",
99
+ "page_title": "Example Domain",
100
+ "format": "png",
101
+ "mime_type": "image/png",
102
+ "width": 1280,
103
+ "height": 720,
104
+ "full_page": True,
105
+ "size_bytes": len(raw),
106
+ "image_base64": b64,
107
+ "data_uri": f"data:image/png;base64,{b64}",
108
+ "metadata": {
109
+ "status_code": 200,
110
+ "cached": False,
111
+ "stealth_used": True,
112
+ "latency_ms": 910,
113
+ "credits_used": 3,
114
+ },
115
+ }
116
+
117
+ def handler(request: httpx.Request) -> httpx.Response:
118
+ assert request.url.path == "/v1/screenshot"
119
+ return httpx.Response(200, json=mock_payload)
120
+
121
+ transport = httpx.MockTransport(handler)
122
+ orig_client = httpx.Client
123
+
124
+ def mocked_client(*args, **kwargs):
125
+ kwargs["transport"] = transport
126
+ return orig_client(*args, **kwargs)
127
+
128
+ out_path = tmp_path / "out.png"
129
+ with patch("clearfetch.client.httpx.Client", side_effect=mocked_client):
130
+ client = ClearFetch(api_key="cf_live_test123")
131
+ res = client.screenshot("https://example.com", full_page=True, width=1280, height=720, output_path=str(out_path))
132
+
133
+ assert res.width == 1280
134
+ assert res.metadata.credits_used == 3
135
+ assert out_path.read_bytes() == raw
136
+
137
+
138
+ @pytest.mark.asyncio
139
+ async def test_async_screenshot_client_call():
140
+ raw = b"\x89PNG\r\n\x1a\nfake-async"
141
+ b64 = base64.b64encode(raw).decode("utf-8")
142
+ mock_payload = {
143
+ "success": True,
144
+ "url": "https://example.com",
145
+ "final_url": "https://example.com/",
146
+ "page_title": "Example Domain",
147
+ "format": "webp",
148
+ "mime_type": "image/webp",
149
+ "width": 390,
150
+ "height": 844,
151
+ "full_page": False,
152
+ "size_bytes": len(raw),
153
+ "image_base64": b64,
154
+ "data_uri": f"data:image/webp;base64,{b64}",
155
+ "metadata": {
156
+ "status_code": 200,
157
+ "cached": False,
158
+ "stealth_used": True,
159
+ "latency_ms": 650,
160
+ "credits_used": 3,
161
+ },
162
+ }
163
+
164
+ def handler(request: httpx.Request) -> httpx.Response:
165
+ assert request.url.path == "/v1/screenshot"
166
+ return httpx.Response(200, json=mock_payload)
167
+
168
+ transport = httpx.MockTransport(handler)
169
+ orig_async = httpx.AsyncClient
170
+
171
+ def mocked_async_client(*args, **kwargs):
172
+ kwargs["transport"] = transport
173
+ return orig_async(*args, **kwargs)
174
+
175
+ with patch("clearfetch.client.httpx.AsyncClient", side_effect=mocked_async_client):
176
+ client = AsyncClearFetch(api_key="cf_live_test123")
177
+ res = await client.screenshot("https://example.com", format="webp", is_mobile=True, width=390, height=844)
178
+
179
+ assert res.format == "webp"
180
+ assert res.width == 390
181
+ assert res.image_bytes == raw
File without changes