File size: 10,589 Bytes
a95b240
 
 
 
3ff5801
 
 
a95b240
 
3ff5801
a95b240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ff5801
 
 
 
 
 
 
d2ed71e
 
3ff5801
 
 
 
 
d2ed71e
3ff5801
 
d2ed71e
3ff5801
 
 
 
 
 
d2ed71e
 
 
 
 
 
 
 
 
 
3ff5801
d2ed71e
 
 
 
 
 
 
 
 
 
3ff5801
d2ed71e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ff5801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b21c4dc
d2ed71e
3ff5801
 
 
d2ed71e
 
 
3ff5801
d2ed71e
 
 
3ff5801
 
 
 
 
 
 
d2ed71e
3ff5801
 
 
d2ed71e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ff5801
 
a95b240
 
be26c88
 
 
 
 
 
 
3ff5801
be26c88
d2ed71e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb4dec8
 
 
bdb15d5
 
ea0509b
e24c1ad
eb4dec8
 
 
 
3ff5801
eb4dec8
 
3ff5801
 
 
 
eb4dec8
 
 
 
 
 
e24c1ad
 
 
 
 
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
import pandas as pd
import streamlit as st
import csv
import io
import openpyxl  # Add this import for Excel handling
from datetime import datetime
import re

def preprocess_csv(input_bytes):
    # Keep this for backward compatibility with CSV files
    text = input_bytes.decode()  # Decode bytes to text
    output = io.StringIO()
    writer = csv.writer(output)

    for row in csv.reader(io.StringIO(text)):  # Read text as csv
        if len(row) > 5:
            row = row[0:5] + [','.join(row[5:])]  # Combine extra fields into one
        writer.writerow(row)

    output.seek(0)  # go to the start of the StringIO object
    return output

def load_data(file):
    column_names = [
        'Functional area',
        'Scenario name',
        'Start datetime',
        'End datetime',
        'Status',
        'Error message'
    ]
    data = pd.read_csv(file, header=None, names=column_names)
    return data

@st.cache_data
def preprocess_xlsx(uploaded_file):
    """Process Excel file with step-level data and convert to scenario-level summary"""
    # Define data types for columns
    dtype_dict = {
        'Feature Name': 'string',
        'Scenario Name': 'string',
        'Total Time Taken (ms)': 'float64',
        'Failed Scenario': 'string'
    }
    
    # Read both the first sheet for error messages and "Time Taken" sheet
    excel_file = pd.ExcelFile(uploaded_file, engine='openpyxl')
    
    # Read detailed step data from first sheet (contains error messages)
    error_df = pd.read_excel(excel_file, sheet_name=0)
    
    # Read time taken data from the "Time Taken" sheet
    df = pd.read_excel(
        excel_file,
        sheet_name='Time Taken',
        dtype=dtype_dict
    )
    
    # Print column names and sample values for debugging
    # st.write("Excel columns:", df.columns.tolist())
    # st.write("Sample data from Time Taken sheet:", df.head())
    # st.write("Unique Feature Names:", df['Feature Name'].unique())
    # st.write("Feature Name count:", df['Feature Name'].nunique())
    
    # # Check for any empty or NaN values in Feature Name
    # empty_features = df['Feature Name'].isna().sum()
    # st.write(f"Empty Feature Names: {empty_features}")
    
    # Convert Failed Scenario column to boolean after reading
    # Handle different possible values (TRUE/FALSE, True/False, etc.)
    df['Failed Scenario'] = df['Failed Scenario'].astype(str).str.upper()
    df['Status'] = df['Failed Scenario'].map(
        lambda x: 'FAILED' if x in ['TRUE', 'YES', 'Y', '1'] else 'PASSED'
    )
    
    # Count failed and passed scenarios
    failed_count = (df['Status'] == 'FAILED').sum()
    passed_count = (df['Status'] == 'PASSED').sum()
   
    
    # Extract error messages from the first sheet
    # Find rows with FAILED result and group by Scenario Name to get the error message
    if 'Result' in error_df.columns:
        failed_steps = error_df[error_df['Result'] == 'FAILED'].copy()
        
        # If there are failed steps, get the error messages
        if not failed_steps.empty:
            # Group by Scenario Name and get the first error message and step for each scenario
            error_messages = failed_steps.groupby('Scenario Name').agg({
                'Error Message': 'first',
                'Step': 'first'  # Capture the step where it failed
            }).reset_index()
        else:
            # Create empty DataFrame with required columns
            error_messages = pd.DataFrame(columns=['Scenario Name', 'Error Message', 'Step'])
    else:
        # If Result column doesn't exist, create empty DataFrame
        error_messages = pd.DataFrame(columns=['Scenario Name', 'Error Message', 'Step'])
    
    # Extract date from filename (e.g., RI2211_batch_20250225_27031.xlsx)
    filename = uploaded_file.name
    date_match = re.search(r'_(\d{8})_', filename)
    if date_match:
        date_str = date_match.group(1)
        file_date = datetime.strptime(date_str, '%Y%m%d').date()
    else:
        st.warning(f"Could not extract date from filename: {filename}. Using current date.")
        file_date = datetime.now().date()
    
    # Extract environment from filename
    if any(pattern in filename for pattern in ['_batch_', '_fin_', '_priority_', '_Puppeteer_']):
        environment = filename.split('_')[0]
    else:
        environment = filename.split('.')[0]
    
    # Create result dataframe
    result_df = pd.DataFrame({
        'Functional area': df['Feature Name'],
        'Scenario Name': df['Scenario Name'],
        'Status': df['Status'],
        'Time spent': df['Total Time Taken (ms)'] / 1000  # Convert ms to seconds
    })
    
    # Fill any NaN values in Functional area
    result_df['Functional area'] = result_df['Functional area'].fillna('Unknown')
    
    # Merge error messages with result dataframe
    if not error_messages.empty:
        result_df = result_df.merge(error_messages[['Scenario Name', 'Error Message', 'Step']], 
                                   on='Scenario Name', how='left')
    
    # Add environment column
    result_df['Environment'] = environment
    
    # Calculate formatted time spent
    result_df['Time spent(m:s)'] = pd.to_datetime(result_df['Time spent'], unit='s').dt.strftime('%M:%S')
    
    
    result_df['Start datetime'] = pd.to_datetime(file_date)
    result_df['End datetime'] = result_df['Start datetime'] + pd.to_timedelta(result_df['Time spent'], unit='s')
    
    # Add failed step information if available
    if 'Step' in result_df.columns:
        result_df['Failed Step'] = result_df['Step']
        result_df.drop('Step', axis=1, inplace=True)
    
    # Extract start time from the first sheet
    before_steps = error_df[error_df['Step'].str.contains('before', case=False, na=False)]
    if not before_steps.empty:
        # Get the first 'before' step for each scenario
        before_steps['Time Stamp'] = pd.to_datetime(before_steps['Time Stamp'], format='%H:%M:%S', errors='coerce')
        start_times = before_steps.groupby('Scenario Name').agg({'Time Stamp': 'first'}).reset_index()
        # Store the timestamps in a variable for efficient reuse
        result_df = result_df.merge(start_times, on='Scenario Name', how='left')
        result_df.rename(columns={'Time Stamp': 'Scenario Start Time'}, inplace=True)
        scenario_start_times = result_df['Scenario Start Time']
        # Combine the date from the filename with the time stamp
        result_df['Start datetime'] = pd.to_datetime(scenario_start_times.dt.strftime('%H:%M:%S') + ' ' + file_date.strftime('%Y-%m-%d'))
    
    # Print counts for debugging
    # st.write(f"Processed data - Failed: {len(result_df[result_df['Status'] == 'FAILED'])}, Passed: {len(result_df[result_df['Status'] == 'PASSED'])}")
    # st.write(f"Unique functional areas in processed data: {result_df['Functional area'].nunique()}")
    # st.write(f"Unique functional areas: {result_df['Functional area'].unique()}")
    
    # Debugging: Print the columns of the first sheet
    # st.write("Columns in the first sheet:", error_df.columns.tolist())
    # st.write("Sample data from the first sheet:", error_df.head())
    
    return result_df

def fill_missing_data(data, column_index, value):
    data.iloc[:, column_index] = data.iloc[:, column_index].fillna(value)
    return data

# Define a function to convert a string to camel case
def to_camel_case(s):
    parts = s.split('_')
    return ''.join([part.capitalize() for part in parts])

# Define the function to preprocess a file (CSV or XLSX)
def preprocess_uploaded_file(uploaded_file):
    # Commenting out the spinner to disable it
    # with st.spinner(f'Processing {uploaded_file.name}...'):
    # Determine file type based on extension
    if uploaded_file.name.lower().endswith('.xlsx'):
        data = preprocess_xlsx(uploaded_file)
    else:
        # Original CSV processing
        file_content = uploaded_file.read()
        processed_output = preprocess_csv(file_content)
        processed_file = io.StringIO(processed_output.getvalue())
        data = load_data(processed_file)
        data = fill_missing_data(data, 4, 0)
        data['Start datetime'] = pd.to_datetime(data['Start datetime'], dayfirst=True, errors='coerce')
        data['End datetime'] = pd.to_datetime(data['End datetime'], dayfirst=True, errors='coerce')
        data['Time spent'] = (data['End datetime'] - data['Start datetime']).dt.total_seconds()
        data['Time spent(m:s)'] = pd.to_datetime(data['Time spent'], unit='s').dt.strftime('%M:%S')
        
        # Extract environment name from filename
        filename = uploaded_file.name
        environment = filename.split('_Puppeteer')[0]
        
        # Add environment column to the dataframe
        data['Environment'] = environment
    return data

def add_app_description():
    app_title = '<p style="font-family:Roboto, sans-serif; color:#004E7C; font-size: 42px;">DataLink Compare</p>'
    st.markdown(app_title, unsafe_allow_html=True)
    
   
    is_selected = st.sidebar.checkbox('Show App Description', value=False)

    if is_selected:
        with st.expander('Show App Description'):
            st.markdown("Welcome to DataLink Compare. This tool allows you to analyze batch run reports and provides insights into their statuses, processing times, and more. You can also compare two files to identify differences and similarities between them.")

            st.markdown("### Instructions:")
            st.write("1. Upload your CSV or XLSX file using the file uploader on the sidebar.")
            st.write("2. Choose between 'Multi', 'Compare', 'Weekly', and 'Multi-Env Compare' mode using the dropdown on the sidebar.")
            st.write("3. In 'Multi' mode, you can upload and analyze multiple files for individual environments.")
            st.write("4. In 'Compare' mode, you can upload two files to compare them.")

            st.markdown("### Features:")
            st.write("- View statistics of passing and failing scenarios.")
            st.write("- Filter scenarios by functional area and status.")
            st.write("- Calculate average time spent for each functional area.")
            st.write("- Display bar graphs showing the number of failed scenarios.")
            st.write("- Identify consistent failures, new failures, and changes in passing scenarios.")

     # Add the new link here
    link_html = '<p style="font-size: 14px;"><a href="https://scenarioswitcher.negadan77.workers.dev/" target="_blank">Open Scenario Processor</a></p>'
    st.markdown(link_html, unsafe_allow_html=True)