-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbpmn_analyzer_STABLE_v2.0.0_REVERT_POINT.py
More file actions
4469 lines (3833 loc) · 255 KB
/
bpmn_analyzer_STABLE_v2.0.0_REVERT_POINT.py
File metadata and controls
4469 lines (3833 loc) · 255 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 streamlit as st
import xmltodict
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
from datetime import datetime
import json
import os
from typing import Dict, List, Any, Tuple
class BPMNAnalyzer:
"""
A comprehensive BPMN analysis tool that extracts business insights,
calculates costs, and provides KPI analysis from BPMN XML files.
"""
def __init__(self):
self.processes = {}
self.tasks = []
self.collaborations = {}
self.total_costs = 0
self.total_time = 0
self.currencies = set()
def parse_bpmn_file(self, file_content: str) -> Dict[str, Any]:
"""
Parse BPMN XML content and extract structured data.
Args:
file_content: XML content as string
Returns:
Dictionary containing parsed BPMN data
"""
try:
# Parse XML to dictionary
xml_dict = xmltodict.parse(file_content)
# Extract basic file information
definitions = xml_dict.get('bpmn:definitions', {})
# Extract collaborations (process participants)
collaborations = definitions.get('bpmn:collaboration', [])
if not isinstance(collaborations, list):
collaborations = [collaborations] if collaborations else []
# Extract processes
processes = definitions.get('bpmn:process', [])
if not isinstance(processes, list):
processes = [processes] if processes else []
# Parse collaborations and create process-to-swimlane mapping
parsed_collaborations = {}
process_to_swimlane = {} # Map process ID to swimlane name
for collab in collaborations:
if collab:
collab_id = collab.get('@id', 'Unknown')
participants = collab.get('bpmn:participant', [])
if not isinstance(participants, list):
participants = [participants] if participants else []
parsed_collaborations[collab_id] = {
'participants': [
{
'id': p.get('@id', 'Unknown'),
'name': p.get('@name', 'Unknown'),
'process_ref': p.get('@processRef', 'Unknown')
}
for p in participants
],
'message_flows': collab.get('bpmn:messageFlow', [])
}
# Create mapping from process ID to swimlane name
for participant in parsed_collaborations[collab_id]['participants']:
process_to_swimlane[participant['process_ref']] = participant['name']
# Parse processes and extract tasks
parsed_processes = {}
all_tasks = []
for process in processes:
if process:
process_id = process.get('@id', 'Unknown')
process_name = process.get('@name', 'Unknown')
# Get swimlane name for this process
swimlane_name = process_to_swimlane.get(process_id, process_name)
# Extract tasks from this process
process_tasks = []
# Look for different types of tasks
task_types = ['bpmn:task', 'bpmn:sendTask', 'bpmn:manualTask']
for task_type in task_types:
tasks = process.get(task_type, [])
if not isinstance(tasks, list):
tasks = [tasks] if tasks else []
for task in tasks:
if task:
parsed_task = self._parse_task(task, swimlane_name, task_type)
if parsed_task:
process_tasks.append(parsed_task)
all_tasks.append(parsed_task)
parsed_processes[process_id] = {
'name': process_name,
'swimlane': swimlane_name,
'tasks': process_tasks,
'start_events': process.get('bpmn:startEvent', []),
'end_events': process.get('bpmn:endEvent', []),
'gateways': process.get('bpmn:exclusiveGateway', [])
}
return {
'collaborations': parsed_collaborations,
'processes': parsed_processes,
'tasks': all_tasks,
'process_to_swimlane': process_to_swimlane,
'file_info': {
'exporter': definitions.get('@exporter', 'Unknown'),
'exporter_version': definitions.get('@exporterVersion', 'Unknown'),
'target_namespace': definitions.get('@targetNamespace', 'Unknown')
}
}
except Exception as e:
st.error(f"Error parsing BPMN file: {str(e)}")
return {}
def _parse_task(self, task: Dict, swimlane_name: str, task_type: str) -> Dict[str, Any]:
"""
Parse individual task and extract business metadata.
Args:
task: Task dictionary from XML
swimlane_name: Name of the swimlane/department this task belongs to
task_type: Type of BPMN task
Returns:
Parsed task dictionary
"""
try:
# Add null checks for task parameter
if task is None:
return self._create_default_task(swimlane_name, task_type)
task_id = task.get('@id', 'Unknown')
task_name = task.get('@name', 'Unknown')
# Extract extension elements (Camunda properties)
extension_elements = task.get('bpmn:extensionElements', {})
camunda_properties = {}
if extension_elements:
properties = extension_elements.get('camunda:properties', {})
if properties:
prop_list = properties.get('camunda:property', [])
if not isinstance(prop_list, list):
prop_list = [prop_list] if prop_list else []
for prop in prop_list:
if prop:
name = prop.get('@name', '')
value = prop.get('@value', '')
camunda_properties[name] = value
# Calculate costs and time
time_hhmm = camunda_properties.get('time_hhmm', '00:00')
# Handle empty string values for numeric fields
cost_per_hour_str = camunda_properties.get('cost_per_hour', '0')
cost_per_hour = float(cost_per_hour_str) if cost_per_hour_str and cost_per_hour_str.strip() else 0
currency = camunda_properties.get('currency', 'Unknown')
other_costs_str = camunda_properties.get('other_costs', '0')
other_costs = float(other_costs_str) if other_costs_str and other_costs_str.strip() else 0
# Parse time from HH:MM format
time_minutes = self._parse_time_to_minutes(time_hhmm)
time_hours = time_minutes / 60 if time_minutes > 0 else 0
# Calculate total cost for this task
labor_cost = time_hours * cost_per_hour
total_task_cost = labor_cost + other_costs
return {
'id': task_id,
'name': task_name,
'swimlane': swimlane_name,
'type': task_type.replace('bpmn:', ''),
'time_hhmm': time_hhmm,
'time_display': self._format_time_display(time_hhmm), # Formatted for display
'time_minutes': time_minutes,
'time_hours': time_hours,
'cost_per_hour': cost_per_hour,
'currency': currency,
'other_costs': other_costs,
'labor_cost': labor_cost,
'total_cost': total_task_cost,
'task_owner': camunda_properties.get('task_owner', 'Unknown'),
'task_description': camunda_properties.get('task_description', ''),
'task_status': camunda_properties.get('task_status', 'Unknown'),
'doc_status': camunda_properties.get('doc_status', 'Unknown'),
'tools_used': camunda_properties.get('tools_used', ''),
'opportunities': camunda_properties.get('opportunities', ''),
'issues_text': camunda_properties.get('issues_text', ''),
'issues_priority': camunda_properties.get('issues_priority', ''),
'faq_q1': camunda_properties.get('faq_q1', ''),
'faq_a1': camunda_properties.get('faq_a1', ''),
'faq_q2': camunda_properties.get('faq_q2', ''),
'faq_a2': camunda_properties.get('faq_a2', ''),
'faq_q3': camunda_properties.get('faq_q3', ''),
'faq_a3': camunda_properties.get('faq_a3', ''),
'task_industry': camunda_properties.get('task_industry', ''),
'doc_url': camunda_properties.get('doc_url', '')
}
except Exception as e:
# Log error but don't show it to user to avoid cluttering the interface
print(f"Warning: Error parsing task {task.get('@id', 'Unknown')}: {str(e)}")
# Return a minimal task object instead of None to avoid breaking the analysis
return self._create_default_task(swimlane_name, task_type)
def _create_default_task(self, swimlane_name: str, task_type: str) -> Dict[str, Any]:
"""Create a default task object when parsing fails."""
return {
'id': 'Unknown',
'name': 'Unknown',
'swimlane': swimlane_name,
'type': task_type.replace('bpmn:', ''),
'time_hhmm': '00:00',
'time_display': '00:00',
'time_minutes': 0,
'time_hours': 0,
'cost_per_hour': 0,
'currency': 'Unknown',
'other_costs': 0,
'labor_cost': 0,
'total_cost': 0,
'task_owner': 'Unknown',
'task_description': '',
'task_status': 'Unknown',
'doc_status': 'Unknown',
'tools_used': '',
'opportunities': '',
'issues_text': '',
'issues_priority': '',
'faq_q1': '',
'faq_a1': '',
'faq_q2': '',
'faq_a2': '',
'faq_q3': '',
'faq_a3': '',
'task_industry': '',
'doc_url': ''
}
def _parse_time_to_minutes(self, time_str: str) -> int:
"""
Convert HH:MM time format to minutes.
Args:
time_str: Time string in HH:MM format (e.g., "1:30", "2:00") or just hours (e.g., "6", "1", "5")
Returns:
Time in minutes
"""
try:
if not time_str or time_str == '' or time_str.strip() == '':
return 0
# Handle cases where time might be just a number (assume it's hours)
if ':' not in time_str:
try:
# If it's just a number like "6", "1", "5", assume it's hours
# This matches the BPMN file format where some tasks have "6" meaning 6 hours
hours = float(time_str)
return int(hours * 60)
except ValueError:
return 0
# Handle HH:MM format
parts = time_str.split(':')
if len(parts) == 2:
hours = int(parts[0]) if parts[0].strip() else 0
minutes = int(parts[1]) if parts[1].strip() else 0
return hours * 60 + minutes
return 0
except (ValueError, TypeError):
return 0
def _format_time_display(self, time_str: str) -> str:
"""
Format time string for consistent display in HH:MM format.
Args:
time_str: Time string (e.g., "6", "1:00", "0:30")
Returns:
Formatted time string in HH:MM format
"""
try:
if not time_str or time_str == '' or time_str.strip() == '':
return "0:00"
# If it's just a number, assume it's hours and format as HH:00
if ':' not in time_str:
try:
hours = int(float(time_str))
return f"{hours:02d}:00"
except ValueError:
return "0:00"
# If it's already in HH:MM format, ensure consistent formatting
parts = time_str.split(':')
if len(parts) == 2:
hours = int(parts[0]) if parts[0].strip() else 0
minutes = int(parts[1]) if parts[1].strip() else 0
return f"{hours:02d}:{minutes:02d}"
return "0:00"
except (ValueError, TypeError):
return "0:00"
def analyze_business_insights(self, parsed_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Analyze parsed BPMN data and extract business insights.
Args:
parsed_data: Parsed BPMN data
Returns:
Dictionary containing business insights and KPIs
"""
tasks = parsed_data.get('tasks', [])
processes = parsed_data.get('processes', {})
collaborations = parsed_data.get('collaborations', {})
if not tasks:
return {}
# Calculate total costs and time
total_cost = sum(task.get('total_cost', 0) for task in tasks)
total_time_minutes = sum(task.get('time_minutes', 0) for task in tasks)
# Use the sum of individual task hours to ensure consistency with table display
total_time_hours = sum(task.get('time_hours', 0) for task in tasks)
# Debug: Print some task details to verify parsing
print(f"DEBUG: Total tasks parsed: {len(tasks)}")
print(f"DEBUG: Total cost calculated: ${total_cost:.2f}")
print(f"DEBUG: Total time calculated: {total_time_hours:.2f} hours")
print(f"DEBUG: Total time from minutes conversion: {total_time_minutes / 60:.2f} hours")
print(f"DEBUG: Expected total time from manual analysis: ~119.75 hours")
print(f"DEBUG: Expected total cost from manual analysis: ~$21,321.25")
print(f"DEBUG: --- First 10 tasks details ---")
for i, task in enumerate(tasks[:10]): # Show first 10 tasks
print(f"DEBUG: Task {i+1}: {task.get('name')}")
print(f" - Time HH:MM: '{task.get('time_hhmm')}'")
print(f" - Time Display: '{task.get('time_display')}'")
print(f" - Time minutes: {task.get('time_minutes')} min")
print(f" - Time hours: {task.get('time_hours'):.2f} hrs")
print(f" - Cost per hour: ${task.get('cost_per_hour', 0):.2f}")
print(f" - Total cost: ${task.get('total_cost', 0):.2f}")
print(f" - Currency: {task.get('currency', 'Unknown')}")
print(f"DEBUG: --- End task details ---")
# Group by swimlane (department)
swimlane_analysis = {}
for process_id, process_data in processes.items():
swimlane_tasks = [t for t in tasks if t.get('swimlane') == process_data.get('swimlane')]
swimlane_cost = sum(t.get('total_cost', 0) for t in swimlane_tasks)
swimlane_time = sum(t.get('time_minutes', 0) for t in swimlane_tasks)
swimlane_name = process_data.get('swimlane', 'Unknown')
if swimlane_name not in swimlane_analysis:
swimlane_analysis[swimlane_name] = {
'task_count': len(swimlane_tasks),
'total_cost': swimlane_cost,
'total_time_minutes': swimlane_time,
'total_time_hours': swimlane_time / 60,
'tasks': swimlane_tasks
}
else:
# Add to existing swimlane if multiple processes share the same swimlane
swimlane_analysis[swimlane_name]['task_count'] += len(swimlane_tasks)
swimlane_analysis[swimlane_name]['total_cost'] += swimlane_cost
swimlane_analysis[swimlane_name]['total_time_minutes'] += swimlane_time
swimlane_analysis[swimlane_name]['total_time_hours'] += swimlane_time / 60
swimlane_analysis[swimlane_name]['tasks'].extend(swimlane_tasks)
# Group by task owner
owner_analysis = {}
for task in tasks:
owner = task.get('task_owner', 'Unknown')
if owner not in owner_analysis:
owner_analysis[owner] = {
'task_count': 0,
'total_cost': 0,
'total_time_minutes': 0
}
owner_analysis[owner]['task_count'] += 1
owner_analysis[owner]['total_cost'] += task.get('total_cost', 0)
owner_analysis[owner]['total_time_minutes'] += task.get('time_minutes', 0)
# Group by task status
status_analysis = {}
for task in tasks:
status = task.get('task_status', 'Unknown')
if status not in status_analysis:
status_analysis[status] = {
'task_count': 0,
'total_cost': 0,
'total_time_minutes': 0
}
status_analysis[status]['task_count'] += 1
status_analysis[status]['total_cost'] += task.get('total_cost', 0)
status_analysis[status]['total_time_minutes'] += task.get('time_minutes', 0)
# Group by issues priority
priority_analysis = {}
for task in tasks:
priority = task.get('issues_priority', 'Unknown')
if priority not in priority_analysis:
priority_analysis[priority] = {
'task_count': 0,
'total_cost': 0,
'total_time_minutes': 0
}
priority_analysis[priority]['task_count'] += 1
priority_analysis[priority]['total_cost'] += task.get('total_cost', 0)
priority_analysis[priority]['total_time_minutes'] += task.get('time_minutes', 0)
# Group by documentation status
doc_status_analysis = {}
for task in tasks:
doc_status = task.get('doc_status', 'Unknown')
if doc_status not in doc_status_analysis:
doc_status_analysis[doc_status] = {
'task_count': 0,
'total_cost': 0,
'total_time_minutes': 0
}
doc_status_analysis[doc_status]['task_count'] += 1
doc_status_analysis[doc_status]['total_cost'] += task.get('total_cost', 0)
doc_status_analysis[doc_status]['total_time_minutes'] += task.get('time_minutes', 0)
# Extract currencies
currencies = set(task.get('currency', 'Unknown') for task in tasks if task.get('currency'))
return {
'summary': {
'total_tasks': len(tasks),
'total_processes': len(processes),
'total_collaborations': len(collaborations),
'total_cost': total_cost,
'total_time_minutes': total_time_minutes,
'total_time_hours': total_time_hours,
'currencies': list(currencies)
},
'swimlane_analysis': swimlane_analysis,
'owner_analysis': owner_analysis,
'status_analysis': status_analysis,
'priority_analysis': priority_analysis,
'doc_status_analysis': doc_status_analysis,
'tasks': tasks
}
def generate_excel_report(self, analysis_data: Dict[str, Any], filename: str = "bpmn_analysis_report.xlsx"):
"""
Generate Excel report with detailed analysis.
Args:
analysis_data: Analysis results
filename: Output filename
"""
try:
with pd.ExcelWriter(filename, engine='openpyxl') as writer:
# Summary sheet
summary_data = analysis_data.get('summary', {})
summary_df = pd.DataFrame([summary_data])
summary_df.to_excel(writer, sheet_name='Summary', index=False)
# Tasks sheet
tasks_df = pd.DataFrame(analysis_data.get('tasks', []))
if not tasks_df.empty:
tasks_df.to_excel(writer, sheet_name='Tasks', index=False)
# Swimlane analysis sheet
swimlane_data = analysis_data.get('swimlane_analysis', {})
if swimlane_data:
swimlane_df = pd.DataFrame(swimlane_data).T.reset_index()
# Ensure all required columns exist
if 'total_time_minutes' in swimlane_df.columns:
swimlane_df['Total Time (hrs)'] = swimlane_df['total_time_minutes'] / 60
else:
swimlane_df['Total Time (hrs)'] = 0
# Rename columns to match expected structure
column_mapping = {
'index': 'Swimlane/Department',
'task_count': 'Task Count',
'total_cost': 'Total Cost',
'total_time_minutes': 'Total Time (min)',
'total_time_hours': 'Total Time (hrs)'
}
# Apply column mapping and add missing columns
for old_col, new_col in column_mapping.items():
if old_col in swimlane_df.columns:
swimlane_df[new_col] = swimlane_df[old_col]
else:
swimlane_df[new_col] = 0
# Ensure all expected columns exist
expected_columns = ['Swimlane/Department', 'Task Count', 'Total Cost', 'Total Time (min)', 'Total Time (hrs)']
for col in expected_columns:
if col not in swimlane_df.columns:
swimlane_df[col] = 0
# Select only the expected columns in the right order
swimlane_df = swimlane_df[expected_columns]
swimlane_df.to_excel(writer, sheet_name='Swimlane Analysis', index=False)
# Owner analysis sheet
owner_data = analysis_data.get('owner_analysis', {})
if owner_data:
owner_df = pd.DataFrame(owner_data).T.reset_index()
# Ensure all required columns exist
if 'total_time_minutes' in owner_df.columns:
owner_df['Total Time (hrs)'] = owner_df['total_time_minutes'] / 60
else:
owner_df['Total Time (hrs)'] = 0
# Rename columns to match expected structure
column_mapping = {
'index': 'Owner',
'task_count': 'Task Count',
'total_cost': 'Total Cost',
'total_time_minutes': 'Total Time (min)',
'total_time_hours': 'Total Time (hrs)'
}
# Apply column mapping and add missing columns
for old_col, new_col in column_mapping.items():
if old_col in owner_df.columns:
owner_df[new_col] = owner_df[old_col]
else:
owner_df[new_col] = 0
# Ensure all expected columns exist
expected_columns = ['Owner', 'Task Count', 'Total Cost', 'Total Time (min)', 'Total Time (hrs)']
for col in expected_columns:
if col not in owner_df.columns:
owner_df[col] = 0
# Select only the expected columns in the right order
owner_df = owner_df[expected_columns]
owner_df.to_excel(writer, sheet_name='Owner Analysis', index=False)
# Status analysis sheet
status_data = analysis_data.get('status_analysis', {})
if status_data:
status_df = pd.DataFrame(status_data).T.reset_index()
# Ensure all required columns exist
if 'total_time_minutes' in status_df.columns:
status_df['Total Time (hrs)'] = status_df['total_time_minutes'] / 60
else:
status_df['Total Time (hrs)'] = 0
# Rename columns to match expected structure
column_mapping = {
'index': 'Status',
'task_count': 'Task Count',
'total_cost': 'Total Cost',
'total_time_minutes': 'Total Time (min)',
'total_time_hours': 'Total Time (hrs)'
}
# Apply column mapping and add missing columns
for old_col, new_col in column_mapping.items():
if old_col in status_df.columns:
status_df[new_col] = status_df[old_col]
else:
status_df[new_col] = 0
# Ensure all expected columns exist
expected_columns = ['Status', 'Task Count', 'Total Cost', 'Total Time (min)', 'Total Time (hrs)']
for col in expected_columns:
if col not in status_df.columns:
status_df[col] = 0
# Select only the expected columns in the right order
status_df = status_df[expected_columns]
status_df.to_excel(writer, sheet_name='Status Analysis', index=False)
# Priority analysis sheet
priority_data = analysis_data.get('priority_analysis', {})
if priority_data:
priority_df = pd.DataFrame(priority_data).T.reset_index()
# Ensure all required columns exist
if 'total_time_minutes' in priority_df.columns:
priority_df['Total Time (hrs)'] = priority_df['total_time_minutes'] / 60
else:
priority_df['Total Time (hrs)'] = 0
# Rename columns to match expected structure
column_mapping = {
'index': 'Priority',
'task_count': 'Task Count',
'total_cost': 'Total Cost',
'total_time_minutes': 'Total Time (min)',
'total_time_hours': 'Total Time (hrs)'
}
# Apply column mapping and add missing columns
for old_col, new_col in column_mapping.items():
if old_col in priority_df.columns:
priority_df[new_col] = priority_df[old_col]
else:
priority_df[new_col] = 0
# Ensure all expected columns exist
expected_columns = ['Priority', 'Task Count', 'Total Cost', 'Total Time (min)', 'Total Time (hrs)']
for col in expected_columns:
if col not in priority_df.columns:
priority_df[col] = 0
# Select only the expected columns in the right order
priority_df = priority_df[expected_columns]
priority_df.to_excel(writer, sheet_name='Priority Analysis', index=False)
# Documentation status analysis sheet
doc_status_data = analysis_data.get('doc_status_analysis', {})
if doc_status_data:
doc_status_df = pd.DataFrame(doc_status_data).T.reset_index()
# Ensure all required columns exist
if 'total_time_minutes' in doc_status_df.columns:
doc_status_df['Total Time (hrs)'] = doc_status_df['total_time_minutes'] / 60
else:
doc_status_df['Total Time (hrs)'] = 0
# Rename columns to match expected structure
column_mapping = {
'index': 'Documentation Status',
'task_count': 'Task Count',
'total_cost': 'Total Cost',
'total_time_minutes': 'Total Time (min)',
'total_time_hours': 'Total Time (hrs)'
}
# Apply column mapping and add missing columns
for old_col, new_col in column_mapping.items():
if old_col in doc_status_df.columns:
doc_status_df[new_col] = doc_status_df[old_col]
else:
doc_status_df[new_col] = 0
# Ensure all expected columns exist
expected_columns = ['Documentation Status', 'Task Count', 'Total Cost', 'Total Time (min)', 'Total Time (hrs)']
for col in expected_columns:
if col not in doc_status_df.columns:
doc_status_df[col] = 0
# Select only the expected columns in the right order
doc_status_df = doc_status_df[expected_columns]
doc_status_df.to_excel(writer, sheet_name='Documentation Status', index=False)
# Tools analysis sheet
tools_data = analysis_data.get('tools_analysis', {})
if tools_data:
tools_df = pd.DataFrame(tools_data).T.reset_index()
# Ensure all required columns exist
if 'total_time_minutes' in tools_df.columns:
tools_df['Total Time (hrs)'] = tools_df['total_time_minutes'] / 60
else:
tools_df['Total Time (hrs)'] = 0
# Rename columns to match expected structure
column_mapping = {
'index': 'Tool',
'task_count': 'Task Count',
'total_cost': 'Total Cost',
'total_time_minutes': 'Total Time (min)',
'total_time_hours': 'Total Time (hrs)'
}
# Apply column mapping and add missing columns
for old_col, new_col in column_mapping.items():
if old_col in tools_df.columns:
tools_df[new_col] = tools_df[old_col]
else:
tools_df[new_col] = 0
# Ensure all expected columns exist
expected_columns = ['Tool', 'Task Count', 'Total Cost', 'Total Time (min)', 'Total Time (hrs)']
for col in expected_columns:
if col not in tools_df.columns:
tools_df[col] = 0
# Select only the expected columns in the right order
tools_df = tools_df[expected_columns]
tools_df.to_excel(writer, sheet_name='Tools Analysis', index=False)
# Tool combinations sheet
tool_combinations_data = analysis_data.get('tool_combinations', {})
if tool_combinations_data:
combo_df = pd.DataFrame(tool_combinations_data).T.reset_index()
# Ensure all required columns exist
if 'total_time_minutes' in combo_df.columns:
combo_df['Total Time (hrs)'] = combo_df['total_time_minutes'] / 60
else:
combo_df['Total Time (hrs)'] = 0
# Rename columns to match expected structure
column_mapping = {
'index': 'Tool Combination',
'task_count': 'Task Count',
'total_cost': 'Total Cost',
'total_time_minutes': 'Total Time (min)',
'total_time_hours': 'Total Time (hrs)'
}
# Apply column mapping and add missing columns
for old_col, new_col in column_mapping.items():
if old_col in combo_df.columns:
combo_df[new_col] = combo_df[old_col]
else:
combo_df[new_col] = 0
# Ensure all expected columns exist
expected_columns = ['Tool Combination', 'Task Count', 'Total Cost', 'Total Time (min)', 'Total Time (hrs)']
for col in expected_columns:
if col not in combo_df.columns:
combo_df[col] = 0
# Select only the expected columns in the right order
combo_df = combo_df[expected_columns]
combo_df.to_excel(writer, sheet_name='Tool Combinations', index=False)
# Quality control sheet
quality_data = analysis_data.get('quality_issues', [])
if quality_data:
quality_df = pd.DataFrame(quality_data)
quality_df.to_excel(writer, sheet_name='Quality Control', index=False)
return filename
except Exception as e:
st.error(f"Error generating Excel report: {str(e)}")
return None
def main():
"""
Main Streamlit application for BPMN analysis.
"""
st.set_page_config(
page_title="Inocta BPM Analysis",
page_icon="📊",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get Help': None,
'Report a bug': None,
'About': None
}
)
st.title("📊 Inocta BPM Analysis")
# Custom CSS to fix any display issues
st.markdown("""
<style>
/* Fix any URL display issues */
.stApp > header {
display: none;
}
/* Ensure clean display */
.main .block-container {
padding-top: 1rem;
}
</style>
""", unsafe_allow_html=True)
st.markdown("""
This tool analyzes BPMN XML files to extract business insights, calculate costs,
and provide KPI analysis for process optimization.
""")
# Initialize analyzer
analyzer = BPMNAnalyzer()
# Sidebar for file upload
st.sidebar.header("📁 File Upload")
uploaded_files = st.sidebar.file_uploader(
"Upload BPMN XML files",
type=['xml', 'bpmn'],
accept_multiple_files=True,
help="Upload one or more BPMN XML files for analysis"
)
if uploaded_files:
st.sidebar.success(f"✅ {len(uploaded_files)} file(s) uploaded")
# Process each file
all_analysis_data = []
for uploaded_file in uploaded_files:
st.sidebar.write(f"📄 {uploaded_file.name}")
# Read file content
file_content = uploaded_file.read().decode('utf-8')
# Parse BPMN file
with st.spinner(f"Analyzing {uploaded_file.name}..."):
parsed_data = analyzer.parse_bpmn_file(file_content)
if parsed_data:
# Analyze business insights
analysis_data = analyzer.analyze_business_insights(parsed_data)
analysis_data['filename'] = uploaded_file.name
all_analysis_data.append(analysis_data)
# Show success with task count
task_count = len(parsed_data.get('tasks', []))
st.success(f"✅ Successfully analyzed {uploaded_file.name} - Found {task_count} tasks")
else:
st.error(f"❌ Failed to analyze {uploaded_file.name}")
if all_analysis_data:
# Display analysis results
st.header("📈 Analysis Results")
# Combine all data for overall analysis
combined_tasks = []
for data in all_analysis_data:
combined_tasks.extend(data.get('tasks', []))
if combined_tasks:
# Overall summary
total_cost = sum(task.get('total_cost', 0) for task in combined_tasks)
total_time = sum(task.get('time_minutes', 0) for task in combined_tasks)
total_tasks = len(combined_tasks)
# Create summary metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Tasks", total_tasks)
with col2:
st.metric("Total Cost", f"${total_cost:,.2f}")
with col3:
st.metric("Total Time", f"{total_time/60:.1f} hours")
with col4:
currencies = set(task.get('currency', 'Unknown') for task in combined_tasks if task.get('currency'))
st.metric("Currencies", ", ".join(currencies) if currencies else "Unknown")
# Detailed analysis tabs
tab_names = [
"📊 Executive Summary",
"📋 Tasks Overview",
"🏭 Swimlane Analysis",
"👥 Owner Analysis",
"📊 Status Analysis",
"📚 Documentation Status",
"🔧 Tools Analysis",
"💡 Opportunities",
"⚠️ Issues & Risks",
"❓ FAQ Knowledge",
"✅ Quality Control",
"💾 Export Data",
"❓ Help & Guide"
]
tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8, tab9, tab10, tab11, tab12, tab13 = st.tabs(tab_names)
with tab1:
st.subheader("📊 Executive Summary")
# High-level KPIs
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric(
"Total Tasks",
f"{len(combined_tasks):,}",
help="Total number of tasks across all processes"
)
with col2:
total_cost = sum(task.get('total_cost', 0) for task in combined_tasks)
currencies = set(task.get('currency', 'Unknown') for task in combined_tasks if task.get('currency'))
currency_display = list(currencies)[0] if currencies else 'Unknown'
st.metric(
"Total Cost",
f"{currency_display} {total_cost:,.2f}",
help="Total cost across all tasks"
)
with col3:
total_time_hours = sum(task.get('time_minutes', 0) for task in combined_tasks) / 60
st.metric(
"Total Time",
f"{total_time_hours:.1f} hrs",
help="Total estimated time across all tasks"
)
with col4:
unique_swimlanes = len(set(task.get('swimlane', 'Unknown') for task in combined_tasks))
st.metric(
"Departments",
f"{unique_swimlanes}",
help="Number of departments/swimlanes involved"
)
# Summary charts row 1
col1, col2 = st.columns(2)
with col1:
# Cost distribution by department
swimlane_costs = {}
for task in combined_tasks:
swimlane = task.get('swimlane', 'Unknown')
if swimlane not in swimlane_costs:
swimlane_costs[swimlane] = 0
swimlane_costs[swimlane] += task.get('total_cost', 0)
if swimlane_costs:
fig = px.pie(
values=list(swimlane_costs.values()),
names=list(swimlane_costs.keys()),
title="Cost Distribution by Department",
color_discrete_sequence=px.colors.qualitative.Set3
)
fig.update_traces(textposition='inside', textinfo='percent+label')
st.plotly_chart(fig, use_container_width=True)
with col2:
# Time distribution by department
swimlane_times = {}
for task in combined_tasks:
swimlane = task.get('swimlane', 'Unknown')
if swimlane not in swimlane_times:
swimlane_times[swimlane] = 0
swimlane_times[swimlane] += task.get('time_minutes', 0)
if swimlane_times:
# Convert to hours for better readability
swimlane_hours = {k: v/60 for k, v in swimlane_times.items()}
fig = px.bar(
x=list(swimlane_hours.keys()),
y=list(swimlane_hours.values()),
title="Time Distribution by Department (Hours)",
color=list(swimlane_hours.values()),
color_continuous_scale='viridis'
)
fig.update_layout(xaxis_title="Department", yaxis_title="Hours")
st.plotly_chart(fig, use_container_width=True)
# Summary charts row 2
col1, col2 = st.columns(2)
with col1:
# Task status overview
status_counts = {}
for task in combined_tasks:
status = task.get('task_status', 'Unknown')
if status not in status_counts:
status_counts[status] = 0
status_counts[status] += 1
if status_counts:
fig = px.pie(
values=list(status_counts.values()),
names=list(status_counts.keys()),
title="Task Status Overview",
color_discrete_sequence=px.colors.qualitative.Pastel
)
fig.update_traces(textposition='inside', textinfo='percent+label')
st.plotly_chart(fig, use_container_width=True)
with col2:
# Documentation status overview
doc_status_counts = {}
for task in combined_tasks: