novelai-python


Namenovelai-python JSON
Version 0.6.1 PyPI version JSON
download
home_pageNone
SummaryNovelAI Python Binding With Pydantic
upload_time2024-12-21 16:23:21
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseApache License 2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ![banner](https://github.com/LlmKira/novelai-python/blob/dev/playground/banner-raw.png?raw=true)

---

[![PyPI version](https://badge.fury.io/py/novelai-python.svg)](https://badge.fury.io/py/novelai-python)
[![Downloads](https://pepy.tech/badge/novelai_python)](https://pepy.tech/project/novelai_python)

✨ NovelAI api python sdk with Pydantic, modern and user-friendly.

The goal of this repository is to use Pydantic to build legitimate requests to access the NovelAI API service.

> Python >= 3.9 is required.

### 📰 News

- [Image Generation Model Release — NovelAI Anime Diffusion V4 Curated Preview (EN)](https://blog.novelai.net/release-novelai-anime-diffusion-v4-curated-preview-en-ca4b0b11e671)
- [Tutorial: Creating Consistent Characters with NovelAI Diffusion Anime [Female]](https://blog.novelai.net/tutorial-en-creating-consistent-characters-with-novelai-diffusion-anime-female-538b4b678a4e)

### 📦 Usage

```shell
pip -U install novelai-python
```

**More examples can be found in the [playground](https://github.com/LlmKira/novelai-python/tree/main/playground)
directory, read code as documentation.**

```python
import asyncio
import os

from dotenv import load_dotenv
from pydantic import SecretStr

from novelai_python import GenerateImageInfer, ImageGenerateResp, ApiCredential
from novelai_python.sdk.ai.generate_image import Model, Character, Sampler, UCPreset
from novelai_python.sdk.ai.generate_image.schema import PositionMap

load_dotenv()
session = ApiCredential(api_token=SecretStr(os.getenv("NOVELAI_JWT")))  # pst-***

prompt = "1girl, year 2023,dynamic angle,  best quality, amazing quality, very aesthetic, absurdres"


async def main():
    gen = GenerateImageInfer.build_generate(
        prompt=prompt,
        model=Model.NAI_DIFFUSION_4_CURATED_PREVIEW,
        character_prompts=[
            Character(
                prompt="1girl",
                uc="red hair",
                center=PositionMap.AUTO
            ),
            Character(
                prompt="1boy",
                center=PositionMap.E5
            )
        ],
        sampler=Sampler.K_EULER_ANCESTRAL,
        ucPreset=UCPreset.TYPE0,
        # Recommended, using preset negative_prompt depends on selected model
        qualitySuffix=True,
        qualityToggle=True,
        decrisp_mode=False,
        variety_boost=True,
        # Checkbox in novelai.net
    )
    cost = gen.calculate_cost(is_opus=True)
    print(f"charge: {cost} if you are vip3")
    resp = await gen.request(session=session)
    resp: ImageGenerateResp
    print(resp.meta)
    file = resp.files[0]
    with open(file[0], "wb") as f:
        f.write(file[1])


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

```

#### 📦 LLM

```python
import asyncio
import os

from dotenv import load_dotenv
from pydantic import SecretStr

from novelai_python import APIError, LoginCredential
from novelai_python.sdk.ai.generate import TextLLMModel, LLM, get_default_preset, AdvanceLLMSetting
from novelai_python.sdk.ai.generate._enum import get_model_preset

load_dotenv()
username = os.getenv("NOVELAI_USER", None)
assert username is not None
# credential = JwtCredential(jwt_token=SecretStr(jwt))
login_credential = LoginCredential(
    username=os.getenv("NOVELAI_USER"),
    password=SecretStr(os.getenv("NOVELAI_PASS"))
)


async def chat(prompt: str):
    try:
        model = TextLLMModel.ERATO  # llama3
        parameters = get_default_preset(model).parameters
        agent = LLM.build(
            prompt=prompt,
            model=model,
            # parameters=None,  # Auto Select or get from preset
            parameters=get_model_preset(TextLLMModel.ERATO).get_all_presets()[0].parameters,  # Select from enum preset
            advanced_setting=AdvanceLLMSetting(
                min_length=1,
                max_length=None,  # Auto
            )
        )
        # NOTE:parameter > advanced_setting, which logic in generate/__init__.py
        # If you not pass the parameter, it will use the default preset.
        # So if you want to set the generation params, you should pass your own params.
        # Only if you want to use some params not affect the generation, you can use advanced_setting.
        result = await agent.request(session=login_credential)
    except APIError as e:
        raise Exception(f"Error: {e.message}")
    print(f"Result: \n{result.text}")


loop = asyncio.get_event_loop()
loop.run_until_complete(chat("Hello"))
```

#### 📦 Random Prompt

```python
from novelai_python.tool.random_prompt import RandomPromptGenerator

prompt = RandomPromptGenerator(nsfw_enabled=False).random_prompt()
print(prompt)
```

#### 📦 Run A Server

```shell
pip install novelai_python
python3 -m novelai_python.server -h '127.0.0.1' -p 7888
```

#### 📦 Tokenizer

```python
from novelai_python._enum import get_tokenizer_model, TextLLMModel
from novelai_python.tokenizer import NaiTokenizer

tokenizer_package = NaiTokenizer(get_tokenizer_model(TextLLMModel.ERATO))
t_text = "a fox jumped over the lazy dog"
encode_tokens = tokenizer_package.encode(t_text)
print(tokenizer_package.tokenize_text(t_text))
print(f"Tokenized text: {encode_tokens}")
print(tokenizer_package.decode(tokenizer_package.encode(t_text)))

```

### 🔨 Roadmap

- [x] tool.random_prompt
- [x] tool.paint_mask
- [x] tool.image_metadata
- [x] tokenizer
- [x] /ai/generate-image
- [x] /user/subscription
- [x] /user/login
- [x] /user/information
- [x] /ai/upscale
- [x] /ai/generate-image/suggest-tags
- [x] /ai/generate-voice
- [x] /ai/generate-stream
- [x] /ai/generate
- [x] /ai/augment-image
- [ ] /ai/annotate-image
- [ ] /ai/classify
- [ ] /ai/generate-prompt

> GenerateImageInfer.calculate_cost is correct in most cases, but please request account information to get accurate
> consumption information.

> This repo is maintained by me personally now. If you have any questions, please feel free to open an issue.

## 🚫 About Nsfw

You might need some solutions for identifying NSFW content and adding a mosaic to prevent operational mishaps.

https://dghs-imgutils.deepghs.org/main/api_doc/detect/nudenet.html

https://dghs-imgutils.deepghs.org/main/api_doc/operate/censor.html

## 🙏 Acknowledgements

[BackEnd](https://api.novelai.net/docs)

[novelai-api](https://github.com/Aedial/novelai-api)

[NovelAI-API](https://github.com/HanaokaYuzu/NovelAI-API)



            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "novelai-python",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": null,
    "author": null,
    "author_email": "sudoskys <coldlando@hotmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/b9/d3/4c82628f678bf5247f924ddeddd50dcf70d559f7624ba3631ac4f0e1b363/novelai_python-0.6.1.tar.gz",
    "platform": null,
    "description": "![banner](https://github.com/LlmKira/novelai-python/blob/dev/playground/banner-raw.png?raw=true)\n\n---\n\n[![PyPI version](https://badge.fury.io/py/novelai-python.svg)](https://badge.fury.io/py/novelai-python)\n[![Downloads](https://pepy.tech/badge/novelai_python)](https://pepy.tech/project/novelai_python)\n\n\u2728 NovelAI api python sdk with Pydantic, modern and user-friendly.\n\nThe goal of this repository is to use Pydantic to build legitimate requests to access the NovelAI API service.\n\n> Python >= 3.9 is required.\n\n### \ud83d\udcf0 News\n\n- [Image Generation Model Release \u2014 NovelAI Anime Diffusion V4 Curated Preview (EN)](https://blog.novelai.net/release-novelai-anime-diffusion-v4-curated-preview-en-ca4b0b11e671)\n- [Tutorial: Creating Consistent Characters with NovelAI Diffusion Anime [Female]](https://blog.novelai.net/tutorial-en-creating-consistent-characters-with-novelai-diffusion-anime-female-538b4b678a4e)\n\n### \ud83d\udce6 Usage\n\n```shell\npip -U install novelai-python\n```\n\n**More examples can be found in the [playground](https://github.com/LlmKira/novelai-python/tree/main/playground)\ndirectory, read code as documentation.**\n\n```python\nimport asyncio\nimport os\n\nfrom dotenv import load_dotenv\nfrom pydantic import SecretStr\n\nfrom novelai_python import GenerateImageInfer, ImageGenerateResp, ApiCredential\nfrom novelai_python.sdk.ai.generate_image import Model, Character, Sampler, UCPreset\nfrom novelai_python.sdk.ai.generate_image.schema import PositionMap\n\nload_dotenv()\nsession = ApiCredential(api_token=SecretStr(os.getenv(\"NOVELAI_JWT\")))  # pst-***\n\nprompt = \"1girl, year 2023,dynamic angle,  best quality, amazing quality, very aesthetic, absurdres\"\n\n\nasync def main():\n    gen = GenerateImageInfer.build_generate(\n        prompt=prompt,\n        model=Model.NAI_DIFFUSION_4_CURATED_PREVIEW,\n        character_prompts=[\n            Character(\n                prompt=\"1girl\",\n                uc=\"red hair\",\n                center=PositionMap.AUTO\n            ),\n            Character(\n                prompt=\"1boy\",\n                center=PositionMap.E5\n            )\n        ],\n        sampler=Sampler.K_EULER_ANCESTRAL,\n        ucPreset=UCPreset.TYPE0,\n        # Recommended, using preset negative_prompt depends on selected model\n        qualitySuffix=True,\n        qualityToggle=True,\n        decrisp_mode=False,\n        variety_boost=True,\n        # Checkbox in novelai.net\n    )\n    cost = gen.calculate_cost(is_opus=True)\n    print(f\"charge: {cost} if you are vip3\")\n    resp = await gen.request(session=session)\n    resp: ImageGenerateResp\n    print(resp.meta)\n    file = resp.files[0]\n    with open(file[0], \"wb\") as f:\n        f.write(file[1])\n\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(main())\n\n```\n\n#### \ud83d\udce6 LLM\n\n```python\nimport asyncio\nimport os\n\nfrom dotenv import load_dotenv\nfrom pydantic import SecretStr\n\nfrom novelai_python import APIError, LoginCredential\nfrom novelai_python.sdk.ai.generate import TextLLMModel, LLM, get_default_preset, AdvanceLLMSetting\nfrom novelai_python.sdk.ai.generate._enum import get_model_preset\n\nload_dotenv()\nusername = os.getenv(\"NOVELAI_USER\", None)\nassert username is not None\n# credential = JwtCredential(jwt_token=SecretStr(jwt))\nlogin_credential = LoginCredential(\n    username=os.getenv(\"NOVELAI_USER\"),\n    password=SecretStr(os.getenv(\"NOVELAI_PASS\"))\n)\n\n\nasync def chat(prompt: str):\n    try:\n        model = TextLLMModel.ERATO  # llama3\n        parameters = get_default_preset(model).parameters\n        agent = LLM.build(\n            prompt=prompt,\n            model=model,\n            # parameters=None,  # Auto Select or get from preset\n            parameters=get_model_preset(TextLLMModel.ERATO).get_all_presets()[0].parameters,  # Select from enum preset\n            advanced_setting=AdvanceLLMSetting(\n                min_length=1,\n                max_length=None,  # Auto\n            )\n        )\n        # NOTE:parameter > advanced_setting, which logic in generate/__init__.py\n        # If you not pass the parameter, it will use the default preset.\n        # So if you want to set the generation params, you should pass your own params.\n        # Only if you want to use some params not affect the generation, you can use advanced_setting.\n        result = await agent.request(session=login_credential)\n    except APIError as e:\n        raise Exception(f\"Error: {e.message}\")\n    print(f\"Result: \\n{result.text}\")\n\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(chat(\"Hello\"))\n```\n\n#### \ud83d\udce6 Random Prompt\n\n```python\nfrom novelai_python.tool.random_prompt import RandomPromptGenerator\n\nprompt = RandomPromptGenerator(nsfw_enabled=False).random_prompt()\nprint(prompt)\n```\n\n#### \ud83d\udce6 Run A Server\n\n```shell\npip install novelai_python\npython3 -m novelai_python.server -h '127.0.0.1' -p 7888\n```\n\n#### \ud83d\udce6 Tokenizer\n\n```python\nfrom novelai_python._enum import get_tokenizer_model, TextLLMModel\nfrom novelai_python.tokenizer import NaiTokenizer\n\ntokenizer_package = NaiTokenizer(get_tokenizer_model(TextLLMModel.ERATO))\nt_text = \"a fox jumped over the lazy dog\"\nencode_tokens = tokenizer_package.encode(t_text)\nprint(tokenizer_package.tokenize_text(t_text))\nprint(f\"Tokenized text: {encode_tokens}\")\nprint(tokenizer_package.decode(tokenizer_package.encode(t_text)))\n\n```\n\n### \ud83d\udd28 Roadmap\n\n- [x] tool.random_prompt\n- [x] tool.paint_mask\n- [x] tool.image_metadata\n- [x] tokenizer\n- [x] /ai/generate-image\n- [x] /user/subscription\n- [x] /user/login\n- [x] /user/information\n- [x] /ai/upscale\n- [x] /ai/generate-image/suggest-tags\n- [x] /ai/generate-voice\n- [x] /ai/generate-stream\n- [x] /ai/generate\n- [x] /ai/augment-image\n- [ ] /ai/annotate-image\n- [ ] /ai/classify\n- [ ] /ai/generate-prompt\n\n> GenerateImageInfer.calculate_cost is correct in most cases, but please request account information to get accurate\n> consumption information.\n\n> This repo is maintained by me personally now. If you have any questions, please feel free to open an issue.\n\n## \ud83d\udeab About Nsfw\n\nYou might need some solutions for identifying NSFW content and adding a mosaic to prevent operational mishaps.\n\nhttps://dghs-imgutils.deepghs.org/main/api_doc/detect/nudenet.html\n\nhttps://dghs-imgutils.deepghs.org/main/api_doc/operate/censor.html\n\n## \ud83d\ude4f Acknowledgements\n\n[BackEnd](https://api.novelai.net/docs)\n\n[novelai-api](https://github.com/Aedial/novelai-api)\n\n[NovelAI-API](https://github.com/HanaokaYuzu/NovelAI-API)\n\n\n",
    "bugtrack_url": null,
    "license": "Apache License 2.0",
    "summary": "NovelAI Python Binding With Pydantic",
    "version": "0.6.1",
    "project_urls": {
        "Issues": "https://github.com/LlmKira/novelai-python/issues",
        "Repository": "https://github.com/LlmKira/novelai-python/"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "fb695335872a2ac8c0cca72b79983bea10d3b3715c30ea2518b4bdfa722a9e40",
                "md5": "f0af15fe70058d1eaaceb47b910beae1",
                "sha256": "71dee5131bf17f226b93c4b1abf99f0819aced9c64ff3c84e1ccc90650a7c352"
            },
            "downloads": -1,
            "filename": "novelai_python-0.6.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "f0af15fe70058d1eaaceb47b910beae1",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 2046458,
            "upload_time": "2024-12-21T16:23:17",
            "upload_time_iso_8601": "2024-12-21T16:23:17.940570Z",
            "url": "https://files.pythonhosted.org/packages/fb/69/5335872a2ac8c0cca72b79983bea10d3b3715c30ea2518b4bdfa722a9e40/novelai_python-0.6.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b9d34c82628f678bf5247f924ddeddd50dcf70d559f7624ba3631ac4f0e1b363",
                "md5": "269af74d0fffd6f7aed2d89048986f9c",
                "sha256": "7c00f91c677ec37194a64990efc026d917b519f2475bc09784e7a1474412dd9a"
            },
            "downloads": -1,
            "filename": "novelai_python-0.6.1.tar.gz",
            "has_sig": false,
            "md5_digest": "269af74d0fffd6f7aed2d89048986f9c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 2022650,
            "upload_time": "2024-12-21T16:23:21",
            "upload_time_iso_8601": "2024-12-21T16:23:21.241519Z",
            "url": "https://files.pythonhosted.org/packages/b9/d3/4c82628f678bf5247f924ddeddd50dcf70d559f7624ba3631ac4f0e1b363/novelai_python-0.6.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-21 16:23:21",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "LlmKira",
    "github_project": "novelai-python",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "novelai-python"
}
        
Elapsed time: 0.41203s