hyperbrowser 0.1.0__py3-none-any.whl

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.

Potentially problematic release.


This version of hyperbrowser might be problematic. Click here for more details.

LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 hyperbrowserai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,5 @@
1
+ from .client.sync import Hyperbrowser
2
+ from .client.async_client import AsyncHyperbrowser
3
+ from .config import ClientConfig
4
+
5
+ __all__ = ['Hyperbrowser', 'AsyncHyperbrowser', 'ClientConfig']
@@ -0,0 +1,37 @@
1
+ from typing import Optional
2
+ from ..transport.async_transport import AsyncTransport
3
+ from .base import HyperbrowserBase
4
+ from ..models.session import SessionDetail, Session, SessionListParams, SessionListResponse
5
+ from ..config import ClientConfig
6
+
7
+ class AsyncHyperbrowser(HyperbrowserBase):
8
+ """Asynchronous Hyperbrowser client"""
9
+ def __init__(
10
+ self,
11
+ config: Optional[ClientConfig] = None,
12
+ api_key: Optional[str] = None,
13
+ base_url: Optional[str] = None,
14
+ ):
15
+ super().__init__(AsyncTransport, config, api_key, base_url)
16
+
17
+ async def create_session(self) -> SessionDetail:
18
+ response = await self.transport.post(self._build_url("/session"))
19
+ return SessionDetail(**response.data)
20
+
21
+ async def get_session(self, id: str) -> SessionDetail:
22
+ response = await self.transport.get(self._build_url(f"/session/{id}"))
23
+ return SessionDetail(**response.data)
24
+
25
+ async def stop_session(self, id: str) -> bool:
26
+ response = await self.transport.put(self._build_url(f"/session/{id}/stop"))
27
+ return response.is_success()
28
+
29
+ async def get_session_list(self, params: SessionListParams) -> SessionListResponse:
30
+ response = await self.transport.get(
31
+ self._build_url("/sessions"),
32
+ params=params.__dict__
33
+ )
34
+ return SessionListResponse(**response.data)
35
+
36
+ async def close(self) -> None:
37
+ await self.transport.close()
@@ -0,0 +1,28 @@
1
+ from typing import Optional
2
+ from ..config import ClientConfig
3
+ from ..transport.base import TransportStrategy
4
+ import os
5
+
6
+ class HyperbrowserBase:
7
+ """Base class with shared functionality for sync/async clients"""
8
+ def __init__(
9
+ self,
10
+ transport: TransportStrategy,
11
+ config: Optional[ClientConfig] = None,
12
+ api_key: Optional[str] = None,
13
+ base_url: Optional[str] = None,
14
+ ):
15
+ if config is None:
16
+ config = ClientConfig(
17
+ api_key=api_key if api_key is not None else os.environ.get("HYPERBROWSER_API_KEY", ""),
18
+ base_url=base_url if base_url is not None else os.environ.get("HYPERBROWSER_BASE_URL", "https://app.hyperbrowser.ai")
19
+ )
20
+
21
+ if not config.api_key:
22
+ raise ValueError("API key must be provided")
23
+
24
+ self.config = config
25
+ self.transport = transport(config.api_key)
26
+
27
+ def _build_url(self, path: str) -> str:
28
+ return f"{self.config.base_url}/api{path}"
@@ -0,0 +1,37 @@
1
+ from typing import Optional
2
+ from ..transport.sync import SyncTransport
3
+ from .base import HyperbrowserBase
4
+ from ..models.session import SessionDetail, Session, SessionListParams, SessionListResponse
5
+ from ..config import ClientConfig
6
+
7
+ class Hyperbrowser(HyperbrowserBase):
8
+ """Synchronous Hyperbrowser client"""
9
+ def __init__(
10
+ self,
11
+ config: Optional[ClientConfig] = None,
12
+ api_key: Optional[str] = None,
13
+ base_url: Optional[str] = None,
14
+ ):
15
+ super().__init__(SyncTransport, config, api_key, base_url)
16
+
17
+ def create_session(self) -> SessionDetail:
18
+ response = self.transport.post(self._build_url("/session"))
19
+ return SessionDetail(**response.data)
20
+
21
+ def get_session(self, id: str) -> SessionDetail:
22
+ response = self.transport.get(self._build_url(f"/session/{id}"))
23
+ return SessionDetail(**response.data)
24
+
25
+ def stop_session(self, id: str) -> bool:
26
+ response = self.transport.put(self._build_url(f"/session/{id}/stop"))
27
+ return response.is_success()
28
+
29
+ def get_session_list(self, params: SessionListParams) -> SessionListResponse:
30
+ response = self.transport.get(
31
+ self._build_url("/sessions"),
32
+ params=params.__dict__
33
+ )
34
+ return SessionListResponse(**response.data)
35
+
36
+ def close(self) -> None:
37
+ self.transport.close()
hyperbrowser/config.py ADDED
@@ -0,0 +1,18 @@
1
+ from dataclasses import dataclass
2
+ from typing import Optional
3
+ import os
4
+
5
+ @dataclass
6
+ class ClientConfig:
7
+ """Configuration for the Hyperbrowser client"""
8
+ api_key: str
9
+ base_url: str = "https://api.hyperbrowser.com"
10
+
11
+ @classmethod
12
+ def from_env(cls) -> 'ClientConfig':
13
+ api_key = os.environ.get("HYPERBROWSER_API_KEY")
14
+ if api_key is None:
15
+ raise ValueError("HYPERBROWSER_API_KEY environment variable is required")
16
+
17
+ base_url = os.environ.get("HYPERBROWSER_BASE_URL", "https://api.hyperbrowser.com")
18
+ return cls(api_key=api_key, base_url=base_url)
@@ -0,0 +1,74 @@
1
+ from typing import List, Literal, Optional, Union
2
+ from datetime import datetime
3
+ from pydantic import BaseModel, Field, ConfigDict, field_validator
4
+
5
+ SessionStatus = Literal["active", "closed", "error"]
6
+
7
+ class Session(BaseModel):
8
+ """
9
+ Represents a basic session in the Hyperbrowser system.
10
+ """
11
+ model_config = ConfigDict(
12
+ populate_by_alias=True,
13
+ )
14
+
15
+ id: str
16
+ team_id: str = Field(alias="teamId")
17
+ status: SessionStatus
18
+ created_at: datetime = Field(alias="createdAt")
19
+ updated_at: datetime = Field(alias="updatedAt")
20
+ start_time: Optional[int] = Field(default=None, alias="startTime")
21
+ end_time: Optional[int] = Field(default=None, alias="endTime")
22
+ duration: Optional[int] = None
23
+ session_url: str = Field(alias="sessionUrl")
24
+
25
+ @field_validator('start_time', 'end_time', mode='before')
26
+ @classmethod
27
+ def parse_timestamp(cls, value: Optional[Union[str, int]]) -> Optional[int]:
28
+ """Convert string timestamps to integers."""
29
+ if value is None:
30
+ return None
31
+ if isinstance(value, str):
32
+ return int(value)
33
+ return value
34
+
35
+ class SessionDetail(Session):
36
+ """
37
+ Detailed session information including websocket endpoint.
38
+ """
39
+ websocket_url: Optional[str] = Field(alias="wsEndpoint", default=None)
40
+
41
+ class SessionListParams(BaseModel):
42
+ """
43
+ Parameters for listing sessions.
44
+ """
45
+ model_config = ConfigDict(
46
+ populate_by_alias=True,
47
+ )
48
+
49
+ status: Optional[SessionStatus] = None
50
+ page: int = Field(default=1, ge=1)
51
+ per_page: int = Field(alias="perPage", default=20, ge=1, le=100)
52
+
53
+ class SessionListResponse(BaseModel):
54
+ """
55
+ Response containing a list of sessions with pagination information.
56
+ """
57
+ model_config = ConfigDict(
58
+ populate_by_alias=True,
59
+ )
60
+
61
+ sessions: List[Session]
62
+ total_count: int = Field(alias="totalCount")
63
+ page: int
64
+ per_page: int = Field(alias="perPage")
65
+
66
+ @property
67
+ def has_more(self) -> bool:
68
+ """Check if there are more pages available."""
69
+ return self.total_count > (self.page * self.per_page)
70
+
71
+ @property
72
+ def total_pages(self) -> int:
73
+ """Calculate the total number of pages."""
74
+ return -(-self.total_count // self.per_page)
@@ -0,0 +1,41 @@
1
+ import aiohttp
2
+ from typing import Optional
3
+ from .base import TransportStrategy, APIResponse
4
+
5
+ class AsyncTransport(TransportStrategy):
6
+ """Asynchronous transport implementation using aiohttp"""
7
+ def __init__(self, api_key: str):
8
+ self.session = aiohttp.ClientSession(headers={"x-api-key": api_key})
9
+
10
+ async def close(self) -> None:
11
+ await self.session.close()
12
+
13
+ async def post(self, url: str) -> APIResponse:
14
+ async with self.session.post(url) as response:
15
+ response.raise_for_status()
16
+ try:
17
+ if response.content_length is None or response.content_length == 0:
18
+ return APIResponse.from_status(response.status)
19
+ return APIResponse(await response.json())
20
+ except aiohttp.ContentTypeError:
21
+ return APIResponse.from_status(response.status)
22
+
23
+ async def get(self, url: str, params: Optional[dict] = None) -> APIResponse:
24
+ async with self.session.get(url, params=params) as response:
25
+ response.raise_for_status()
26
+ try:
27
+ if response.content_length is None or response.content_length == 0:
28
+ return APIResponse.from_status(response.status)
29
+ return APIResponse(await response.json())
30
+ except aiohttp.ContentTypeError:
31
+ return APIResponse.from_status(response.status)
32
+
33
+ async def put(self, url: str) -> APIResponse:
34
+ async with self.session.put(url) as response:
35
+ response.raise_for_status()
36
+ try:
37
+ if response.content_length is None or response.content_length == 0:
38
+ return APIResponse.from_status(response.status)
39
+ return APIResponse(await response.json())
40
+ except aiohttp.ContentTypeError:
41
+ return APIResponse.from_status(response.status)
@@ -0,0 +1,56 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Optional, TypeVar, Generic, Type, Union
3
+
4
+ T = TypeVar('T')
5
+
6
+ class APIResponse(Generic[T]):
7
+ """
8
+ Wrapper for API responses to standardize sync/async handling.
9
+
10
+ Attributes:
11
+ data: The parsed response data, if any
12
+ status_code: HTTP status code of the response
13
+ """
14
+ def __init__(
15
+ self,
16
+ data: Optional[Union[dict, T]] = None,
17
+ status_code: int = 200
18
+ ):
19
+ self.data = data
20
+ self.status_code = status_code
21
+
22
+ @classmethod
23
+ def from_json(cls, json_data: dict, model: Type[T]) -> 'APIResponse[T]':
24
+ """Create an APIResponse from JSON data with a specific model."""
25
+ return cls(data=model(**json_data))
26
+
27
+ @classmethod
28
+ def from_status(cls, status_code: int) -> 'APIResponse[None]':
29
+ """Create an APIResponse from just a status code."""
30
+ return cls(data=None, status_code=status_code)
31
+
32
+ def is_success(self) -> bool:
33
+ """Check if the response indicates success."""
34
+ return 200 <= self.status_code < 300
35
+
36
+ class TransportStrategy(ABC):
37
+ """Abstract base class for different transport implementations"""
38
+ @abstractmethod
39
+ def __init__(self, api_key: str):
40
+ pass
41
+
42
+ @abstractmethod
43
+ def close(self) -> None:
44
+ pass
45
+
46
+ @abstractmethod
47
+ def post(self, url: str) -> APIResponse:
48
+ pass
49
+
50
+ @abstractmethod
51
+ def get(self, url: str, params: Optional[dict] = None) -> APIResponse:
52
+ pass
53
+
54
+ @abstractmethod
55
+ def put(self, url: str) -> APIResponse:
56
+ pass
@@ -0,0 +1,36 @@
1
+ import requests
2
+ from typing import Optional
3
+ from .base import TransportStrategy, APIResponse
4
+
5
+ class SyncTransport(TransportStrategy):
6
+ """Synchronous transport implementation using requests"""
7
+ def __init__(self, api_key: str):
8
+ self.session = requests.Session()
9
+ self.session.headers.update({"x-api-key": api_key})
10
+
11
+ def close(self) -> None:
12
+ self.session.close()
13
+
14
+ def post(self, url: str) -> APIResponse:
15
+ response = self.session.post(url)
16
+ response.raise_for_status()
17
+ try:
18
+ return APIResponse(response.json()) if response.content else APIResponse.from_status(response.status_code)
19
+ except requests.exceptions.JSONDecodeError:
20
+ return APIResponse.from_status(response.status_code)
21
+
22
+ def get(self, url: str, params: Optional[dict] = None) -> APIResponse:
23
+ response = self.session.get(url, params=params)
24
+ response.raise_for_status()
25
+ try:
26
+ return APIResponse(response.json()) if response.content else APIResponse.from_status(response.status_code)
27
+ except requests.exceptions.JSONDecodeError:
28
+ return APIResponse.from_status(response.status_code)
29
+
30
+ def put(self, url: str) -> APIResponse:
31
+ response = self.session.put(url)
32
+ response.raise_for_status()
33
+ try:
34
+ return APIResponse(response.json()) if response.content else APIResponse.from_status(response.status_code)
35
+ except requests.exceptions.JSONDecodeError:
36
+ return APIResponse.from_status(response.status_code)
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 hyperbrowserai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.1
2
+ Name: hyperbrowser
3
+ Version: 0.1.0
4
+ Summary: Python SDK for hyperbrowser
5
+ Home-page: https://github.com/hyperbrowserai/python-sdk
6
+ License: MIT
7
+ Author: Nikhil Shahi
8
+ Author-email: nshahi1998@gmail.com
9
+ Requires-Python: >=3.9,<4.0
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Requires-Dist: aiohttp (>=3.11.7,<4.0.0)
18
+ Requires-Dist: pydantic (>=2.10.0,<3.0.0)
19
+ Requires-Dist: requests (>=2.32.3,<3.0.0)
20
+ Project-URL: Repository, https://github.com/hyperbrowserai/python-sdk
21
+ Description-Content-Type: text/markdown
22
+
23
+ ## Installation
24
+
25
+ Currently Hyperbrowser supports creating a browser session in two ways:
26
+
27
+ - Async Client
28
+ - Sync Client
29
+
30
+ It can be installed from `pypi` by running :
31
+
32
+ ```shell
33
+ pip install hyperbrowser
34
+ ```
35
+
36
+ ## Configuration
37
+
38
+ Both the sync and async client follow similar configuration params
39
+
40
+ ### API Key
41
+ The API key can be configured either from the constructor arguments or environment variables using `HYPERBROWSER_API_KEY`
42
+
43
+ ## Usage
44
+
45
+ ### Async
46
+
47
+ ```python
48
+ import asyncio
49
+ from pyppeteer import connect
50
+ from hyperbrowser.client.async_client import AsyncHyperbrowser as Hyperbrowser
51
+
52
+ HYPERBROWSER_API_KEY = "test-key"
53
+
54
+ async def main():
55
+ client = Hyperbrowser(api_key=HYPERBROWSER_API_KEY)
56
+ session = await client.create_session()
57
+
58
+ ws_endpoint = f"{session.websocket_url}&apiKey={HYPERBROWSER_API_KEY}"
59
+ browser = await connect(browserWSEndpoint=ws_endpoint, defaultViewport=None)
60
+
61
+ # Get pages
62
+ pages = await browser.pages()
63
+ if not pages:
64
+ raise Exception("No pages available")
65
+
66
+ page = pages[0]
67
+
68
+ # Navigate to a website
69
+ print("Navigating to Hacker News...")
70
+ await page.goto("https://news.ycombinator.com/")
71
+ page_title = await page.title()
72
+ print("Page title:", page_title)
73
+
74
+ await page.close()
75
+ await browser.disconnect()
76
+ print("Session completed!")
77
+
78
+ # Run the asyncio event loop
79
+ asyncio.get_event_loop().run_until_complete(main())
80
+ ```
81
+ ### Sync
82
+
83
+ ```python
84
+ from playwright.sync_api import sync_playwright
85
+ from hyperbrowser.client.sync import Hyperbrowser
86
+
87
+ HYPERBROWSER_API_KEY = "test-key"
88
+
89
+ def main():
90
+ client = Hyperbrowser(api_key=HYPERBROWSER_API_KEY)
91
+ session = client.create_session()
92
+
93
+ ws_endpoint = f"{session.websocket_url}&apiKey={HYPERBROWSER_API_KEY}"
94
+
95
+ # Launch Playwright and connect to the remote browser
96
+ with sync_playwright() as p:
97
+ browser = p.chromium.connect_over_cdp(ws_endpoint)
98
+ context = browser.new_context()
99
+
100
+ # Get the first page or create a new one
101
+ if len(context.pages) == 0:
102
+ page = context.new_page()
103
+ else:
104
+ page = context.pages[0]
105
+
106
+ # Navigate to a website
107
+ print("Navigating to Hacker News...")
108
+ page.goto("https://news.ycombinator.com/")
109
+ page_title = page.title()
110
+ print("Page title:", page_title)
111
+
112
+ page.close()
113
+ browser.close()
114
+ print("Session completed!")
115
+
116
+ # Run the asyncio event loop
117
+ main()
118
+ ```
@@ -0,0 +1,14 @@
1
+ LICENSE,sha256=6rUGKlyKb_1ZAH7h7YITYAAUNFN3MNGGKCyfrw49NLE,1071
2
+ hyperbrowser/__init__.py,sha256=cQiqqEJ18tN7L1a6B_ZysI0NuKZwwUjG5r4NOye4z9Y,187
3
+ hyperbrowser/client/async_client.py,sha256=2ftnenY8Qth9BW2GLSFk7OsQQF3lulSrJPymgct3TOY,1442
4
+ hyperbrowser/client/base.py,sha256=eOw_K_TgKyJMb9E4RH65bBS-Uw7fIkdD92-wufw3kVM,1004
5
+ hyperbrowser/client/sync.py,sha256=cVoErVoXIisp555J0vA5K7yyFExB5qBfU4SjVTk5vPk,1362
6
+ hyperbrowser/config.py,sha256=HK35QfVMkt82nbEzYJdf1nuWVLs71HP2vjquzSaD_0w,608
7
+ hyperbrowser/models/session.py,sha256=oxJ7uW1oN_0IoOD8kQEKW790cCyQvS0klz5_W5B4DXw,2271
8
+ hyperbrowser/transport/async_transport.py,sha256=iP2ctyeui0tVgm6Ej4qDlPu1zLhLPQ7XKZ9JmUqOOFw,1872
9
+ hyperbrowser/transport/base.py,sha256=u4eIToyBtzAT8lk3Q-11sHS0xImllafc1QT_FdZos4A,1581
10
+ hyperbrowser/transport/sync.py,sha256=IkZcmmdairQTLJbKQOoNU4sKN2cRYgSL5r0Fx37O6jo,1555
11
+ hyperbrowser-0.1.0.dist-info/LICENSE,sha256=6rUGKlyKb_1ZAH7h7YITYAAUNFN3MNGGKCyfrw49NLE,1071
12
+ hyperbrowser-0.1.0.dist-info/METADATA,sha256=ODvwG95cLhoPa4sV8ueVJodRcBAYiFp3IDwSg_oR1sA,3286
13
+ hyperbrowser-0.1.0.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
14
+ hyperbrowser-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.9.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any