Spaces:
Runtime error

File size: 1,926 Bytes
44482d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from config import MODEL_ID

class Generation(BaseModel):
    model_config = ConfigDict(extra="forbid")
    model: Literal[MODEL_ID] = MODEL_ID
    prompt: str = Field(min_length=1, max_length=12000)
    size: str | None = None
    width: int = Field(default=1024, ge=256, le=2048)
    height: int = Field(default=1024, ge=256, le=2048)
    steps: int = Field(default=4, ge=1, le=50)
    guidance_scale: Literal[1.0] = 1.0
    seed: int | None = Field(default=None, ge=0, le=2**32 - 5)
    n: int = Field(default=1, ge=1, le=4)
    output_format: Literal["png", "jpeg", "webp"] = "png"
    response_format: Literal["b64_json", "url"] = "b64_json"

    @model_validator(mode="before")
    @classmethod
    def parse_size(cls, values):
        if not isinstance(values, dict):
            raise ValueError("Expected a JSON object")
        values = dict(values)
        if values.get("size"):
            match = re.fullmatch(r"(\d{3,4})x(\d{3,4})", str(values["size"]))
            if not match:
                raise ValueError("size must be WIDTHxHEIGHT, such as 1024x1024")
            w, h = map(int, match.groups())
            if ("width" in values and int(values["width"]) != w) or ("height" in values and int(values["height"]) != h):
                raise ValueError("size conflicts with width or height")
            values.update(width=w, height=h)
        return values

    @model_validator(mode="after")
    def check(self):
        if not self.prompt.strip():
            raise ValueError("Prompt must contain text")
        if self.width % 16 or self.height % 16:
            raise ValueError("Dimensions must be multiples of 16; no silent rounding is performed")
        if self.width * self.height > 2048 * 1024:
            raise ValueError("Maximum output area is 2,097,152 pixels")
        return self