This repository was archived by the owner on Sep 15, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathserialization.py
More file actions
520 lines (454 loc) · 18.4 KB
/
Copy pathserialization.py
File metadata and controls
520 lines (454 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
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
from transforms import RelationTypes
from utils import CANVAS_SIZE, ID2LABEL, LAYOUT_DOMAIN
PREAMBLE = (
"Please generate a layout based on the given information. "
"You need to ensure that the generated layout looks realistic, with elements well aligned and avoiding unnecessary overlap.\n"
"Task Description: {}\n"
"Layout Domain: {} layout\n"
"Canvas Size: canvas width is {}px, canvas height is {}px"
)
HTML_PREFIX = """<html>
<body>
<div class="canvas" style="left: 0px; top: 0px; width: {}px; height: {}px"></div>
"""
HTML_SUFFIX = """</body>
</html>"""
HTML_TEMPLATE = """<div class="{}" style="left: {}px; top: {}px; width: {}px; height: {}px"></div>
"""
HTML_TEMPLATE_WITH_INDEX = """<div class="{}" style="index: {}; left: {}px; top: {}px; width: {}px; height: {}px"></div>
"""
class Serializer:
def __init__(
self,
input_format: str,
output_format: str,
index2label: dict,
canvas_width: int,
canvas_height: int,
add_index_token: bool = True,
add_sep_token: bool = True,
sep_token: str = "|",
add_unk_token: bool = False,
unk_token: str = "<unk>",
):
self.input_format = input_format
self.output_format = output_format
self.index2label = index2label
self.canvas_width = canvas_width
self.canvas_height = canvas_height
self.add_index_token = add_index_token
self.add_sep_token = add_sep_token
self.sep_token = sep_token
self.add_unk_token = add_unk_token
self.unk_token = unk_token
def build_input(self, data):
if self.input_format == "seq":
return self._build_seq_input(data)
elif self.input_format == "html":
return self._build_html_input(data)
else:
raise ValueError(f"Unsupported input format: {self.input_format}")
def _build_seq_input(self, data):
raise NotImplementedError
def _build_html_input(self, data):
raise NotImplementedError
def build_output(self, data, label_key="labels", bbox_key="discrete_gold_bboxes"):
if self.output_format == "seq":
return self._build_seq_output(data, label_key, bbox_key)
elif self.output_format == "html":
return self._build_html_output(data, label_key, bbox_key)
def _build_seq_output(self, data, label_key, bbox_key):
labels = data[label_key]
bboxes = data[bbox_key]
tokens = []
for idx in range(len(labels)):
label = self.index2label[int(labels[idx])]
bbox = bboxes[idx].tolist()
tokens.append(label)
if self.add_index_token:
tokens.append(str(idx))
tokens.extend(map(str, bbox))
if self.add_sep_token and idx < len(labels) - 1:
tokens.append(self.sep_token)
return " ".join(tokens)
def _build_html_output(self, data, label_key, bbox_key):
labels = data[label_key]
bboxes = data[bbox_key]
htmls = [HTML_PREFIX.format(self.canvas_width, self.canvas_height)]
_TEMPLATE = HTML_TEMPLATE_WITH_INDEX if self.add_index_token else HTML_TEMPLATE
for idx in range(len(labels)):
label = self.index2label[int(labels[idx])]
bbox = bboxes[idx].tolist()
element = [label]
if self.add_index_token:
element.append(str(idx))
element.extend(map(str, bbox))
htmls.append(_TEMPLATE.format(*element))
htmls.append(HTML_SUFFIX)
return "".join(htmls)
class GenTypeSerializer(Serializer):
task_type = "generation conditioned on given element types"
constraint_type = ["Element Type Constraint: "]
HTML_TEMPLATE_WITHOUT_ANK = '<div class="{}"></div>\n'
HTML_TEMPLATE_WITHOUT_ANK_WITH_INDEX = '<div class="{}" style="index: {}"></div>\n'
def _build_seq_input(self, data):
labels = data["labels"]
tokens = []
for idx in range(len(labels)):
label = self.index2label[int(labels[idx])]
tokens.append(label)
if self.add_index_token:
tokens.append(str(idx))
if self.add_unk_token:
tokens += [self.unk_token] * 4
if self.add_sep_token and idx < len(labels) - 1:
tokens.append(self.sep_token)
return " ".join(tokens)
def _build_html_input(self, data):
labels = data["labels"]
htmls = [HTML_PREFIX.format(self.canvas_width, self.canvas_height)]
if self.add_index_token and self.add_unk_token:
_TEMPLATE = HTML_TEMPLATE_WITH_INDEX
elif self.add_index_token and not self.add_unk_token:
_TEMPLATE = self.HTML_TEMPLATE_WITHOUT_ANK_WITH_INDEX
elif not self.add_index_token and self.add_unk_token:
_TEMPLATE = HTML_TEMPLATE
else:
_TEMPLATE = self.HTML_TEMPLATE_WITHOUT_ANK
for idx in range(len(labels)):
label = self.index2label[int(labels[idx])]
element = [label]
if self.add_index_token:
element.append(str(idx))
if self.add_unk_token:
element += [self.unk_token] * 4
htmls.append(_TEMPLATE.format(*element))
htmls.append(HTML_SUFFIX)
return "".join(htmls)
def build_input(self, data):
return self.constraint_type[0] + super().build_input(data)
class GenTypeSizeSerializer(Serializer):
task_type = "generation conditioned on given element types and sizes"
constraint_type = ["Element Type and Size Constraint: "]
HTML_TEMPLATE_WITHOUT_ANK = (
'<div class="{}" style="width: {}px; height: {}px"></div>\n'
)
HTML_TEMPLATE_WITHOUT_ANK_WITH_INDEX = (
'<div class="{}" style="index: {}; width: {}px; height: {}px"></div>\n'
)
def _build_seq_input(self, data):
labels = data["labels"]
bboxes = data["discrete_gold_bboxes"]
tokens = []
for idx in range(len(labels)):
label = self.index2label[int(labels[idx])]
bbox = bboxes[idx].tolist()
tokens.append(label)
if self.add_index_token:
tokens.append(str(idx))
if self.add_unk_token:
tokens += [self.unk_token] * 2
tokens.extend(map(str, bbox[2:]))
if self.add_sep_token and idx < len(labels) - 1:
tokens.append(self.sep_token)
return " ".join(tokens)
def _build_html_input(self, data):
labels = data["labels"]
bboxes = data["discrete_gold_bboxes"]
htmls = [HTML_PREFIX.format(self.canvas_width, self.canvas_height)]
if self.add_index_token and self.add_unk_token:
_TEMPLATE = HTML_TEMPLATE_WITH_INDEX
elif self.add_index_token and not self.add_unk_token:
_TEMPLATE = self.HTML_TEMPLATE_WITHOUT_ANK_WITH_INDEX
elif not self.add_index_token and self.add_unk_token:
_TEMPLATE = HTML_TEMPLATE
else:
_TEMPLATE = self.HTML_TEMPLATE_WITHOUT_ANK
for idx in range(len(labels)):
label = self.index2label[int(labels[idx])]
bbox = bboxes[idx].tolist()
element = [label]
if self.add_index_token:
element.append(str(idx))
if self.add_unk_token:
element += [self.unk_token] * 2
element.extend(map(str, bbox[2:]))
htmls.append(_TEMPLATE.format(*element))
htmls.append(HTML_SUFFIX)
return "".join(htmls)
def build_input(self, data):
return self.constraint_type[0] + super().build_input(data)
class GenRelationSerializer(Serializer):
task_type = (
"generation conditioned on given element relationships\n"
"'A left B' means that the center coordinate of A is to the left of the center coordinate of B. "
"'A right B' means that the center coordinate of A is to the right of the center coordinate of B. "
"'A top B' means that the center coordinate of A is above the center coordinate of B. "
"'A bottom B' means that the center coordinate of A is below the center coordinate of B. "
"'A center B' means that the center coordinate of A and the center coordinate of B are very close. "
"'A smaller B' means that the area of A is smaller than the ares of B. "
"'A larger B' means that the area of A is larger than the ares of B. "
"'A equal B' means that the area of A and the ares of B are very close. "
"Here, center coordinate = (left + width / 2, top + height / 2), "
"area = width * height"
)
constraint_type = ["Element Type Constraint: ", "Element Relationship Constraint: "]
HTML_TEMPLATE_WITHOUT_ANK = '<div class="{}"></div>\n'
HTML_TEMPLATE_WITHOUT_ANK_WITH_INDEX = '<div class="{}" style="index: {}"></div>\n'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.index2type = RelationTypes.index2type()
def _build_seq_input(self, data):
labels = data["labels"]
relations = data["relations"]
tokens = []
for idx in range(len(labels)):
label = self.index2label[int(labels[idx])]
tokens.append(label)
if self.add_index_token:
tokens.append(str(idx))
if self.add_unk_token:
tokens += [self.unk_token] * 4
if self.add_sep_token and idx < len(labels) - 1:
tokens.append(self.sep_token)
type_cons = " ".join(tokens)
if len(relations) == 0:
return self.constraint_type[0] + type_cons
tokens = []
for idx in range(len(relations)):
label_i = relations[idx][2]
index_i = relations[idx][3]
if label_i != 0:
tokens.append("{} {}".format(self.index2label[int(label_i)], index_i))
else:
tokens.append("canvas")
tokens.append(self.index2type[int(relations[idx][4])])
label_j = relations[idx][0]
index_j = relations[idx][1]
if label_j != 0:
tokens.append("{} {}".format(self.index2label[int(label_j)], index_j))
else:
tokens.append("canvas")
if self.add_sep_token and idx < len(relations) - 1:
tokens.append(self.sep_token)
relation_cons = " ".join(tokens)
return (
self.constraint_type[0]
+ type_cons
+ "\n"
+ self.constraint_type[1]
+ relation_cons
)
def _build_html_input(self, data):
labels = data["labels"]
relations = data["relations"]
htmls = [HTML_PREFIX.format(self.canvas_width, self.canvas_height)]
if self.add_index_token and self.add_unk_token:
_TEMPLATE = HTML_TEMPLATE_WITH_INDEX
elif self.add_index_token and not self.add_unk_token:
_TEMPLATE = self.HTML_TEMPLATE_WITHOUT_ANK_WITH_INDEX
elif not self.add_index_token and self.add_unk_token:
_TEMPLATE = HTML_TEMPLATE
else:
_TEMPLATE = self.HTML_TEMPLATE_WITHOUT_ANK
for idx in range(len(labels)):
label = self.index2label[int(labels[idx])]
element = [label]
if self.add_index_token:
element.append(str(idx))
if self.add_unk_token:
element += [self.unk_token] * 4
htmls.append(_TEMPLATE.format(*element))
htmls.append(HTML_SUFFIX)
type_cons = "".join(htmls)
if len(relations) == 0:
return self.constraint_type[0] + type_cons
tokens = []
for idx in range(len(relations)):
label_i = relations[idx][2]
index_i = relations[idx][3]
if label_i != 0:
tokens.append("{} {}".format(self.index2label[int(label_i)], index_i))
else:
tokens.append("canvas")
tokens.append(self.index2type[int(relations[idx][4])])
label_j = relations[idx][0]
index_j = relations[idx][1]
if label_j != 0:
tokens.append("{} {}".format(self.index2label[int(label_j)], index_j))
else:
tokens.append("canvas")
if self.add_sep_token and idx < len(relations) - 1:
tokens.append(self.sep_token)
relation_cons = " ".join(tokens)
return (
self.constraint_type[0]
+ type_cons
+ "\n"
+ self.constraint_type[1]
+ relation_cons
)
class CompletionSerializer(Serializer):
task_type = "layout completion"
constraint_type = ["Partial Layout: "]
def _build_seq_input(self, data):
data["partial_labels"] = data["labels"][:1]
data["partial_bboxes"] = data["discrete_bboxes"][:1, :]
return self._build_seq_output(data, "partial_labels", "partial_bboxes")
def _build_html_input(self, data):
data["partial_labels"] = data["labels"][:1]
data["partial_bboxes"] = data["discrete_bboxes"][:1, :]
return self._build_html_output(data, "partial_labels", "partial_bboxes")
def build_input(self, data):
return self.constraint_type[0] + super().build_input(data)
class RefinementSerializer(Serializer):
task_type = "layout refinement"
constraint_type = ["Noise Layout: "]
def _build_seq_input(self, data):
return self._build_seq_output(data, "labels", "discrete_bboxes")
def _build_html_input(self, data):
return self._build_html_output(data, "labels", "discrete_bboxes")
def build_input(self, data):
return self.constraint_type[0] + super().build_input(data)
class ContentAwareSerializer(Serializer):
task_type = (
"content-aware layout generation\n"
"Please place the following elements to avoid salient content, and underlay must be the background of text or logo."
)
constraint_type = ["Content Constraint: ", "Element Type Constraint: "]
CONTENT_TEMPLATE = "left {}px, top {}px, width {}px, height {}px"
def _build_seq_input(self, data):
labels = data["labels"]
content_bboxes = data["discrete_content_bboxes"]
tokens = []
for idx in range(len(content_bboxes)):
content_bbox = content_bboxes[idx].tolist()
tokens.append(self.CONTENT_TEMPLATE.format(*content_bbox))
if self.add_index_token and idx < len(content_bboxes) - 1:
tokens.append(self.sep_token)
content_cons = " ".join(tokens)
tokens = []
for idx in range(len(labels)):
label = self.index2label[int(labels[idx])]
tokens.append(label)
if self.add_index_token:
tokens.append(str(idx))
if self.add_unk_token:
tokens += [self.unk_token] * 4
if self.add_sep_token and idx < len(labels) - 1:
tokens.append(self.sep_token)
type_cons = " ".join(tokens)
return (
self.constraint_type[0]
+ content_cons
+ "\n"
+ self.constraint_type[1]
+ type_cons
)
class TextToLayoutSerializer(Serializer):
task_type = (
"text-to-layout\n"
"There are ten optional element types, including: image, icon, logo, background, title, description, text, link, input, button. "
"Please do not exceed the boundaries of the canvas. "
"Besides, do not generate elements at the edge of the canvas, that is, reduce top: 0px and left: 0px predictions as much as possible."
)
constraint_type = ["Text: "]
def _build_seq_input(self, data):
return data["text"]
def build_input(self, data):
return self.constraint_type[0] + super().build_input(data)
SERIALIZER_MAP = {
"gent": GenTypeSerializer,
"gents": GenTypeSizeSerializer,
"genr": GenRelationSerializer,
"completion": CompletionSerializer,
"refinement": RefinementSerializer,
"content": ContentAwareSerializer,
"text": TextToLayoutSerializer,
}
def create_serializer(
dataset,
task,
input_format,
output_format,
add_index_token,
add_sep_token,
add_unk_token,
):
serializer_cls = SERIALIZER_MAP[task]
index2label = ID2LABEL[dataset]
canvas_width, canvas_height = CANVAS_SIZE[dataset]
serializer = serializer_cls(
input_format=input_format,
output_format=output_format,
index2label=index2label,
canvas_width=canvas_width,
canvas_height=canvas_height,
add_index_token=add_index_token,
add_sep_token=add_sep_token,
add_unk_token=add_unk_token,
)
return serializer
def build_prompt(
serializer,
exemplars,
test_data,
dataset,
max_length=8000,
separator_in_samples="\n",
separator_between_samples="\n\n",
):
prompt = [
PREAMBLE.format(
serializer.task_type, LAYOUT_DOMAIN[dataset], *CANVAS_SIZE[dataset]
)
]
for i in range(len(exemplars)):
_prompt = (
serializer.build_input(exemplars[i])
+ separator_in_samples
+ serializer.build_output(exemplars[i])
)
if len(separator_between_samples.join(prompt) + _prompt) <= max_length:
prompt.append(_prompt)
else:
break
prompt.append(serializer.build_input(test_data) + separator_in_samples)
return separator_between_samples.join(prompt)
if __name__ == "__main__":
import torch
from utils import ID2LABEL
ls = RefinementSerializer(
input_format="seq",
output_format="html",
index2label=ID2LABEL["publaynet"],
canvas_width=120,
canvas_height=160,
add_sep_token=True,
add_unk_token=False,
add_index_token=True,
)
labels = torch.tensor([4, 4, 1, 1, 1, 1])
bboxes = torch.tensor(
[
[29, 14, 59, 2],
[10, 18, 99, 57],
[10, 79, 99, 4],
[10, 85, 99, 7],
[10, 99, 47, 50],
[61, 99, 47, 50],
]
)
rearranged_labels = torch.tensor([1, 4, 1, 4, 1, 1])
relations = torch.tensor([[4, 1, 0, 1, 4], [1, 2, 1, 3, 2]])
data = {
"labels": labels,
"discrete_bboxes": bboxes,
"discrete_gold_bboxes": bboxes,
"relations": relations,
"rearranged_labels": rearranged_labels,
}
print("--------")
print(ls.build_input(data))
print("--------")
print(ls.build_output(data))