Skip to content

Posterllama

PosterLlama processor, parser, and layout-generation pipeline.

PosterLlamaConfig

Bases: PretrainedConfig

Configuration for local PosterLlama recipe artifacts.

Parameters:

Name Type Description Default
checkpoint_repo_id str

Source Hub repository containing the raw checkpoint.

'poong/PosterLlama'
base_llm_repo_id str

Preferred CodeLLaMA/LLaMA backbone repository id.

'codellama/CodeLlama-7b-hf'
alternate_base_llm_repo_ids Sequence[str]

Alternate backbone ids recorded for audit.

('meta-llama/Llama-2-7b-chat-hf',)
vision_encoder_repo_id str

Vision encoder repository id.

'facebook/dinov2-base'
vision_model_name PosterLlamaVisionModelName

Original vision tower selector.

'dino_v2'
lora_r int

LoRA rank used by the released recipe.

64
lora_alpha int

LoRA alpha used by the released recipe.

16
lora_dropout float

LoRA dropout used by the released recipe.

0.05
lora_target_modules Sequence[str]

LLM projection module names targeted by LoRA.

('q_proj', 'v_proj')
prompt_template str

Wrapper applied around generated layout prompts.

'{}'
image_placeholder str

Placeholder token used for image feature insertion.

'<ImageHere>'
image_end_token str

End marker for image features.

'</Img>'
max_txt_len int

Original maximum text length.

400
max_context_len int

Original context length budget.

3800
default_max_new_tokens int

Default generation budget.

1024
default_do_sample bool

Default sampled-generation flag.

True
default_temperature float

Default generation temperature.

0.6
default_top_p float

Default nucleus sampling value.

0.9
default_top_k int

Default top-k sampling value.

40
default_num_beams int

Default beam count.

4
dataset_name PosterLlamaDatasetName

Poster dataset key.

'cgl'
id2label Mapping[int | str, str] | None

Dataset-local label vocabulary.

None
canvas_size tuple[int, int] | list[int] | None

Optional default canvas size as (width, height).

None
checkpoint_license_status PosterLlamaLicenseStatus

Redistribution status for converted weights.

'unverified'
processor_subfolder str

Pipeline processor subfolder.

'processor'
runtime_subfolder str

Optional converted runtime subfolder.

'runtime'
kwargs PosterLlamaConfigValue

Extra PretrainedConfig keyword arguments.

{}

Examples:

>>> cfg = PosterLlamaConfig(canvas_size=(360, 504))
>>> cfg.id2label[1]
'text'
Source code in models/posterllama/src/posterllama/configuration_posterllama.py
 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
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
class PosterLlamaConfig(PretrainedConfig):
    """Configuration for local PosterLlama recipe artifacts.

    Args:
        checkpoint_repo_id: Source Hub repository containing the raw checkpoint.
        base_llm_repo_id: Preferred CodeLLaMA/LLaMA backbone repository id.
        alternate_base_llm_repo_ids: Alternate backbone ids recorded for audit.
        vision_encoder_repo_id: Vision encoder repository id.
        vision_model_name: Original vision tower selector.
        lora_r: LoRA rank used by the released recipe.
        lora_alpha: LoRA alpha used by the released recipe.
        lora_dropout: LoRA dropout used by the released recipe.
        lora_target_modules: LLM projection module names targeted by LoRA.
        prompt_template: Wrapper applied around generated layout prompts.
        image_placeholder: Placeholder token used for image feature insertion.
        image_end_token: End marker for image features.
        max_txt_len: Original maximum text length.
        max_context_len: Original context length budget.
        default_max_new_tokens: Default generation budget.
        default_do_sample: Default sampled-generation flag.
        default_temperature: Default generation temperature.
        default_top_p: Default nucleus sampling value.
        default_top_k: Default top-k sampling value.
        default_num_beams: Default beam count.
        dataset_name: Poster dataset key.
        id2label: Dataset-local label vocabulary.
        canvas_size: Optional default canvas size as ``(width, height)``.
        checkpoint_license_status: Redistribution status for converted weights.
        processor_subfolder: Pipeline processor subfolder.
        runtime_subfolder: Optional converted runtime subfolder.
        kwargs: Extra ``PretrainedConfig`` keyword arguments.

    Examples:
        >>> cfg = PosterLlamaConfig(canvas_size=(360, 504))
        >>> cfg.id2label[1]
        'text'
    """

    model_type = "posterllama"

    def __init__(
        self,
        checkpoint_repo_id: str = "poong/PosterLlama",
        base_llm_repo_id: str = "codellama/CodeLlama-7b-hf",
        alternate_base_llm_repo_ids: Sequence[str] = ("meta-llama/Llama-2-7b-chat-hf",),
        vision_encoder_repo_id: str = "facebook/dinov2-base",
        vision_model_name: PosterLlamaVisionModelName = "dino_v2",
        lora_r: int = 64,
        lora_alpha: int = 16,
        lora_dropout: float = 0.05,
        lora_target_modules: Sequence[str] = ("q_proj", "v_proj"),
        prompt_template: str = "{}",
        image_placeholder: str = "<ImageHere>",
        image_end_token: str = "</Img>",
        max_txt_len: int = 400,
        max_context_len: int = 3800,
        default_max_new_tokens: int = 1024,
        default_do_sample: bool = True,
        default_temperature: float = 0.6,
        default_top_p: float = 0.9,
        default_top_k: int = 40,
        default_num_beams: int = 4,
        dataset_name: PosterLlamaDatasetName = "cgl",
        id2label: Mapping[int | str, str] | None = None,
        canvas_size: tuple[int, int] | list[int] | None = None,
        checkpoint_license_status: PosterLlamaLicenseStatus = "unverified",
        processor_subfolder: str = "processor",
        runtime_subfolder: str = "runtime",
        **kwargs: PosterLlamaConfigValue,
    ) -> None:
        """Initialize configuration values."""
        labels = (
            id2label_for_dataset(dataset_name)
            if id2label is None
            else {int(key): str(value) for key, value in id2label.items()}
        )
        kwargs.pop("model_type", None)
        kwargs.pop("id2label", None)
        kwargs.pop("label2id", None)
        super().__init__(
            id2label=labels,
            label2id={label: idx for idx, label in labels.items()},
        )
        self.checkpoint_repo_id = checkpoint_repo_id
        self.base_llm_repo_id = base_llm_repo_id
        self.alternate_base_llm_repo_ids = list(alternate_base_llm_repo_ids)
        self.vision_encoder_repo_id = vision_encoder_repo_id
        self.vision_model_name = vision_model_name

        self.lora_r = int(lora_r)
        self.lora_alpha = int(lora_alpha)
        self.lora_dropout = float(lora_dropout)
        self.lora_target_modules = list(lora_target_modules)

        self.prompt_template = prompt_template
        self.image_placeholder = image_placeholder
        self.image_end_token = image_end_token

        self.max_txt_len = int(max_txt_len)
        self.max_context_len = int(max_context_len)

        self.default_max_new_tokens = int(default_max_new_tokens)
        self.default_do_sample = bool(default_do_sample)
        self.default_temperature = float(default_temperature)
        self.default_top_p = float(default_top_p)
        self.default_top_k = int(default_top_k)
        self.default_num_beams = int(default_num_beams)

        self.dataset_name = dataset_name
        self.canvas_size = tuple(canvas_size) if canvas_size is not None else None
        self.checkpoint_license_status = checkpoint_license_status
        self.processor_subfolder = processor_subfolder
        self.runtime_subfolder = runtime_subfolder

        for key, value in kwargs.items():
            setattr(self, key, value)

__init__

__init__(
    checkpoint_repo_id: str = "poong/PosterLlama",
    base_llm_repo_id: str = "codellama/CodeLlama-7b-hf",
    alternate_base_llm_repo_ids: Sequence[str] = (
        "meta-llama/Llama-2-7b-chat-hf",
    ),
    vision_encoder_repo_id: str = "facebook/dinov2-base",
    vision_model_name: PosterLlamaVisionModelName = "dino_v2",
    lora_r: int = 64,
    lora_alpha: int = 16,
    lora_dropout: float = 0.05,
    lora_target_modules: Sequence[str] = (
        "q_proj",
        "v_proj",
    ),
    prompt_template: str = "{}",
    image_placeholder: str = "<ImageHere>",
    image_end_token: str = "</Img>",
    max_txt_len: int = 400,
    max_context_len: int = 3800,
    default_max_new_tokens: int = 1024,
    default_do_sample: bool = True,
    default_temperature: float = 0.6,
    default_top_p: float = 0.9,
    default_top_k: int = 40,
    default_num_beams: int = 4,
    dataset_name: PosterLlamaDatasetName = "cgl",
    id2label: Mapping[int | str, str] | None = None,
    canvas_size: tuple[int, int] | list[int] | None = None,
    checkpoint_license_status: PosterLlamaLicenseStatus = "unverified",
    processor_subfolder: str = "processor",
    runtime_subfolder: str = "runtime",
    **kwargs: PosterLlamaConfigValue,
) -> None

Initialize configuration values.

Source code in models/posterllama/src/posterllama/configuration_posterllama.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def __init__(
    self,
    checkpoint_repo_id: str = "poong/PosterLlama",
    base_llm_repo_id: str = "codellama/CodeLlama-7b-hf",
    alternate_base_llm_repo_ids: Sequence[str] = ("meta-llama/Llama-2-7b-chat-hf",),
    vision_encoder_repo_id: str = "facebook/dinov2-base",
    vision_model_name: PosterLlamaVisionModelName = "dino_v2",
    lora_r: int = 64,
    lora_alpha: int = 16,
    lora_dropout: float = 0.05,
    lora_target_modules: Sequence[str] = ("q_proj", "v_proj"),
    prompt_template: str = "{}",
    image_placeholder: str = "<ImageHere>",
    image_end_token: str = "</Img>",
    max_txt_len: int = 400,
    max_context_len: int = 3800,
    default_max_new_tokens: int = 1024,
    default_do_sample: bool = True,
    default_temperature: float = 0.6,
    default_top_p: float = 0.9,
    default_top_k: int = 40,
    default_num_beams: int = 4,
    dataset_name: PosterLlamaDatasetName = "cgl",
    id2label: Mapping[int | str, str] | None = None,
    canvas_size: tuple[int, int] | list[int] | None = None,
    checkpoint_license_status: PosterLlamaLicenseStatus = "unverified",
    processor_subfolder: str = "processor",
    runtime_subfolder: str = "runtime",
    **kwargs: PosterLlamaConfigValue,
) -> None:
    """Initialize configuration values."""
    labels = (
        id2label_for_dataset(dataset_name)
        if id2label is None
        else {int(key): str(value) for key, value in id2label.items()}
    )
    kwargs.pop("model_type", None)
    kwargs.pop("id2label", None)
    kwargs.pop("label2id", None)
    super().__init__(
        id2label=labels,
        label2id={label: idx for idx, label in labels.items()},
    )
    self.checkpoint_repo_id = checkpoint_repo_id
    self.base_llm_repo_id = base_llm_repo_id
    self.alternate_base_llm_repo_ids = list(alternate_base_llm_repo_ids)
    self.vision_encoder_repo_id = vision_encoder_repo_id
    self.vision_model_name = vision_model_name

    self.lora_r = int(lora_r)
    self.lora_alpha = int(lora_alpha)
    self.lora_dropout = float(lora_dropout)
    self.lora_target_modules = list(lora_target_modules)

    self.prompt_template = prompt_template
    self.image_placeholder = image_placeholder
    self.image_end_token = image_end_token

    self.max_txt_len = int(max_txt_len)
    self.max_context_len = int(max_context_len)

    self.default_max_new_tokens = int(default_max_new_tokens)
    self.default_do_sample = bool(default_do_sample)
    self.default_temperature = float(default_temperature)
    self.default_top_p = float(default_top_p)
    self.default_top_k = int(default_top_k)
    self.default_num_beams = int(default_num_beams)

    self.dataset_name = dataset_name
    self.canvas_size = tuple(canvas_size) if canvas_size is not None else None
    self.checkpoint_license_status = checkpoint_license_status
    self.processor_subfolder = processor_subfolder
    self.runtime_subfolder = runtime_subfolder

    for key, value in kwargs.items():
        setattr(self, key, value)

PosterLlamaImageProcessor

Bases: BaseImageProcessor

Prepare RGB images for PosterLlama smoke and recipe paths.

Parameters:

Name Type Description Default
image_size tuple[int, int] | None

Optional (height, width) resize target.

None
vision_encoder_repo_id str

Vision encoder id recorded with the processor.

'facebook/dinov2-base'

Examples:

>>> processor = PosterLlamaImageProcessor(image_size=(8, 8))
>>> out = processor.preprocess(torch.zeros(3, 8, 8))
>>> tuple(out["pixel_values"].shape)
(1, 3, 8, 8)
Source code in models/posterllama/src/posterllama/image_processing_posterllama.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class PosterLlamaImageProcessor(BaseImageProcessor):
    """Prepare RGB images for PosterLlama smoke and recipe paths.

    Args:
        image_size: Optional ``(height, width)`` resize target.
        vision_encoder_repo_id: Vision encoder id recorded with the processor.

    Examples:
        >>> processor = PosterLlamaImageProcessor(image_size=(8, 8))
        >>> out = processor.preprocess(torch.zeros(3, 8, 8))
        >>> tuple(out["pixel_values"].shape)
        (1, 3, 8, 8)
    """

    model_input_names = ["pixel_values"]

    def __init__(
        self,
        image_size: tuple[int, int] | None = None,
        vision_encoder_repo_id: str = "facebook/dinov2-base",
        **kwargs: PosterLlamaImageProcessorKwarg,
    ) -> None:
        """Initialize image processor metadata."""
        super().__init__(**kwargs)  # ty: ignore[invalid-argument-type]
        self.image_size = tuple(image_size) if image_size is not None else None
        self.vision_encoder_repo_id = vision_encoder_repo_id

    def preprocess(
        self,
        images: ImageInput | Sequence[ImageInput] | None,
        return_tensors: Literal["pt"] = "pt",
        **kwargs: PosterLlamaImageProcessorKwarg,
    ) -> BatchFeature:
        """Convert images to tensors.

        Args:
            images: PIL, NumPy, or torch image inputs. Omitted images create a
                zero placeholder for parser-only smoke calls.
            return_tensors: Tensor return format. Only ``pt`` is supported.
            kwargs: Reserved image-processing options.

        Returns:
            BatchFeature containing ``pixel_values``.

        Raises:
            ValueError: If ``return_tensors`` is not ``pt``.
        """
        _ = kwargs
        if return_tensors != "pt":
            raise ValueError("PosterLlamaImageProcessor supports return_tensors='pt'")

        items = (
            _as_image_list(images) if images is not None else [torch.zeros(3, 64, 64)]
        )
        pixel_values = torch.stack([_image_to_tensor(item) for item in items])
        if self.image_size is not None:
            pixel_values = torch.nn.functional.interpolate(
                pixel_values,
                size=self.image_size,
                mode="bilinear",
                align_corners=False,
            )
        return BatchFeature({"pixel_values": pixel_values}, tensor_type=return_tensors)

    def to_dict(self) -> dict[str, str | tuple[int, int] | None]:
        """Serialize image processor metadata."""
        data = cast(dict[str, str | tuple[int, int] | None], super().to_dict())
        data["image_size"] = self.image_size
        data["vision_encoder_repo_id"] = self.vision_encoder_repo_id
        return data

__init__

__init__(
    image_size: tuple[int, int] | None = None,
    vision_encoder_repo_id: str = "facebook/dinov2-base",
    **kwargs: PosterLlamaImageProcessorKwarg,
) -> None

Initialize image processor metadata.

Source code in models/posterllama/src/posterllama/image_processing_posterllama.py
83
84
85
86
87
88
89
90
91
92
def __init__(
    self,
    image_size: tuple[int, int] | None = None,
    vision_encoder_repo_id: str = "facebook/dinov2-base",
    **kwargs: PosterLlamaImageProcessorKwarg,
) -> None:
    """Initialize image processor metadata."""
    super().__init__(**kwargs)  # ty: ignore[invalid-argument-type]
    self.image_size = tuple(image_size) if image_size is not None else None
    self.vision_encoder_repo_id = vision_encoder_repo_id

preprocess

preprocess(
    images: ImageInput | Sequence[ImageInput] | None,
    return_tensors: Literal["pt"] = "pt",
    **kwargs: PosterLlamaImageProcessorKwarg,
) -> BatchFeature

Convert images to tensors.

Parameters:

Name Type Description Default
images ImageInput | Sequence[ImageInput] | None

PIL, NumPy, or torch image inputs. Omitted images create a zero placeholder for parser-only smoke calls.

required
return_tensors Literal['pt']

Tensor return format. Only pt is supported.

'pt'
kwargs PosterLlamaImageProcessorKwarg

Reserved image-processing options.

{}

Returns:

Type Description
BatchFeature

BatchFeature containing pixel_values.

Raises:

Type Description
ValueError

If return_tensors is not pt.

Source code in models/posterllama/src/posterllama/image_processing_posterllama.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def preprocess(
    self,
    images: ImageInput | Sequence[ImageInput] | None,
    return_tensors: Literal["pt"] = "pt",
    **kwargs: PosterLlamaImageProcessorKwarg,
) -> BatchFeature:
    """Convert images to tensors.

    Args:
        images: PIL, NumPy, or torch image inputs. Omitted images create a
            zero placeholder for parser-only smoke calls.
        return_tensors: Tensor return format. Only ``pt`` is supported.
        kwargs: Reserved image-processing options.

    Returns:
        BatchFeature containing ``pixel_values``.

    Raises:
        ValueError: If ``return_tensors`` is not ``pt``.
    """
    _ = kwargs
    if return_tensors != "pt":
        raise ValueError("PosterLlamaImageProcessor supports return_tensors='pt'")

    items = (
        _as_image_list(images) if images is not None else [torch.zeros(3, 64, 64)]
    )
    pixel_values = torch.stack([_image_to_tensor(item) for item in items])
    if self.image_size is not None:
        pixel_values = torch.nn.functional.interpolate(
            pixel_values,
            size=self.image_size,
            mode="bilinear",
            align_corners=False,
        )
    return BatchFeature({"pixel_values": pixel_values}, tensor_type=return_tensors)

to_dict

to_dict() -> dict[str, str | tuple[int, int] | None]

Serialize image processor metadata.

Source code in models/posterllama/src/posterllama/image_processing_posterllama.py
131
132
133
134
135
136
def to_dict(self) -> dict[str, str | tuple[int, int] | None]:
    """Serialize image processor metadata."""
    data = cast(dict[str, str | tuple[int, int] | None], super().to_dict())
    data["image_size"] = self.image_size
    data["vision_encoder_repo_id"] = self.vision_encoder_repo_id
    return data

PosterLlamaPipeline

Bases: LayoutGenerationPipeline

Compose a PosterLlama processor and converted runtime.

Parameters:

Name Type Description Default
config PosterLlamaConfig

Explicit pipeline configuration.

required
processor PosterLlamaProcessor

Explicit processor.

required
runtime PosterLlamaRuntime | None

Optional converted runtime. Parser-only saved artifacts may omit it.

None

Examples:

>>> cfg = PosterLlamaConfig(canvas_size=(100, 100))
>>> text = '<svg width="100" height="100"><rect data-category="text" x="0" y="0" width="10" height="10"/></svg>'
>>> pipe = PosterLlamaPipeline(
...     config=cfg,
...     processor=PosterLlamaProcessor.from_config(cfg),
...     runtime=PosterLlamaRuntime(text),
... )
>>> pipe(images=None).bbox.shape
torch.Size([1, 1, 4])
Source code in models/posterllama/src/posterllama/pipeline_posterllama.py
 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
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
class PosterLlamaPipeline(LayoutGenerationPipeline):
    """Compose a PosterLlama processor and converted runtime.

    Args:
        config: Explicit pipeline configuration.
        processor: Explicit processor.
        runtime: Optional converted runtime. Parser-only saved artifacts may omit it.

    Examples:
        >>> cfg = PosterLlamaConfig(canvas_size=(100, 100))
        >>> text = '<svg width="100" height="100"><rect data-category="text" x="0" y="0" width="10" height="10"/></svg>'
        >>> pipe = PosterLlamaPipeline(
        ...     config=cfg,
        ...     processor=PosterLlamaProcessor.from_config(cfg),
        ...     runtime=PosterLlamaRuntime(text),
        ... )
        >>> pipe(images=None).bbox.shape
        torch.Size([1, 1, 4])
    """

    config_class: ClassVar[type[PretrainedConfig]] = PosterLlamaConfig
    component_specs: ClassVar[dict[str, PipelineComponentSpec]] = {
        "processor": PipelineComponentSpec(
            attribute_name="processor",
            loader=_load_processor_component,
            config_subfolder_attribute="processor_subfolder",
            marker_file="processor_config.json",
            save_with_is_main_process=False,
        ),
        "runtime": PipelineComponentSpec(
            attribute_name="runtime",
            loader=_load_runtime_component,
            config_subfolder_attribute="runtime_subfolder",
            required=False,
            marker_file="runtime_config.json",
        ),
    }

    config: PosterLlamaConfig
    processor: PosterLlamaProcessor
    runtime: PosterLlamaRuntime | None

    def __init__(
        self,
        *,
        config: PosterLlamaConfig,
        processor: PosterLlamaProcessor,
        runtime: PosterLlamaRuntime | None = None,
    ) -> None:
        """Initialize pipeline components."""
        super().__init__(config)
        self.config = config
        self.processor = processor
        self.runtime = runtime

    @classmethod
    def _from_pretrained_components(  # ty: ignore[invalid-method-override]
        cls,
        *,
        config: PretrainedConfig,
        components: Mapping[str, PosterLlamaProcessor | PosterLlamaRuntime | None],
    ) -> "PosterLlamaPipeline":
        """Build a pipeline from loaded components."""
        return cls(
            config=cast(PosterLlamaConfig, config),
            processor=cast(PosterLlamaProcessor, components["processor"]),
            runtime=cast(PosterLlamaRuntime | None, components["runtime"]),
        )

    @torch.no_grad()
    def __call__(  # ty: ignore[invalid-method-override]
        self,
        *,
        images: ImageInput | Sequence[ImageInput] | None = None,
        prompt: str | Sequence[str] | None = None,
        content: Mapping[str, str | int | float | bool | None]
        | Sequence[Mapping[str, str | int | float | bool | None]]
        | None = None,
        texts: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
        batch_size: int = 1,
        seed: int | None = None,
        generator: torch.Generator | None = None,
        condition_type: ConditionType | str = ConditionType.content_image,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None = None,
        bbox: Float[torch.Tensor, "..."]
        | Sequence[Sequence[Sequence[float | int]]]
        | Sequence[Sequence[float | int]]
        | Sequence[float | int]
        | None = None,
        mask: Bool[torch.Tensor, "..."]
        | Sequence[Sequence[bool]]
        | Sequence[bool]
        | None = None,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
        box_format: BoxFormat | str = BoxFormat.xywh,
        normalized: bool = True,
        canvas_size: tuple[int, int] | None = None,
        num_inference_steps: int | None = None,
        output_type: Literal["dataclass", "dict"] = "dataclass",
        return_intermediates: bool = False,
        max_new_tokens: int | None = None,
        do_sample: bool | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        top_k: int | None = None,
        num_beams: int | None = None,
    ) -> (
        LayoutGenerationOutput
        | dict[
            str,
            Float[torch.Tensor, "..."]
            | Int[torch.Tensor, "..."]
            | Bool[torch.Tensor, "..."]
            | dict[int, str]
            | Mapping[str, str | bytes | int | float | bool | None]
            | list[str]
            | list[tuple[float, float, float, float]]
            | tuple[int, int]
            | str
            | bytes
            | int
            | float
            | bool
            | None,
        ]
    ):
        """Generate a poster layout.

        Args:
            images: Poster image inputs.
            prompt: Optional prompt prefix override.
            content: Optional content metadata.
            texts: Optional poster text strings.
            batch_size: Batch size when images are omitted.
            seed: Convenience seed used only when ``generator`` is absent.
            generator: Explicit PyTorch generator; takes precedence over ``seed``.
            condition_type: Canonical condition or PosterLlama release alias.
            labels: Optional label constraints.
            bbox: Optional box constraints.
            mask: Optional valid-element mask.
            num_elements: Optional requested element count.
            box_format: Input box format.
            normalized: Whether boxes are normalized.
            canvas_size: Canvas size as ``(width, height)``.
            num_inference_steps: Reserved shared argument.
            output_type: ``dataclass`` or ``dict``.
            return_intermediates: Whether to include prompt and parse diagnostics.
            max_new_tokens: Generation token budget.
            do_sample: Sampling flag.
            temperature: Sampling temperature.
            top_p: Nucleus sampling value.
            top_k: Top-k sampling value.
            num_beams: Beam count.

        Returns:
            LayoutGenerationOutput or dictionary.

        Raises:
            RuntimeError: If converted runtime assets are absent.
        """
        _ = num_inference_steps
        batch = self.processor(
            images=images,
            prompt=prompt,
            content=content,
            texts=texts,
            batch_size=batch_size,
            condition_type=condition_type,
            labels=labels,
            bbox=bbox,
            mask=mask,
            num_elements=num_elements,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas_size,
        )
        if self.runtime is None:
            raise RuntimeError(
                "PosterLlama runtime assets are missing. A processor-only artifact "
                "can build prompts and parse outputs, but generation requires a "
                "converted local runtime."
            )

        active_generator = self.prepare_generator(generator=generator, seed=seed)
        generation_args = {
            "max_new_tokens": max_new_tokens or self.config.default_max_new_tokens,
            "do_sample": self.config.default_do_sample
            if do_sample is None
            else do_sample,
            "temperature": self.config.default_temperature
            if temperature is None
            else temperature,
            "top_p": self.config.default_top_p if top_p is None else top_p,
            "top_k": self.config.default_top_k if top_k is None else top_k,
            "num_beams": self.config.default_num_beams
            if num_beams is None
            else num_beams,
        }
        generated = self.runtime.generate_texts(
            cast(list[str], batch["prompts"]),
            pixel_values=cast(torch.Tensor, batch["pixel_values"]),
            generator=active_generator,
            **generation_args,
        )
        output = self.processor.parse_output(
            generated[0],
            canvas_size=canvas_size,
            output_type="dataclass",
            return_intermediates=return_intermediates,
        )
        result = cast(LayoutGenerationOutput, output)
        if return_intermediates:
            existing = cast(
                dict[
                    str,
                    str
                    | bytes
                    | int
                    | float
                    | bool
                    | None
                    | Mapping[str, str | int | float | bool | None],
                ],
                result.intermediates or {},
            )
            existing["prompt_bytes"] = cast(list[str], batch["prompts"])[0].encode()
            existing["raw_generated_text"] = generated[0]
            existing["condition_type"] = str(batch["condition_type"])
            existing["generation_args"] = generation_args
            result.intermediates = existing
        if output_type == "dict":
            return dict(result)
        if output_type != "dataclass":
            raise ValueError(f"Unsupported output_type: {output_type}")

        return result

__init__

__init__(
    *,
    config: PosterLlamaConfig,
    processor: PosterLlamaProcessor,
    runtime: PosterLlamaRuntime | None = None,
) -> None

Initialize pipeline components.

Source code in models/posterllama/src/posterllama/pipeline_posterllama.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def __init__(
    self,
    *,
    config: PosterLlamaConfig,
    processor: PosterLlamaProcessor,
    runtime: PosterLlamaRuntime | None = None,
) -> None:
    """Initialize pipeline components."""
    super().__init__(config)
    self.config = config
    self.processor = processor
    self.runtime = runtime

__call__

__call__(
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    prompt: str | Sequence[str] | None = None,
    content: Mapping[str, str | int | float | bool | None]
    | Sequence[
        Mapping[str, str | int | float | bool | None]
    ]
    | None = None,
    texts: str
    | Sequence[str]
    | Sequence[Sequence[str]]
    | None = None,
    batch_size: int = 1,
    seed: int | None = None,
    generator: Generator | None = None,
    condition_type: ConditionType
    | str = ConditionType.content_image,
    labels: Int[Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[Tensor, "..."]
    | Sequence[Sequence[Sequence[float | int]]]
    | Sequence[Sequence[float | int]]
    | Sequence[float | int]
    | None = None,
    mask: Bool[Tensor, "..."]
    | Sequence[Sequence[bool]]
    | Sequence[bool]
    | None = None,
    num_elements: int
    | Sequence[int]
    | Int[Tensor, "batch"]
    | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    num_inference_steps: int | None = None,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    return_intermediates: bool = False,
    max_new_tokens: int | None = None,
    do_sample: bool | None = None,
    temperature: float | None = None,
    top_p: float | None = None,
    top_k: int | None = None,
    num_beams: int | None = None,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Float[torch.Tensor, "..."]
        | Int[torch.Tensor, "..."]
        | Bool[torch.Tensor, "..."]
        | dict[int, str]
        | Mapping[
            str, str | bytes | int | float | bool | None
        ]
        | list[str]
        | list[tuple[float, float, float, float]]
        | tuple[int, int]
        | str
        | bytes
        | int
        | float
        | bool
        | None,
    ]
)

Generate a poster layout.

Parameters:

Name Type Description Default
images ImageInput | Sequence[ImageInput] | None

Poster image inputs.

None
prompt str | Sequence[str] | None

Optional prompt prefix override.

None
content Mapping[str, str | int | float | bool | None] | Sequence[Mapping[str, str | int | float | bool | None]] | None

Optional content metadata.

None
texts str | Sequence[str] | Sequence[Sequence[str]] | None

Optional poster text strings.

None
batch_size int

Batch size when images are omitted.

1
seed int | None

Convenience seed used only when generator is absent.

None
generator Generator | None

Explicit PyTorch generator; takes precedence over seed.

None
condition_type ConditionType | str

Canonical condition or PosterLlama release alias.

content_image
labels Int[Tensor, '...'] | Sequence[Sequence[int | str]] | Sequence[int | str] | None

Optional label constraints.

None
bbox Float[Tensor, '...'] | Sequence[Sequence[Sequence[float | int]]] | Sequence[Sequence[float | int]] | Sequence[float | int] | None

Optional box constraints.

None
mask Bool[Tensor, '...'] | Sequence[Sequence[bool]] | Sequence[bool] | None

Optional valid-element mask.

None
num_elements int | Sequence[int] | Int[Tensor, 'batch'] | None

Optional requested element count.

None
box_format BoxFormat | str

Input box format.

xywh
normalized bool

Whether boxes are normalized.

True
canvas_size tuple[int, int] | None

Canvas size as (width, height).

None
num_inference_steps int | None

Reserved shared argument.

None
output_type Literal['dataclass', 'dict']

dataclass or dict.

'dataclass'
return_intermediates bool

Whether to include prompt and parse diagnostics.

False
max_new_tokens int | None

Generation token budget.

None
do_sample bool | None

Sampling flag.

None
temperature float | None

Sampling temperature.

None
top_p float | None

Nucleus sampling value.

None
top_k int | None

Top-k sampling value.

None
num_beams int | None

Beam count.

None

Returns:

Type Description
LayoutGenerationOutput | dict[str, Float[Tensor, '...'] | Int[Tensor, '...'] | Bool[Tensor, '...'] | dict[int, str] | Mapping[str, str | bytes | int | float | bool | None] | list[str] | list[tuple[float, float, float, float]] | tuple[int, int] | str | bytes | int | float | bool | None]

LayoutGenerationOutput or dictionary.

Raises:

Type Description
RuntimeError

If converted runtime assets are absent.

Source code in models/posterllama/src/posterllama/pipeline_posterllama.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
@torch.no_grad()
def __call__(  # ty: ignore[invalid-method-override]
    self,
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    prompt: str | Sequence[str] | None = None,
    content: Mapping[str, str | int | float | bool | None]
    | Sequence[Mapping[str, str | int | float | bool | None]]
    | None = None,
    texts: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
    batch_size: int = 1,
    seed: int | None = None,
    generator: torch.Generator | None = None,
    condition_type: ConditionType | str = ConditionType.content_image,
    labels: Int[torch.Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[torch.Tensor, "..."]
    | Sequence[Sequence[Sequence[float | int]]]
    | Sequence[Sequence[float | int]]
    | Sequence[float | int]
    | None = None,
    mask: Bool[torch.Tensor, "..."]
    | Sequence[Sequence[bool]]
    | Sequence[bool]
    | None = None,
    num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    num_inference_steps: int | None = None,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    return_intermediates: bool = False,
    max_new_tokens: int | None = None,
    do_sample: bool | None = None,
    temperature: float | None = None,
    top_p: float | None = None,
    top_k: int | None = None,
    num_beams: int | None = None,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Float[torch.Tensor, "..."]
        | Int[torch.Tensor, "..."]
        | Bool[torch.Tensor, "..."]
        | dict[int, str]
        | Mapping[str, str | bytes | int | float | bool | None]
        | list[str]
        | list[tuple[float, float, float, float]]
        | tuple[int, int]
        | str
        | bytes
        | int
        | float
        | bool
        | None,
    ]
):
    """Generate a poster layout.

    Args:
        images: Poster image inputs.
        prompt: Optional prompt prefix override.
        content: Optional content metadata.
        texts: Optional poster text strings.
        batch_size: Batch size when images are omitted.
        seed: Convenience seed used only when ``generator`` is absent.
        generator: Explicit PyTorch generator; takes precedence over ``seed``.
        condition_type: Canonical condition or PosterLlama release alias.
        labels: Optional label constraints.
        bbox: Optional box constraints.
        mask: Optional valid-element mask.
        num_elements: Optional requested element count.
        box_format: Input box format.
        normalized: Whether boxes are normalized.
        canvas_size: Canvas size as ``(width, height)``.
        num_inference_steps: Reserved shared argument.
        output_type: ``dataclass`` or ``dict``.
        return_intermediates: Whether to include prompt and parse diagnostics.
        max_new_tokens: Generation token budget.
        do_sample: Sampling flag.
        temperature: Sampling temperature.
        top_p: Nucleus sampling value.
        top_k: Top-k sampling value.
        num_beams: Beam count.

    Returns:
        LayoutGenerationOutput or dictionary.

    Raises:
        RuntimeError: If converted runtime assets are absent.
    """
    _ = num_inference_steps
    batch = self.processor(
        images=images,
        prompt=prompt,
        content=content,
        texts=texts,
        batch_size=batch_size,
        condition_type=condition_type,
        labels=labels,
        bbox=bbox,
        mask=mask,
        num_elements=num_elements,
        box_format=box_format,
        normalized=normalized,
        canvas_size=canvas_size,
    )
    if self.runtime is None:
        raise RuntimeError(
            "PosterLlama runtime assets are missing. A processor-only artifact "
            "can build prompts and parse outputs, but generation requires a "
            "converted local runtime."
        )

    active_generator = self.prepare_generator(generator=generator, seed=seed)
    generation_args = {
        "max_new_tokens": max_new_tokens or self.config.default_max_new_tokens,
        "do_sample": self.config.default_do_sample
        if do_sample is None
        else do_sample,
        "temperature": self.config.default_temperature
        if temperature is None
        else temperature,
        "top_p": self.config.default_top_p if top_p is None else top_p,
        "top_k": self.config.default_top_k if top_k is None else top_k,
        "num_beams": self.config.default_num_beams
        if num_beams is None
        else num_beams,
    }
    generated = self.runtime.generate_texts(
        cast(list[str], batch["prompts"]),
        pixel_values=cast(torch.Tensor, batch["pixel_values"]),
        generator=active_generator,
        **generation_args,
    )
    output = self.processor.parse_output(
        generated[0],
        canvas_size=canvas_size,
        output_type="dataclass",
        return_intermediates=return_intermediates,
    )
    result = cast(LayoutGenerationOutput, output)
    if return_intermediates:
        existing = cast(
            dict[
                str,
                str
                | bytes
                | int
                | float
                | bool
                | None
                | Mapping[str, str | int | float | bool | None],
            ],
            result.intermediates or {},
        )
        existing["prompt_bytes"] = cast(list[str], batch["prompts"])[0].encode()
        existing["raw_generated_text"] = generated[0]
        existing["condition_type"] = str(batch["condition_type"])
        existing["generation_args"] = generation_args
        result.intermediates = existing
    if output_type == "dict":
        return dict(result)
    if output_type != "dataclass":
        raise ValueError(f"Unsupported output_type: {output_type}")

    return result

PosterLlamaProcessor

Bases: ProcessorMixin

Build PosterLlama prompts and decode generated HTML/SVG layouts.

Parameters:

Name Type Description Default
image_processor PosterLlamaImageProcessor

Image processor metadata wrapper.

required
config PosterLlamaConfig

Explicit PosterLlama configuration.

required

Examples:

>>> processor = PosterLlamaProcessor.from_config(PosterLlamaConfig())
>>> "Generate poster layout" in processor.build_prompt(condition_type="unconditional")
True
Source code in models/posterllama/src/posterllama/processing_posterllama.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
class PosterLlamaProcessor(ProcessorMixin):
    """Build PosterLlama prompts and decode generated HTML/SVG layouts.

    Args:
        image_processor: Image processor metadata wrapper.
        config: Explicit PosterLlama configuration.

    Examples:
        >>> processor = PosterLlamaProcessor.from_config(PosterLlamaConfig())
        >>> "Generate poster layout" in processor.build_prompt(condition_type="unconditional")
        True
    """

    attributes = ["image_processor"]
    image_processor_class = "PosterLlamaImageProcessor"

    def __init__(
        self,
        image_processor: PosterLlamaImageProcessor,
        config: PosterLlamaConfig,
    ) -> None:
        """Initialize processor components."""
        self.image_processor = image_processor
        self.config = config
        super().__init__(image_processor)

    @classmethod
    def from_config(cls, config: PosterLlamaConfig) -> "PosterLlamaProcessor":
        """Create a processor from an explicit config.

        Args:
            config: Processor configuration.

        Returns:
            PosterLlamaProcessor instance.

        Examples:
            >>> PosterLlamaProcessor.from_config(PosterLlamaConfig()).config.model_type
            'posterllama'
        """
        return cls(
            image_processor=PosterLlamaImageProcessor(
                vision_encoder_repo_id=config.vision_encoder_repo_id,
            ),
            config=config,
        )

    def save_pretrained(
        self,
        save_directory: str | PathLike[str],
        push_to_hub: bool = False,
        **kwargs: str | int | float | bool | None,
    ) -> None:
        """Save processor metadata.

        Args:
            save_directory: Directory to write.
            push_to_hub: Accepted for ProcessorMixin compatibility; ignored.
            kwargs: Accepted for ProcessorMixin compatibility; ignored.
        """
        _ = (push_to_hub, kwargs)
        root = Path(save_directory)
        root.mkdir(parents=True, exist_ok=True)
        self.config.save_pretrained(root)
        self.image_processor.save_pretrained(root)
        (root / "processor_config.json").write_text(
            json.dumps(
                {
                    "processor_class": self.__class__.__name__,
                    "image_processor_class": self.image_processor.__class__.__name__,
                },
                indent=2,
                sort_keys=True,
            ),
            encoding="utf-8",
        )

    @classmethod
    def from_pretrained(
        cls,
        pretrained_model_name_or_path: str | PathLike[str],
        cache_dir: str | PathLike[str] | None = None,
        force_download: bool = False,
        local_files_only: bool = False,
        token: str | bool | None = None,
        revision: str = "main",
        *,
        subfolder: str | None = None,
        **kwargs: PosterLlamaImageProcessorKwarg,
    ) -> "PosterLlamaProcessor":
        """Load processor metadata.

        Args:
            pretrained_model_name_or_path: Checkpoint root or processor folder.
            cache_dir: Accepted for ProcessorMixin compatibility.
            force_download: Accepted for ProcessorMixin compatibility.
            local_files_only: Whether to avoid network access.
            token: Accepted for ProcessorMixin compatibility.
            revision: Accepted for ProcessorMixin compatibility.
            subfolder: Optional processor subfolder.
            kwargs: Accepted for ProcessorMixin compatibility.

        Returns:
            Loaded PosterLlamaProcessor.
        """
        _ = (cache_dir, force_download, token, revision, kwargs)
        root = Path(pretrained_model_name_or_path)
        if subfolder is not None:
            root = root / subfolder
        config = PosterLlamaConfig.from_pretrained(
            root, local_files_only=local_files_only
        )
        return cls(
            image_processor=PosterLlamaImageProcessor.from_pretrained(root),
            config=config,
        )

    def normalize_condition_type(
        self,
        condition_type: ConditionType | str,
    ) -> ConditionType:
        """Normalize PosterLlama condition aliases.

        Args:
            condition_type: Canonical condition or PosterLlama release alias.

        Returns:
            Supported canonical condition.

        Raises:
            NotImplementedError: If the condition is known but unsupported.
            ValueError: If the condition is unknown.
        """
        if isinstance(condition_type, str):
            alias = condition_type.lower().replace("-", "_")
            if alias in REQUEST_CONDITION_ALIASES:
                return REQUEST_CONDITION_ALIASES[alias]
        condition = normalize_condition_type(condition_type)
        if condition in UNSUPPORTED_CONDITIONS:
            raise NotImplementedError(f"PosterLlama does not support {condition}")

        if condition not in SUPPORTED_CONDITIONS:
            raise NotImplementedError(f"PosterLlama does not support {condition}")

        return condition

    def __call__(
        self,
        *,
        images: ImageInput | Sequence[ImageInput] | None = None,
        prompt: str | Sequence[str] | None = None,
        content: Mapping[str, str | int | float | bool | None]
        | Sequence[Mapping[str, str | int | float | bool | None]]
        | None = None,
        texts: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
        batch_size: int = 1,
        condition_type: ConditionType | str = ConditionType.content_image,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None = None,
        bbox: Float[torch.Tensor, "..."]
        | Sequence[Sequence[Sequence[float | int]]]
        | Sequence[Sequence[float | int]]
        | Sequence[float | int]
        | None = None,
        mask: Bool[torch.Tensor, "..."]
        | Sequence[Sequence[bool]]
        | Sequence[bool]
        | None = None,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
        box_format: BoxFormat | str = BoxFormat.xywh,
        normalized: bool = True,
        canvas_size: tuple[int, int] | None = None,
        return_tensors: Literal["pt"] = "pt",
    ) -> BatchEncoding:
        """Encode public inputs into recipe prompt and image tensors.

        Args:
            images: Poster image inputs.
            prompt: Optional user-provided prompt text.
            content: Optional content metadata.
            texts: Optional poster text strings.
            batch_size: Batch size when no images are supplied.
            condition_type: Canonical condition or PosterLlama release alias.
            labels: Optional element label constraints.
            bbox: Optional element boxes.
            mask: Optional valid-element mask.
            num_elements: Optional requested element count.
            box_format: Input box format.
            normalized: Whether boxes are normalized.
            canvas_size: Canvas size for pixel boxes and prompt rendering.
            return_tensors: Tensor return format. Only ``pt`` is supported.

        Returns:
            BatchEncoding containing prompt strings and tensors.
        """
        condition = self.normalize_condition_type(condition_type)
        canvas = self._resolve_canvas_size(canvas_size)
        prompt_text = self.build_prompt(
            condition_type=condition,
            prompt=prompt,
            content=content,
            texts=texts,
            labels=labels,
            bbox=bbox,
            mask=mask,
            num_elements=num_elements,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas,
        )
        image_batch = self.image_processor(images, return_tensors=return_tensors)
        return BatchEncoding(
            {
                "pixel_values": image_batch["pixel_values"],
                "prompts": prompt_text
                if isinstance(prompt_text, list)
                else [prompt_text] * batch_size,
                "condition_type": condition,
                "canvas_size": canvas,
            }
        )

    def build_prompt(
        self,
        *,
        condition_type: ConditionType | str = ConditionType.content_image,
        prompt: str | Sequence[str] | None = None,
        content: Mapping[str, str | int | float | bool | None]
        | Sequence[Mapping[str, str | int | float | bool | None]]
        | None = None,
        texts: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None = None,
        bbox: Float[torch.Tensor, "..."]
        | Sequence[Sequence[Sequence[float | int]]]
        | Sequence[Sequence[float | int]]
        | Sequence[float | int]
        | None = None,
        mask: Bool[torch.Tensor, "..."]
        | Sequence[Sequence[bool]]
        | Sequence[bool]
        | None = None,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
        box_format: BoxFormat | str = BoxFormat.xywh,
        normalized: bool = True,
        canvas_size: tuple[int, int] | None = None,
    ) -> str | list[str]:
        """Build a deterministic PosterLlama HTML prompt.

        Args:
            condition_type: Canonical condition or PosterLlama release alias.
            prompt: Optional prompt prefix override.
            content: Optional content metadata included in diagnostics text.
            texts: Optional poster text strings.
            labels: Optional label constraints.
            bbox: Optional box constraints.
            mask: Optional valid-element mask.
            num_elements: Requested element count for unconstrained slots.
            box_format: Input box format.
            normalized: Whether boxes are normalized.
            canvas_size: Canvas size as ``(width, height)``.

        Returns:
            Prompt string or list of prompt strings.
        """
        _ = content
        condition = self.normalize_condition_type(condition_type)
        canvas = self._resolve_canvas_size(canvas_size)
        base_prompt = self._first_prompt(prompt)
        text_line = self._texts_line(texts)
        known_markup = self._constraint_markup(
            condition=condition,
            labels=labels,
            bbox=bbox,
            mask=mask,
            num_elements=num_elements,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas,
        )
        bbox_html = HTML_TEMPLATE.format(
            width=canvas[0],
            height=canvas[1],
            content=known_markup,
        )
        source_key = self._source_condition_key(condition)
        task_instruction = SOURCE_TASK_INSTRUCTIONS[self.config.dataset_name]
        if text_line:
            instruction = SOURCE_TEXT_INSTRUCTIONS[source_key].format(
                text=text_line,
                bbox_html=bbox_html,
            )
        else:
            instruction = SOURCE_INSTRUCTIONS[source_key].format(bbox_html=bbox_html)
        body = f"{base_prompt}{task_instruction}{instruction} <MID>"
        return self.config.prompt_template.format(body)

    def parse_output(
        self,
        text: str,
        *,
        canvas_size: tuple[int, int] | None = None,
        output_type: Literal["dataclass", "dict"] = "dataclass",
        return_intermediates: bool = False,
        strict: bool = False,
    ) -> (
        LayoutGenerationOutput
        | dict[
            str,
            Float[torch.Tensor, "..."]
            | Int[torch.Tensor, "..."]
            | Bool[torch.Tensor, "..."]
            | dict[int, str]
            | list[str]
            | list[tuple[float, float, float, float]]
            | tuple[int, int]
            | str
            | int
            | float
            | bool
            | None,
        ]
    ):
        """Parse generated HTML/SVG into public layout output.

        Args:
            text: Generated markup.
            canvas_size: Canvas size override.
            output_type: Return dataclass or dictionary.
            return_intermediates: Whether to include parse diagnostics.
            strict: Whether malformed rectangles raise.

        Returns:
            LayoutGenerationOutput or dictionary.
        """
        parsed = parse_rectangles(text, self._label2id(), strict=strict)
        canvas = canvas_size or parsed.canvas_size or self.config.canvas_size
        if canvas is None:
            raise ValueError(
                "canvas_size is required when generated SVG lacks width/height"
            )

        resolved_canvas = (int(canvas[0]), int(canvas[1]))
        output = rect_ltwh_to_output(
            parsed,
            canvas_size=resolved_canvas,
            id2label=cast(dict[int, str], self.config.id2label),
            return_intermediates=return_intermediates,
        )
        if output_type == "dict":
            return dict(output)
        if output_type != "dataclass":
            raise ValueError(f"Unsupported output_type: {output_type}")

        return output

    def _resolve_canvas_size(
        self,
        canvas_size: tuple[int, int] | None,
    ) -> tuple[int, int]:
        canvas = canvas_size or self.config.canvas_size
        if canvas is None:
            return (360, 504)
        return int(canvas[0]), int(canvas[1])

    def _first_prompt(self, prompt: str | Sequence[str] | None) -> str:
        if prompt is None:
            return ""
        if isinstance(prompt, str):
            return prompt
        return next(iter(prompt), "")

    def _texts_line(
        self,
        texts: str | Sequence[str] | Sequence[Sequence[str]] | None,
    ) -> str:
        if texts is None:
            return ""
        if isinstance(texts, str):
            values = [texts]
        else:
            first = next(iter(texts), "")
            if isinstance(first, str):
                values = cast(list[str], list(texts))
            else:
                values = [str(value) for value in first]
        return " | ".join(values)

    def _constraint_markup(
        self,
        *,
        condition: ConditionType,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None,
        bbox: Float[torch.Tensor, "..."]
        | Sequence[Sequence[Sequence[float | int]]]
        | Sequence[Sequence[float | int]]
        | Sequence[float | int]
        | None,
        mask: Bool[torch.Tensor, "..."]
        | Sequence[Sequence[bool]]
        | Sequence[bool]
        | None,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None,
        box_format: BoxFormat | str,
        normalized: bool,
        canvas_size: tuple[int, int],
    ) -> str:
        if labels is None:
            if condition in {ConditionType.content_image, ConditionType.unconditional}:
                return ""
            count = self._num_elements(num_elements)
            return " ".join(self._fill_rect(index) for index in range(count))
        label_tensor = self._labels_to_tensor(labels)
        bbox_tensor = self._bbox_to_tensor(
            bbox,
            labels=label_tensor,
            mask=mask,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas_size,
        )
        rects: list[str] = []
        fill_index = 1
        for index, (label, box) in enumerate(
            zip(label_tensor[0].tolist(), bbox_tensor[0].tolist(), strict=True)
        ):
            rect, fill_index = self._rect_for_condition(
                condition=condition,
                label=int(label),
                bbox_ltwh=(
                    float(box[0]),
                    float(box[1]),
                    float(box[2]),
                    float(box[3]),
                ),
                fill_index=fill_index,
            )
            if rect:
                rects.append(rect)
        return " ".join(rects)

    def _labels_to_tensor(
        self,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str],
    ) -> Int[torch.Tensor, "batch elements"]:
        if isinstance(labels, torch.Tensor):
            tensor = labels.long()
            return tensor.unsqueeze(0) if tensor.ndim == 1 else tensor
        rows = cast(Sequence[int | str | Sequence[int | str]], labels)
        if rows and isinstance(rows[0], Sequence) and not isinstance(rows[0], str):
            row = cast(Sequence[int | str], rows[0])
        else:
            row = cast(Sequence[int | str], rows)
        label2id = self._label2id()
        values = [
            label2id[self._normalize_input_label(item)]
            if isinstance(item, str)
            else int(item)
            for item in row
        ]
        return torch.tensor([values], dtype=torch.long)

    def _bbox_to_tensor(
        self,
        bbox: Float[torch.Tensor, "..."]
        | Sequence[Sequence[Sequence[float | int]]]
        | Sequence[Sequence[float | int]]
        | Sequence[float | int]
        | None,
        *,
        labels: Int[torch.Tensor, "batch elements"],
        mask: Bool[torch.Tensor, "..."]
        | Sequence[Sequence[bool]]
        | Sequence[bool]
        | None,
        box_format: BoxFormat | str,
        normalized: bool,
        canvas_size: tuple[int, int],
    ) -> Float[torch.Tensor, "batch elements 4"]:
        if bbox is None:
            return torch.zeros((labels.size(0), labels.size(1), 4), dtype=torch.float32)
        bbox_t, _, _ = prepare_layout_tensors(
            bbox=bbox,
            labels=labels,
            mask=mask,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas_size,
        )
        if bbox_t.ndim == 2:
            bbox_t = bbox_t.unsqueeze(0)
        return denormalize_boxes(bbox_t, canvas_size=canvas_size, box_format="ltwh")

    def _rect_for_condition(
        self,
        *,
        condition: ConditionType,
        label: int,
        bbox_ltwh: tuple[float, float, float, float],
        fill_index: int,
    ) -> tuple[str, int]:
        label_name = str(cast(dict[int, str], self.config.id2label)[label])
        x, y, width, height = bbox_ltwh

        if condition is ConditionType.label:
            x, y, width, height = self._fill_values(fill_index, 4)
            fill_index += 4

        elif condition is ConditionType.label_size:
            x, y = self._fill_values(fill_index, 2)
            fill_index += 2

        elif condition is ConditionType.completion:
            x, y, width, height = self._fill_values(fill_index, 4)
            fill_index += 4

        elif condition is ConditionType.refinement:
            width, height = self._fill_values(fill_index, 2)
            fill_index += 2

        elif condition in {ConditionType.content_image, ConditionType.unconditional}:
            return "", fill_index

        x, y, width, height = (
            _format_source_number(value) for value in (x, y, width, height)
        )
        return (
            RECT_TEMPLATE.format(
                label=label_name,
                x=x,
                y=y,
                width=width,
                height=height,
            ),
            fill_index,
        )

    def _fill_rect(self, index: int) -> str:
        label, x, y, width, height = self._fill_values(index + 1, 5)
        return RECT_TEMPLATE.format(label=label, x=x, y=y, width=width, height=height)

    def _fill_values(self, start: int, count: int) -> tuple[str, ...]:
        return tuple(
            FILL_TEMPLATE.format(index) for index in range(start, start + count)
        )

    def _source_condition_key(self, condition: ConditionType) -> str:
        if condition is ConditionType.label:
            return "cond_cate_to_size_pos"
        if condition is ConditionType.label_size:
            return "cond_cate_size_to_pos"
        if condition is ConditionType.completion:
            return "cond_random_mask"
        if condition is ConditionType.refinement:
            return "cond_cate_pos_to_size"
        return "unconditional"

    def _num_elements(
        self,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None,
    ) -> int:
        if num_elements is None:
            return 1
        if isinstance(num_elements, torch.Tensor):
            return int(num_elements.flatten()[0].item())
        if isinstance(num_elements, Sequence) and not isinstance(num_elements, str):
            return int(cast(int, num_elements[0]))
        return int(cast(int, num_elements))

    def _label2id(self) -> dict[str, int]:
        return {
            self._normalize_input_label(label): int(index)
            for index, label in cast(dict[int, str], self.config.id2label).items()
        }

    def _normalize_input_label(self, label: int | str) -> str:
        return str(label).strip().lower().replace("_", " ")

__init__

__init__(
    image_processor: PosterLlamaImageProcessor,
    config: PosterLlamaConfig,
) -> None

Initialize processor components.

Source code in models/posterllama/src/posterllama/processing_posterllama.py
108
109
110
111
112
113
114
115
116
def __init__(
    self,
    image_processor: PosterLlamaImageProcessor,
    config: PosterLlamaConfig,
) -> None:
    """Initialize processor components."""
    self.image_processor = image_processor
    self.config = config
    super().__init__(image_processor)

from_config classmethod

from_config(
    config: PosterLlamaConfig,
) -> "PosterLlamaProcessor"

Create a processor from an explicit config.

Parameters:

Name Type Description Default
config PosterLlamaConfig

Processor configuration.

required

Returns:

Type Description
'PosterLlamaProcessor'

PosterLlamaProcessor instance.

Examples:

>>> PosterLlamaProcessor.from_config(PosterLlamaConfig()).config.model_type
'posterllama'
Source code in models/posterllama/src/posterllama/processing_posterllama.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@classmethod
def from_config(cls, config: PosterLlamaConfig) -> "PosterLlamaProcessor":
    """Create a processor from an explicit config.

    Args:
        config: Processor configuration.

    Returns:
        PosterLlamaProcessor instance.

    Examples:
        >>> PosterLlamaProcessor.from_config(PosterLlamaConfig()).config.model_type
        'posterllama'
    """
    return cls(
        image_processor=PosterLlamaImageProcessor(
            vision_encoder_repo_id=config.vision_encoder_repo_id,
        ),
        config=config,
    )

save_pretrained

save_pretrained(
    save_directory: str | PathLike[str],
    push_to_hub: bool = False,
    **kwargs: str | int | float | bool | None,
) -> None

Save processor metadata.

Parameters:

Name Type Description Default
save_directory str | PathLike[str]

Directory to write.

required
push_to_hub bool

Accepted for ProcessorMixin compatibility; ignored.

False
kwargs str | int | float | bool | None

Accepted for ProcessorMixin compatibility; ignored.

{}
Source code in models/posterllama/src/posterllama/processing_posterllama.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def save_pretrained(
    self,
    save_directory: str | PathLike[str],
    push_to_hub: bool = False,
    **kwargs: str | int | float | bool | None,
) -> None:
    """Save processor metadata.

    Args:
        save_directory: Directory to write.
        push_to_hub: Accepted for ProcessorMixin compatibility; ignored.
        kwargs: Accepted for ProcessorMixin compatibility; ignored.
    """
    _ = (push_to_hub, kwargs)
    root = Path(save_directory)
    root.mkdir(parents=True, exist_ok=True)
    self.config.save_pretrained(root)
    self.image_processor.save_pretrained(root)
    (root / "processor_config.json").write_text(
        json.dumps(
            {
                "processor_class": self.__class__.__name__,
                "image_processor_class": self.image_processor.__class__.__name__,
            },
            indent=2,
            sort_keys=True,
        ),
        encoding="utf-8",
    )

from_pretrained classmethod

from_pretrained(
    pretrained_model_name_or_path: str | PathLike[str],
    cache_dir: str | PathLike[str] | None = None,
    force_download: bool = False,
    local_files_only: bool = False,
    token: str | bool | None = None,
    revision: str = "main",
    *,
    subfolder: str | None = None,
    **kwargs: PosterLlamaImageProcessorKwarg,
) -> "PosterLlamaProcessor"

Load processor metadata.

Parameters:

Name Type Description Default
pretrained_model_name_or_path str | PathLike[str]

Checkpoint root or processor folder.

required
cache_dir str | PathLike[str] | None

Accepted for ProcessorMixin compatibility.

None
force_download bool

Accepted for ProcessorMixin compatibility.

False
local_files_only bool

Whether to avoid network access.

False
token str | bool | None

Accepted for ProcessorMixin compatibility.

None
revision str

Accepted for ProcessorMixin compatibility.

'main'
subfolder str | None

Optional processor subfolder.

None
kwargs PosterLlamaImageProcessorKwarg

Accepted for ProcessorMixin compatibility.

{}

Returns:

Type Description
'PosterLlamaProcessor'

Loaded PosterLlamaProcessor.

Source code in models/posterllama/src/posterllama/processing_posterllama.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
@classmethod
def from_pretrained(
    cls,
    pretrained_model_name_or_path: str | PathLike[str],
    cache_dir: str | PathLike[str] | None = None,
    force_download: bool = False,
    local_files_only: bool = False,
    token: str | bool | None = None,
    revision: str = "main",
    *,
    subfolder: str | None = None,
    **kwargs: PosterLlamaImageProcessorKwarg,
) -> "PosterLlamaProcessor":
    """Load processor metadata.

    Args:
        pretrained_model_name_or_path: Checkpoint root or processor folder.
        cache_dir: Accepted for ProcessorMixin compatibility.
        force_download: Accepted for ProcessorMixin compatibility.
        local_files_only: Whether to avoid network access.
        token: Accepted for ProcessorMixin compatibility.
        revision: Accepted for ProcessorMixin compatibility.
        subfolder: Optional processor subfolder.
        kwargs: Accepted for ProcessorMixin compatibility.

    Returns:
        Loaded PosterLlamaProcessor.
    """
    _ = (cache_dir, force_download, token, revision, kwargs)
    root = Path(pretrained_model_name_or_path)
    if subfolder is not None:
        root = root / subfolder
    config = PosterLlamaConfig.from_pretrained(
        root, local_files_only=local_files_only
    )
    return cls(
        image_processor=PosterLlamaImageProcessor.from_pretrained(root),
        config=config,
    )

normalize_condition_type

normalize_condition_type(
    condition_type: ConditionType | str,
) -> ConditionType

Normalize PosterLlama condition aliases.

Parameters:

Name Type Description Default
condition_type ConditionType | str

Canonical condition or PosterLlama release alias.

required

Returns:

Type Description
ConditionType

Supported canonical condition.

Raises:

Type Description
NotImplementedError

If the condition is known but unsupported.

ValueError

If the condition is unknown.

Source code in models/posterllama/src/posterllama/processing_posterllama.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def normalize_condition_type(
    self,
    condition_type: ConditionType | str,
) -> ConditionType:
    """Normalize PosterLlama condition aliases.

    Args:
        condition_type: Canonical condition or PosterLlama release alias.

    Returns:
        Supported canonical condition.

    Raises:
        NotImplementedError: If the condition is known but unsupported.
        ValueError: If the condition is unknown.
    """
    if isinstance(condition_type, str):
        alias = condition_type.lower().replace("-", "_")
        if alias in REQUEST_CONDITION_ALIASES:
            return REQUEST_CONDITION_ALIASES[alias]
    condition = normalize_condition_type(condition_type)
    if condition in UNSUPPORTED_CONDITIONS:
        raise NotImplementedError(f"PosterLlama does not support {condition}")

    if condition not in SUPPORTED_CONDITIONS:
        raise NotImplementedError(f"PosterLlama does not support {condition}")

    return condition

__call__

__call__(
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    prompt: str | Sequence[str] | None = None,
    content: Mapping[str, str | int | float | bool | None]
    | Sequence[
        Mapping[str, str | int | float | bool | None]
    ]
    | None = None,
    texts: str
    | Sequence[str]
    | Sequence[Sequence[str]]
    | None = None,
    batch_size: int = 1,
    condition_type: ConditionType
    | str = ConditionType.content_image,
    labels: Int[Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[Tensor, "..."]
    | Sequence[Sequence[Sequence[float | int]]]
    | Sequence[Sequence[float | int]]
    | Sequence[float | int]
    | None = None,
    mask: Bool[Tensor, "..."]
    | Sequence[Sequence[bool]]
    | Sequence[bool]
    | None = None,
    num_elements: int
    | Sequence[int]
    | Int[Tensor, "batch"]
    | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    return_tensors: Literal["pt"] = "pt",
) -> BatchEncoding

Encode public inputs into recipe prompt and image tensors.

Parameters:

Name Type Description Default
images ImageInput | Sequence[ImageInput] | None

Poster image inputs.

None
prompt str | Sequence[str] | None

Optional user-provided prompt text.

None
content Mapping[str, str | int | float | bool | None] | Sequence[Mapping[str, str | int | float | bool | None]] | None

Optional content metadata.

None
texts str | Sequence[str] | Sequence[Sequence[str]] | None

Optional poster text strings.

None
batch_size int

Batch size when no images are supplied.

1
condition_type ConditionType | str

Canonical condition or PosterLlama release alias.

content_image
labels Int[Tensor, '...'] | Sequence[Sequence[int | str]] | Sequence[int | str] | None

Optional element label constraints.

None
bbox Float[Tensor, '...'] | Sequence[Sequence[Sequence[float | int]]] | Sequence[Sequence[float | int]] | Sequence[float | int] | None

Optional element boxes.

None
mask Bool[Tensor, '...'] | Sequence[Sequence[bool]] | Sequence[bool] | None

Optional valid-element mask.

None
num_elements int | Sequence[int] | Int[Tensor, 'batch'] | None

Optional requested element count.

None
box_format BoxFormat | str

Input box format.

xywh
normalized bool

Whether boxes are normalized.

True
canvas_size tuple[int, int] | None

Canvas size for pixel boxes and prompt rendering.

None
return_tensors Literal['pt']

Tensor return format. Only pt is supported.

'pt'

Returns:

Type Description
BatchEncoding

BatchEncoding containing prompt strings and tensors.

Source code in models/posterllama/src/posterllama/processing_posterllama.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def __call__(
    self,
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    prompt: str | Sequence[str] | None = None,
    content: Mapping[str, str | int | float | bool | None]
    | Sequence[Mapping[str, str | int | float | bool | None]]
    | None = None,
    texts: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
    batch_size: int = 1,
    condition_type: ConditionType | str = ConditionType.content_image,
    labels: Int[torch.Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[torch.Tensor, "..."]
    | Sequence[Sequence[Sequence[float | int]]]
    | Sequence[Sequence[float | int]]
    | Sequence[float | int]
    | None = None,
    mask: Bool[torch.Tensor, "..."]
    | Sequence[Sequence[bool]]
    | Sequence[bool]
    | None = None,
    num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    return_tensors: Literal["pt"] = "pt",
) -> BatchEncoding:
    """Encode public inputs into recipe prompt and image tensors.

    Args:
        images: Poster image inputs.
        prompt: Optional user-provided prompt text.
        content: Optional content metadata.
        texts: Optional poster text strings.
        batch_size: Batch size when no images are supplied.
        condition_type: Canonical condition or PosterLlama release alias.
        labels: Optional element label constraints.
        bbox: Optional element boxes.
        mask: Optional valid-element mask.
        num_elements: Optional requested element count.
        box_format: Input box format.
        normalized: Whether boxes are normalized.
        canvas_size: Canvas size for pixel boxes and prompt rendering.
        return_tensors: Tensor return format. Only ``pt`` is supported.

    Returns:
        BatchEncoding containing prompt strings and tensors.
    """
    condition = self.normalize_condition_type(condition_type)
    canvas = self._resolve_canvas_size(canvas_size)
    prompt_text = self.build_prompt(
        condition_type=condition,
        prompt=prompt,
        content=content,
        texts=texts,
        labels=labels,
        bbox=bbox,
        mask=mask,
        num_elements=num_elements,
        box_format=box_format,
        normalized=normalized,
        canvas_size=canvas,
    )
    image_batch = self.image_processor(images, return_tensors=return_tensors)
    return BatchEncoding(
        {
            "pixel_values": image_batch["pixel_values"],
            "prompts": prompt_text
            if isinstance(prompt_text, list)
            else [prompt_text] * batch_size,
            "condition_type": condition,
            "canvas_size": canvas,
        }
    )

build_prompt

build_prompt(
    *,
    condition_type: ConditionType
    | str = ConditionType.content_image,
    prompt: str | Sequence[str] | None = None,
    content: Mapping[str, str | int | float | bool | None]
    | Sequence[
        Mapping[str, str | int | float | bool | None]
    ]
    | None = None,
    texts: str
    | Sequence[str]
    | Sequence[Sequence[str]]
    | None = None,
    labels: Int[Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[Tensor, "..."]
    | Sequence[Sequence[Sequence[float | int]]]
    | Sequence[Sequence[float | int]]
    | Sequence[float | int]
    | None = None,
    mask: Bool[Tensor, "..."]
    | Sequence[Sequence[bool]]
    | Sequence[bool]
    | None = None,
    num_elements: int
    | Sequence[int]
    | Int[Tensor, "batch"]
    | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
) -> str | list[str]

Build a deterministic PosterLlama HTML prompt.

Parameters:

Name Type Description Default
condition_type ConditionType | str

Canonical condition or PosterLlama release alias.

content_image
prompt str | Sequence[str] | None

Optional prompt prefix override.

None
content Mapping[str, str | int | float | bool | None] | Sequence[Mapping[str, str | int | float | bool | None]] | None

Optional content metadata included in diagnostics text.

None
texts str | Sequence[str] | Sequence[Sequence[str]] | None

Optional poster text strings.

None
labels Int[Tensor, '...'] | Sequence[Sequence[int | str]] | Sequence[int | str] | None

Optional label constraints.

None
bbox Float[Tensor, '...'] | Sequence[Sequence[Sequence[float | int]]] | Sequence[Sequence[float | int]] | Sequence[float | int] | None

Optional box constraints.

None
mask Bool[Tensor, '...'] | Sequence[Sequence[bool]] | Sequence[bool] | None

Optional valid-element mask.

None
num_elements int | Sequence[int] | Int[Tensor, 'batch'] | None

Requested element count for unconstrained slots.

None
box_format BoxFormat | str

Input box format.

xywh
normalized bool

Whether boxes are normalized.

True
canvas_size tuple[int, int] | None

Canvas size as (width, height).

None

Returns:

Type Description
str | list[str]

Prompt string or list of prompt strings.

Source code in models/posterllama/src/posterllama/processing_posterllama.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def build_prompt(
    self,
    *,
    condition_type: ConditionType | str = ConditionType.content_image,
    prompt: str | Sequence[str] | None = None,
    content: Mapping[str, str | int | float | bool | None]
    | Sequence[Mapping[str, str | int | float | bool | None]]
    | None = None,
    texts: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
    labels: Int[torch.Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[torch.Tensor, "..."]
    | Sequence[Sequence[Sequence[float | int]]]
    | Sequence[Sequence[float | int]]
    | Sequence[float | int]
    | None = None,
    mask: Bool[torch.Tensor, "..."]
    | Sequence[Sequence[bool]]
    | Sequence[bool]
    | None = None,
    num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
) -> str | list[str]:
    """Build a deterministic PosterLlama HTML prompt.

    Args:
        condition_type: Canonical condition or PosterLlama release alias.
        prompt: Optional prompt prefix override.
        content: Optional content metadata included in diagnostics text.
        texts: Optional poster text strings.
        labels: Optional label constraints.
        bbox: Optional box constraints.
        mask: Optional valid-element mask.
        num_elements: Requested element count for unconstrained slots.
        box_format: Input box format.
        normalized: Whether boxes are normalized.
        canvas_size: Canvas size as ``(width, height)``.

    Returns:
        Prompt string or list of prompt strings.
    """
    _ = content
    condition = self.normalize_condition_type(condition_type)
    canvas = self._resolve_canvas_size(canvas_size)
    base_prompt = self._first_prompt(prompt)
    text_line = self._texts_line(texts)
    known_markup = self._constraint_markup(
        condition=condition,
        labels=labels,
        bbox=bbox,
        mask=mask,
        num_elements=num_elements,
        box_format=box_format,
        normalized=normalized,
        canvas_size=canvas,
    )
    bbox_html = HTML_TEMPLATE.format(
        width=canvas[0],
        height=canvas[1],
        content=known_markup,
    )
    source_key = self._source_condition_key(condition)
    task_instruction = SOURCE_TASK_INSTRUCTIONS[self.config.dataset_name]
    if text_line:
        instruction = SOURCE_TEXT_INSTRUCTIONS[source_key].format(
            text=text_line,
            bbox_html=bbox_html,
        )
    else:
        instruction = SOURCE_INSTRUCTIONS[source_key].format(bbox_html=bbox_html)
    body = f"{base_prompt}{task_instruction}{instruction} <MID>"
    return self.config.prompt_template.format(body)

parse_output

parse_output(
    text: str,
    *,
    canvas_size: tuple[int, int] | None = None,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    return_intermediates: bool = False,
    strict: bool = False,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Float[torch.Tensor, "..."]
        | Int[torch.Tensor, "..."]
        | Bool[torch.Tensor, "..."]
        | dict[int, str]
        | list[str]
        | list[tuple[float, float, float, float]]
        | tuple[int, int]
        | str
        | int
        | float
        | bool
        | None,
    ]
)

Parse generated HTML/SVG into public layout output.

Parameters:

Name Type Description Default
text str

Generated markup.

required
canvas_size tuple[int, int] | None

Canvas size override.

None
output_type Literal['dataclass', 'dict']

Return dataclass or dictionary.

'dataclass'
return_intermediates bool

Whether to include parse diagnostics.

False
strict bool

Whether malformed rectangles raise.

False

Returns:

Type Description
LayoutGenerationOutput | dict[str, Float[Tensor, '...'] | Int[Tensor, '...'] | Bool[Tensor, '...'] | dict[int, str] | list[str] | list[tuple[float, float, float, float]] | tuple[int, int] | str | int | float | bool | None]

LayoutGenerationOutput or dictionary.

Source code in models/posterllama/src/posterllama/processing_posterllama.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def parse_output(
    self,
    text: str,
    *,
    canvas_size: tuple[int, int] | None = None,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    return_intermediates: bool = False,
    strict: bool = False,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Float[torch.Tensor, "..."]
        | Int[torch.Tensor, "..."]
        | Bool[torch.Tensor, "..."]
        | dict[int, str]
        | list[str]
        | list[tuple[float, float, float, float]]
        | tuple[int, int]
        | str
        | int
        | float
        | bool
        | None,
    ]
):
    """Parse generated HTML/SVG into public layout output.

    Args:
        text: Generated markup.
        canvas_size: Canvas size override.
        output_type: Return dataclass or dictionary.
        return_intermediates: Whether to include parse diagnostics.
        strict: Whether malformed rectangles raise.

    Returns:
        LayoutGenerationOutput or dictionary.
    """
    parsed = parse_rectangles(text, self._label2id(), strict=strict)
    canvas = canvas_size or parsed.canvas_size or self.config.canvas_size
    if canvas is None:
        raise ValueError(
            "canvas_size is required when generated SVG lacks width/height"
        )

    resolved_canvas = (int(canvas[0]), int(canvas[1]))
    output = rect_ltwh_to_output(
        parsed,
        canvas_size=resolved_canvas,
        id2label=cast(dict[int, str], self.config.id2label),
        return_intermediates=return_intermediates,
    )
    if output_type == "dict":
        return dict(output)
    if output_type != "dataclass":
        raise ValueError(f"Unsupported output_type: {output_type}")

    return output

configuration_posterllama

Configuration for PosterLlama inference recipes.

PosterLlamaConfig

Bases: PretrainedConfig

Configuration for local PosterLlama recipe artifacts.

Parameters:

Name Type Description Default
checkpoint_repo_id str

Source Hub repository containing the raw checkpoint.

'poong/PosterLlama'
base_llm_repo_id str

Preferred CodeLLaMA/LLaMA backbone repository id.

'codellama/CodeLlama-7b-hf'
alternate_base_llm_repo_ids Sequence[str]

Alternate backbone ids recorded for audit.

('meta-llama/Llama-2-7b-chat-hf',)
vision_encoder_repo_id str

Vision encoder repository id.

'facebook/dinov2-base'
vision_model_name PosterLlamaVisionModelName

Original vision tower selector.

'dino_v2'
lora_r int

LoRA rank used by the released recipe.

64
lora_alpha int

LoRA alpha used by the released recipe.

16
lora_dropout float

LoRA dropout used by the released recipe.

0.05
lora_target_modules Sequence[str]

LLM projection module names targeted by LoRA.

('q_proj', 'v_proj')
prompt_template str

Wrapper applied around generated layout prompts.

'{}'
image_placeholder str

Placeholder token used for image feature insertion.

'<ImageHere>'
image_end_token str

End marker for image features.

'</Img>'
max_txt_len int

Original maximum text length.

400
max_context_len int

Original context length budget.

3800
default_max_new_tokens int

Default generation budget.

1024
default_do_sample bool

Default sampled-generation flag.

True
default_temperature float

Default generation temperature.

0.6
default_top_p float

Default nucleus sampling value.

0.9
default_top_k int

Default top-k sampling value.

40
default_num_beams int

Default beam count.

4
dataset_name PosterLlamaDatasetName

Poster dataset key.

'cgl'
id2label Mapping[int | str, str] | None

Dataset-local label vocabulary.

None
canvas_size tuple[int, int] | list[int] | None

Optional default canvas size as (width, height).

None
checkpoint_license_status PosterLlamaLicenseStatus

Redistribution status for converted weights.

'unverified'
processor_subfolder str

Pipeline processor subfolder.

'processor'
runtime_subfolder str

Optional converted runtime subfolder.

'runtime'
kwargs PosterLlamaConfigValue

Extra PretrainedConfig keyword arguments.

{}

Examples:

>>> cfg = PosterLlamaConfig(canvas_size=(360, 504))
>>> cfg.id2label[1]
'text'
Source code in models/posterllama/src/posterllama/configuration_posterllama.py
 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
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
class PosterLlamaConfig(PretrainedConfig):
    """Configuration for local PosterLlama recipe artifacts.

    Args:
        checkpoint_repo_id: Source Hub repository containing the raw checkpoint.
        base_llm_repo_id: Preferred CodeLLaMA/LLaMA backbone repository id.
        alternate_base_llm_repo_ids: Alternate backbone ids recorded for audit.
        vision_encoder_repo_id: Vision encoder repository id.
        vision_model_name: Original vision tower selector.
        lora_r: LoRA rank used by the released recipe.
        lora_alpha: LoRA alpha used by the released recipe.
        lora_dropout: LoRA dropout used by the released recipe.
        lora_target_modules: LLM projection module names targeted by LoRA.
        prompt_template: Wrapper applied around generated layout prompts.
        image_placeholder: Placeholder token used for image feature insertion.
        image_end_token: End marker for image features.
        max_txt_len: Original maximum text length.
        max_context_len: Original context length budget.
        default_max_new_tokens: Default generation budget.
        default_do_sample: Default sampled-generation flag.
        default_temperature: Default generation temperature.
        default_top_p: Default nucleus sampling value.
        default_top_k: Default top-k sampling value.
        default_num_beams: Default beam count.
        dataset_name: Poster dataset key.
        id2label: Dataset-local label vocabulary.
        canvas_size: Optional default canvas size as ``(width, height)``.
        checkpoint_license_status: Redistribution status for converted weights.
        processor_subfolder: Pipeline processor subfolder.
        runtime_subfolder: Optional converted runtime subfolder.
        kwargs: Extra ``PretrainedConfig`` keyword arguments.

    Examples:
        >>> cfg = PosterLlamaConfig(canvas_size=(360, 504))
        >>> cfg.id2label[1]
        'text'
    """

    model_type = "posterllama"

    def __init__(
        self,
        checkpoint_repo_id: str = "poong/PosterLlama",
        base_llm_repo_id: str = "codellama/CodeLlama-7b-hf",
        alternate_base_llm_repo_ids: Sequence[str] = ("meta-llama/Llama-2-7b-chat-hf",),
        vision_encoder_repo_id: str = "facebook/dinov2-base",
        vision_model_name: PosterLlamaVisionModelName = "dino_v2",
        lora_r: int = 64,
        lora_alpha: int = 16,
        lora_dropout: float = 0.05,
        lora_target_modules: Sequence[str] = ("q_proj", "v_proj"),
        prompt_template: str = "{}",
        image_placeholder: str = "<ImageHere>",
        image_end_token: str = "</Img>",
        max_txt_len: int = 400,
        max_context_len: int = 3800,
        default_max_new_tokens: int = 1024,
        default_do_sample: bool = True,
        default_temperature: float = 0.6,
        default_top_p: float = 0.9,
        default_top_k: int = 40,
        default_num_beams: int = 4,
        dataset_name: PosterLlamaDatasetName = "cgl",
        id2label: Mapping[int | str, str] | None = None,
        canvas_size: tuple[int, int] | list[int] | None = None,
        checkpoint_license_status: PosterLlamaLicenseStatus = "unverified",
        processor_subfolder: str = "processor",
        runtime_subfolder: str = "runtime",
        **kwargs: PosterLlamaConfigValue,
    ) -> None:
        """Initialize configuration values."""
        labels = (
            id2label_for_dataset(dataset_name)
            if id2label is None
            else {int(key): str(value) for key, value in id2label.items()}
        )
        kwargs.pop("model_type", None)
        kwargs.pop("id2label", None)
        kwargs.pop("label2id", None)
        super().__init__(
            id2label=labels,
            label2id={label: idx for idx, label in labels.items()},
        )
        self.checkpoint_repo_id = checkpoint_repo_id
        self.base_llm_repo_id = base_llm_repo_id
        self.alternate_base_llm_repo_ids = list(alternate_base_llm_repo_ids)
        self.vision_encoder_repo_id = vision_encoder_repo_id
        self.vision_model_name = vision_model_name

        self.lora_r = int(lora_r)
        self.lora_alpha = int(lora_alpha)
        self.lora_dropout = float(lora_dropout)
        self.lora_target_modules = list(lora_target_modules)

        self.prompt_template = prompt_template
        self.image_placeholder = image_placeholder
        self.image_end_token = image_end_token

        self.max_txt_len = int(max_txt_len)
        self.max_context_len = int(max_context_len)

        self.default_max_new_tokens = int(default_max_new_tokens)
        self.default_do_sample = bool(default_do_sample)
        self.default_temperature = float(default_temperature)
        self.default_top_p = float(default_top_p)
        self.default_top_k = int(default_top_k)
        self.default_num_beams = int(default_num_beams)

        self.dataset_name = dataset_name
        self.canvas_size = tuple(canvas_size) if canvas_size is not None else None
        self.checkpoint_license_status = checkpoint_license_status
        self.processor_subfolder = processor_subfolder
        self.runtime_subfolder = runtime_subfolder

        for key, value in kwargs.items():
            setattr(self, key, value)

__init__

__init__(
    checkpoint_repo_id: str = "poong/PosterLlama",
    base_llm_repo_id: str = "codellama/CodeLlama-7b-hf",
    alternate_base_llm_repo_ids: Sequence[str] = (
        "meta-llama/Llama-2-7b-chat-hf",
    ),
    vision_encoder_repo_id: str = "facebook/dinov2-base",
    vision_model_name: PosterLlamaVisionModelName = "dino_v2",
    lora_r: int = 64,
    lora_alpha: int = 16,
    lora_dropout: float = 0.05,
    lora_target_modules: Sequence[str] = (
        "q_proj",
        "v_proj",
    ),
    prompt_template: str = "{}",
    image_placeholder: str = "<ImageHere>",
    image_end_token: str = "</Img>",
    max_txt_len: int = 400,
    max_context_len: int = 3800,
    default_max_new_tokens: int = 1024,
    default_do_sample: bool = True,
    default_temperature: float = 0.6,
    default_top_p: float = 0.9,
    default_top_k: int = 40,
    default_num_beams: int = 4,
    dataset_name: PosterLlamaDatasetName = "cgl",
    id2label: Mapping[int | str, str] | None = None,
    canvas_size: tuple[int, int] | list[int] | None = None,
    checkpoint_license_status: PosterLlamaLicenseStatus = "unverified",
    processor_subfolder: str = "processor",
    runtime_subfolder: str = "runtime",
    **kwargs: PosterLlamaConfigValue,
) -> None

Initialize configuration values.

Source code in models/posterllama/src/posterllama/configuration_posterllama.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def __init__(
    self,
    checkpoint_repo_id: str = "poong/PosterLlama",
    base_llm_repo_id: str = "codellama/CodeLlama-7b-hf",
    alternate_base_llm_repo_ids: Sequence[str] = ("meta-llama/Llama-2-7b-chat-hf",),
    vision_encoder_repo_id: str = "facebook/dinov2-base",
    vision_model_name: PosterLlamaVisionModelName = "dino_v2",
    lora_r: int = 64,
    lora_alpha: int = 16,
    lora_dropout: float = 0.05,
    lora_target_modules: Sequence[str] = ("q_proj", "v_proj"),
    prompt_template: str = "{}",
    image_placeholder: str = "<ImageHere>",
    image_end_token: str = "</Img>",
    max_txt_len: int = 400,
    max_context_len: int = 3800,
    default_max_new_tokens: int = 1024,
    default_do_sample: bool = True,
    default_temperature: float = 0.6,
    default_top_p: float = 0.9,
    default_top_k: int = 40,
    default_num_beams: int = 4,
    dataset_name: PosterLlamaDatasetName = "cgl",
    id2label: Mapping[int | str, str] | None = None,
    canvas_size: tuple[int, int] | list[int] | None = None,
    checkpoint_license_status: PosterLlamaLicenseStatus = "unverified",
    processor_subfolder: str = "processor",
    runtime_subfolder: str = "runtime",
    **kwargs: PosterLlamaConfigValue,
) -> None:
    """Initialize configuration values."""
    labels = (
        id2label_for_dataset(dataset_name)
        if id2label is None
        else {int(key): str(value) for key, value in id2label.items()}
    )
    kwargs.pop("model_type", None)
    kwargs.pop("id2label", None)
    kwargs.pop("label2id", None)
    super().__init__(
        id2label=labels,
        label2id={label: idx for idx, label in labels.items()},
    )
    self.checkpoint_repo_id = checkpoint_repo_id
    self.base_llm_repo_id = base_llm_repo_id
    self.alternate_base_llm_repo_ids = list(alternate_base_llm_repo_ids)
    self.vision_encoder_repo_id = vision_encoder_repo_id
    self.vision_model_name = vision_model_name

    self.lora_r = int(lora_r)
    self.lora_alpha = int(lora_alpha)
    self.lora_dropout = float(lora_dropout)
    self.lora_target_modules = list(lora_target_modules)

    self.prompt_template = prompt_template
    self.image_placeholder = image_placeholder
    self.image_end_token = image_end_token

    self.max_txt_len = int(max_txt_len)
    self.max_context_len = int(max_context_len)

    self.default_max_new_tokens = int(default_max_new_tokens)
    self.default_do_sample = bool(default_do_sample)
    self.default_temperature = float(default_temperature)
    self.default_top_p = float(default_top_p)
    self.default_top_k = int(default_top_k)
    self.default_num_beams = int(default_num_beams)

    self.dataset_name = dataset_name
    self.canvas_size = tuple(canvas_size) if canvas_size is not None else None
    self.checkpoint_license_status = checkpoint_license_status
    self.processor_subfolder = processor_subfolder
    self.runtime_subfolder = runtime_subfolder

    for key, value in kwargs.items():
        setattr(self, key, value)

image_processing_posterllama

Image processor metadata wrapper for PosterLlama recipes.

PosterLlamaImageProcessor

Bases: BaseImageProcessor

Prepare RGB images for PosterLlama smoke and recipe paths.

Parameters:

Name Type Description Default
image_size tuple[int, int] | None

Optional (height, width) resize target.

None
vision_encoder_repo_id str

Vision encoder id recorded with the processor.

'facebook/dinov2-base'

Examples:

>>> processor = PosterLlamaImageProcessor(image_size=(8, 8))
>>> out = processor.preprocess(torch.zeros(3, 8, 8))
>>> tuple(out["pixel_values"].shape)
(1, 3, 8, 8)
Source code in models/posterllama/src/posterllama/image_processing_posterllama.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class PosterLlamaImageProcessor(BaseImageProcessor):
    """Prepare RGB images for PosterLlama smoke and recipe paths.

    Args:
        image_size: Optional ``(height, width)`` resize target.
        vision_encoder_repo_id: Vision encoder id recorded with the processor.

    Examples:
        >>> processor = PosterLlamaImageProcessor(image_size=(8, 8))
        >>> out = processor.preprocess(torch.zeros(3, 8, 8))
        >>> tuple(out["pixel_values"].shape)
        (1, 3, 8, 8)
    """

    model_input_names = ["pixel_values"]

    def __init__(
        self,
        image_size: tuple[int, int] | None = None,
        vision_encoder_repo_id: str = "facebook/dinov2-base",
        **kwargs: PosterLlamaImageProcessorKwarg,
    ) -> None:
        """Initialize image processor metadata."""
        super().__init__(**kwargs)  # ty: ignore[invalid-argument-type]
        self.image_size = tuple(image_size) if image_size is not None else None
        self.vision_encoder_repo_id = vision_encoder_repo_id

    def preprocess(
        self,
        images: ImageInput | Sequence[ImageInput] | None,
        return_tensors: Literal["pt"] = "pt",
        **kwargs: PosterLlamaImageProcessorKwarg,
    ) -> BatchFeature:
        """Convert images to tensors.

        Args:
            images: PIL, NumPy, or torch image inputs. Omitted images create a
                zero placeholder for parser-only smoke calls.
            return_tensors: Tensor return format. Only ``pt`` is supported.
            kwargs: Reserved image-processing options.

        Returns:
            BatchFeature containing ``pixel_values``.

        Raises:
            ValueError: If ``return_tensors`` is not ``pt``.
        """
        _ = kwargs
        if return_tensors != "pt":
            raise ValueError("PosterLlamaImageProcessor supports return_tensors='pt'")

        items = (
            _as_image_list(images) if images is not None else [torch.zeros(3, 64, 64)]
        )
        pixel_values = torch.stack([_image_to_tensor(item) for item in items])
        if self.image_size is not None:
            pixel_values = torch.nn.functional.interpolate(
                pixel_values,
                size=self.image_size,
                mode="bilinear",
                align_corners=False,
            )
        return BatchFeature({"pixel_values": pixel_values}, tensor_type=return_tensors)

    def to_dict(self) -> dict[str, str | tuple[int, int] | None]:
        """Serialize image processor metadata."""
        data = cast(dict[str, str | tuple[int, int] | None], super().to_dict())
        data["image_size"] = self.image_size
        data["vision_encoder_repo_id"] = self.vision_encoder_repo_id
        return data

__init__

__init__(
    image_size: tuple[int, int] | None = None,
    vision_encoder_repo_id: str = "facebook/dinov2-base",
    **kwargs: PosterLlamaImageProcessorKwarg,
) -> None

Initialize image processor metadata.

Source code in models/posterllama/src/posterllama/image_processing_posterllama.py
83
84
85
86
87
88
89
90
91
92
def __init__(
    self,
    image_size: tuple[int, int] | None = None,
    vision_encoder_repo_id: str = "facebook/dinov2-base",
    **kwargs: PosterLlamaImageProcessorKwarg,
) -> None:
    """Initialize image processor metadata."""
    super().__init__(**kwargs)  # ty: ignore[invalid-argument-type]
    self.image_size = tuple(image_size) if image_size is not None else None
    self.vision_encoder_repo_id = vision_encoder_repo_id

preprocess

preprocess(
    images: ImageInput | Sequence[ImageInput] | None,
    return_tensors: Literal["pt"] = "pt",
    **kwargs: PosterLlamaImageProcessorKwarg,
) -> BatchFeature

Convert images to tensors.

Parameters:

Name Type Description Default
images ImageInput | Sequence[ImageInput] | None

PIL, NumPy, or torch image inputs. Omitted images create a zero placeholder for parser-only smoke calls.

required
return_tensors Literal['pt']

Tensor return format. Only pt is supported.

'pt'
kwargs PosterLlamaImageProcessorKwarg

Reserved image-processing options.

{}

Returns:

Type Description
BatchFeature

BatchFeature containing pixel_values.

Raises:

Type Description
ValueError

If return_tensors is not pt.

Source code in models/posterllama/src/posterllama/image_processing_posterllama.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def preprocess(
    self,
    images: ImageInput | Sequence[ImageInput] | None,
    return_tensors: Literal["pt"] = "pt",
    **kwargs: PosterLlamaImageProcessorKwarg,
) -> BatchFeature:
    """Convert images to tensors.

    Args:
        images: PIL, NumPy, or torch image inputs. Omitted images create a
            zero placeholder for parser-only smoke calls.
        return_tensors: Tensor return format. Only ``pt`` is supported.
        kwargs: Reserved image-processing options.

    Returns:
        BatchFeature containing ``pixel_values``.

    Raises:
        ValueError: If ``return_tensors`` is not ``pt``.
    """
    _ = kwargs
    if return_tensors != "pt":
        raise ValueError("PosterLlamaImageProcessor supports return_tensors='pt'")

    items = (
        _as_image_list(images) if images is not None else [torch.zeros(3, 64, 64)]
    )
    pixel_values = torch.stack([_image_to_tensor(item) for item in items])
    if self.image_size is not None:
        pixel_values = torch.nn.functional.interpolate(
            pixel_values,
            size=self.image_size,
            mode="bilinear",
            align_corners=False,
        )
    return BatchFeature({"pixel_values": pixel_values}, tensor_type=return_tensors)

to_dict

to_dict() -> dict[str, str | tuple[int, int] | None]

Serialize image processor metadata.

Source code in models/posterllama/src/posterllama/image_processing_posterllama.py
131
132
133
134
135
136
def to_dict(self) -> dict[str, str | tuple[int, int] | None]:
    """Serialize image processor metadata."""
    data = cast(dict[str, str | tuple[int, int] | None], super().to_dict())
    data["image_size"] = self.image_size
    data["vision_encoder_repo_id"] = self.vision_encoder_repo_id
    return data

model_card

Model-card metadata for PosterLlama recipe artifacts.

model_card_metadata

model_card_metadata(
    config: PosterLlamaConfig, *, hub_id: str
) -> dict[str, str | list[str]]

Return model-card metadata for a PosterLlama recipe artifact.

Source code in models/posterllama/src/posterllama/model_card.py
 8
 9
10
11
12
13
14
15
16
17
18
19
def model_card_metadata(
    config: PosterLlamaConfig, *, hub_id: str
) -> dict[str, str | list[str]]:
    """Return model-card metadata for a PosterLlama recipe artifact."""
    _ = config
    return {
        "hub_id": hub_id,
        "library_name": "transformers",
        "pipeline_tag": "image-text-to-text",
        "tags": ["layout-generation", "poster-generation", "posterllama"],
        "datasets": ["creative-graphic-design/CGL"],
    }

modeling_posterllama

Runtime adapter interfaces for converted PosterLlama components.

PosterLlamaRuntime

Bases: Module

Minimal runtime interface used by PosterLlamaPipeline.

The full MiniGPT/DINO/CodeLLaMA stack is created by local conversion tools. This lightweight adapter keeps the public package importable in ordinary CI and gives tests a serializable runtime shape.

Parameters:

Name Type Description Default
generated_text str | None

Optional deterministic text emitted by this runtime.

None

Examples:

>>> runtime = PosterLlamaRuntime('<svg width="1" height="1"></svg>')
>>> runtime.generate_texts(["prompt"])
['<svg width="1" height="1"></svg>']
Source code in models/posterllama/src/posterllama/modeling_posterllama.py
 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
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
class PosterLlamaRuntime(torch.nn.Module):
    """Minimal runtime interface used by ``PosterLlamaPipeline``.

    The full MiniGPT/DINO/CodeLLaMA stack is created by local conversion tools.
    This lightweight adapter keeps the public package importable in ordinary CI
    and gives tests a serializable runtime shape.

    Args:
        generated_text: Optional deterministic text emitted by this runtime.

    Examples:
        >>> runtime = PosterLlamaRuntime('<svg width="1" height="1"></svg>')
        >>> runtime.generate_texts(["prompt"])
        ['<svg width="1" height="1"></svg>']
    """

    def __init__(self, generated_text: str | None = None) -> None:
        """Initialize deterministic runtime metadata."""
        super().__init__()
        self.generated_text = generated_text

    def generate_texts(
        self,
        prompts: Sequence[str],
        *,
        pixel_values: Float[torch.Tensor, "batch channels height width"] | None = None,
        generator: torch.Generator | None = None,
        max_new_tokens: int = 1024,
        do_sample: bool = False,
        temperature: float = 1.0,
        top_p: float = 0.9,
        top_k: int | None = None,
        num_beams: int = 1,
    ) -> list[str]:
        """Generate markup text for prompts.

        Args:
            prompts: Prompt strings.
            pixel_values: Optional image tensors.
            generator: Optional PyTorch generator.
            max_new_tokens: Generation length budget.
            do_sample: Sampling flag.
            temperature: Sampling temperature.
            top_p: Nucleus sampling value.
            top_k: Top-k sampling value.
            num_beams: Beam count.

        Returns:
            Generated markup strings.

        Raises:
            RuntimeError: If no converted runtime text generator is available.
        """
        _ = (
            pixel_values,
            generator,
            max_new_tokens,
            do_sample,
            temperature,
            top_p,
            top_k,
            num_beams,
        )
        if self.generated_text is None:
            raise RuntimeError(
                "PosterLlama runtime assets are missing. Run the local conversion "
                "script with the raw checkpoint and backbone paths before inference."
            )

        return [self.generated_text for _ in prompts]

    def save_pretrained(
        self,
        save_directory: str | PathLike[str],
        *,
        is_main_process: bool = True,
    ) -> None:
        """Save runtime metadata.

        Args:
            save_directory: Directory to write.
            is_main_process: Whether this process should write files.
        """
        if not is_main_process:
            return
        root = Path(save_directory)
        root.mkdir(parents=True, exist_ok=True)
        (root / "runtime_config.json").write_text(
            json.dumps({"generated_text": self.generated_text}, indent=2),
            encoding="utf-8",
        )

    @classmethod
    def from_pretrained(
        cls,
        pretrained_model_name_or_path: str | PathLike[str],
        *,
        local_files_only: bool = False,
        subfolder: str | None = None,
    ) -> "PosterLlamaRuntime":
        """Load runtime metadata.

        Args:
            pretrained_model_name_or_path: Runtime directory.
            local_files_only: Accepted for loader compatibility.
            subfolder: Optional subfolder.

        Returns:
            PosterLlamaRuntime instance.
        """
        _ = local_files_only
        root = Path(pretrained_model_name_or_path)
        if subfolder is not None:
            root = root / subfolder
        data = json.loads((root / "runtime_config.json").read_text(encoding="utf-8"))
        return cls(generated_text=data.get("generated_text"))

__init__

__init__(generated_text: str | None = None) -> None

Initialize deterministic runtime metadata.

Source code in models/posterllama/src/posterllama/modeling_posterllama.py
30
31
32
33
def __init__(self, generated_text: str | None = None) -> None:
    """Initialize deterministic runtime metadata."""
    super().__init__()
    self.generated_text = generated_text

generate_texts

generate_texts(
    prompts: Sequence[str],
    *,
    pixel_values: Float[
        Tensor, "batch channels height width"
    ]
    | None = None,
    generator: Generator | None = None,
    max_new_tokens: int = 1024,
    do_sample: bool = False,
    temperature: float = 1.0,
    top_p: float = 0.9,
    top_k: int | None = None,
    num_beams: int = 1,
) -> list[str]

Generate markup text for prompts.

Parameters:

Name Type Description Default
prompts Sequence[str]

Prompt strings.

required
pixel_values Float[Tensor, 'batch channels height width'] | None

Optional image tensors.

None
generator Generator | None

Optional PyTorch generator.

None
max_new_tokens int

Generation length budget.

1024
do_sample bool

Sampling flag.

False
temperature float

Sampling temperature.

1.0
top_p float

Nucleus sampling value.

0.9
top_k int | None

Top-k sampling value.

None
num_beams int

Beam count.

1

Returns:

Type Description
list[str]

Generated markup strings.

Raises:

Type Description
RuntimeError

If no converted runtime text generator is available.

Source code in models/posterllama/src/posterllama/modeling_posterllama.py
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
76
77
78
79
80
81
82
83
def generate_texts(
    self,
    prompts: Sequence[str],
    *,
    pixel_values: Float[torch.Tensor, "batch channels height width"] | None = None,
    generator: torch.Generator | None = None,
    max_new_tokens: int = 1024,
    do_sample: bool = False,
    temperature: float = 1.0,
    top_p: float = 0.9,
    top_k: int | None = None,
    num_beams: int = 1,
) -> list[str]:
    """Generate markup text for prompts.

    Args:
        prompts: Prompt strings.
        pixel_values: Optional image tensors.
        generator: Optional PyTorch generator.
        max_new_tokens: Generation length budget.
        do_sample: Sampling flag.
        temperature: Sampling temperature.
        top_p: Nucleus sampling value.
        top_k: Top-k sampling value.
        num_beams: Beam count.

    Returns:
        Generated markup strings.

    Raises:
        RuntimeError: If no converted runtime text generator is available.
    """
    _ = (
        pixel_values,
        generator,
        max_new_tokens,
        do_sample,
        temperature,
        top_p,
        top_k,
        num_beams,
    )
    if self.generated_text is None:
        raise RuntimeError(
            "PosterLlama runtime assets are missing. Run the local conversion "
            "script with the raw checkpoint and backbone paths before inference."
        )

    return [self.generated_text for _ in prompts]

save_pretrained

save_pretrained(
    save_directory: str | PathLike[str],
    *,
    is_main_process: bool = True,
) -> None

Save runtime metadata.

Parameters:

Name Type Description Default
save_directory str | PathLike[str]

Directory to write.

required
is_main_process bool

Whether this process should write files.

True
Source code in models/posterllama/src/posterllama/modeling_posterllama.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def save_pretrained(
    self,
    save_directory: str | PathLike[str],
    *,
    is_main_process: bool = True,
) -> None:
    """Save runtime metadata.

    Args:
        save_directory: Directory to write.
        is_main_process: Whether this process should write files.
    """
    if not is_main_process:
        return
    root = Path(save_directory)
    root.mkdir(parents=True, exist_ok=True)
    (root / "runtime_config.json").write_text(
        json.dumps({"generated_text": self.generated_text}, indent=2),
        encoding="utf-8",
    )

from_pretrained classmethod

from_pretrained(
    pretrained_model_name_or_path: str | PathLike[str],
    *,
    local_files_only: bool = False,
    subfolder: str | None = None,
) -> "PosterLlamaRuntime"

Load runtime metadata.

Parameters:

Name Type Description Default
pretrained_model_name_or_path str | PathLike[str]

Runtime directory.

required
local_files_only bool

Accepted for loader compatibility.

False
subfolder str | None

Optional subfolder.

None

Returns:

Type Description
'PosterLlamaRuntime'

PosterLlamaRuntime instance.

Source code in models/posterllama/src/posterllama/modeling_posterllama.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
@classmethod
def from_pretrained(
    cls,
    pretrained_model_name_or_path: str | PathLike[str],
    *,
    local_files_only: bool = False,
    subfolder: str | None = None,
) -> "PosterLlamaRuntime":
    """Load runtime metadata.

    Args:
        pretrained_model_name_or_path: Runtime directory.
        local_files_only: Accepted for loader compatibility.
        subfolder: Optional subfolder.

    Returns:
        PosterLlamaRuntime instance.
    """
    _ = local_files_only
    root = Path(pretrained_model_name_or_path)
    if subfolder is not None:
        root = root / subfolder
    data = json.loads((root / "runtime_config.json").read_text(encoding="utf-8"))
    return cls(generated_text=data.get("generated_text"))

pipeline_posterllama

Pipeline orchestration for PosterLlama inference recipes.

PosterLlamaPipeline

Bases: LayoutGenerationPipeline

Compose a PosterLlama processor and converted runtime.

Parameters:

Name Type Description Default
config PosterLlamaConfig

Explicit pipeline configuration.

required
processor PosterLlamaProcessor

Explicit processor.

required
runtime PosterLlamaRuntime | None

Optional converted runtime. Parser-only saved artifacts may omit it.

None

Examples:

>>> cfg = PosterLlamaConfig(canvas_size=(100, 100))
>>> text = '<svg width="100" height="100"><rect data-category="text" x="0" y="0" width="10" height="10"/></svg>'
>>> pipe = PosterLlamaPipeline(
...     config=cfg,
...     processor=PosterLlamaProcessor.from_config(cfg),
...     runtime=PosterLlamaRuntime(text),
... )
>>> pipe(images=None).bbox.shape
torch.Size([1, 1, 4])
Source code in models/posterllama/src/posterllama/pipeline_posterllama.py
 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
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
class PosterLlamaPipeline(LayoutGenerationPipeline):
    """Compose a PosterLlama processor and converted runtime.

    Args:
        config: Explicit pipeline configuration.
        processor: Explicit processor.
        runtime: Optional converted runtime. Parser-only saved artifacts may omit it.

    Examples:
        >>> cfg = PosterLlamaConfig(canvas_size=(100, 100))
        >>> text = '<svg width="100" height="100"><rect data-category="text" x="0" y="0" width="10" height="10"/></svg>'
        >>> pipe = PosterLlamaPipeline(
        ...     config=cfg,
        ...     processor=PosterLlamaProcessor.from_config(cfg),
        ...     runtime=PosterLlamaRuntime(text),
        ... )
        >>> pipe(images=None).bbox.shape
        torch.Size([1, 1, 4])
    """

    config_class: ClassVar[type[PretrainedConfig]] = PosterLlamaConfig
    component_specs: ClassVar[dict[str, PipelineComponentSpec]] = {
        "processor": PipelineComponentSpec(
            attribute_name="processor",
            loader=_load_processor_component,
            config_subfolder_attribute="processor_subfolder",
            marker_file="processor_config.json",
            save_with_is_main_process=False,
        ),
        "runtime": PipelineComponentSpec(
            attribute_name="runtime",
            loader=_load_runtime_component,
            config_subfolder_attribute="runtime_subfolder",
            required=False,
            marker_file="runtime_config.json",
        ),
    }

    config: PosterLlamaConfig
    processor: PosterLlamaProcessor
    runtime: PosterLlamaRuntime | None

    def __init__(
        self,
        *,
        config: PosterLlamaConfig,
        processor: PosterLlamaProcessor,
        runtime: PosterLlamaRuntime | None = None,
    ) -> None:
        """Initialize pipeline components."""
        super().__init__(config)
        self.config = config
        self.processor = processor
        self.runtime = runtime

    @classmethod
    def _from_pretrained_components(  # ty: ignore[invalid-method-override]
        cls,
        *,
        config: PretrainedConfig,
        components: Mapping[str, PosterLlamaProcessor | PosterLlamaRuntime | None],
    ) -> "PosterLlamaPipeline":
        """Build a pipeline from loaded components."""
        return cls(
            config=cast(PosterLlamaConfig, config),
            processor=cast(PosterLlamaProcessor, components["processor"]),
            runtime=cast(PosterLlamaRuntime | None, components["runtime"]),
        )

    @torch.no_grad()
    def __call__(  # ty: ignore[invalid-method-override]
        self,
        *,
        images: ImageInput | Sequence[ImageInput] | None = None,
        prompt: str | Sequence[str] | None = None,
        content: Mapping[str, str | int | float | bool | None]
        | Sequence[Mapping[str, str | int | float | bool | None]]
        | None = None,
        texts: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
        batch_size: int = 1,
        seed: int | None = None,
        generator: torch.Generator | None = None,
        condition_type: ConditionType | str = ConditionType.content_image,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None = None,
        bbox: Float[torch.Tensor, "..."]
        | Sequence[Sequence[Sequence[float | int]]]
        | Sequence[Sequence[float | int]]
        | Sequence[float | int]
        | None = None,
        mask: Bool[torch.Tensor, "..."]
        | Sequence[Sequence[bool]]
        | Sequence[bool]
        | None = None,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
        box_format: BoxFormat | str = BoxFormat.xywh,
        normalized: bool = True,
        canvas_size: tuple[int, int] | None = None,
        num_inference_steps: int | None = None,
        output_type: Literal["dataclass", "dict"] = "dataclass",
        return_intermediates: bool = False,
        max_new_tokens: int | None = None,
        do_sample: bool | None = None,
        temperature: float | None = None,
        top_p: float | None = None,
        top_k: int | None = None,
        num_beams: int | None = None,
    ) -> (
        LayoutGenerationOutput
        | dict[
            str,
            Float[torch.Tensor, "..."]
            | Int[torch.Tensor, "..."]
            | Bool[torch.Tensor, "..."]
            | dict[int, str]
            | Mapping[str, str | bytes | int | float | bool | None]
            | list[str]
            | list[tuple[float, float, float, float]]
            | tuple[int, int]
            | str
            | bytes
            | int
            | float
            | bool
            | None,
        ]
    ):
        """Generate a poster layout.

        Args:
            images: Poster image inputs.
            prompt: Optional prompt prefix override.
            content: Optional content metadata.
            texts: Optional poster text strings.
            batch_size: Batch size when images are omitted.
            seed: Convenience seed used only when ``generator`` is absent.
            generator: Explicit PyTorch generator; takes precedence over ``seed``.
            condition_type: Canonical condition or PosterLlama release alias.
            labels: Optional label constraints.
            bbox: Optional box constraints.
            mask: Optional valid-element mask.
            num_elements: Optional requested element count.
            box_format: Input box format.
            normalized: Whether boxes are normalized.
            canvas_size: Canvas size as ``(width, height)``.
            num_inference_steps: Reserved shared argument.
            output_type: ``dataclass`` or ``dict``.
            return_intermediates: Whether to include prompt and parse diagnostics.
            max_new_tokens: Generation token budget.
            do_sample: Sampling flag.
            temperature: Sampling temperature.
            top_p: Nucleus sampling value.
            top_k: Top-k sampling value.
            num_beams: Beam count.

        Returns:
            LayoutGenerationOutput or dictionary.

        Raises:
            RuntimeError: If converted runtime assets are absent.
        """
        _ = num_inference_steps
        batch = self.processor(
            images=images,
            prompt=prompt,
            content=content,
            texts=texts,
            batch_size=batch_size,
            condition_type=condition_type,
            labels=labels,
            bbox=bbox,
            mask=mask,
            num_elements=num_elements,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas_size,
        )
        if self.runtime is None:
            raise RuntimeError(
                "PosterLlama runtime assets are missing. A processor-only artifact "
                "can build prompts and parse outputs, but generation requires a "
                "converted local runtime."
            )

        active_generator = self.prepare_generator(generator=generator, seed=seed)
        generation_args = {
            "max_new_tokens": max_new_tokens or self.config.default_max_new_tokens,
            "do_sample": self.config.default_do_sample
            if do_sample is None
            else do_sample,
            "temperature": self.config.default_temperature
            if temperature is None
            else temperature,
            "top_p": self.config.default_top_p if top_p is None else top_p,
            "top_k": self.config.default_top_k if top_k is None else top_k,
            "num_beams": self.config.default_num_beams
            if num_beams is None
            else num_beams,
        }
        generated = self.runtime.generate_texts(
            cast(list[str], batch["prompts"]),
            pixel_values=cast(torch.Tensor, batch["pixel_values"]),
            generator=active_generator,
            **generation_args,
        )
        output = self.processor.parse_output(
            generated[0],
            canvas_size=canvas_size,
            output_type="dataclass",
            return_intermediates=return_intermediates,
        )
        result = cast(LayoutGenerationOutput, output)
        if return_intermediates:
            existing = cast(
                dict[
                    str,
                    str
                    | bytes
                    | int
                    | float
                    | bool
                    | None
                    | Mapping[str, str | int | float | bool | None],
                ],
                result.intermediates or {},
            )
            existing["prompt_bytes"] = cast(list[str], batch["prompts"])[0].encode()
            existing["raw_generated_text"] = generated[0]
            existing["condition_type"] = str(batch["condition_type"])
            existing["generation_args"] = generation_args
            result.intermediates = existing
        if output_type == "dict":
            return dict(result)
        if output_type != "dataclass":
            raise ValueError(f"Unsupported output_type: {output_type}")

        return result

__init__

__init__(
    *,
    config: PosterLlamaConfig,
    processor: PosterLlamaProcessor,
    runtime: PosterLlamaRuntime | None = None,
) -> None

Initialize pipeline components.

Source code in models/posterllama/src/posterllama/pipeline_posterllama.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def __init__(
    self,
    *,
    config: PosterLlamaConfig,
    processor: PosterLlamaProcessor,
    runtime: PosterLlamaRuntime | None = None,
) -> None:
    """Initialize pipeline components."""
    super().__init__(config)
    self.config = config
    self.processor = processor
    self.runtime = runtime

__call__

__call__(
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    prompt: str | Sequence[str] | None = None,
    content: Mapping[str, str | int | float | bool | None]
    | Sequence[
        Mapping[str, str | int | float | bool | None]
    ]
    | None = None,
    texts: str
    | Sequence[str]
    | Sequence[Sequence[str]]
    | None = None,
    batch_size: int = 1,
    seed: int | None = None,
    generator: Generator | None = None,
    condition_type: ConditionType
    | str = ConditionType.content_image,
    labels: Int[Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[Tensor, "..."]
    | Sequence[Sequence[Sequence[float | int]]]
    | Sequence[Sequence[float | int]]
    | Sequence[float | int]
    | None = None,
    mask: Bool[Tensor, "..."]
    | Sequence[Sequence[bool]]
    | Sequence[bool]
    | None = None,
    num_elements: int
    | Sequence[int]
    | Int[Tensor, "batch"]
    | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    num_inference_steps: int | None = None,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    return_intermediates: bool = False,
    max_new_tokens: int | None = None,
    do_sample: bool | None = None,
    temperature: float | None = None,
    top_p: float | None = None,
    top_k: int | None = None,
    num_beams: int | None = None,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Float[torch.Tensor, "..."]
        | Int[torch.Tensor, "..."]
        | Bool[torch.Tensor, "..."]
        | dict[int, str]
        | Mapping[
            str, str | bytes | int | float | bool | None
        ]
        | list[str]
        | list[tuple[float, float, float, float]]
        | tuple[int, int]
        | str
        | bytes
        | int
        | float
        | bool
        | None,
    ]
)

Generate a poster layout.

Parameters:

Name Type Description Default
images ImageInput | Sequence[ImageInput] | None

Poster image inputs.

None
prompt str | Sequence[str] | None

Optional prompt prefix override.

None
content Mapping[str, str | int | float | bool | None] | Sequence[Mapping[str, str | int | float | bool | None]] | None

Optional content metadata.

None
texts str | Sequence[str] | Sequence[Sequence[str]] | None

Optional poster text strings.

None
batch_size int

Batch size when images are omitted.

1
seed int | None

Convenience seed used only when generator is absent.

None
generator Generator | None

Explicit PyTorch generator; takes precedence over seed.

None
condition_type ConditionType | str

Canonical condition or PosterLlama release alias.

content_image
labels Int[Tensor, '...'] | Sequence[Sequence[int | str]] | Sequence[int | str] | None

Optional label constraints.

None
bbox Float[Tensor, '...'] | Sequence[Sequence[Sequence[float | int]]] | Sequence[Sequence[float | int]] | Sequence[float | int] | None

Optional box constraints.

None
mask Bool[Tensor, '...'] | Sequence[Sequence[bool]] | Sequence[bool] | None

Optional valid-element mask.

None
num_elements int | Sequence[int] | Int[Tensor, 'batch'] | None

Optional requested element count.

None
box_format BoxFormat | str

Input box format.

xywh
normalized bool

Whether boxes are normalized.

True
canvas_size tuple[int, int] | None

Canvas size as (width, height).

None
num_inference_steps int | None

Reserved shared argument.

None
output_type Literal['dataclass', 'dict']

dataclass or dict.

'dataclass'
return_intermediates bool

Whether to include prompt and parse diagnostics.

False
max_new_tokens int | None

Generation token budget.

None
do_sample bool | None

Sampling flag.

None
temperature float | None

Sampling temperature.

None
top_p float | None

Nucleus sampling value.

None
top_k int | None

Top-k sampling value.

None
num_beams int | None

Beam count.

None

Returns:

Type Description
LayoutGenerationOutput | dict[str, Float[Tensor, '...'] | Int[Tensor, '...'] | Bool[Tensor, '...'] | dict[int, str] | Mapping[str, str | bytes | int | float | bool | None] | list[str] | list[tuple[float, float, float, float]] | tuple[int, int] | str | bytes | int | float | bool | None]

LayoutGenerationOutput or dictionary.

Raises:

Type Description
RuntimeError

If converted runtime assets are absent.

Source code in models/posterllama/src/posterllama/pipeline_posterllama.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
@torch.no_grad()
def __call__(  # ty: ignore[invalid-method-override]
    self,
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    prompt: str | Sequence[str] | None = None,
    content: Mapping[str, str | int | float | bool | None]
    | Sequence[Mapping[str, str | int | float | bool | None]]
    | None = None,
    texts: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
    batch_size: int = 1,
    seed: int | None = None,
    generator: torch.Generator | None = None,
    condition_type: ConditionType | str = ConditionType.content_image,
    labels: Int[torch.Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[torch.Tensor, "..."]
    | Sequence[Sequence[Sequence[float | int]]]
    | Sequence[Sequence[float | int]]
    | Sequence[float | int]
    | None = None,
    mask: Bool[torch.Tensor, "..."]
    | Sequence[Sequence[bool]]
    | Sequence[bool]
    | None = None,
    num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    num_inference_steps: int | None = None,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    return_intermediates: bool = False,
    max_new_tokens: int | None = None,
    do_sample: bool | None = None,
    temperature: float | None = None,
    top_p: float | None = None,
    top_k: int | None = None,
    num_beams: int | None = None,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Float[torch.Tensor, "..."]
        | Int[torch.Tensor, "..."]
        | Bool[torch.Tensor, "..."]
        | dict[int, str]
        | Mapping[str, str | bytes | int | float | bool | None]
        | list[str]
        | list[tuple[float, float, float, float]]
        | tuple[int, int]
        | str
        | bytes
        | int
        | float
        | bool
        | None,
    ]
):
    """Generate a poster layout.

    Args:
        images: Poster image inputs.
        prompt: Optional prompt prefix override.
        content: Optional content metadata.
        texts: Optional poster text strings.
        batch_size: Batch size when images are omitted.
        seed: Convenience seed used only when ``generator`` is absent.
        generator: Explicit PyTorch generator; takes precedence over ``seed``.
        condition_type: Canonical condition or PosterLlama release alias.
        labels: Optional label constraints.
        bbox: Optional box constraints.
        mask: Optional valid-element mask.
        num_elements: Optional requested element count.
        box_format: Input box format.
        normalized: Whether boxes are normalized.
        canvas_size: Canvas size as ``(width, height)``.
        num_inference_steps: Reserved shared argument.
        output_type: ``dataclass`` or ``dict``.
        return_intermediates: Whether to include prompt and parse diagnostics.
        max_new_tokens: Generation token budget.
        do_sample: Sampling flag.
        temperature: Sampling temperature.
        top_p: Nucleus sampling value.
        top_k: Top-k sampling value.
        num_beams: Beam count.

    Returns:
        LayoutGenerationOutput or dictionary.

    Raises:
        RuntimeError: If converted runtime assets are absent.
    """
    _ = num_inference_steps
    batch = self.processor(
        images=images,
        prompt=prompt,
        content=content,
        texts=texts,
        batch_size=batch_size,
        condition_type=condition_type,
        labels=labels,
        bbox=bbox,
        mask=mask,
        num_elements=num_elements,
        box_format=box_format,
        normalized=normalized,
        canvas_size=canvas_size,
    )
    if self.runtime is None:
        raise RuntimeError(
            "PosterLlama runtime assets are missing. A processor-only artifact "
            "can build prompts and parse outputs, but generation requires a "
            "converted local runtime."
        )

    active_generator = self.prepare_generator(generator=generator, seed=seed)
    generation_args = {
        "max_new_tokens": max_new_tokens or self.config.default_max_new_tokens,
        "do_sample": self.config.default_do_sample
        if do_sample is None
        else do_sample,
        "temperature": self.config.default_temperature
        if temperature is None
        else temperature,
        "top_p": self.config.default_top_p if top_p is None else top_p,
        "top_k": self.config.default_top_k if top_k is None else top_k,
        "num_beams": self.config.default_num_beams
        if num_beams is None
        else num_beams,
    }
    generated = self.runtime.generate_texts(
        cast(list[str], batch["prompts"]),
        pixel_values=cast(torch.Tensor, batch["pixel_values"]),
        generator=active_generator,
        **generation_args,
    )
    output = self.processor.parse_output(
        generated[0],
        canvas_size=canvas_size,
        output_type="dataclass",
        return_intermediates=return_intermediates,
    )
    result = cast(LayoutGenerationOutput, output)
    if return_intermediates:
        existing = cast(
            dict[
                str,
                str
                | bytes
                | int
                | float
                | bool
                | None
                | Mapping[str, str | int | float | bool | None],
            ],
            result.intermediates or {},
        )
        existing["prompt_bytes"] = cast(list[str], batch["prompts"])[0].encode()
        existing["raw_generated_text"] = generated[0]
        existing["condition_type"] = str(batch["condition_type"])
        existing["generation_args"] = generation_args
        result.intermediates = existing
    if output_type == "dict":
        return dict(result)
    if output_type != "dataclass":
        raise ValueError(f"Unsupported output_type: {output_type}")

    return result

postprocessing

HTML/SVG postprocessing for PosterLlama generated layouts.

ParsedPosterRectangle dataclass

One parsed PosterLlama rectangle in source pixel ltwh format.

Source code in models/posterllama/src/posterllama/postprocessing.py
30
31
32
33
34
35
36
@dataclass(frozen=True)
class ParsedPosterRectangle:
    """One parsed PosterLlama rectangle in source pixel ``ltwh`` format."""

    label: int
    raw_label: str
    bbox_ltwh: tuple[float, float, float, float]

ParsedPosterMarkup dataclass

Parsed PosterLlama markup and diagnostics.

Source code in models/posterllama/src/posterllama/postprocessing.py
39
40
41
42
43
44
45
@dataclass(frozen=True)
class ParsedPosterMarkup:
    """Parsed PosterLlama markup and diagnostics."""

    rectangles: tuple[ParsedPosterRectangle, ...]
    canvas_size: tuple[int, int] | None
    warnings: tuple[str, ...]

extract_svg_canvas

extract_svg_canvas(markup: str) -> tuple[int, int] | None

Extract (width, height) from the first <svg> element.

Parameters:

Name Type Description Default
markup str

Generated HTML/SVG text.

required

Returns:

Type Description
tuple[int, int] | None

Canvas size when both dimensions are present; otherwise None.

Examples:

>>> extract_svg_canvas('<svg width="360" height="504"></svg>')
(360, 504)
Source code in models/posterllama/src/posterllama/postprocessing.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def extract_svg_canvas(markup: str) -> tuple[int, int] | None:
    """Extract ``(width, height)`` from the first ``<svg>`` element.

    Args:
        markup: Generated HTML/SVG text.

    Returns:
        Canvas size when both dimensions are present; otherwise ``None``.

    Examples:
        >>> extract_svg_canvas('<svg width="360" height="504"></svg>')
        (360, 504)
    """
    match = SVG_RE.search(markup)
    if match is None:
        return None
    attrs = _parse_attributes(match.group("attrs"))
    width = _parse_number(attrs.get("width"))
    height = _parse_number(attrs.get("height"))
    if width is None or height is None:
        return None
    return int(width), int(height)

parse_rectangles

parse_rectangles(
    markup: str,
    label2id: Mapping[str, int],
    *,
    strict: bool = False,
) -> ParsedPosterMarkup

Parse generated <rect> tags into rectangle records.

Parameters:

Name Type Description Default
markup str

Generated HTML/SVG text.

required
label2id Mapping[str, int]

Normalized label-name to dataset id mapping.

required
strict bool

Whether malformed rectangles and unknown labels raise errors.

False

Returns:

Type Description
ParsedPosterMarkup

Parsed rectangles, canvas size, and warnings.

Raises:

Type Description
ValueError

If strict is true and a rectangle cannot be parsed.

Examples:

>>> parsed = parse_rectangles(
...     '<svg width="100" height="100"><rect data-category="text" x="1" y="2" width="3" height="4"/></svg>',
...     {"text": 1},
... )
>>> parsed.rectangles[0].bbox_ltwh
(1.0, 2.0, 3.0, 4.0)
Source code in models/posterllama/src/posterllama/postprocessing.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def parse_rectangles(
    markup: str,
    label2id: Mapping[str, int],
    *,
    strict: bool = False,
) -> ParsedPosterMarkup:
    """Parse generated ``<rect>`` tags into rectangle records.

    Args:
        markup: Generated HTML/SVG text.
        label2id: Normalized label-name to dataset id mapping.
        strict: Whether malformed rectangles and unknown labels raise errors.

    Returns:
        Parsed rectangles, canvas size, and warnings.

    Raises:
        ValueError: If ``strict`` is true and a rectangle cannot be parsed.

    Examples:
        >>> parsed = parse_rectangles(
        ...     '<svg width="100" height="100"><rect data-category="text" x="1" y="2" width="3" height="4"/></svg>',
        ...     {"text": 1},
        ... )
        >>> parsed.rectangles[0].bbox_ltwh
        (1.0, 2.0, 3.0, 4.0)
    """
    warnings: list[str] = []
    rectangles: list[ParsedPosterRectangle] = []
    for match in RECT_RE.finditer(markup):
        attrs = _parse_attributes(match.group("attrs"))
        raw_label = _label_from_attributes(attrs)
        if raw_label is None:
            _warn_or_raise("rect is missing data-category", strict, warnings)
            continue
        label_key = _normalize_label(raw_label)
        label_id = label2id.get(label_key)
        if label_id is None:
            _warn_or_raise(f"unknown label skipped: {raw_label}", strict, warnings)
            continue
        values = tuple(
            _parse_number(attrs.get(key)) for key in ("x", "y", "width", "height")
        )
        if any(value is None for value in values):
            _warn_or_raise(
                f"rect has malformed numeric attributes: {raw_label}", strict, warnings
            )
            continue
        left, top, width, height = (
            float(value) for value in values if value is not None
        )
        if width <= 0 or height <= 0:
            _warn_or_raise(f"rect has non-positive size: {raw_label}", strict, warnings)
            continue
        rectangles.append(
            ParsedPosterRectangle(
                label=label_id,
                raw_label=raw_label,
                bbox_ltwh=(left, top, width, height),
            )
        )
    return ParsedPosterMarkup(
        rectangles=tuple(rectangles),
        canvas_size=extract_svg_canvas(markup),
        warnings=tuple(warnings),
    )

rect_ltwh_to_output

rect_ltwh_to_output(
    parsed: ParsedPosterMarkup,
    *,
    canvas_size: tuple[int, int],
    id2label: Mapping[int, str],
    return_intermediates: bool = False,
) -> LayoutGenerationOutput

Convert parsed pixel ltwh rectangles to public layout output.

Parameters:

Name Type Description Default
parsed ParsedPosterMarkup

Parsed rectangle records.

required
canvas_size tuple[int, int]

Canvas size as (width, height).

required
id2label Mapping[int, str]

Dataset-local id-to-label mapping.

required
return_intermediates bool

Whether to include parser diagnostics.

False

Returns:

Type Description
LayoutGenerationOutput

LayoutGenerationOutput with normalized center xywh boxes.

Examples:

>>> parsed = ParsedPosterMarkup((ParsedPosterRectangle(1, "text", (0, 0, 10, 20)),), (100, 100), ())
>>> rect_ltwh_to_output(parsed, canvas_size=(100, 100), id2label={1: "text"}).bbox.shape
torch.Size([1, 1, 4])
Source code in models/posterllama/src/posterllama/postprocessing.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def rect_ltwh_to_output(
    parsed: ParsedPosterMarkup,
    *,
    canvas_size: tuple[int, int],
    id2label: Mapping[int, str],
    return_intermediates: bool = False,
) -> LayoutGenerationOutput:
    """Convert parsed pixel ``ltwh`` rectangles to public layout output.

    Args:
        parsed: Parsed rectangle records.
        canvas_size: Canvas size as ``(width, height)``.
        id2label: Dataset-local id-to-label mapping.
        return_intermediates: Whether to include parser diagnostics.

    Returns:
        LayoutGenerationOutput with normalized center ``xywh`` boxes.

    Examples:
        >>> parsed = ParsedPosterMarkup((ParsedPosterRectangle(1, "text", (0, 0, 10, 20)),), (100, 100), ())
        >>> rect_ltwh_to_output(parsed, canvas_size=(100, 100), id2label={1: "text"}).bbox.shape
        torch.Size([1, 1, 4])
    """
    if not parsed.rectangles:
        bbox = torch.zeros((1, 0, 4), dtype=torch.float32)
        labels = torch.zeros((1, 0), dtype=torch.long)
        mask = torch.zeros((1, 0), dtype=torch.bool)
    else:
        bbox_ltwh: Float[torch.Tensor, "batch elements 4"] = torch.tensor(
            [[rect.bbox_ltwh for rect in parsed.rectangles]],
            dtype=torch.float32,
        )
        bbox = normalize_boxes(
            bbox_ltwh,
            canvas_size=canvas_size,
            box_format="ltwh",
        )
        labels: Int[torch.Tensor, "batch elements"] = torch.tensor(
            [[rect.label for rect in parsed.rectangles]],
            dtype=torch.long,
        )
        mask = torch.ones(labels.shape, dtype=torch.bool)
    intermediates = None
    if return_intermediates:
        intermediates = {
            "bbox_ltwh": [rect.bbox_ltwh for rect in parsed.rectangles],
            "raw_labels": [rect.raw_label for rect in parsed.rectangles],
            "canvas_size": canvas_size,
            "parse_warnings": list(parsed.warnings),
        }
    return LayoutGenerationOutput(
        bbox=bbox,
        labels=labels,
        mask=mask,
        id2label={int(key): value for key, value in id2label.items()},
        intermediates=intermediates,
    )

processing_posterllama

Processor for PosterLlama prompt construction and output parsing.

PosterLlamaProcessor

Bases: ProcessorMixin

Build PosterLlama prompts and decode generated HTML/SVG layouts.

Parameters:

Name Type Description Default
image_processor PosterLlamaImageProcessor

Image processor metadata wrapper.

required
config PosterLlamaConfig

Explicit PosterLlama configuration.

required

Examples:

>>> processor = PosterLlamaProcessor.from_config(PosterLlamaConfig())
>>> "Generate poster layout" in processor.build_prompt(condition_type="unconditional")
True
Source code in models/posterllama/src/posterllama/processing_posterllama.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
class PosterLlamaProcessor(ProcessorMixin):
    """Build PosterLlama prompts and decode generated HTML/SVG layouts.

    Args:
        image_processor: Image processor metadata wrapper.
        config: Explicit PosterLlama configuration.

    Examples:
        >>> processor = PosterLlamaProcessor.from_config(PosterLlamaConfig())
        >>> "Generate poster layout" in processor.build_prompt(condition_type="unconditional")
        True
    """

    attributes = ["image_processor"]
    image_processor_class = "PosterLlamaImageProcessor"

    def __init__(
        self,
        image_processor: PosterLlamaImageProcessor,
        config: PosterLlamaConfig,
    ) -> None:
        """Initialize processor components."""
        self.image_processor = image_processor
        self.config = config
        super().__init__(image_processor)

    @classmethod
    def from_config(cls, config: PosterLlamaConfig) -> "PosterLlamaProcessor":
        """Create a processor from an explicit config.

        Args:
            config: Processor configuration.

        Returns:
            PosterLlamaProcessor instance.

        Examples:
            >>> PosterLlamaProcessor.from_config(PosterLlamaConfig()).config.model_type
            'posterllama'
        """
        return cls(
            image_processor=PosterLlamaImageProcessor(
                vision_encoder_repo_id=config.vision_encoder_repo_id,
            ),
            config=config,
        )

    def save_pretrained(
        self,
        save_directory: str | PathLike[str],
        push_to_hub: bool = False,
        **kwargs: str | int | float | bool | None,
    ) -> None:
        """Save processor metadata.

        Args:
            save_directory: Directory to write.
            push_to_hub: Accepted for ProcessorMixin compatibility; ignored.
            kwargs: Accepted for ProcessorMixin compatibility; ignored.
        """
        _ = (push_to_hub, kwargs)
        root = Path(save_directory)
        root.mkdir(parents=True, exist_ok=True)
        self.config.save_pretrained(root)
        self.image_processor.save_pretrained(root)
        (root / "processor_config.json").write_text(
            json.dumps(
                {
                    "processor_class": self.__class__.__name__,
                    "image_processor_class": self.image_processor.__class__.__name__,
                },
                indent=2,
                sort_keys=True,
            ),
            encoding="utf-8",
        )

    @classmethod
    def from_pretrained(
        cls,
        pretrained_model_name_or_path: str | PathLike[str],
        cache_dir: str | PathLike[str] | None = None,
        force_download: bool = False,
        local_files_only: bool = False,
        token: str | bool | None = None,
        revision: str = "main",
        *,
        subfolder: str | None = None,
        **kwargs: PosterLlamaImageProcessorKwarg,
    ) -> "PosterLlamaProcessor":
        """Load processor metadata.

        Args:
            pretrained_model_name_or_path: Checkpoint root or processor folder.
            cache_dir: Accepted for ProcessorMixin compatibility.
            force_download: Accepted for ProcessorMixin compatibility.
            local_files_only: Whether to avoid network access.
            token: Accepted for ProcessorMixin compatibility.
            revision: Accepted for ProcessorMixin compatibility.
            subfolder: Optional processor subfolder.
            kwargs: Accepted for ProcessorMixin compatibility.

        Returns:
            Loaded PosterLlamaProcessor.
        """
        _ = (cache_dir, force_download, token, revision, kwargs)
        root = Path(pretrained_model_name_or_path)
        if subfolder is not None:
            root = root / subfolder
        config = PosterLlamaConfig.from_pretrained(
            root, local_files_only=local_files_only
        )
        return cls(
            image_processor=PosterLlamaImageProcessor.from_pretrained(root),
            config=config,
        )

    def normalize_condition_type(
        self,
        condition_type: ConditionType | str,
    ) -> ConditionType:
        """Normalize PosterLlama condition aliases.

        Args:
            condition_type: Canonical condition or PosterLlama release alias.

        Returns:
            Supported canonical condition.

        Raises:
            NotImplementedError: If the condition is known but unsupported.
            ValueError: If the condition is unknown.
        """
        if isinstance(condition_type, str):
            alias = condition_type.lower().replace("-", "_")
            if alias in REQUEST_CONDITION_ALIASES:
                return REQUEST_CONDITION_ALIASES[alias]
        condition = normalize_condition_type(condition_type)
        if condition in UNSUPPORTED_CONDITIONS:
            raise NotImplementedError(f"PosterLlama does not support {condition}")

        if condition not in SUPPORTED_CONDITIONS:
            raise NotImplementedError(f"PosterLlama does not support {condition}")

        return condition

    def __call__(
        self,
        *,
        images: ImageInput | Sequence[ImageInput] | None = None,
        prompt: str | Sequence[str] | None = None,
        content: Mapping[str, str | int | float | bool | None]
        | Sequence[Mapping[str, str | int | float | bool | None]]
        | None = None,
        texts: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
        batch_size: int = 1,
        condition_type: ConditionType | str = ConditionType.content_image,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None = None,
        bbox: Float[torch.Tensor, "..."]
        | Sequence[Sequence[Sequence[float | int]]]
        | Sequence[Sequence[float | int]]
        | Sequence[float | int]
        | None = None,
        mask: Bool[torch.Tensor, "..."]
        | Sequence[Sequence[bool]]
        | Sequence[bool]
        | None = None,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
        box_format: BoxFormat | str = BoxFormat.xywh,
        normalized: bool = True,
        canvas_size: tuple[int, int] | None = None,
        return_tensors: Literal["pt"] = "pt",
    ) -> BatchEncoding:
        """Encode public inputs into recipe prompt and image tensors.

        Args:
            images: Poster image inputs.
            prompt: Optional user-provided prompt text.
            content: Optional content metadata.
            texts: Optional poster text strings.
            batch_size: Batch size when no images are supplied.
            condition_type: Canonical condition or PosterLlama release alias.
            labels: Optional element label constraints.
            bbox: Optional element boxes.
            mask: Optional valid-element mask.
            num_elements: Optional requested element count.
            box_format: Input box format.
            normalized: Whether boxes are normalized.
            canvas_size: Canvas size for pixel boxes and prompt rendering.
            return_tensors: Tensor return format. Only ``pt`` is supported.

        Returns:
            BatchEncoding containing prompt strings and tensors.
        """
        condition = self.normalize_condition_type(condition_type)
        canvas = self._resolve_canvas_size(canvas_size)
        prompt_text = self.build_prompt(
            condition_type=condition,
            prompt=prompt,
            content=content,
            texts=texts,
            labels=labels,
            bbox=bbox,
            mask=mask,
            num_elements=num_elements,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas,
        )
        image_batch = self.image_processor(images, return_tensors=return_tensors)
        return BatchEncoding(
            {
                "pixel_values": image_batch["pixel_values"],
                "prompts": prompt_text
                if isinstance(prompt_text, list)
                else [prompt_text] * batch_size,
                "condition_type": condition,
                "canvas_size": canvas,
            }
        )

    def build_prompt(
        self,
        *,
        condition_type: ConditionType | str = ConditionType.content_image,
        prompt: str | Sequence[str] | None = None,
        content: Mapping[str, str | int | float | bool | None]
        | Sequence[Mapping[str, str | int | float | bool | None]]
        | None = None,
        texts: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None = None,
        bbox: Float[torch.Tensor, "..."]
        | Sequence[Sequence[Sequence[float | int]]]
        | Sequence[Sequence[float | int]]
        | Sequence[float | int]
        | None = None,
        mask: Bool[torch.Tensor, "..."]
        | Sequence[Sequence[bool]]
        | Sequence[bool]
        | None = None,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
        box_format: BoxFormat | str = BoxFormat.xywh,
        normalized: bool = True,
        canvas_size: tuple[int, int] | None = None,
    ) -> str | list[str]:
        """Build a deterministic PosterLlama HTML prompt.

        Args:
            condition_type: Canonical condition or PosterLlama release alias.
            prompt: Optional prompt prefix override.
            content: Optional content metadata included in diagnostics text.
            texts: Optional poster text strings.
            labels: Optional label constraints.
            bbox: Optional box constraints.
            mask: Optional valid-element mask.
            num_elements: Requested element count for unconstrained slots.
            box_format: Input box format.
            normalized: Whether boxes are normalized.
            canvas_size: Canvas size as ``(width, height)``.

        Returns:
            Prompt string or list of prompt strings.
        """
        _ = content
        condition = self.normalize_condition_type(condition_type)
        canvas = self._resolve_canvas_size(canvas_size)
        base_prompt = self._first_prompt(prompt)
        text_line = self._texts_line(texts)
        known_markup = self._constraint_markup(
            condition=condition,
            labels=labels,
            bbox=bbox,
            mask=mask,
            num_elements=num_elements,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas,
        )
        bbox_html = HTML_TEMPLATE.format(
            width=canvas[0],
            height=canvas[1],
            content=known_markup,
        )
        source_key = self._source_condition_key(condition)
        task_instruction = SOURCE_TASK_INSTRUCTIONS[self.config.dataset_name]
        if text_line:
            instruction = SOURCE_TEXT_INSTRUCTIONS[source_key].format(
                text=text_line,
                bbox_html=bbox_html,
            )
        else:
            instruction = SOURCE_INSTRUCTIONS[source_key].format(bbox_html=bbox_html)
        body = f"{base_prompt}{task_instruction}{instruction} <MID>"
        return self.config.prompt_template.format(body)

    def parse_output(
        self,
        text: str,
        *,
        canvas_size: tuple[int, int] | None = None,
        output_type: Literal["dataclass", "dict"] = "dataclass",
        return_intermediates: bool = False,
        strict: bool = False,
    ) -> (
        LayoutGenerationOutput
        | dict[
            str,
            Float[torch.Tensor, "..."]
            | Int[torch.Tensor, "..."]
            | Bool[torch.Tensor, "..."]
            | dict[int, str]
            | list[str]
            | list[tuple[float, float, float, float]]
            | tuple[int, int]
            | str
            | int
            | float
            | bool
            | None,
        ]
    ):
        """Parse generated HTML/SVG into public layout output.

        Args:
            text: Generated markup.
            canvas_size: Canvas size override.
            output_type: Return dataclass or dictionary.
            return_intermediates: Whether to include parse diagnostics.
            strict: Whether malformed rectangles raise.

        Returns:
            LayoutGenerationOutput or dictionary.
        """
        parsed = parse_rectangles(text, self._label2id(), strict=strict)
        canvas = canvas_size or parsed.canvas_size or self.config.canvas_size
        if canvas is None:
            raise ValueError(
                "canvas_size is required when generated SVG lacks width/height"
            )

        resolved_canvas = (int(canvas[0]), int(canvas[1]))
        output = rect_ltwh_to_output(
            parsed,
            canvas_size=resolved_canvas,
            id2label=cast(dict[int, str], self.config.id2label),
            return_intermediates=return_intermediates,
        )
        if output_type == "dict":
            return dict(output)
        if output_type != "dataclass":
            raise ValueError(f"Unsupported output_type: {output_type}")

        return output

    def _resolve_canvas_size(
        self,
        canvas_size: tuple[int, int] | None,
    ) -> tuple[int, int]:
        canvas = canvas_size or self.config.canvas_size
        if canvas is None:
            return (360, 504)
        return int(canvas[0]), int(canvas[1])

    def _first_prompt(self, prompt: str | Sequence[str] | None) -> str:
        if prompt is None:
            return ""
        if isinstance(prompt, str):
            return prompt
        return next(iter(prompt), "")

    def _texts_line(
        self,
        texts: str | Sequence[str] | Sequence[Sequence[str]] | None,
    ) -> str:
        if texts is None:
            return ""
        if isinstance(texts, str):
            values = [texts]
        else:
            first = next(iter(texts), "")
            if isinstance(first, str):
                values = cast(list[str], list(texts))
            else:
                values = [str(value) for value in first]
        return " | ".join(values)

    def _constraint_markup(
        self,
        *,
        condition: ConditionType,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str]
        | None,
        bbox: Float[torch.Tensor, "..."]
        | Sequence[Sequence[Sequence[float | int]]]
        | Sequence[Sequence[float | int]]
        | Sequence[float | int]
        | None,
        mask: Bool[torch.Tensor, "..."]
        | Sequence[Sequence[bool]]
        | Sequence[bool]
        | None,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None,
        box_format: BoxFormat | str,
        normalized: bool,
        canvas_size: tuple[int, int],
    ) -> str:
        if labels is None:
            if condition in {ConditionType.content_image, ConditionType.unconditional}:
                return ""
            count = self._num_elements(num_elements)
            return " ".join(self._fill_rect(index) for index in range(count))
        label_tensor = self._labels_to_tensor(labels)
        bbox_tensor = self._bbox_to_tensor(
            bbox,
            labels=label_tensor,
            mask=mask,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas_size,
        )
        rects: list[str] = []
        fill_index = 1
        for index, (label, box) in enumerate(
            zip(label_tensor[0].tolist(), bbox_tensor[0].tolist(), strict=True)
        ):
            rect, fill_index = self._rect_for_condition(
                condition=condition,
                label=int(label),
                bbox_ltwh=(
                    float(box[0]),
                    float(box[1]),
                    float(box[2]),
                    float(box[3]),
                ),
                fill_index=fill_index,
            )
            if rect:
                rects.append(rect)
        return " ".join(rects)

    def _labels_to_tensor(
        self,
        labels: Int[torch.Tensor, "..."]
        | Sequence[Sequence[int | str]]
        | Sequence[int | str],
    ) -> Int[torch.Tensor, "batch elements"]:
        if isinstance(labels, torch.Tensor):
            tensor = labels.long()
            return tensor.unsqueeze(0) if tensor.ndim == 1 else tensor
        rows = cast(Sequence[int | str | Sequence[int | str]], labels)
        if rows and isinstance(rows[0], Sequence) and not isinstance(rows[0], str):
            row = cast(Sequence[int | str], rows[0])
        else:
            row = cast(Sequence[int | str], rows)
        label2id = self._label2id()
        values = [
            label2id[self._normalize_input_label(item)]
            if isinstance(item, str)
            else int(item)
            for item in row
        ]
        return torch.tensor([values], dtype=torch.long)

    def _bbox_to_tensor(
        self,
        bbox: Float[torch.Tensor, "..."]
        | Sequence[Sequence[Sequence[float | int]]]
        | Sequence[Sequence[float | int]]
        | Sequence[float | int]
        | None,
        *,
        labels: Int[torch.Tensor, "batch elements"],
        mask: Bool[torch.Tensor, "..."]
        | Sequence[Sequence[bool]]
        | Sequence[bool]
        | None,
        box_format: BoxFormat | str,
        normalized: bool,
        canvas_size: tuple[int, int],
    ) -> Float[torch.Tensor, "batch elements 4"]:
        if bbox is None:
            return torch.zeros((labels.size(0), labels.size(1), 4), dtype=torch.float32)
        bbox_t, _, _ = prepare_layout_tensors(
            bbox=bbox,
            labels=labels,
            mask=mask,
            box_format=box_format,
            normalized=normalized,
            canvas_size=canvas_size,
        )
        if bbox_t.ndim == 2:
            bbox_t = bbox_t.unsqueeze(0)
        return denormalize_boxes(bbox_t, canvas_size=canvas_size, box_format="ltwh")

    def _rect_for_condition(
        self,
        *,
        condition: ConditionType,
        label: int,
        bbox_ltwh: tuple[float, float, float, float],
        fill_index: int,
    ) -> tuple[str, int]:
        label_name = str(cast(dict[int, str], self.config.id2label)[label])
        x, y, width, height = bbox_ltwh

        if condition is ConditionType.label:
            x, y, width, height = self._fill_values(fill_index, 4)
            fill_index += 4

        elif condition is ConditionType.label_size:
            x, y = self._fill_values(fill_index, 2)
            fill_index += 2

        elif condition is ConditionType.completion:
            x, y, width, height = self._fill_values(fill_index, 4)
            fill_index += 4

        elif condition is ConditionType.refinement:
            width, height = self._fill_values(fill_index, 2)
            fill_index += 2

        elif condition in {ConditionType.content_image, ConditionType.unconditional}:
            return "", fill_index

        x, y, width, height = (
            _format_source_number(value) for value in (x, y, width, height)
        )
        return (
            RECT_TEMPLATE.format(
                label=label_name,
                x=x,
                y=y,
                width=width,
                height=height,
            ),
            fill_index,
        )

    def _fill_rect(self, index: int) -> str:
        label, x, y, width, height = self._fill_values(index + 1, 5)
        return RECT_TEMPLATE.format(label=label, x=x, y=y, width=width, height=height)

    def _fill_values(self, start: int, count: int) -> tuple[str, ...]:
        return tuple(
            FILL_TEMPLATE.format(index) for index in range(start, start + count)
        )

    def _source_condition_key(self, condition: ConditionType) -> str:
        if condition is ConditionType.label:
            return "cond_cate_to_size_pos"
        if condition is ConditionType.label_size:
            return "cond_cate_size_to_pos"
        if condition is ConditionType.completion:
            return "cond_random_mask"
        if condition is ConditionType.refinement:
            return "cond_cate_pos_to_size"
        return "unconditional"

    def _num_elements(
        self,
        num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None,
    ) -> int:
        if num_elements is None:
            return 1
        if isinstance(num_elements, torch.Tensor):
            return int(num_elements.flatten()[0].item())
        if isinstance(num_elements, Sequence) and not isinstance(num_elements, str):
            return int(cast(int, num_elements[0]))
        return int(cast(int, num_elements))

    def _label2id(self) -> dict[str, int]:
        return {
            self._normalize_input_label(label): int(index)
            for index, label in cast(dict[int, str], self.config.id2label).items()
        }

    def _normalize_input_label(self, label: int | str) -> str:
        return str(label).strip().lower().replace("_", " ")

__init__

__init__(
    image_processor: PosterLlamaImageProcessor,
    config: PosterLlamaConfig,
) -> None

Initialize processor components.

Source code in models/posterllama/src/posterllama/processing_posterllama.py
108
109
110
111
112
113
114
115
116
def __init__(
    self,
    image_processor: PosterLlamaImageProcessor,
    config: PosterLlamaConfig,
) -> None:
    """Initialize processor components."""
    self.image_processor = image_processor
    self.config = config
    super().__init__(image_processor)

from_config classmethod

from_config(
    config: PosterLlamaConfig,
) -> "PosterLlamaProcessor"

Create a processor from an explicit config.

Parameters:

Name Type Description Default
config PosterLlamaConfig

Processor configuration.

required

Returns:

Type Description
'PosterLlamaProcessor'

PosterLlamaProcessor instance.

Examples:

>>> PosterLlamaProcessor.from_config(PosterLlamaConfig()).config.model_type
'posterllama'
Source code in models/posterllama/src/posterllama/processing_posterllama.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@classmethod
def from_config(cls, config: PosterLlamaConfig) -> "PosterLlamaProcessor":
    """Create a processor from an explicit config.

    Args:
        config: Processor configuration.

    Returns:
        PosterLlamaProcessor instance.

    Examples:
        >>> PosterLlamaProcessor.from_config(PosterLlamaConfig()).config.model_type
        'posterllama'
    """
    return cls(
        image_processor=PosterLlamaImageProcessor(
            vision_encoder_repo_id=config.vision_encoder_repo_id,
        ),
        config=config,
    )

save_pretrained

save_pretrained(
    save_directory: str | PathLike[str],
    push_to_hub: bool = False,
    **kwargs: str | int | float | bool | None,
) -> None

Save processor metadata.

Parameters:

Name Type Description Default
save_directory str | PathLike[str]

Directory to write.

required
push_to_hub bool

Accepted for ProcessorMixin compatibility; ignored.

False
kwargs str | int | float | bool | None

Accepted for ProcessorMixin compatibility; ignored.

{}
Source code in models/posterllama/src/posterllama/processing_posterllama.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def save_pretrained(
    self,
    save_directory: str | PathLike[str],
    push_to_hub: bool = False,
    **kwargs: str | int | float | bool | None,
) -> None:
    """Save processor metadata.

    Args:
        save_directory: Directory to write.
        push_to_hub: Accepted for ProcessorMixin compatibility; ignored.
        kwargs: Accepted for ProcessorMixin compatibility; ignored.
    """
    _ = (push_to_hub, kwargs)
    root = Path(save_directory)
    root.mkdir(parents=True, exist_ok=True)
    self.config.save_pretrained(root)
    self.image_processor.save_pretrained(root)
    (root / "processor_config.json").write_text(
        json.dumps(
            {
                "processor_class": self.__class__.__name__,
                "image_processor_class": self.image_processor.__class__.__name__,
            },
            indent=2,
            sort_keys=True,
        ),
        encoding="utf-8",
    )

from_pretrained classmethod

from_pretrained(
    pretrained_model_name_or_path: str | PathLike[str],
    cache_dir: str | PathLike[str] | None = None,
    force_download: bool = False,
    local_files_only: bool = False,
    token: str | bool | None = None,
    revision: str = "main",
    *,
    subfolder: str | None = None,
    **kwargs: PosterLlamaImageProcessorKwarg,
) -> "PosterLlamaProcessor"

Load processor metadata.

Parameters:

Name Type Description Default
pretrained_model_name_or_path str | PathLike[str]

Checkpoint root or processor folder.

required
cache_dir str | PathLike[str] | None

Accepted for ProcessorMixin compatibility.

None
force_download bool

Accepted for ProcessorMixin compatibility.

False
local_files_only bool

Whether to avoid network access.

False
token str | bool | None

Accepted for ProcessorMixin compatibility.

None
revision str

Accepted for ProcessorMixin compatibility.

'main'
subfolder str | None

Optional processor subfolder.

None
kwargs PosterLlamaImageProcessorKwarg

Accepted for ProcessorMixin compatibility.

{}

Returns:

Type Description
'PosterLlamaProcessor'

Loaded PosterLlamaProcessor.

Source code in models/posterllama/src/posterllama/processing_posterllama.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
@classmethod
def from_pretrained(
    cls,
    pretrained_model_name_or_path: str | PathLike[str],
    cache_dir: str | PathLike[str] | None = None,
    force_download: bool = False,
    local_files_only: bool = False,
    token: str | bool | None = None,
    revision: str = "main",
    *,
    subfolder: str | None = None,
    **kwargs: PosterLlamaImageProcessorKwarg,
) -> "PosterLlamaProcessor":
    """Load processor metadata.

    Args:
        pretrained_model_name_or_path: Checkpoint root or processor folder.
        cache_dir: Accepted for ProcessorMixin compatibility.
        force_download: Accepted for ProcessorMixin compatibility.
        local_files_only: Whether to avoid network access.
        token: Accepted for ProcessorMixin compatibility.
        revision: Accepted for ProcessorMixin compatibility.
        subfolder: Optional processor subfolder.
        kwargs: Accepted for ProcessorMixin compatibility.

    Returns:
        Loaded PosterLlamaProcessor.
    """
    _ = (cache_dir, force_download, token, revision, kwargs)
    root = Path(pretrained_model_name_or_path)
    if subfolder is not None:
        root = root / subfolder
    config = PosterLlamaConfig.from_pretrained(
        root, local_files_only=local_files_only
    )
    return cls(
        image_processor=PosterLlamaImageProcessor.from_pretrained(root),
        config=config,
    )

normalize_condition_type

normalize_condition_type(
    condition_type: ConditionType | str,
) -> ConditionType

Normalize PosterLlama condition aliases.

Parameters:

Name Type Description Default
condition_type ConditionType | str

Canonical condition or PosterLlama release alias.

required

Returns:

Type Description
ConditionType

Supported canonical condition.

Raises:

Type Description
NotImplementedError

If the condition is known but unsupported.

ValueError

If the condition is unknown.

Source code in models/posterllama/src/posterllama/processing_posterllama.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def normalize_condition_type(
    self,
    condition_type: ConditionType | str,
) -> ConditionType:
    """Normalize PosterLlama condition aliases.

    Args:
        condition_type: Canonical condition or PosterLlama release alias.

    Returns:
        Supported canonical condition.

    Raises:
        NotImplementedError: If the condition is known but unsupported.
        ValueError: If the condition is unknown.
    """
    if isinstance(condition_type, str):
        alias = condition_type.lower().replace("-", "_")
        if alias in REQUEST_CONDITION_ALIASES:
            return REQUEST_CONDITION_ALIASES[alias]
    condition = normalize_condition_type(condition_type)
    if condition in UNSUPPORTED_CONDITIONS:
        raise NotImplementedError(f"PosterLlama does not support {condition}")

    if condition not in SUPPORTED_CONDITIONS:
        raise NotImplementedError(f"PosterLlama does not support {condition}")

    return condition

__call__

__call__(
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    prompt: str | Sequence[str] | None = None,
    content: Mapping[str, str | int | float | bool | None]
    | Sequence[
        Mapping[str, str | int | float | bool | None]
    ]
    | None = None,
    texts: str
    | Sequence[str]
    | Sequence[Sequence[str]]
    | None = None,
    batch_size: int = 1,
    condition_type: ConditionType
    | str = ConditionType.content_image,
    labels: Int[Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[Tensor, "..."]
    | Sequence[Sequence[Sequence[float | int]]]
    | Sequence[Sequence[float | int]]
    | Sequence[float | int]
    | None = None,
    mask: Bool[Tensor, "..."]
    | Sequence[Sequence[bool]]
    | Sequence[bool]
    | None = None,
    num_elements: int
    | Sequence[int]
    | Int[Tensor, "batch"]
    | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    return_tensors: Literal["pt"] = "pt",
) -> BatchEncoding

Encode public inputs into recipe prompt and image tensors.

Parameters:

Name Type Description Default
images ImageInput | Sequence[ImageInput] | None

Poster image inputs.

None
prompt str | Sequence[str] | None

Optional user-provided prompt text.

None
content Mapping[str, str | int | float | bool | None] | Sequence[Mapping[str, str | int | float | bool | None]] | None

Optional content metadata.

None
texts str | Sequence[str] | Sequence[Sequence[str]] | None

Optional poster text strings.

None
batch_size int

Batch size when no images are supplied.

1
condition_type ConditionType | str

Canonical condition or PosterLlama release alias.

content_image
labels Int[Tensor, '...'] | Sequence[Sequence[int | str]] | Sequence[int | str] | None

Optional element label constraints.

None
bbox Float[Tensor, '...'] | Sequence[Sequence[Sequence[float | int]]] | Sequence[Sequence[float | int]] | Sequence[float | int] | None

Optional element boxes.

None
mask Bool[Tensor, '...'] | Sequence[Sequence[bool]] | Sequence[bool] | None

Optional valid-element mask.

None
num_elements int | Sequence[int] | Int[Tensor, 'batch'] | None

Optional requested element count.

None
box_format BoxFormat | str

Input box format.

xywh
normalized bool

Whether boxes are normalized.

True
canvas_size tuple[int, int] | None

Canvas size for pixel boxes and prompt rendering.

None
return_tensors Literal['pt']

Tensor return format. Only pt is supported.

'pt'

Returns:

Type Description
BatchEncoding

BatchEncoding containing prompt strings and tensors.

Source code in models/posterllama/src/posterllama/processing_posterllama.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def __call__(
    self,
    *,
    images: ImageInput | Sequence[ImageInput] | None = None,
    prompt: str | Sequence[str] | None = None,
    content: Mapping[str, str | int | float | bool | None]
    | Sequence[Mapping[str, str | int | float | bool | None]]
    | None = None,
    texts: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
    batch_size: int = 1,
    condition_type: ConditionType | str = ConditionType.content_image,
    labels: Int[torch.Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[torch.Tensor, "..."]
    | Sequence[Sequence[Sequence[float | int]]]
    | Sequence[Sequence[float | int]]
    | Sequence[float | int]
    | None = None,
    mask: Bool[torch.Tensor, "..."]
    | Sequence[Sequence[bool]]
    | Sequence[bool]
    | None = None,
    num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
    return_tensors: Literal["pt"] = "pt",
) -> BatchEncoding:
    """Encode public inputs into recipe prompt and image tensors.

    Args:
        images: Poster image inputs.
        prompt: Optional user-provided prompt text.
        content: Optional content metadata.
        texts: Optional poster text strings.
        batch_size: Batch size when no images are supplied.
        condition_type: Canonical condition or PosterLlama release alias.
        labels: Optional element label constraints.
        bbox: Optional element boxes.
        mask: Optional valid-element mask.
        num_elements: Optional requested element count.
        box_format: Input box format.
        normalized: Whether boxes are normalized.
        canvas_size: Canvas size for pixel boxes and prompt rendering.
        return_tensors: Tensor return format. Only ``pt`` is supported.

    Returns:
        BatchEncoding containing prompt strings and tensors.
    """
    condition = self.normalize_condition_type(condition_type)
    canvas = self._resolve_canvas_size(canvas_size)
    prompt_text = self.build_prompt(
        condition_type=condition,
        prompt=prompt,
        content=content,
        texts=texts,
        labels=labels,
        bbox=bbox,
        mask=mask,
        num_elements=num_elements,
        box_format=box_format,
        normalized=normalized,
        canvas_size=canvas,
    )
    image_batch = self.image_processor(images, return_tensors=return_tensors)
    return BatchEncoding(
        {
            "pixel_values": image_batch["pixel_values"],
            "prompts": prompt_text
            if isinstance(prompt_text, list)
            else [prompt_text] * batch_size,
            "condition_type": condition,
            "canvas_size": canvas,
        }
    )

build_prompt

build_prompt(
    *,
    condition_type: ConditionType
    | str = ConditionType.content_image,
    prompt: str | Sequence[str] | None = None,
    content: Mapping[str, str | int | float | bool | None]
    | Sequence[
        Mapping[str, str | int | float | bool | None]
    ]
    | None = None,
    texts: str
    | Sequence[str]
    | Sequence[Sequence[str]]
    | None = None,
    labels: Int[Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[Tensor, "..."]
    | Sequence[Sequence[Sequence[float | int]]]
    | Sequence[Sequence[float | int]]
    | Sequence[float | int]
    | None = None,
    mask: Bool[Tensor, "..."]
    | Sequence[Sequence[bool]]
    | Sequence[bool]
    | None = None,
    num_elements: int
    | Sequence[int]
    | Int[Tensor, "batch"]
    | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
) -> str | list[str]

Build a deterministic PosterLlama HTML prompt.

Parameters:

Name Type Description Default
condition_type ConditionType | str

Canonical condition or PosterLlama release alias.

content_image
prompt str | Sequence[str] | None

Optional prompt prefix override.

None
content Mapping[str, str | int | float | bool | None] | Sequence[Mapping[str, str | int | float | bool | None]] | None

Optional content metadata included in diagnostics text.

None
texts str | Sequence[str] | Sequence[Sequence[str]] | None

Optional poster text strings.

None
labels Int[Tensor, '...'] | Sequence[Sequence[int | str]] | Sequence[int | str] | None

Optional label constraints.

None
bbox Float[Tensor, '...'] | Sequence[Sequence[Sequence[float | int]]] | Sequence[Sequence[float | int]] | Sequence[float | int] | None

Optional box constraints.

None
mask Bool[Tensor, '...'] | Sequence[Sequence[bool]] | Sequence[bool] | None

Optional valid-element mask.

None
num_elements int | Sequence[int] | Int[Tensor, 'batch'] | None

Requested element count for unconstrained slots.

None
box_format BoxFormat | str

Input box format.

xywh
normalized bool

Whether boxes are normalized.

True
canvas_size tuple[int, int] | None

Canvas size as (width, height).

None

Returns:

Type Description
str | list[str]

Prompt string or list of prompt strings.

Source code in models/posterllama/src/posterllama/processing_posterllama.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def build_prompt(
    self,
    *,
    condition_type: ConditionType | str = ConditionType.content_image,
    prompt: str | Sequence[str] | None = None,
    content: Mapping[str, str | int | float | bool | None]
    | Sequence[Mapping[str, str | int | float | bool | None]]
    | None = None,
    texts: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
    labels: Int[torch.Tensor, "..."]
    | Sequence[Sequence[int | str]]
    | Sequence[int | str]
    | None = None,
    bbox: Float[torch.Tensor, "..."]
    | Sequence[Sequence[Sequence[float | int]]]
    | Sequence[Sequence[float | int]]
    | Sequence[float | int]
    | None = None,
    mask: Bool[torch.Tensor, "..."]
    | Sequence[Sequence[bool]]
    | Sequence[bool]
    | None = None,
    num_elements: int | Sequence[int] | Int[torch.Tensor, "batch"] | None = None,
    box_format: BoxFormat | str = BoxFormat.xywh,
    normalized: bool = True,
    canvas_size: tuple[int, int] | None = None,
) -> str | list[str]:
    """Build a deterministic PosterLlama HTML prompt.

    Args:
        condition_type: Canonical condition or PosterLlama release alias.
        prompt: Optional prompt prefix override.
        content: Optional content metadata included in diagnostics text.
        texts: Optional poster text strings.
        labels: Optional label constraints.
        bbox: Optional box constraints.
        mask: Optional valid-element mask.
        num_elements: Requested element count for unconstrained slots.
        box_format: Input box format.
        normalized: Whether boxes are normalized.
        canvas_size: Canvas size as ``(width, height)``.

    Returns:
        Prompt string or list of prompt strings.
    """
    _ = content
    condition = self.normalize_condition_type(condition_type)
    canvas = self._resolve_canvas_size(canvas_size)
    base_prompt = self._first_prompt(prompt)
    text_line = self._texts_line(texts)
    known_markup = self._constraint_markup(
        condition=condition,
        labels=labels,
        bbox=bbox,
        mask=mask,
        num_elements=num_elements,
        box_format=box_format,
        normalized=normalized,
        canvas_size=canvas,
    )
    bbox_html = HTML_TEMPLATE.format(
        width=canvas[0],
        height=canvas[1],
        content=known_markup,
    )
    source_key = self._source_condition_key(condition)
    task_instruction = SOURCE_TASK_INSTRUCTIONS[self.config.dataset_name]
    if text_line:
        instruction = SOURCE_TEXT_INSTRUCTIONS[source_key].format(
            text=text_line,
            bbox_html=bbox_html,
        )
    else:
        instruction = SOURCE_INSTRUCTIONS[source_key].format(bbox_html=bbox_html)
    body = f"{base_prompt}{task_instruction}{instruction} <MID>"
    return self.config.prompt_template.format(body)

parse_output

parse_output(
    text: str,
    *,
    canvas_size: tuple[int, int] | None = None,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    return_intermediates: bool = False,
    strict: bool = False,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Float[torch.Tensor, "..."]
        | Int[torch.Tensor, "..."]
        | Bool[torch.Tensor, "..."]
        | dict[int, str]
        | list[str]
        | list[tuple[float, float, float, float]]
        | tuple[int, int]
        | str
        | int
        | float
        | bool
        | None,
    ]
)

Parse generated HTML/SVG into public layout output.

Parameters:

Name Type Description Default
text str

Generated markup.

required
canvas_size tuple[int, int] | None

Canvas size override.

None
output_type Literal['dataclass', 'dict']

Return dataclass or dictionary.

'dataclass'
return_intermediates bool

Whether to include parse diagnostics.

False
strict bool

Whether malformed rectangles raise.

False

Returns:

Type Description
LayoutGenerationOutput | dict[str, Float[Tensor, '...'] | Int[Tensor, '...'] | Bool[Tensor, '...'] | dict[int, str] | list[str] | list[tuple[float, float, float, float]] | tuple[int, int] | str | int | float | bool | None]

LayoutGenerationOutput or dictionary.

Source code in models/posterllama/src/posterllama/processing_posterllama.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def parse_output(
    self,
    text: str,
    *,
    canvas_size: tuple[int, int] | None = None,
    output_type: Literal["dataclass", "dict"] = "dataclass",
    return_intermediates: bool = False,
    strict: bool = False,
) -> (
    LayoutGenerationOutput
    | dict[
        str,
        Float[torch.Tensor, "..."]
        | Int[torch.Tensor, "..."]
        | Bool[torch.Tensor, "..."]
        | dict[int, str]
        | list[str]
        | list[tuple[float, float, float, float]]
        | tuple[int, int]
        | str
        | int
        | float
        | bool
        | None,
    ]
):
    """Parse generated HTML/SVG into public layout output.

    Args:
        text: Generated markup.
        canvas_size: Canvas size override.
        output_type: Return dataclass or dictionary.
        return_intermediates: Whether to include parse diagnostics.
        strict: Whether malformed rectangles raise.

    Returns:
        LayoutGenerationOutput or dictionary.
    """
    parsed = parse_rectangles(text, self._label2id(), strict=strict)
    canvas = canvas_size or parsed.canvas_size or self.config.canvas_size
    if canvas is None:
        raise ValueError(
            "canvas_size is required when generated SVG lacks width/height"
        )

    resolved_canvas = (int(canvas[0]), int(canvas[1]))
    output = rect_ltwh_to_output(
        parsed,
        canvas_size=resolved_canvas,
        id2label=cast(dict[int, str], self.config.id2label),
        return_intermediates=return_intermediates,
    )
    if output_type == "dict":
        return dict(output)
    if output_type != "dataclass":
        raise ValueError(f"Unsupported output_type: {output_type}")

    return output