-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathserver.py
2612 lines (2126 loc) · 92.2 KB
/
server.py
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
import os
import sys
import copy
import uuid
import glob
import json
import html
import shutil
import hashlib
import operator
import functools
import itertools
import subprocess
from collections import defaultdict, Counter
from dataclasses import dataclass
from functools import lru_cache
import tabulate
import pydot
import pysolr
import markdown
import bs4
# we depend on dictionaries with insertion order
assert sys.version_info[0:2] >= (3, 6)
def BeautifulSoup(*args):
return bs4.BeautifulSoup(*args, features="lxml")
import flask
from flask import (
Flask,
send_file,
render_template,
render_template_string,
abort,
url_for,
request,
send_from_directory,
jsonify,
g as X
)
import md as mdp
from extract_concepts_from_xmi import parse_bindings
app = Flask(__name__)
is_iso = os.environ.get('ISO', '0') == '1'
is_package = os.environ.get('PACKAGE', '0') == '1'
if is_package:
base = "/HTML"
else:
base = "/IFC/RELEASE/IFC4x3/HTML"
def make_url(fragment=None):
return base + "/" + fragment if fragment else "/"
identity = lambda x: x
REPO_DIR = os.path.abspath(os.environ.get("REPO_DIR", os.path.join(os.path.dirname(__file__), "..")))
REPO_BRANCH = os.environ.get("REPO_BRANCH", "master")
class schema_resource:
def __init__(self, path, transform=identity):
self.path = path
self.transform = transform
self.mtime = 0
self.data = None
def load(fn):
def inner(self, *args):
try:
mt = os.path.getmtime(self.path)
if mt > self.mtime:
self.data = self.transform(json.load(open(self.path, encoding="utf-8")))
self.mtime = mt
except:
print("Path", self.path, "not available")
abort(503)
return fn(self, *args)
return inner
@load
def __getitem__(self, k):
return self.data[k]
@load
def __contains__(self, k):
return k in self.data
@load
def get(self, k, default=None):
return self.data.get(k, default)
@load
def items(self):
return self.data.items()
@load
def keys(self):
return self.data.keys()
@load
def values(self):
return self.data.values()
class resource_manager:
entity_attributes = schema_resource("entity_attributes.json")
entity_definitions = schema_resource("entity_definitions.json")
entity_to_package = schema_resource("entity_to_package.json")
entity_supertype = schema_resource("entity_supertype.json")
entity_where_clauses = schema_resource("entity_where_clauses.json")
pset_definitions = schema_resource("pset_definitions.json")
changes_by_type = schema_resource("changes_by_type.json")
deprecated_entities = schema_resource("deprecated_entities.json", transform=set)
abstract_entities = schema_resource("abstract_entities.json", transform=set)
type_values = schema_resource("type_values.json")
hierarchy = schema_resource("hierarchy.json")
xmi_concepts = schema_resource("xmi_concepts.json")
xmi_mvd_concepts = schema_resource("xmi_mvd_concepts.json")
examples_by_type = schema_resource("examples_by_type.json")
mvd_entity_usage = schema_resource("mvd_entity_usage.json")
listing_references = schema_resource("listing_references.json")
listing_tables = schema_resource("listing_tables.json")
listing_figures = schema_resource("listing_figures.json")
R = resource_manager()
def resource_paths(pairs, path=None):
if isinstance(pairs, dict):
pairs = list(pairs.items())
if isinstance(pairs[0], str):
for v in pairs:
yield v, path
return
for p, vs in pairs:
yield from resource_paths(vs, (path or ()) + ((p.split(" ")[0].lower() if path is None else p),))
def get_resource_path(resource, abort_on_error=True):
v = dict(resource_paths(R.hierarchy)).get(resource)
if not v:
if abort_on_error:
return abort(404)
else:
return None
return (
os.path.join(REPO_DIR, "docs/schemas", *v, resource + ".md")
.replace("Property Sets", "PropertySets")
.replace("Quantity Sets", "QuantitySets")
.replace("Rules", "GlobalRules")
)
navigation = [
[
{"name": "Cover", "url": make_url()},
{"name": "Contents", "url": make_url("toc.html")},
{"name": "Foreword", "url": make_url("content/foreword.htm")},
{"name": "Introduction", "url": make_url("content/introduction.htm")},
],
[
{"number": 1, "name": "Scope", "url": make_url("content/scope.htm")},
{"number": 2, "name": "Normative references", "url": make_url("content/normative_references.htm")},
{
"number": 3,
"name": "Terms, definitions, and abbreviated terms",
"url": make_url("content/terms_and_definitions.htm"),
},
{"number": 4, "name": "Fundamental concepts and assumptions", "url": make_url("concepts/content.html")},
{"number": 5, "name": "Core data schemas", "url": make_url("chapter-5/")},
{"number": 6, "name": "Shared element data schemas", "url": make_url("chapter-6/")},
{"number": 7, "name": "Domain specific data schemas", "url": make_url("chapter-7/")},
{"number": 8, "name": "Resource definition data schemas", "url": make_url("chapter-8/")},
],
[
{"number": "A", "name": "Computer interpretable listings", "url": make_url("annex-a.html")},
{"number": "B", "name": "Alphabetical listings", "url": make_url("annex-b.html")},
{"number": "C", "name": "Inheritance listings", "url": make_url("annex-c.html")},
{"number": "D", "name": "Diagrams", "url": make_url("annex-d.html")},
{"number": "E", "name": "Examples", "url": make_url("annex-e.html")},
{"number": "F", "name": "Change logs", "url": make_url("annex-f.html")},
],
[
{"name": "Bibliography", "url": make_url("content/bibliography.htm")},
# What is this? It's a broken link.
{"name": "Index", "url": make_url("index.htm")},
],
]
annex_b_navigation = [
{"number": "B.1", "name": "Entities", "url": make_url("annex-b1.html")},
{"number": "B.2", "name": "Types", "url": make_url("annex-b2.html")},
{"number": "B.3", "name": "Property sets", "url": make_url("annex-b3.html")},
{"number": "B.4", "name": "Properties", "url": make_url("annex-b4.html")},
{"number": "B.5", "name": "Functions", "url": make_url("annex-b5.html")},
{"number": "B.6", "name": "Rules", "url": make_url("annex-b6.html")},
{"number": "B.7", "name": "Property Enumerations", "url": make_url("annex-b7.html")},
]
def get_navigation(resource=None, number=None):
if not number and resource:
number = name_to_number()[resource]
numbers = []
if isinstance(number, str):
numbers = number.split(".")
number = int(numbers[0])
for section in navigation:
for item in section:
item["subitems"] = []
if item["url"] == request.path:
item["is_current"] = True
elif number and item.get("number", None) == number:
item["is_current"] = True
if number in (5, 6, 7, 8) and len(numbers) >= 2:
subchapters = [items for t, items in R.hierarchy if t == item["name"]][0]
for i, subchapter in enumerate(subchapters, 1):
data = {
"url": url_for("schema", name=subchapter[0].lower()),
"number": f"{number}.{i}",
"name": subchapter[0],
}
if i == int(numbers[1]):
data["is_current"] = True
item["subitems"].append(data)
elif "annex-b" in request.path and item.get("number", None) == "B":
item["is_current"] = True
for subitem in copy.deepcopy(annex_b_navigation):
if ("annex-" + subitem["number"]).lower().replace(".", "") in request.path:
subitem["is_current"] = True
item["subitems"].append(subitem)
else:
item["is_current"] = False
return navigation
@dataclass(order=True, eq=True, frozen=True)
class toc_entry:
text: str
number: str = None
url: str = None
parent: object = None
children: list = None
mvds: list = None
def find(self, lbl):
def traverse(te, path=None):
p = (path or []) + [te]
if te.text == lbl:
yield p
else:
for ch in (te.children or []):
yield from traverse(ch, p)
li = list(traverse(self))
if li:
return li[0][-1]
content_names = ["scope", "normative_references", "terms_and_definitions", "concepts"]
content_names_2 = ["cover", "foreword", "introduction", "bibliography"]
def chapter_lookup(number=None, cat=None):
def do_chapter_lookup(x):
if isinstance(x, (list, tuple)):
return next((v for v in map(do_chapter_lookup, x) if v is not None), None)
if number is not None and x.get("number", None) == number:
return x
if cat is not None and x["name"].split(" ")[0].lower() == cat:
return x
return do_chapter_lookup(navigation)
entity_names = lambda: sorted(sum([schema.get("Entities", []) for _, cat in R.hierarchy for __, schema in cat], []))
function_names = lambda: sorted(sum([schema.get("Functions", []) for _, cat in R.hierarchy for __, schema in cat], []))
rule_names = lambda: sorted(sum([schema.get("Rules", []) for _, cat in R.hierarchy for __, schema in cat], []))
type_names = lambda: sorted(sum([schema.get("Types", []) for _, cat in R.hierarchy for __, schema in cat], []))
propertyenumeration_names = lambda: sorted(sum([schema.get("PropertyEnumerations", []) for _, cat in R.hierarchy for __, schema in cat], []))
@lru_cache()
def name_to_number():
ntn = {}
for i, (cat, schemas) in enumerate(R.hierarchy, start=5):
for j, (schema_name, members) in enumerate(schemas, start=1):
for k, ke in enumerate(
["Types", "Entities", "Property Sets", "Quantity Sets", "Functions", "Rules", "PropertyEnumerations"], start=2
):
for l, name in enumerate(members.get(ke, ()), start=1):
ntn[name] = ".".join(map(str, (i, j, k, l)))
return ntn
def get_inheritance_graph(current_entity):
graph = []
tier = []
for subclass in sorted([k for k, v in R.entity_supertype.items() if v == current_entity]):
tier.append(
{
"name": subclass,
"is_deprecated": subclass in R.deprecated_entities,
"is_abstract": subclass in R.abstract_entities,
"is_subclass": True,
}
)
if tier:
graph.append(tier)
previous = None
entity = current_entity
while entity:
tier = []
parent = R.entity_supertype.get(entity, None)
if parent:
siblings = sorted([k for k, v in R.entity_supertype.items() if v == parent])
else:
siblings = [entity]
for sibling in siblings:
data = {
"name": sibling,
"is_deprecated": sibling in R.deprecated_entities,
"is_abstract": sibling in R.abstract_entities,
"is_current": sibling == current_entity,
"is_ancestor": sibling == entity,
}
if data["is_current"] or data["is_ancestor"]:
tier.insert(0, data)
else:
tier.append(data)
graph.append(tier)
entity, old = R.entity_supertype.get(entity), entity
return reversed(graph)
def get_node_type(n):
try:
n = n.replace("<br />", "")
n = re.findall(r'Ifc\w+', n)[0]
except:
return "attribute"
if n not in R.entity_definitions:
return "attribute"
def is_relationship(ty=n):
if ty == "IfcRelationship" or ty == "IfcResourceLevelRelationship":
return True
ty = R.entity_supertype.get(ty)
if ty:
return is_relationship(ty)
return False
return "relationship" if is_relationship() else "entity"
def transform_graph(current_entity, graph_data, only_urls=False):
graphs = pydot.graph_from_dot_data(graph_data)
# collect all node names to see if we need to insert args in cluster
all_nodes = set()
def collect_nodes(g):
all_nodes.update(n.get_name() for n in g.get_nodes())
for sg in g.get_subgraphs():
collect_nodes(sg)
for graph in graphs:
collect_nodes(graph)
# now visit graph and decorate nodes
def visit_graph(g):
names_seen = {}
edge_nodes_in_cluster = set()
for e in g.get_edges():
edge_nodes_in_cluster.add(e.get_source())
edge_nodes_in_cluster.add(e.get_destination())
# add nodes to cluster that aren't explicitly declared
# in the graph
for n in edge_nodes_in_cluster - all_nodes:
g.add_node(pydot.Node(n))
for n in list(g.get_nodes()):
nm = n.get_label() or n.get_name()
if nm == '"\\n"':
# not sure where this comes from, some artefact
# of the pydot parsing, but it can't be reproduced
# consistently
g.del_node(n)
continue
if nm in {"graph", "edge", "node"}:
continue
if not only_urls:
if n.get_name() in names_seen:
# rank=same groupings otherwise cause
# node names to be listed twice
args = names_seen[n.get_name()]
else:
node_type = get_node_type(nm)
args = {
"shape": "box",
"style": "filled",
"penwidth": 0.2,
"width": 2,
"height": 0.5,
"color": "#000000",
}
if node_type == "entity":
args["fillcolor"] = "#1976d2"
elif node_type == "relationship":
args["fillcolor"] = "#E9D758"
else:
args["style"] = ""
args["shape"] = "plain"
# A pipe is the symbol for a table
if "|" in nm:
# Experimenting with "Mrecord" incase it looks nicer
args["shape"] = "record"
if nm.strip('"').split(" ")[0] == current_entity:
args["fillcolor"] = "#1976d2"
args["penwidth"] = "1"
names_seen[n.get_name()] = args
for kv in args.items():
n.set(*kv)
if nm.startswith("Ifc"):
n.set("URL", url_for("resource", resource=nm, _external=True))
for sg in g.get_subgraphs():
visit_graph(sg)
for graph in graphs:
visit_graph(graph)
return graph.to_string()
def process_graphviz(current_entity, md):
def is_figure(s):
if "dot_figure" in s:
return 1
elif "dot_inheritance" in s:
return 2
elif "dot_neato" in s:
return 3
else:
return 0
is_markdown = True
graphviz_code = list(filter(is_figure, re.findall("```(.*?)```", md or "", re.S)))
# This is a hack to allow markdown that is already in HTML to still get diagrams generated.
if not graphviz_code:
is_markdown = False
graphviz_code = filter(is_figure, re.findall("<pre><code>(.*?)</code></pre>", md or "", re.S))
for c in graphviz_code:
if not is_markdown:
escaped_c = c
c = html.unescape(c)
layout_engine = "dot"
if is_figure(c) == 3:
layout_engine = "neato"
hash = hashlib.sha256(c.encode("utf-8")).hexdigest()
fn = os.path.join("svgs", current_entity + "_" + hash + ".dot")
c2 = transform_graph(current_entity, c, only_urls=is_figure(c) == 2)
with open(fn, "w") as f:
f.write(c2)
if is_markdown:
md = md.replace("```%s```" % c, "" % (current_entity, hash))
else:
md = md.replace("<pre><code>%s</code></pre>" % escaped_c, "" % (current_entity, hash))
subprocess.call([
shutil.which("dot") or "dot",
f"-K{layout_engine}",
"-O",
"-Tsvg",
"-n2",
#"-Gsize=10,8",
"-Gbgcolor=#ffffff00",
"-Earrowsize=0.5",
"-Earrowhead=dot",
fn
])
return md or ""
def create_entity_definition(e, bindings, ports):
# unique name (postfix for multiple occurrences, can have template bindings)
EE = e
# schema name, updated when traversing supertypes
e = e.split("_")[0]
# schema name, constant
E = e
table = []
bindings_seen = set()
def attributes_backward(e):
while e:
keys = [x for x in R.entity_attributes.keys() if x.startswith(e + ".")]
yield from list(zip(keys, map(R.entity_attributes.__getitem__, keys)))[::-1]
e = R.entity_supertype.get(e)
attributes = list(attributes_backward(E))
fwd_attr_idx = sum([is_fwd == "forward" for k, (is_fwd, ty) in attributes])
for k, (is_fwd, ty) in attributes:
if is_fwd == "derived":
# don't show them for now
continue
label = name = k.split(".")[1]
if is_fwd == "forward":
label = "%d. %s" % (fwd_attr_idx, name)
fwd_attr_idx -= 1
elif is_fwd == "inverse":
label = " %s" % name
cardinality = re.findall(r"(\[.+?\])", ty)
if cardinality:
cardinality = cardinality[0]
elif is_fwd:
cardinality = "[0:1]" if "OPTIONAL" in ty else "[1:1]"
else:
# default inverse cardinality
cardinality = "[1:1]"
binding = bindings.get((EE, name), "")
if binding:
table.append({"label": label, "name": name, "cardinality": cardinality, "is_bound": True, "is_port": name in ports})
bindings_seen.add((EE, name))
table.append({"label": binding, "name": binding, "is_binding": True})
else:
table.append({"label": label, "name": name, "cardinality": cardinality, "is_port": name in ports})
is_first = True
for (ent, attr), binding in bindings.items():
if ent != EE:
continue
if (ent, attr) in bindings_seen:
continue
if is_first:
table.insert(0, {"label": "...", "name": "..."})
table.insert(0, {"label": binding, "name": binding, "is_binding": True})
table.insert(0, {"label": attr, "name": attr, "is_bound": True, "is_port": attr in ports})
is_first = False
table.append({"label": E, "name": E, "is_title": True})
table = table[::-1]
html = '<<table border="0" cellborder="1" cellspacing="0" cellpadding="5px">'
for row in table:
height = 18
align = "left"
is_bold = False
bgcolor = "white"
color = "#333333"
if row.get("is_title"):
bgcolor = "#1976d2"
color = "white"
is_bold = True
if row.get("is_binding"):
is_bold = True
align = "center"
bgcolor = "#eeeeee"
if row.get("is_bound"):
bgcolor = "#eeeeee"
if row.get("is_port"):
bgcolor = "#dddddd"
name = row["name"]
html += '<tr>'
html += f'<td sides="b" width="250" height="{height}" bgcolor="{bgcolor}" align="{align}" port="{name}0">'
if is_bold:
html += '<b>'
html += f'<font color="{color}">{row["label"]}</font>'
if is_bold:
html += '</b>'
html += '</td>'
html += f'<td sides="b" width="20" height="{height}" bgcolor="{bgcolor}" align="right" port="{name}1">'
html += row.get("cardinality", "")
html += '</td>'
html += '</tr>'
html += '</table>>'
return html
def process_graphviz_concept(name, md):
graphviz_code = filter(lambda s: s.strip().startswith("concept"), re.findall("```(.*?)```", md, re.S))
def replace_edge(match):
is_direct_attribute = True
entity = match.group(1).split('_')[0]
attribute = match.group(2)
while entity:
data = R.entity_attributes.get(f"{entity}.{attribute}", None)
if data:
is_direct_attribute = data[0] == "forward"
break
entity = R.entity_supertype.get(entity)
endpoint = match.group(3)
if ":" not in endpoint:
endpoint += ":" + endpoint.split("_")[0]
result = f"{match.group(1)}:{match.group(2)}1 -> {endpoint}"
if not is_direct_attribute:
result += "[dir=back]"
return result
def replace_edge2(match):
# I don't understand this one yet.
return f"{match.group(1)} -> {match.group(2)}:{match.group(3)}0"
for c in graphviz_code:
hash = hashlib.sha256(c.encode("utf-8")).hexdigest()
fn = os.path.join("svgs", name + "_" + hash + ".dot")
c2 = c.replace("concept", "digraph") # transform_graph(current_entity, c, only_urls=is_figure(c) == 2)
c2 = re.sub("(?<=\w)\-(?=\w)", "", c2)
nodes = set(n.split(":")[0] for n in (re.findall("([\:\w]+)\s*\->", c2) + re.findall("\->\s*([\:\w]+)", c2)))
node_ports = {n: [] for n in nodes}
[node_ports[n.split(":")[0]].append(n.split(":")[1]) for n in (re.findall("([\:\w]+)\s*\->", c2) + re.findall("\->\s*([\:\w]+)", c2)) if len(n.split(":")) > 1]
c2 = re.sub(r"(\w+)\:(\w+)\s*\->\s*([\:\w]+)", replace_edge, c2)
c2 = re.sub(r"([\w\:]+)\s*\->\s*(\w+)\:(\w+)", replace_edge2, c2)
bindings = {}
for ent, attr, bind in re.findall(r'(\w+)\:(\w+)\[binding="([\w_]+)"\]', c2):
bindings[(ent, attr)] = bind
c2 = re.sub(r'\w+\:\w+\[binding="[\w_]+"\]', "", c2)
G = pydot.graph_from_dot_data(c2)[0]
G.set_node_defaults(shape="plaintext", width="3")
G.set_nodesep("0.1")
G.set_splines("polyline")
G.set_rankdir("LR")
for n in nodes:
if n.startswith("Ifc"):
G.add_node(pydot.Node(n, label=create_entity_definition(n, bindings, node_ports.get(n, []))))
elif n.startswith("constraint_"):
G.get_node(n)[0].set_fillcolor("#ffaaaa")
G.get_node(n)[0].set_shape("rect")
G.get_node(n)[0].set_style("filled")
else:
url = {}
label = n.replace("_", " ")
N = make_concept(["Partial Templates"], exclude_partial=False).find(label)
if N:
url = {'URL': N.url}
G.add_node(pydot.Node(n, label=label, fillcolor="#aaffaa", shape="rect", style="filled", **url))
# this is ugly, but the node defaults need to come before the edges
G.obj_dict["nodes"]["node"][0]["sequence"] = -1
c3 = G.to_string()
with open(fn, "w") as f:
f.write(c3)
md = md.replace("```%s```" % c, "" % (name, hash))
subprocess.call([shutil.which("dot") or "dot", "-O", "-Tsvg", "-Gbgcolor=#ffffff00", fn])
return md
def get_applicable_relationships(usage, concept, resource):
rows = copy.deepcopy(R.xmi_concepts[usage].get(concept, []))
rows = [r for r in rows if r.get("ApplicableEntity") == resource]
if not rows:
return
if len(rows[0].keys()) == 1:
# There must be at least one key which defines the ApplicableEntity
# In this case, there is no interesting information to display
return
data = []
should_show_as_table = False
headers = []
for row in rows:
del row["ApplicableEntity"]
predefined_type = row.pop("PredefinedType", None)
# Some concepts are better displayed in a table, if they are complex and
# have multiple variables involved. Otherwise, a list is preferred.
should_show_as_table = len(row.values()) > 1
if should_show_as_table:
if predefined_type:
row["PredefinedType"] = predefined_type
# There seems to be a convention in the markdown that you can
# describe something using a header which is a concatenation of the
# values in the relationship.
name = []
if not headers:
for key, value in row.items():
if key not in ["ApplicableEntity"]:
headers.append(key)
for key, value in row.items():
if key not in ["ApplicableEntity"]:
name.append(value)
row["name"] = "_".join(name)
data.append(row)
else:
data.append({"predefined_type": predefined_type, "name": list(row.values())[0]})
return {"relationships": data, "should_show_as_table": should_show_as_table, "headers": headers}
def separate_camel(s):
return " ".join(re.split("(?=[A-Z])", s)[1:])
@app.route(make_url("figures/<fig>"))
def get_figure(fig):
return send_from_directory(os.path.join(REPO_DIR, "docs/figures"), fig)
@app.route(make_url("figures/examples/<fig>"))
def get_example_figure(fig):
# @todo
return send_from_directory(os.path.join(REPO_DIR, "docs/figures/examples"), fig)
@app.route(make_url("assets/<path:asset>"))
def get_asset(asset):
return send_from_directory(os.path.join(REPO_DIR, "docs", "assets"), asset)
@app.route(make_url("examples/<path:example>"))
def get_example(example):
return send_from_directory(os.path.join(REPO_DIR, "..", "examples", "models"), example)
# The markdown is littered with this type of annotation tag. Does it have meaning? We strip it out everywhere.
DOC_ANNOTATION_PATTERN = re.compile(r"\{\s*\..+?\}")
class resource_documentation_builder:
def __init__(self, resource):
self.resource = resource
self.md = get_resource_path(resource)
@property
def markdown(self):
with open(self.md, "r", encoding="utf-8") as f:
return re.sub(DOC_ANNOTATION_PATTERN, "", "\n".join(f.readlines()[2:]))
def get_markdown_content(self, heading):
attrs = []
direct_attrs = []
entity = self.resource
while entity:
markdown_filename = get_resource_path(entity)
try:
md_entity = re.sub(DOC_ANNOTATION_PATTERN, "", open(markdown_filename, encoding="utf-8").read())
except:
md_entity = None
entity_attrs = []
try:
if md_entity:
entity_attrs = list(mdp.markdown_attribute_parser(data=md_entity, heading_name=heading, as_text=False))
except:
import traceback
traceback.print_exc()
if heading == "Attributes":
entity_attr_di = dict(entity_attrs)
for a in [k.split(".")[1] for k in R.entity_attributes.keys() if k.startswith(f"{entity}.")][::-1]:
content = entity_attr_di.get(a, "")
is_fwd, attr_entity = R.entity_attributes[".".join((entity, a))]
attrs.append((entity, a, attr_entity, content))
if is_fwd == "forward":
direct_attrs.append(a)
else:
for a, content in entity_attrs[::-1]:
# remove underscored words:
attrs.append((entity, a, content))
entity = R.entity_supertype.get(entity)
attrs = attrs[::-1]
if heading == "Attributes":
# Decorate with attribute index
attr_index = {b: a for a, b in enumerate(direct_attrs[::-1], 1)}
attrs = [(a, attr_index.get(b, ""), b, c, d) for a, b, c, d in attrs]
return attrs
@property
def attributes(self):
return self.get_markdown_content("Attributes")
@property
def formal_propositions(self):
return self.get_markdown_content("Formal Propositions")
@property
def concepts(self):
return self.get_markdown_content("Concepts")
@app.route("/api/v0/resource/<resource>")
def api_resource(resource):
b = resource_documentation_builder(resource)
if b.attributes is None:
abort(404)
definition = b.markdown
if "\n\n" in definition:
definition = definition[0 : definition.index("\n\n")]
definition = markdown.markdown(definition)
attributes = [a[1:] for a in b.attributes]
return jsonify({"resource": resource, "definition": definition, "attributes": attributes})
@app.route(make_url("property/<prop>.htm"))
def property(prop):
prop = "".join(c for c in prop if c.isalnum() or c in "_")
md = os.path.join(REPO_DIR, "docs", "properties", prop[0].lower(), prop + ".md")
try:
mdc = open(md, "r", encoding="utf-8").read()
except:
mdc = ""
idx = ""
mdc = re.sub(DOC_ANNOTATION_PATTERN, "", mdc)
psets = [[pset] for pset, pdef in R.pset_definitions.items() if any(p["name"] == prop for p in pdef["properties"])]
html = process_markdown(prop, mdc)
html += tabulate.tabulate(psets, headers=["Referenced in"], tablefmt="html")
return render_template(
"property.html",
navigation=get_navigation(),
content=html,
number=idx,
entity=prop,
path=md[len(REPO_DIR) + 1 :].replace("\\", "/"),
)
def process_markdown(resource, mdc, process_quotes=True, number_headings=False, chapter=None):
html = markdown.markdown(process_graphviz(resource, mdc), extensions=["tables", "fenced_code"])
soup = BeautifulSoup(html)
# First h1 is handled by the template
try:
soup.find("h1").decompose()
except:
# only entities have H1?
pass
# Change svg img references to embedded svg because otherwise URLS are not interactive
for img in soup.findAll("img"):
if img["src"].endswith(".svg"):
entity, hash = img["src"].split("/")[-1].split(".")[0].split("_")
svg = BeautifulSoup(open(os.path.join("svgs", entity + "_" + hash + ".dot.svg")))
img.replaceWith(svg.find("svg"))
img = svg
elif img["src"].startswith("http"):
pass
else:
if img["src"] and img["src"].startswith("../../figures/examples/"):
img["src"] = url_for('get_example_figure', fig=img["src"].replace("../../figures/examples/", ""))
else:
img["src"] = img["src"][9:]
if number_headings:
assert chapter
headings = soup.find_all(('h3', 'h4', 'h5'))
stack = list(chapter)
orig_length = len(stack) - 2
for h in headings:
level = int(h.name[1:]) + orig_length
if level == len(stack):
stack[-1] += 1
elif len(stack) < level:
stack += [1] * (level - len(stack))
else:
stack = stack[0:level]
stack[-1] += 1
span1 = soup.new_tag('div')
span1['class'] = 'number'
span1.string = ".".join(map(str, stack))
span2 = soup.new_tag('div')
span2.string = h.text
h.contents = [span1, span2]
for svg in soup.findAll("svg"):
# Graphviz diagrams use pt, a hackish way to isolate them
if "pt" in svg.attrs["width"]:
svg.attrs["width"] = "%dpx" % (int(svg.attrs["width"][0:-2]) * 1)
svg.attrs["height"] = "%dpx" % (int(svg.attrs["height"][0:-2]) * 1)
# Tag all special notes separately. In markdown they are all lumped in a single block quote.
for blockquote in soup.findAll("blockquote"):
has_aside = False
non_aside_ps = []
for p in blockquote.findAll("p"):
try:
keyword, contents = p.text.split(" ", 1)
keyword = keyword.strip()
except:
continue
valid_keywords = ["HISTORY", "IFC", "EXAMPLE", "NOTE", "REFERENCE"]
has_valid_keyword = any(v in keyword for v in valid_keywords)
if not has_valid_keyword:
non_aside_ps.append(p)
continue
has_aside = True
p.name = "aside"
if process_quotes:
if keyword.startswith("IFC"):
# This is typically something like "IFC4 CHANGE" denoting a historic change reason
keyword, keyword2, contents = p.text.split(" ", 2)
p.contents = BeautifulSoup(str(p).replace(keyword + " " + keyword2, "")).html.body.aside.contents
keyword = keyword.strip()
keyword2 = keyword2.strip()
keyword = "-".join((keyword, keyword2))
else:
p.contents = BeautifulSoup(str(p).replace(keyword, "")).html.body.aside.contents
css_class = keyword.lower()
if "addendum" in css_class or "change" in css_class:
css_class = "change"
if "deprecation" in css_class:
css_class = "deprecation"
p["class"] = f"aside-{css_class}"
mark = soup.new_tag("mark")
mark.string = keyword
if "deprecation" in css_class:
anchor = soup.new_tag("a", href=f"{base}/content/terms_and_definitions.htm#deprecation")