Alef1986 commited on
Commit
74beae5
·
verified ·
1 Parent(s): f73739d

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +165 -13
src/streamlit_app.py CHANGED
@@ -318,15 +318,19 @@ def load_and_parse_xml(file_path):
318
  # ==========================================
319
  # MODULE: Code Generation (NetworkX to Mermaid)
320
  # ==========================================
321
- def graph_to_mermaid_and_data(G_active, nodes_to_include, edges_to_include, render_subgraphs=False):
322
  """
323
  Translates a NetworkX subgraph into Mermaid.js syntax.
324
  If render_subgraphs=True, groups BusinessProcesses inside their parent BusinessFunctions
325
  and forces a Top-to-Bottom vertical layout using invisible links (~~~) inside the subgraphs.
 
326
  """
327
  if not nodes_to_include:
328
  return "", "{}"
329
 
 
 
 
330
  lines = [
331
  "flowchart LR",
332
  "classDef process fill:#FFF2CC,stroke:#D6B656,stroke-width:2px,color:#000;",
@@ -343,7 +347,6 @@ def graph_to_mermaid_and_data(G_active, nodes_to_include, edges_to_include, rend
343
  u_type = G_active.nodes[u].get('type', '')
344
  v_type = G_active.nodes[v].get('type', '')
345
 
346
- # If U (Function) is composed of V (Process)
347
  if 'Composition' in data.get('type', '') and 'BusinessFunction' in u_type and 'BusinessProcess' in v_type:
348
  parent_map[v] = u
349
  else:
@@ -373,7 +376,7 @@ def graph_to_mermaid_and_data(G_active, nodes_to_include, edges_to_include, rend
373
  if p_id in nodes_to_include:
374
  p_data = G_active.nodes[p_id]
375
  m_pid = p_id.replace("-", "_")
376
- p_name = p_data.get("name", "Unknown").replace('"', "'")
377
 
378
  lines.append(f' subgraph {m_pid} ["{p_name}"]')
379
  lines.append(f' direction TB')
@@ -383,14 +386,12 @@ def graph_to_mermaid_and_data(G_active, nodes_to_include, edges_to_include, rend
383
  for c_id in children:
384
  c_data = G_active.nodes[c_id]
385
  m_cid = c_id.replace("-", "_")
386
- c_name = c_data.get("name", "Unknown").replace('"', "'")
387
 
388
  lines.append(f' {m_cid}("{c_name}"):::process')
389
  lines.append(f' click {m_cid} call handleNodeClick()')
390
  nodes_data[m_cid] = {"name": c_name, "doc": c_data.get("doc", "").replace('"', "'").replace("\n", " ")}
391
 
392
- # INVISIBLE LINKS HACK: Forces dagre layout engine to stack nodes vertically
393
- # even when they have external horizontal connections in an LR flowchart.
394
  if prev_cid:
395
  lines.append(f' {prev_cid} ~~~ {m_cid}')
396
  prev_cid = m_cid
@@ -406,7 +407,7 @@ def graph_to_mermaid_and_data(G_active, nodes_to_include, edges_to_include, rend
406
  for n_id in standalone_nodes:
407
  data = G_active.nodes.get(n_id, {})
408
  m_id = n_id.replace("-", "_")
409
- name = data.get("name", "Unknown").replace('"', "'")
410
  n_type = data.get("type", "")
411
  doc = data.get("doc", "").replace('"', "'").replace("\n", " ")
412
 
@@ -503,7 +504,8 @@ mode = st.radio(
503
  "Case 3: Closest STRUCTURAL connection (Undirected)",
504
  "Case 4: All possible DATA FLOW paths (Directed)",
505
  "Case 5: Process Neighborhood & Internal Steps (Subgraphs)",
506
- "Case 6: Shortest connection between Business Objects (Undirected)"
 
507
  )
508
  )
509
 
@@ -667,11 +669,9 @@ elif mode.startswith("Case 5"):
667
  nodes_to_draw = set([p_id])
668
  edges_to_draw = []
669
 
670
- # 1. Find all internal steps (BusinessProcesses connected via Composition)
671
  children = [v for u, v, d in G_full.out_edges(p_id, data=True) if 'Composition' in d.get('type','') and 'BusinessProcess' in G_full.nodes[v].get('type','')]
672
  nodes_to_draw.update(children)
673
 
674
- # 2. Extract outward neighborhood iteratively
675
  visited = set(nodes_to_draw)
676
  current_front = set(nodes_to_draw)
677
 
@@ -681,14 +681,12 @@ elif mode.startswith("Case 5"):
681
  for neighbor in U_active.neighbors(node):
682
  if neighbor not in visited:
683
  n_type = G_full.nodes[neighbor].get('type', '')
684
- # Expand only into Objects, not jumping into other Functions/Processes
685
  if 'BusinessFunction' not in n_type and 'BusinessProcess' not in n_type:
686
  next_front.add(neighbor)
687
  visited.add(neighbor)
688
  nodes_to_draw.update(next_front)
689
  current_front = next_front
690
 
691
- # 3. Collect all valid edges inside this subgraph
692
  existing_edges = set()
693
  for u in nodes_to_draw:
694
  for v in nodes_to_draw:
@@ -726,4 +724,158 @@ elif mode.startswith("Case 6"):
726
  mermaid_code, json_data = graph_to_mermaid_and_data(G_active, path, edges_in_path)
727
  render_mermaid(mermaid_code, json_data)
728
  except nx.NetworkXNoPath:
729
- st.error("These objects are completely disconnected in the model.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  # ==========================================
319
  # MODULE: Code Generation (NetworkX to Mermaid)
320
  # ==========================================
321
+ def graph_to_mermaid_and_data(G_active, nodes_to_include, edges_to_include, render_subgraphs=False, custom_labels=None):
322
  """
323
  Translates a NetworkX subgraph into Mermaid.js syntax.
324
  If render_subgraphs=True, groups BusinessProcesses inside their parent BusinessFunctions
325
  and forces a Top-to-Bottom vertical layout using invisible links (~~~) inside the subgraphs.
326
+ Supports a custom_labels map for overwriting rendering names dynamically.
327
  """
328
  if not nodes_to_include:
329
  return "", "{}"
330
 
331
+ if custom_labels is None:
332
+ custom_labels = {}
333
+
334
  lines = [
335
  "flowchart LR",
336
  "classDef process fill:#FFF2CC,stroke:#D6B656,stroke-width:2px,color:#000;",
 
347
  u_type = G_active.nodes[u].get('type', '')
348
  v_type = G_active.nodes[v].get('type', '')
349
 
 
350
  if 'Composition' in data.get('type', '') and 'BusinessFunction' in u_type and 'BusinessProcess' in v_type:
351
  parent_map[v] = u
352
  else:
 
376
  if p_id in nodes_to_include:
377
  p_data = G_active.nodes[p_id]
378
  m_pid = p_id.replace("-", "_")
379
+ p_name = custom_labels.get(p_id, p_data.get("name", "Unknown")).replace('"', "'")
380
 
381
  lines.append(f' subgraph {m_pid} ["{p_name}"]')
382
  lines.append(f' direction TB')
 
386
  for c_id in children:
387
  c_data = G_active.nodes[c_id]
388
  m_cid = c_id.replace("-", "_")
389
+ c_name = custom_labels.get(c_id, c_data.get("name", "Unknown")).replace('"', "'")
390
 
391
  lines.append(f' {m_cid}("{c_name}"):::process')
392
  lines.append(f' click {m_cid} call handleNodeClick()')
393
  nodes_data[m_cid] = {"name": c_name, "doc": c_data.get("doc", "").replace('"', "'").replace("\n", " ")}
394
 
 
 
395
  if prev_cid:
396
  lines.append(f' {prev_cid} ~~~ {m_cid}')
397
  prev_cid = m_cid
 
407
  for n_id in standalone_nodes:
408
  data = G_active.nodes.get(n_id, {})
409
  m_id = n_id.replace("-", "_")
410
+ name = custom_labels.get(n_id, data.get("name", "Unknown")).replace('"', "'")
411
  n_type = data.get("type", "")
412
  doc = data.get("doc", "").replace('"', "'").replace("\n", " ")
413
 
 
504
  "Case 3: Closest STRUCTURAL connection (Undirected)",
505
  "Case 4: All possible DATA FLOW paths (Directed)",
506
  "Case 5: Process Neighborhood & Internal Steps (Subgraphs)",
507
+ "Case 6: Shortest connection between Business Objects (Undirected)",
508
+ "Case 7: N2 Chart Simulation (Process Inputs & Outputs)"
509
  )
510
  )
511
 
 
669
  nodes_to_draw = set([p_id])
670
  edges_to_draw = []
671
 
 
672
  children = [v for u, v, d in G_full.out_edges(p_id, data=True) if 'Composition' in d.get('type','') and 'BusinessProcess' in G_full.nodes[v].get('type','')]
673
  nodes_to_draw.update(children)
674
 
 
675
  visited = set(nodes_to_draw)
676
  current_front = set(nodes_to_draw)
677
 
 
681
  for neighbor in U_active.neighbors(node):
682
  if neighbor not in visited:
683
  n_type = G_full.nodes[neighbor].get('type', '')
 
684
  if 'BusinessFunction' not in n_type and 'BusinessProcess' not in n_type:
685
  next_front.add(neighbor)
686
  visited.add(neighbor)
687
  nodes_to_draw.update(next_front)
688
  current_front = next_front
689
 
 
690
  existing_edges = set()
691
  for u in nodes_to_draw:
692
  for v in nodes_to_draw:
 
724
  mermaid_code, json_data = graph_to_mermaid_and_data(G_active, path, edges_in_path)
725
  render_mermaid(mermaid_code, json_data)
726
  except nx.NetworkXNoPath:
727
+ st.error("These objects are completely disconnected in the model.")
728
+
729
+ elif mode.startswith("Case 7"):
730
+ st.write("Simulates an N2 Chart. Select a central process, then choose which of its actual inputs and outputs to analyze.")
731
+
732
+ # 1. Step: Select the central process
733
+ p_center_name = st.selectbox("Select Central Process (Business Function):", sorted_process_names, key="c7_p_center")
734
+ p_center_id = [k for k, v in processes.items() if v == p_center_name][0]
735
+
736
+ # 2. Step: Find explicit input/output artifacts (strictly filter out internal steps and functions)
737
+ actual_inputs_ids = []
738
+ for n in G_active.predecessors(p_center_id):
739
+ n_type = G_active.nodes[n].get('type', '')
740
+ if 'BusinessProcess' not in n_type and 'BusinessFunction' not in n_type:
741
+ actual_inputs_ids.append(n)
742
+
743
+ actual_outputs_ids = []
744
+ for n in G_active.successors(p_center_id):
745
+ n_type = G_active.nodes[n].get('type', '')
746
+ if 'BusinessProcess' not in n_type and 'BusinessFunction' not in n_type:
747
+ actual_outputs_ids.append(n)
748
+
749
+ inputs_dict = {n: G_active.nodes[n].get('name', 'Unnamed') for n in actual_inputs_ids}
750
+ outputs_dict = {n: G_active.nodes[n].get('name', 'Unnamed') for n in actual_outputs_ids}
751
+
752
+ sorted_inputs_names = sorted(list(inputs_dict.values()))
753
+ sorted_outputs_names = sorted(list(outputs_dict.values()))
754
+
755
+ # 3. Step: Render the 3-column N2 interactive interface
756
+ st.write("Configure N2 Chart Interface:")
757
+ col_l, col_m, col_r = st.columns(3)
758
+
759
+ with col_l:
760
+ selected_inputs = st.multiselect("Input Artifacts (from XML):", sorted_inputs_names, max_selections=5, key="c7_inputs")
761
+ with col_m:
762
+ st.info(f"**Central Process Node:** {p_center_name}") # Double newline preserves real paragraph rendering
763
+ with col_r:
764
+ selected_outputs = st.multiselect("Output Artifacts (from XML):", sorted_outputs_names, max_selections=5, key="c7_outputs")
765
+
766
+ # Toggle to control if alternative producers for the output artifacts should be visualized
767
+ show_all_producers_for_outputs = st.checkbox("Show all producing processes for selected output artifacts", value=False)
768
+
769
+ if st.button("Generate Diagram"):
770
+ nodes_to_draw = set([p_center_id])
771
+ edges_to_draw = []
772
+ custom_labels = {}
773
+
774
+ # Helper to compute full structural cluster when use_hierarchy is checked
775
+ def get_artifact_cluster(start_node):
776
+ if not use_hierarchy:
777
+ return set([start_node])
778
+ visited = set([start_node])
779
+ queue = [start_node]
780
+ while queue:
781
+ curr = queue.pop(0)
782
+ for neighbor in G_full.neighbors(curr):
783
+ if neighbor not in visited:
784
+ edata = G_full[curr][neighbor]
785
+ if any(x in edata.get('type', '') for x in ['Composition', 'Aggregation', 'Specialization']) or edata.get('access') == 'hierarchy_reverse':
786
+ ntype = G_full.nodes[neighbor].get('type', '')
787
+ if 'BusinessProcess' not in ntype and 'BusinessFunction' not in ntype:
788
+ visited.add(neighbor)
789
+ queue.append(neighbor)
790
+ for neighbor in G_full.predecessors(curr):
791
+ if neighbor not in visited:
792
+ edata = G_full[neighbor][curr]
793
+ if any(x in edata.get('type', '') for x in ['Composition', 'Aggregation', 'Specialization']) or edata.get('access') == 'hierarchy_reverse':
794
+ ntype = G_full.nodes[neighbor].get('type', '')
795
+ if 'BusinessProcess' not in ntype and 'BusinessFunction' not in ntype:
796
+ visited.add(neighbor)
797
+ queue.append(neighbor)
798
+ return visited
799
+
800
+ def add_custom_edge(u, v):
801
+ if G_active.has_edge(u, v) and G_active[u][v].get('access') != 'hierarchy_reverse':
802
+ edges_to_draw.append((u, v, G_active[u][v]))
803
+ elif G_active.has_edge(v, u) and G_active[v][u].get('access') != 'hierarchy_reverse':
804
+ edges_to_draw.append((v, u, G_active[v][u]))
805
+
806
+ # Trace Input Artifacts and find upstream producers across the cluster
807
+ sel_input_ids = [k for k, v in inputs_dict.items() if v in selected_inputs]
808
+ for in_id in sel_input_ids:
809
+ cluster = get_artifact_cluster(in_id)
810
+ nodes_to_draw.update(cluster)
811
+
812
+ # Map structural relations inside the cluster
813
+ for u in cluster:
814
+ for v in cluster:
815
+ if G_active.has_edge(u, v) and G_active[u][v].get('access') != 'hierarchy_reverse':
816
+ edges_to_draw.append((u, v, G_active[u][v]))
817
+
818
+ add_custom_edge(in_id, p_center_id)
819
+
820
+ # Find closest generating processes for any element inside the cluster
821
+ for c_item in cluster:
822
+ for pred in G_full.predecessors(c_item):
823
+ p_type = G_full.nodes[pred].get('type', '')
824
+ if ('BusinessFunction' in p_type or 'BusinessProcess' in p_type) and pred != p_center_id:
825
+ if G_full.has_edge(pred, c_item) and G_full[pred][c_item].get('access') != 'hierarchy_reverse':
826
+ nodes_to_draw.add(pred)
827
+ edges_to_draw.append((pred, c_item, G_full[pred][c_item]))
828
+
829
+ # Trace Output Artifacts and find downstream consumers across the cluster
830
+ sel_output_ids = [k for k, v in outputs_dict.items() if v in selected_outputs]
831
+ for out_id in sel_output_ids:
832
+ cluster = get_artifact_cluster(out_id)
833
+ nodes_to_draw.update(cluster)
834
+
835
+ # Map structural relations inside the cluster
836
+ for u in cluster:
837
+ for v in cluster:
838
+ if G_active.has_edge(u, v) and G_active[u][v].get('access') != 'hierarchy_reverse':
839
+ edges_to_draw.append((u, v, G_active[u][v]))
840
+
841
+ add_custom_edge(p_center_id, out_id)
842
+
843
+ # FIXED: Determine producers strictly for the chosen artifact itself (out_id)
844
+ direct_producers = set()
845
+ for pred in G_full.predecessors(out_id):
846
+ p_type = G_full.nodes[pred].get('type', '')
847
+ if 'BusinessFunction' in p_type or 'BusinessProcess' in p_type:
848
+ if G_full.has_edge(pred, out_id) and G_full[pred][out_id].get('access') != 'hierarchy_reverse':
849
+ direct_producers.add(pred)
850
+
851
+ # Mark as Shared Output ONLY if this specific item has multiple direct producers
852
+ if len(direct_producers) > 1:
853
+ orig_name = G_active.nodes[out_id].get('name', 'Unnamed')
854
+ custom_labels[out_id] = f"{orig_name} [Shared Output]"
855
+
856
+ # If explicit toggle is on, inject alternative producers into the view
857
+ if show_all_producers_for_outputs:
858
+ for c_item in cluster:
859
+ for pred in G_full.predecessors(c_item):
860
+ p_type = G_full.nodes[pred].get('type', '')
861
+ if 'BusinessFunction' in p_type or 'BusinessProcess' in p_type:
862
+ if G_full.has_edge(pred, c_item) and G_full[pred][c_item].get('access') != 'hierarchy_reverse':
863
+ if pred != p_center_id:
864
+ nodes_to_draw.add(pred)
865
+ edges_to_draw.append((pred, c_item, G_full[pred][c_item]))
866
+
867
+ # Find all downstream consuming processes for elements inside the cluster (retains structural traceability)
868
+ for c_item in cluster:
869
+ for succ in G_full.successors(c_item):
870
+ s_type = G_full.nodes[succ].get('type', '')
871
+ if ('BusinessFunction' in s_type or 'BusinessProcess' in s_type) and succ != p_center_id:
872
+ if G_full.has_edge(c_item, succ):
873
+ nodes_to_draw.add(succ)
874
+ edges_to_draw.append((c_item, succ, G_full[c_item][succ]))
875
+
876
+ if connect_border_objects:
877
+ edges_to_draw = enforce_border_object_relations(G_active, nodes_to_draw, edges_to_draw)
878
+
879
+ st.success("N2 Chart simulation diagram compiled!")
880
+ mermaid_code, json_data = graph_to_mermaid_and_data(G_active, nodes_to_draw, edges_to_draw, custom_labels=custom_labels)
881
+ render_mermaid(mermaid_code, json_data)