Skip to content

Commit

Permalink
Added .gitignore, fixed dependencies installing, added get_models cli…
Browse files Browse the repository at this point in the history
…ent method, version incremented to 0.3, added suppport for dict data in AIHordeClient._run
  • Loading branch information
lapismyt committed May 24, 2024
1 parent 415d908 commit 6722da1
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 19 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
__pycache__
*/__pycache__
build
*.egg_info
24 changes: 22 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
# Async Python client library for AI Horde

## Usage examples:
Here you can find some usage examples of library
## Installation:
Warning: supports only Python 3.11 or later
```bash
python3.11 -m pip install aihorde
```

## Usage examples

### Image generation
```python
Expand Down Expand Up @@ -54,3 +59,18 @@ async def text():
asyncio.run(text())
```

### Get active models list
```python
import asyncio
from aihorde.client import AIHordeClient
from aihorde import models

API_KEY = '0000000000' # Your API key from aihorde.net/register. You can also use 0000000000.

async def models():
client = AIHordeClient(API_KEY)
active_models: list[models.ActiveModel] = await client.get_models(type='image') # or 'text'
print(repr(active_models))

asyncio.run(models())
```
Binary file removed aihorde/__pycache__/__init__.cpython-311.pyc
Binary file not shown.
Binary file removed aihorde/__pycache__/client.cpython-311.pyc
Binary file not shown.
Binary file removed aihorde/__pycache__/models.cpython-311.pyc
Binary file not shown.
45 changes: 33 additions & 12 deletions aihorde/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
from aihorde import __version__ as version
import time
import asyncio
from typing import Optional
from PIL import Image
from typing import Optional, Literal, Union


class AIHordeClient:
Expand All @@ -19,21 +18,22 @@ def __init__(
) -> None:
self.api_key = api_key
self.base_url = base_url.rstrip("/")
self.session = aiohttp.ClientSession()
self.client_agent = client_agent
self.version = version

async def _run(
self, method: str, path: str, data: Optional[models.AIHordeModel] = None
) -> dict:
json = data.to_dict() if data is not None else None
self, method: str, path: str, data: Optional[Union[dict, models.AIHordeModel]] = None # data is not AIHordeModel, but idk how i supposed to figure out 'subclass of AIHordeModel'
) -> Union[list, dict]:
if not isinstance(data, dict):
data = data.to_dict() if data is not None else {}
headers = {"apikey": self.api_key}
kwargs = {"json": json} if method.upper() == "POST" else {"params": data}
async with self.session.request(
method, self.base_url + path, headers=headers, **kwargs
) as response:
resp = await response.json()
return resp
kwargs = {"json": data} if method.upper() == "POST" else {"params": data}
async with aiohttp.ClientSession() as session:
async with session.request(
method, self.base_url + path, headers=headers, **kwargs
) as response:
resp = await response.json()
return resp

async def generate_image_request(
self, request: models.GenerationInputStable
Expand Down Expand Up @@ -86,3 +86,24 @@ async def generate_text(
return status.generations
else:
await asyncio.sleep(int(status.wait_time / 1.5))

async def get_models(
self,
type: Optional[Literal['text', 'image']] = 'image',
min_count: Optional[int] = None,
max_count: Optional[int] = None,
model_state: Optional[Literal['known', 'custom', 'all']] = 'all'
) -> list[models.ActiveModel]:
data = {'type': type,
'min_count': min_count,
'max_count': max_count,
'model_state': model_state}
cleaned = {}
for key, value in data.items():
if not value is None:
cleaned[key] = value
active_models: list[dict] = await self._run('GET', '/v2/status/models', data=cleaned)
converted = []
for active_model in active_models:
converted.append(models.ActiveModel.from_dict(active_model))
return converted
8 changes: 4 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
[build-system]
requires = ["setuptools>=42", "wheel", "aiohttp", "msgspec"]
requires = ["setuptools>=62", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "aihorde"
version = "0.2"
version = "0.3"
description = "Python client for AI Horde API"
dependencies = ["aiohttp", "msgspec"]
authors = [
{name = "LapisMYT (Nikita Gavrilin)", email = "[email protected]"}
{name = "LapisMYT (Nikita Ugnich)", email = "[email protected]"}
]
readme = "README.md"
classifiers = ["Development Status :: 4 - Beta",
"Framework :: aiohttp",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
Expand Down
7 changes: 6 additions & 1 deletion test.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,10 @@ async def image():
for generation in generations:
print(f'{generation.model}: {generation.img}')

async def models():
client = AIHordeClient(API_KEY)
models = await client.get_models()
print(repr(models[0]))

if __name__ == '__main__':
asyncio.run(text())
asyncio.run(models())

0 comments on commit 6722da1

Please sign in to comment.