Metadata-Version: 2.4
Name: boorux
Version: 0.1.0
Summary: Modern, async, strictly-typed Python API client for Booru imageboards (Danbooru, Moebooru, Gelbooru)
Keywords: booru,danbooru,moebooru,gelbooru,konachan,yandere,safebooru,sakugabooru,async,httpx,pydantic
Author: itsDersty
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: AsyncIO
Classifier: Framework :: Pydantic :: 2
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Dist: httpx[http2]>=0.28.1
Requires-Dist: pydantic>=2.14.3
Requires-Python: >=3.12
Project-URL: Homepage, https://github.com/itsDersty/boorux
Project-URL: Documentation, https://boorux.readthedocs.io
Project-URL: Repository, https://github.com/itsDersty/boorux
Project-URL: Issues, https://github.com/itsDersty/boorux/issues
Project-URL: Changelog, https://github.com/itsDersty/boorux/releases
Description-Content-Type: text/markdown

<img src="https://github.com/itsDersty/boorux/blob/main/assets/boorux_banner.jpg?raw=true">

[![PyPI version](https://img.shields.io/pypi/v/boorux.svg)](https://pypi.org/project/boorux)
[![CI](https://img.shields.io/github/actions/workflow/status/itsDersty/boorux/ci.yml?branch=main&label=CI)](https://github.com/itsDersty/boorux/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Coverage](https://img.shields.io/codecov/c/github/itsDersty/boorux)](https://codecov.io/gh/itsDersty/boorux)
[![Docs](https://readthedocs.org/projects/boorux/badge/?version=latest)](https://boorux.readthedocs.io/en/latest/)
[![Code style: Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)

A unified, async, type-safe Python client for Booru imageboards (Danbooru, Moebooru, Gelbooru), built with HTTPX and Pydantic v2.

---

## Key Features

- **Unified & Engine-Specific Models:** Consistent base schemas (`Post`, `Comment`, `Tag`, `Pool`) across all imageboards, extended with full engine-specific fields (`DanbooruPost`, `MoebooruPost`, `GelbooruPost`, `DanbooruMediaAsset`) validated via Pydantic v2.
- **Full IDE Autocomplete for Queries:** Search methods use `TypedDict` + `Unpack` (PEP 692), giving you static type checking and IDE autocomplete for query filters, sorting literals, and date parameters.
- **Polymorphic Capability Protocols:** Write generic, type-safe code against `@runtime_checkable` protocols (`SupportsPosts`, `SupportsComments`, `SupportsTags`, `SupportsPools`).
- **Clear Exception Hierarchy:** All API errors map to structured `BooruXError` subclasses (`NotFoundError`, `RateLimitError`, `CloudflareChallengeError`, `AuthenticationError`, `APIError`).
- **HTTP/2 & Dependency Injection:** Runs on `httpx.AsyncClient` with HTTP/2 enabled by default, or lets you inject your own configured `AsyncClient` for custom proxies, timeouts, headers, or mock transports.

---

## Installation

Using `pip`:

```bash
pip install boorux
```

Or using `uv`:

```bash
uv add boorux
```

---

## Quick Start

### Basic Usage

Use any site client as an async context manager:

```python
import asyncio
from boorux import Danbooru, Rating


async def main() -> None:
    async with Danbooru() as client:
        posts = await client.post_list(
            tags=["hakurei_reimu", "solo"],
            rating=Rating.GENERAL,
            limit=5,
        )
        for post in posts:
            print(
                f"#{post.id} [{post.rating}] {post.width}x{post.height} -> {post.file_url}"
            )


asyncio.run(main())
```

### Engine-Specific Features

Each client returns models tailored to its underlying platform while keeping common fields consistent:

```python
import asyncio
from boorux import Danbooru, Konachan


async def main() -> None:
    async with Danbooru() as danbooru:
        # Categorized tag lists, media variants, and cursor pagination
        posts = await danbooru.post_list(tags=["forest"], before_id=12_400_000, limit=5)
        if posts:
            print("Artists:", posts[0].tags_artist)
            print("Characters:", posts[0].tags_character)

    async with Konachan() as konachan:
        pool = await konachan.pool_get(17)
        print(f"Pool '{pool.name}': {len(pool.posts)} posts, IDs: {pool.post_ids[:5]}")


asyncio.run(main())
```

### Polymorphic Code with Protocols

Write functions that work across any compatible imageboard, or check optional features at runtime:

```python
import asyncio
from boorux import Danbooru, Safebooru, SupportsPools, SupportsPosts


async def inspect_board(client: SupportsPosts, tag: str) -> None:
    posts = await client.post_list(tags=[tag], limit=1)
    if posts:
        post = posts[0]
        print(f"Found #{post.id} ({post.width}x{post.height}): {post.file_url}")

    if isinstance(client, SupportsPools):
        pools = await client.pool_list(limit=1)
        print("Supports pools! Latest:", pools[0].name if pools else "none")
    else:
        print("This board does not support pools.")


async def main() -> None:
    async with Danbooru() as danbooru, Safebooru() as safebooru:
        await inspect_board(danbooru, "forest")
        await inspect_board(safebooru, "forest")


asyncio.run(main())
```

### Custom `httpx.AsyncClient` & Mirrors

Pass an external `httpx.AsyncClient` to configure proxies, timeouts, custom `User-Agent` headers (recommended by Danbooru for bots), or alternative transports. When an external client is provided, BooruX will not close it on context exit:

```python
import asyncio
import httpx
from boorux import Danbooru, Konachan


async def main() -> None:
    custom_http = httpx.AsyncClient(
        http2=True,
        headers={"User-Agent": "MyBot/1.0 (user #12345)"},
        timeout=httpx.Timeout(30.0),
    )

    async with Danbooru(httpx_client=custom_http) as client:
        post = await client.post_get(12370421)
        print(post.file_url)

    await custom_http.aclose()

    # Override base_url to use mirrors (e.g., Konachan's SFW mirror)
    async with Konachan(base_url="https://konachan.net") as sfw_konachan:
        posts = await sfw_konachan.post_list(tags=["forest"], limit=5)
        print(f"Fetched {len(posts)} posts from mirror")


asyncio.run(main())
```

---

## Supported Sites & Capabilities

| Site | Default URL | Engine | Posts | Comments | Tags | Pools |
| :--- | :--- | :--- | :---: | :---: | :---: | :---: |
| **Danbooru** | `danbooru.donmai.us` | `DanbooruEngine` | ✅ | ✅ | ✅ | ✅ |
| **Konachan** | `konachan.com` | `MoebooruEngine` | ✅ | ✅ | ✅ | ✅ |
| **Yandere** | `yande.re` | `MoebooruEngine` | ✅ | ✅ | ✅ | ✅ |
| **Sakugabooru** | `www.sakugabooru.com` | `MoebooruEngine` | ✅ | ✅ | ✅ | ✅ |
| **Safebooru** | `safebooru.org` | `GelbooruEngine` | ✅ | ⚠️ *List only* | ✅ | ❌ |

> **Note:**
> - **Safebooru:** Supports `comment_list`, but does not provide a `comment_get` endpoint or a pools API (`pool_list` / `pool_get`).
> - **Danbooru Limits:** Unauthenticated users are limited to searching 2 tags per query (registered accounts get 3). System metatags such as `rating:`, `score`, `id`, and `md5:` are exempt from this limit. Maximum page size is `200` for posts and `1000` for other endpoints.

---

## Error Handling

API-level errors raise subclasses of `BooruXError`:

```python
import asyncio
import httpx
from boorux import (
    APIError,
    AuthenticationError,
    BooruXError,
    CloudflareChallengeError,
    Danbooru,
    NotFoundError,
    RateLimitError,
)


async def main() -> None:
    async with Danbooru() as client:
        try:
            post = await client.post_get(999_999_999)
        except NotFoundError:
            print("Resource does not exist.")
        except RateLimitError as exc:
            print(f"Rate limited ({exc.status_code}) at {exc.url}")
        except CloudflareChallengeError as exc:
            print(f"Blocked by Cloudflare challenge at {exc.url}")
        except AuthenticationError as exc:
            print(f"Access denied ({exc.status_code}) at {exc.url}")
        except APIError as exc:
            print(f"API error ({exc.status_code}) at {exc.url}")
        except BooruXError as exc:
            print(f"BooruX error: {exc}")
        except httpx.RequestError as exc:
            print(f"Network or timeout error: {exc}")


asyncio.run(main())
```

> **Note:** Low-level transport errors (`httpx.RequestError`, timeouts) and schema validation errors (`pydantic.ValidationError`) are propagated directly from `httpx` and `pydantic` rather than being masked.

---

## Roadmap

Planned additions for future releases:

- **Authentication & Write Endpoints:** API key and hash authentication, creating comments, voting, and uploading posts.
- **More Sites:** Wider booru sites support.
- **Built-in Tools (`boorux.tools`):** Streaming media downloader, concurrent batch downloads, and async auto-pagination iterators.

---

## License

This project is licensed under the [MIT License](https://github.com/itsDersty/boorux/blob/main/LICENSE).