-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgenerate_visual_intuitive.py
More file actions
4265 lines (3563 loc) · 195 KB
/
generate_visual_intuitive.py
File metadata and controls
4265 lines (3563 loc) · 195 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
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
from lxml import etree
import math
import os
from IPython.display import SVG, display
from collections import defaultdict
import random
import copy
import difflib
import inflect
# Global cache for SVG files in each directory
_svg_directory_cache = {}
# Initialize the inflect engine
p = inflect.engine()
error_message = ""
def extract_visual_language(text):
"""
Extracts the visual_language expression from the given text.
It finds the last occurrence of 'visual_language:' and extracts everything after it.
"""
keyword = "visual_language:"
last_index = text.rfind(keyword) # Find the last occurrence of 'visual_language:'
if last_index != -1:
return text[last_index:].strip() # Extract and return everything after the last occurrence
else:
return None # Return None if no match is found
def parse_dsl(dsl_str):
operations_list = ["addition", "subtraction", "multiplication", "division", "surplus", "unittrans","area"]
def split_containers(inside_str):
"""Safely splits containers or nested operations while balancing parentheses and square brackets."""
containers = []
balance_paren = 0
balance_bracket = 0
buffer = ""
for char in inside_str:
if char == "(":
balance_paren += 1
elif char == ")":
balance_paren -= 1
elif char == "[":
balance_bracket += 1
elif char == "]":
balance_bracket -= 1
if char == "," and balance_paren == 0 and balance_bracket == 0:
containers.append(buffer.strip())
buffer = ""
else:
buffer += char
if buffer:
containers.append(buffer.strip())
return containers
def recursive_parse(input_str):
"""Recursively parses operations and containers."""
input_str = " ".join(input_str.strip().split()) # Clean spaces
# func_pattern = r"(\w+)\((.*)\)"
func_pattern = r"(\w+)\s*\((.*)\)"
match = re.match(func_pattern, input_str)
if not match:
raise ValueError(f"DSL does not match the expected pattern: {input_str}")
operation, inside = match.groups() # Extract operation and content
parsed_containers = []
result_container = None
# Safely split containers
for entity in split_containers(inside):
if any(entity.startswith(op) for op in operations_list):
# Recognize and recurse into nested operations
parsed_containers.append(recursive_parse(entity))
else:
# Parse as a basic entity
entity_pattern = r"(\w+)\[(.*?)\]"
entity_match = re.match(entity_pattern, entity)
if not entity_match:
raise ValueError(f"Entity format is incorrect: {entity}")
entity_name, entity_content = entity_match.groups()
parts = [p.strip() for p in entity_content.split(',')]
entity_dict = {"name": entity_name, "item": {}}
for part in parts:
if ':' in part:
key, val = part.split(':', 1)
key, val = key.strip(), val.strip()
if key == "entity_quantity":
try:
entity_dict["item"]["entity_quantity"] = float(val)
except ValueError:
entity_dict["item"]["entity_quantity"] = 0.0 # Default to 0.0 if conversion fails
elif key == "entity_type":
entity_dict["item"]["entity_type"] = val
else:
entity_dict[key] = val
# Check if this is a result_container
if entity_name == "result_container":
result_container = entity_dict
else:
parsed_containers.append(entity_dict)
result = {"operation": operation, "containers": parsed_containers}
if result_container:
result["result_container"] = result_container
return result
return recursive_parse(dsl_str)
def remove_svg_blanks(svg_path, output_path):
# Parse the SVG
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(svg_path, parser)
root = tree.getroot()
# Namespace handling
nsmap = {"svg": "http://www.w3.org/2000/svg"}
if "xmlns" in root.attrib:
nsmap["svg"] = root.attrib["xmlns"]
# Calculate bounding box
min_x, min_y, max_x, max_y = float("inf"), float("inf"), float("-inf"), float("-inf")
for elem in root.xpath("//*[local-name()='path' or local-name()='rect' or local-name()='circle' or local-name()='line' or local-name()='polygon' or local-name()='ellipse']", namespaces=nsmap):
bbox = elem.attrib.get("d") # For paths, you might need a library like `svg.path` for accurate parsing
tag = etree.QName(elem.tag).localname
if tag in {"rect", "circle", "ellipse", "line", "polygon"}:
# Extract specific bounding attributes
if tag == "rect":
x = float(elem.attrib.get("x", 0))
y = float(elem.attrib.get("y", 0))
w = float(elem.attrib.get("width", 0))
h = float(elem.attrib.get("height", 0))
min_x = min(min_x, x)
min_y = min(min_y, y)
max_x = max(max_x, x + w)
max_y = max(max_y, y + h)
elif tag == "circle":
cx = float(elem.attrib.get("cx", 0))
cy = float(elem.attrib.get("cy", 0))
r = float(elem.attrib.get("r", 0))
min_x = min(min_x, cx - r)
min_y = min(min_y, cy - r)
max_x = max(max_x, cx + r)
max_y = max(max_y, cy + r)
# Handle other shapes like line, ellipse, etc., similarly.
# Update viewBox and dimensions
if min_x < float("inf") and min_y < float("inf"):
new_width = max_x - min_x
new_height = max_y - min_y
root.attrib["viewBox"] = f"{min_x} {min_y} {new_width} {new_height}"
root.attrib["width"] = str(new_width)
root.attrib["height"] = str(new_height)
# Write the cleaned SVG back
tree.write(output_path, pretty_print=True, xml_declaration=True, encoding="utf-8")
print(f"Cleaned SVG saved to {output_path}")
def render_svgs_from_data(output_file, resources_path, data):
global error_message
NS = "http://www.w3.org/2000/svg"
svg_root = etree.Element("svg", nsmap={None: NS})
def get_priority(op_name):
"""
Returns a numeric priority for an operation name.
Higher number => higher precedence.
"""
if op_name in ("multiplication", "division"):
return 2
elif op_name in ("addition", "subtraction"):
return 1
else:
# Default or fallback
return 0
def can_skip_same_precedence(parent_op, child_op):
"""
Returns True if we can safely omit parentheses around the child sub-expression
when the parent_op and child_op have the same precedence.
- addition is associative
- multiplication is associative
- subtraction/division are not
"""
# For addition: A + (B + C) == (A + B) + C
# For multiplication: A * (B * C) == (A * B) * C
# So skip brackets if both are addition or both are multiplication
if parent_op == "addition" and child_op == "addition":
return True
if parent_op == "multiplication" and child_op == "multiplication":
return True
return False
def extract_operations_and_containers(
node,
operations=None,
containers=None,
result_containers=None,
parent_op=None,
parent_container_name=None
):
if operations is None:
operations = []
if containers is None:
containers = []
if result_containers is None:
result_containers = []
op = node.get("operation", "")
# 1) If operation is "unittrans", just handle special logic and return
if op == "unittrans":
sub_ents = node.get("containers", [])
if len(sub_ents) == 2:
main_entity = sub_ents[0]
unit_entity = sub_ents[1]
# Example: store unit conversion info
main_entity["unittrans_unit"] = unit_entity["name"]
main_entity["unittrans_value"] = unit_entity["item"]["entity_quantity"]
containers.append(main_entity)
return operations, containers, result_containers
# 2) "comparison"? If not handled, raise or skip
if op == "comparison":
raise ValueError("We do not handle 'comparison' in this snippet")
# 3) For normal operations (like addition, subtraction, multiplication, division)
child_ents = node.get("containers", [])
my_result = node.get("result_container")
if len(child_ents) < 2:
# Not enough children to form an operation—skip
return operations, containers, result_containers
left_child = child_ents[0]
right_child = child_ents[1]
# Determine this node's container_name (if any)
if my_result and isinstance(my_result, dict):
container_name = my_result.get("container_name")
else:
container_name = None
# Decide if the entire sub-expression needs brackets
need_brackets = False
if parent_op is not None:
parent_priority = get_priority(parent_op)
current_priority = get_priority(op)
if parent_priority > current_priority:
# Strictly higher priority => definitely bracket
need_brackets = True
elif parent_priority == current_priority:
print("container_name: ", container_name)
print("parent_container_name: ", parent_container_name)
# Possibly skip brackets if the parent/child op is associative
# and container_name is the same, etc. Tweak logic as desired:
if not can_skip_same_precedence(parent_op, op):
# It's a non-associative scenario => must bracket
need_brackets = True
# Track how many containers we already had before handling this sub-expression
start_len = len(containers)
# --- A) Handle left child ---
if "operation" in left_child:
extract_operations_and_containers(
left_child,
operations,
containers,
result_containers,
parent_op=op,
parent_container_name=container_name
)
else:
# Leaf entity
containers.append(left_child)
# --- B) Record the current operation ---
operations.append(op)
# --- C) Handle right child ---
if "operation" in right_child:
extract_operations_and_containers(
right_child,
operations,
containers,
result_containers,
parent_op=op,
parent_container_name=container_name
)
else:
# Leaf entity
containers.append(right_child)
# --- D) Mark brackets if needed ---
if need_brackets:
# The entire sub-expression is in containers[start_len:]
if len(containers) > start_len:
# Mark the first entity with bracket="left"
containers[start_len]["bracket"] = "left"
# Mark the last entity in this chunk with bracket="right"
containers[-1]["bracket"] = "right"
# --- E) If this is the top-level node (no parent_op), record the result entity ---
if parent_op is None and my_result:
if isinstance(my_result, dict):
result_containers.append(my_result)
return operations, containers, result_containers
def extract_operations_and_containers_for_comparison(data):
"""
Extract two sides (compare1 and compare2) from a top-level comparison.
We assume data["operation"] == "comparison".
Returns 6 separate lists:
compare1_operations, compare1_containers, compare1_result_containers,
compare2_operations, compare2_containers, compare2_result_containers
"""
# Make sure data["containers"] exists and has 2 items
if "containers" not in data or len(data["containers"]) < 2:
# Malformed data => Return empty
return [], [], [], [], [], []
# The first item is compare1, the second is compare2
compare1_data = data["containers"][0]
compare2_data = data["containers"][1]
# We'll parse each side with your original function
# But that function might return 2 items or 3 items depending on 'unittrans'
def safe_extract(data_piece):
ret = extract_operations_and_containers(data_piece)
if len(ret) == 2:
# Means it was (operations, containers_list) => no result containers returned
ops, ents = ret
res = []
else:
# Means it was (operations, containers_list, result_containers_list)
ops, ents, res = ret
return ops, ents, res
# 1) Parse compare1 side
if isinstance(compare1_data, dict) and "operation" in compare1_data:
compare1_ops, compare1_ents, compare1_res = safe_extract(compare1_data)
else:
# If it's just a single entity, no operation
compare1_ops = []
compare1_ents = [compare1_data]
compare1_res = []
# 2) Parse compare2 side
if isinstance(compare2_data, dict) and "operation" in compare2_data:
compare2_ops, compare2_ents, compare2_res = safe_extract(compare2_data)
else:
compare2_ops = []
compare2_ents = [compare2_data]
compare2_res = []
# Return 6 separate lists
return (
compare1_ops,
compare1_ents,
compare1_res,
compare2_ops,
compare2_ents,
compare2_res
)
# return containers
def update_container_types_optimized(containers, result_containers):
"""
Update the container_type for containers in the same group (by container_type)
when there is more than one unique container_name. In addition, treat the last
item of result_containers as one of the containers (by reference) so that its
container_type is updated if necessary.
If there is only one unique container_name for a given container_type,
leave it unchanged. Otherwise, assign a unique container_type value for each
container_name within that group.
Parameters:
containers (list): List of entity dictionaries.
result_containers (list): List of result entity dictionaries.
If non-empty, the last item will be processed along with containers.
Returns:
A tuple (containers, result_containers) where:
- containers: the original list (with updated container_type values)
- result_containers: the modified list (the last item updated as needed)
"""
# Create a temporary combined list from containers.
combined = containers[:] # shallow copy; dictionary objects remain the same
if result_containers:
# Append the last result entity (by reference) to combined.
combined.append(result_containers[-1])
# Group combined items by the original container_type.
entity_type_to_containers = defaultdict(list)
for entity in combined:
entity_type_to_containers[entity['container_type']].append(entity)
# Iterate through each container_type group.
for container_type, group in entity_type_to_containers.items():
# Group further by container_name.
name_to_containers = defaultdict(list)
for entity in group:
name_to_containers[entity['container_name']].append(entity)
# If there is only one unique container_name in this group, nothing to change.
if len(name_to_containers) <= 1:
continue
# Initialize modification index.
modification_index = 1 # for the first unique container_name, leave container_type unchanged.
# Iterate through unique container_name groups in insertion order.
for name, ent_group in name_to_containers.items():
if modification_index == 1:
# Use the original container_type for the first group.
new_entity_type = container_type
else:
new_entity_type = container_type + "-" + str(modification_index)
# Set the container_type for all containers in this group.
for entity in ent_group:
entity['container_type'] = new_entity_type
modification_index += 1
return containers, result_containers
def handle_multiplication(operations, containers, svg_root, resources_path,result_containers,start_x = 50,start_y = 150):
global error_message
print("Handling multiplication")
# We assume exactly 2 containers, where the second is the multiplier
if containers[1].get("item", {}).get("entity_quantity", 0) > 12:
print("No INTUITIVE visual can be generated because of multiplier has entity_quantity higher than 12")
error_message = "No INTUITIVE visual can be generated because of multiplier has entity_quantity higher than 12"
return
if len(containers) == 2 and containers[1]["item"].get("entity_type", "") == "multiplier":
# How many times to replicate
multiplier_val = int(containers[1]["item"].get("entity_quantity", 1))
# Make copies of the first entity
base_entity = containers[0]
replicated = []
for i in range(multiplier_val):
e_copy = copy.deepcopy(base_entity)
# Optionally tag each copy for debugging
e_copy["replica_index"] = i
replicated.append(e_copy)
containers = replicated
# Constants
UNIT_SIZE = 40
APPLE_SCALE = 0.75
ITEM_SIZE = int(UNIT_SIZE * APPLE_SCALE)
ITEM_PADDING = int(UNIT_SIZE * 0.25)
BOX_PADDING = UNIT_SIZE
OPERATOR_SIZE = 30
MAX_ITEM_DISPLAY = 10
MARGIN = 50
if any("unittrans_unit" in entity for entity in containers):
ITEM_SIZE = 3 * ITEM_SIZE
# Extract quantities and entity_types
quantities = [e["item"].get("entity_quantity", 0) for e in containers]
entity_types = [e["item"].get("entity_type", "") for e in containers]
any_multiplier = any(t == "multiplier" for t in entity_types)
any_above_20 = any(q > MAX_ITEM_DISPLAY for q in quantities)
# Determine entity layout entity_type first
for e in containers:
q = e["item"].get("entity_quantity", 0)
t = e["item"].get("entity_type", "")
container = e.get("container_type", "")
attr = e.get("attr_type", "")
if t == "multiplier":
e["layout"] = "multiplier"
elif q > MAX_ITEM_DISPLAY or q % 1 != 0:
e["layout"] = "large"
else:
if "row" in [container, attr]:
e["layout"] = "row"
elif "column" in [container, attr]:
e["layout"] = "column"
else:
e["layout"] = "normal"
# Focus on normal layout containers
normal_container = [e for e in containers if e["layout"] == "normal"]
# Compute global layout for normal containers:
# 1. Find the largest entity_quantity among normal layout containers
if normal_container:
largest_normal_q = max(e["item"].get("entity_quantity",0) for e in normal_container)
else:
largest_normal_q = 1
# 2. Compute global max_cols and max_rows for this largest normal q
if largest_normal_q > 0:
max_cols = int(math.ceil(math.sqrt(largest_normal_q)))
max_rows = (largest_normal_q + max_cols - 1) // max_cols
else:
max_cols, max_rows = 1, 1
# Assign these global cols and rows to all normal containers
for e in normal_container:
e["cols"] = max_cols
e["rows"] = max_rows
# For row/column containers and large containers, compute cols/rows individually
unit_trans_padding = 0
for e in containers:
if e["layout"] == "large":
# Large scenario doesn't rely on cols/rows for layout calculation (just 1x1 effectively)
e["cols"] = 1
e["rows"] = 1
elif e["layout"] == "row":
q = e["item"].get("entity_quantity", 0)
e["cols"] = q if q > 0 else 1
e["rows"] = 1
elif e["layout"] == "column":
q = e["item"].get("entity_quantity", 0)
e["cols"] = 1
e["rows"] = q if q > 0 else 1
elif e["layout"] == "multiplier":
e["cols"] = 1
e["rows"] = 1
if e.get("unittrans_unit", ""):
unit_trans_padding = 50
# normal layout already assigned
# Compute normal box size using global max_cols and max_rows
normal_box_width = max_cols * (ITEM_SIZE + ITEM_PADDING) + BOX_PADDING
normal_box_height = max_rows * (ITEM_SIZE + ITEM_PADDING + unit_trans_padding) + BOX_PADDING
# Large scenario box dimension
largest_q = max(quantities) if quantities else 1
q_str = str(largest_q)
text_width = len(q_str)*20
# large_total_width = text_width + 10 + UNIT_SIZE + 10 + UNIT_SIZE #
large_total_width = ITEM_SIZE * 4
large_box_width = large_total_width + BOX_PADDING
# large_box_height = UNIT_SIZE + BOX_PADDING*2 + unit_trans_padding
large_box_height = ITEM_SIZE * 4 + BOX_PADDING
# Decide reference box size if large scenario or multiplier
if any_multiplier or any_above_20:
ref_box_width = max(normal_box_width, large_box_width)
ref_box_height = max(normal_box_height, large_box_height)
else:
ref_box_width = normal_box_width
ref_box_height = normal_box_height
# Compute final box size for each entity based on layout
def compute_entity_box_size(e):
q = e["item"].get("entity_quantity", 0)
t = e["item"].get("entity_type", "")
layout = e["layout"]
unit_trans_padding = 0
if layout == "multiplier":
# Multiplier: minimal width, same height as ref to align
return (UNIT_SIZE * 2, ref_box_height )
if layout == "large":
return (large_box_width, large_box_height )
elif layout == "normal":
# Use global normal box size
return (normal_box_width, normal_box_height)
elif layout == "row":
cols = e["cols"] # q items in a row
rows = 1
w = cols*(ITEM_SIZE+ITEM_PADDING)+BOX_PADDING
h = rows*(ITEM_SIZE+ITEM_PADDING)+BOX_PADDING
return (w, h)
elif layout == "column":
cols = 1
rows = e["rows"]
w = cols*(ITEM_SIZE+ITEM_PADDING)+BOX_PADDING
h = rows*(ITEM_SIZE+ITEM_PADDING)+BOX_PADDING
return (w, h)
# fallback
return (normal_box_width, normal_box_height)
for e in containers:
w,h = compute_entity_box_size(e)
e["planned_width"] = w
if e.get("unittrans_unit", ""):
e["planned_height"] = h + 50
else:
e["planned_height"] = h
# print('e["planned_width"]', e["planned_width"])
# print('e["planned_height"]', e["planned_height"])
# Position planning
# 1) Separate out repeated containers vs. multiplier
repeated_ents = [e for e in containers if e.get("layout") != "multiplier"]
container_name = containers[0].get('container_name',"")
print("container_name: ",container_name)
# 2) Decide how to lay out repeated containers in a grid
count = len(repeated_ents)
if container_name == "row":
grid_cols = 1
grid_rows = (count + grid_cols - 1) // grid_cols
elif container_name == "column":
grid_rows = 1
grid_cols = (count + grid_rows - 1) // grid_rows
elif count > 0:
grid_cols = int(math.ceil(math.sqrt(count)))
grid_rows = (count + grid_cols - 1) // grid_cols
else:
grid_cols = 1
grid_rows = 1
# Adjust how much horizontal/vertical gap between entity boxes
gap_x = 20
gap_y = 20
# start_x, start_y = 50, 150
# start_x, start_y
# We'll store the maximum X and Y for final SVG size
current_max_x = 0
current_max_y = 0
# 3) Assign positions to each repeated entity
# Add an extra (UNIT_SIZE + 5) vertical offset per row to ensure
# any top text does not collide with the entity above.
for i, e in enumerate(repeated_ents):
row = i // grid_cols
col = i % grid_cols
if i == 0:
# Compute top-left corner
x_pos = start_x
# Notice we add (UNIT_SIZE + 5) extra for each new row:
y_pos = start_y
else:
x_pos = start_x + col * (repeated_ents[i-1]["planned_width"] + gap_x)
# Notice we add (UNIT_SIZE + 5) extra for each new row:
y_pos = start_y + row * (repeated_ents[i-1]["planned_height"] + gap_y + UNIT_SIZE + 5)
e["planned_x"] = x_pos
e["planned_y"] = y_pos
e["planned_box_y"] = y_pos
# Track how far right/down we've gone
right_edge = x_pos + e["planned_width"]
bottom_edge = y_pos + e["planned_height"]
if right_edge > current_max_x:
current_max_x = right_edge
if bottom_edge > current_max_y:
current_max_y = bottom_edge
max_x, max_y = 0,0
def update_max_dimensions(x_val, y_val):
nonlocal max_x, max_y
if x_val > max_x:
max_x = x_val
if y_val > max_y:
max_y = y_val
def embed_svg(file_path, x, y, width, height):
global error_message, _svg_directory_cache
if not os.path.exists(file_path):
print("SVG file not found:", file_path)
# Get the directory and base name from the file_path
dir_path = os.path.dirname(file_path)
base_name = os.path.splitext(os.path.basename(file_path))[0]
# Use cached candidate list if available
if dir_path in _svg_directory_cache:
candidate_files = _svg_directory_cache[dir_path]
else:
candidate_files = [f for f in os.listdir(dir_path) if f.lower().endswith(".svg")]
_svg_directory_cache[dir_path] = candidate_files
# Build candidate paths
candidate_paths = [os.path.join(dir_path, f) for f in candidate_files]
found_path = None
# Helper: Try a candidate name against all files (case-insensitive)
def try_candidate(name):
for candidate in candidate_paths:
candidate_base = os.path.splitext(os.path.basename(candidate))[0]
if candidate_base.lower() == name.lower():
return candidate
return None
# 1. Try exact match using the given base_name
found_path = try_candidate(base_name)
# 2. Try using singular and plural forms using inflect
if not found_path:
singular_form = p.singular_noun(base_name) or base_name
plural_form = p.plural_noun(base_name) or base_name
for mod_name in (plural_form, singular_form):
found_path = try_candidate(mod_name)
if found_path:
break
# 3. If a hyphen exists, try matching only the part after the hyphen (and its variants)
if not found_path and "-" in base_name:
after_hyphen = base_name.split("-")[-1]
singular_after = p.singular_noun(after_hyphen) or after_hyphen
plural_after = p.plural_noun(after_hyphen) or after_hyphen
for mod_name in (after_hyphen, plural_after, singular_after):
found_path = try_candidate(mod_name)
if found_path:
break
# 4. As a last resort, use fuzzy matching to select the best candidate.
if not found_path:
candidate_bases = [os.path.splitext(f)[0] for f in candidate_files]
close_matches = difflib.get_close_matches(base_name, candidate_bases, n=1, cutoff=0.6)
if close_matches:
match = close_matches[0]
found_path = try_candidate(match)
if found_path:
file_path = found_path
print("Found alternative SVG file:", file_path)
else:
print("SVG file not found using alternative search:", file_path)
error_message = f"SVG file not found using alternative search: {file_path}"
raise FileNotFoundError(f"SVG file not found: {file_path}")
# If file_path exists now, parse and update attributes.
tree = etree.parse(file_path)
root = tree.getroot()
root.attrib["x"] = str(x)
root.attrib["y"] = str(y)
root.attrib["width"] = str(width)
root.attrib["height"] = str(height)
update_max_dimensions(x + width, y + height)
return root
def get_figure_svg_path(attr_type):
global error_message
if attr_type:
return os.path.join(resources_path, f"{attr_type}.svg")
error_message = "Cannot find figure path for attr_type: " + attr_type
print("Cannot find figure path for attr_type: ", attr_type)
return None
def embed_top_figures_and_text(parent, box_x, box_y, box_width, container_type, container_name, attr_type, attr_name):
print("calling embed_top_figures_and_text")
# print("container_type", container_type)
# print("container_name", container_name)
items = []
show_something = container_name or container_type or attr_name or attr_type
print("container_type", container_type)
if not show_something:
items.append(("text", ""))
else:
# Check if container_type exists and the corresponding SVG file is valid
if container_type:
figure_path = get_figure_svg_path(container_type)
if figure_path and os.path.exists(figure_path):
items.append(("svg", container_type))
else:
print(f"SVG for container_type '{container_type}' does not exist. Ignoring container_type.")
if container_name:
items.append(("text", container_name))
if attr_type and attr_name:
figure_path = get_figure_svg_path(attr_type)
if figure_path and os.path.exists(figure_path):
items.append(("svg", attr_type))
items.append(("text", attr_name))
total_width = 0
for idx, (t, v) in enumerate(items):
if t == "svg":
total_width += UNIT_SIZE
else:
total_width += 50
if idx < len(items) - 1:
total_width += 10
group = etree.SubElement(parent, "g")
start_x_txt = box_x + (box_width - total_width) / 2
center_y = box_y - UNIT_SIZE - 5
current_x = start_x_txt
for idx, (t, v) in enumerate(items):
if t == "svg":
figure_path = get_figure_svg_path(v)
if figure_path and os.path.exists(figure_path):
svg_el = embed_svg(figure_path, x=current_x, y=center_y, width=UNIT_SIZE, height=UNIT_SIZE)
# Append the returned svg element to the group
group.append(svg_el)
current_x += UNIT_SIZE
else:
text_y = center_y + UNIT_SIZE / 2
text_element = etree.SubElement(group, "text", x=str(current_x), y=str(text_y),
style="font-size: 15px;", dominant_baseline="middle")
text_element.text = v
current_x += 50
if idx < len(items) - 1:
current_x += 10
def draw_entity(e):
print('new entity:', e)
q = e["item"].get("entity_quantity", 0)
t = e["item"].get("entity_type", "apple")
container_name = e.get("container_name", "").strip()
container_type = e.get("container_type", "").strip()
attr_name = e.get("attr_name", "").strip()
attr_type = e.get("attr_type", "").strip()
# UnitTrans-specific attributes
unittrans_unit = e.get("unittrans_unit", "")
unittrans_value = e.get("unittrans_value", "")
x = e["planned_x"]
y = e["planned_y"]
box_y = e["planned_box_y"]
box_y = e["planned_box_y"]
w = e["planned_width"]
h = e["planned_height"]
layout = e["layout"]
cols = e["cols"]
rows = e["rows"]
q = float(q)
if layout == "multiplier":
if q.is_integer():
q_str = str(int(q)) # Convert to integer
else:
q_str = str(q) # Keep as is
text_x = x
# Adjust text_y to align with operator
text_y = start_y + (containers[0]["planned_height"] / 2) - (OPERATOR_SIZE / 2) + 30
text_element = etree.SubElement(svg_root, "text", x=str(text_x), y=str(text_y),
style="font-size: 50px;", dominant_baseline="middle")
text_element.text = q_str
update_max_dimensions(text_x + len(q_str)*30, text_y + 50)
return
# Draw box
etree.SubElement(svg_root, "rect", x=str(x), y=str(box_y),
width=str(w), height=str(h), stroke="black", fill="none")
update_max_dimensions(x + w, y + h)
# Embed text or figures at the top of each entity box
embed_top_figures_and_text(svg_root, x, box_y, w, container_type, container_name, attr_type, attr_name)
if layout == "large":
# Large scenario
q = float(q)
if q.is_integer():
q_str = str(int(q)) # Convert to integer
else:
q_str = str(q) # Keep as is
tw = len(q_str)*20
total_width = ITEM_SIZE * 4
start_x_line = x + (w - total_width)/2
svg_x = start_x_line
center_y_line = y + (h - UNIT_SIZE)/2
svg_y = center_y_line - 1.5 * ITEM_SIZE
svg_y = y + ITEM_PADDING
text_y = y + ITEM_PADDING + 2.4 * ITEM_SIZE
text_x = svg_x+ITEM_SIZE*1.
unit_trans_padding = 50 if unittrans_unit else 0
svg_y = svg_y + unit_trans_padding
# Add item SVG
item_svg_path = os.path.join(resources_path, f"{t}.svg")
svg_root.append(embed_svg(item_svg_path, x=svg_x, y= svg_y, width=ITEM_SIZE * 4 , height=ITEM_SIZE * 4)) #
# Add entity_quantity text
if unittrans_unit and unittrans_value is not None:
text_element = etree.SubElement(svg_root, "text", x=str(text_x),
y=str(text_y),
style="font-size: 100px; fill: white; font-weight: bold; stroke: black; stroke-width: 2px;", dominant_baseline="middle")
else:
text_element = etree.SubElement(svg_root, "text", x=str(text_x),
y=str(text_y),
style="font-size: 45px; fill: white; font-weight: bold; stroke: black; stroke-width: 2px;", dominant_baseline="middle")
text_element.text = q_str
update_max_dimensions(start_x_line + tw, center_y_line + 40)
if unittrans_unit and unittrans_value is not None:
# Define circle position
circle_radius = 30
unit_trans_padding = 50
# circle_center_x = item_x + ITEM_SIZE -5
# item_x = x + BOX_PADDING / 2 + ITEM_SIZE + ITEM_PADDING
item_x = start_x_line
item_y = y + BOX_PADDING / 2 + ITEM_SIZE + ITEM_PADDING + unit_trans_padding
circle_center_x = x + 2 * ITEM_SIZE
circle_center_y = svg_y - circle_radius # Above the top-right corner of the item
# Add purple circle
etree.SubElement(svg_root, "circle", cx=str(circle_center_x), cy=str(circle_center_y),
r=str(circle_radius), fill="#BBA7F4")
unittrans_text = f"{unittrans_value}"
text_element = etree.SubElement(svg_root, "text",
x=str(circle_center_x-15), #
y=str(circle_center_y + 5), # Center text vertically
style="font-size: 15px;",
text_anchor="middle", # Center align text
dominant_baseline="middle") # Center align text vertically
text_element.text = unittrans_text
else:
# Use global cols and rows for normal, row, column layouts
if layout in ["normal", "row", "column"]:
item_svg_path = os.path.join(resources_path, f"{t}.svg")
# Draw the item
for i in range(int(q)):
row = i // cols
col = i % cols
unit_trans_padding = 0
if unittrans_unit:
unit_trans_padding = 50
item_x = x + BOX_PADDING / 2 + col * (ITEM_SIZE + ITEM_PADDING)
if row == 0:
item_y = y + BOX_PADDING / 2 + unit_trans_padding
else:
item_y = y + BOX_PADDING / 2 + row * (ITEM_SIZE + ITEM_PADDING + unit_trans_padding) + unit_trans_padding
# Draw the item
svg_root.append(embed_svg(item_svg_path, x=item_x, y=item_y, width=ITEM_SIZE, height=ITEM_SIZE))
# Cross colors (use predefined and fallback to random colors if needed)
cross_colors = ["black", "red", "blue"]
used_colors = set()
# Iterate through each subtrahend
for idx, sub_entity_quantity in enumerate(e.get("subtrahend_entity_quantity", [])):
color = cross_colors[idx] if idx < len(cross_colors) else f"#{''.join([random.choice('0123456789ABCDEF') for _ in range(6)])}"
while color in used_colors: # Ensure no duplicate random colors
color = f"#{''.join([random.choice('0123456789ABCDEF') for _ in range(6)])}"
used_colors.add(color)
# Determine the number of items to cross for this subtrahend
start_cross_idx = int(q) - sum(e["subtrahend_entity_quantity"][:idx + 1]) # Start index for current subtrahend
end_cross_idx = int(q) - sum(e["subtrahend_entity_quantity"][:idx]) # End index for current subtrahend
# Apply crosses for the current subtrahend
for i in range(start_cross_idx, end_cross_idx):
row = i // cols
col = i % cols
item_x = x + BOX_PADDING / 2 + col * (ITEM_SIZE + ITEM_PADDING)
item_y = y + BOX_PADDING / 2 + row * (ITEM_SIZE + ITEM_PADDING)
# Draw horizontal line of the cross
line1 = etree.Element(
"line",
x1=str(item_x),
y1=str(item_y),