summaryrefslogtreecommitdiffstats
path: root/g4f/Provider/nexra/NexraSD21.py
blob: fc5c90d98f68ef69483349c16e622948851176e0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from __future__ import annotations

import json
from aiohttp import ClientSession
from ...image import ImageResponse

from ...typing import AsyncResult, Messages
from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin


class NexraSD21(AsyncGeneratorProvider, ProviderModelMixin):
    label = "Nexra Stable Diffusion 2.1"
    url = "https://nexra.aryahcr.cc/documentation/stable-diffusion/en"
    api_endpoint = "https://nexra.aryahcr.cc/api/image/complements"
    working = True
    
    default_model = 'stablediffusion-2.1'
    models = [default_model]
    
    model_aliases = {
        "sd-2.1": "stablediffusion-2.1",
    }

    @classmethod
    def get_model(cls, model: str) -> str:
        if model in cls.models:
            return model
        elif model in cls.model_aliases:
            return cls.model_aliases[model]
        else:
            return cls.default_model

    @classmethod
    async def create_async_generator(
        cls,
        model: str,
        messages: Messages,
        proxy: str = None,
        response: str = "url",  # base64 or url
        **kwargs
    ) -> AsyncResult:
        model = cls.get_model(model)
        
        headers = {
            "Content-Type": "application/json",
        }
        async with ClientSession(headers=headers) as session:
            # Directly use the messages as the prompt
            data = {
                "prompt": messages,
                "model": model,
                "response": response,
                "data": {
                    "prompt_negative": "",
                    "guidance_scale": 9
                }
            }
            async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:
                response.raise_for_status()
                text_response = await response.text()

                # Clean the response by removing unexpected characters
                cleaned_response = text_response.strip('__')

                if not cleaned_response.strip():
                    raise ValueError("Received an empty response from the server.")

                try:
                    json_response = json.loads(cleaned_response)
                    image_url = json_response.get("images", [])[0]
                    # Create an ImageResponse object
                    image_response = ImageResponse(images=image_url, alt="Generated Image")
                    yield image_response
                except json.JSONDecodeError:
                    raise ValueError("Unable to decode JSON from the received text response.")