File size: 8,848 Bytes
0dd91bb
 
399384d
 
0dd91bb
 
 
 
 
ec8df18
0dd91bb
 
 
 
399384d
 
 
 
 
 
 
0dd91bb
399384d
 
 
 
 
 
0dd91bb
 
 
399384d
 
 
 
 
0dd91bb
399384d
 
 
 
 
0dd91bb
399384d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec8df18
 
 
 
399384d
 
 
 
 
 
0dd91bb
ec8df18
399384d
 
 
 
 
 
 
 
 
 
 
 
 
 
a86665e
399384d
 
 
 
 
 
a86665e
 
 
ec8df18
 
 
e3bd00e
 
399384d
 
 
 
 
 
 
0dd91bb
 
 
399384d
 
 
 
 
 
 
 
 
 
0dd91bb
399384d
 
 
 
 
 
 
0dd91bb
399384d
 
 
 
 
 
 
0dd91bb
399384d
 
 
 
 
 
0dd91bb
399384d
cf6458e
 
 
 
 
399384d
 
 
0dd91bb
 
 
399384d
8bfc25e
399384d
 
 
 
 
 
 
 
 
 
 
 
 
0dd91bb
 
 
399384d
 
8bfc25e
399384d
 
8bfc25e
399384d
 
 
 
ec8df18
 
 
0dd91bb
ec8df18
0dd91bb
 
8bfc25e
 
 
 
399384d
0dd91bb
399384d
 
 
 
 
0dd91bb
cf6458e
8bfc25e
399384d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dd91bb
399384d
 
 
 
 
 
 
 
 
 
 
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
"""Streamlit UI for the DECODE Correlation Network Generator."""

import streamlit as st
import pandas as pd

from parse_excel import (
    detect_data_start_row,
    detect_cutoff_value,
    detect_correlation_column_start,
    detect_reward_territories,
    detect_nonrewards_patterns,
    extract_network_data,
)
from build_network import generate_network_html

# =============================================================================
# PAGE CONFIG
# =============================================================================
st.set_page_config(
    page_title="DECODE Correlation Network Generator",
    page_icon="πŸ”—",
    layout="wide",
)

st.title("πŸ”— DECODE Correlation Network Generator")
st.markdown("**Generate interactive HTML network visualizations from correlation matrices (DEVIATION data)**")
st.markdown("---")

# =============================================================================
# 1. FILE UPLOAD
# =============================================================================
st.header("1. Upload Excel File")

uploaded_file = st.file_uploader(
    "Choose your correlation Excel file",
    type=['xlsx', 'xls'],
    help="Upload the Excel file containing your correlation matrix",
)

worksheet_name = st.text_input(
    "Worksheet Name",
    value="Results Correls",
    help="Name of the worksheet containing the correlation data",
)

# Initialize session state
if 'df' not in st.session_state:
    st.session_state.df = None
if 'detected_values' not in st.session_state:
    st.session_state.detected_values = {}

# Load and analyze file
if uploaded_file is not None:
    try:
        df = pd.read_excel(uploaded_file, sheet_name=worksheet_name, header=None)
        st.session_state.df = df

        detected_row, blocks = detect_data_start_row(df)
        detected_cutoff = detect_cutoff_value(df)
        detected_col = detect_correlation_column_start(df)
        rewards_factors = detect_reward_territories(df)
        patterns = detect_nonrewards_patterns(
            df, detected_row - 1 if detected_row else 95, rewards_factors
        )

        st.session_state.detected_values = {
            'row': detected_row,
            'col': detected_col,
            'cutoff': detected_cutoff,
            'blocks': blocks,
            'patterns': patterns,
            'rewards_factors': rewards_factors,
        }

        st.success(f"βœ… File loaded: {df.shape[0]} rows Γ— {df.shape[1]} columns")

        with st.expander("πŸ“Š Auto-detected Values", expanded=True):
            col1, col2 = st.columns(2)
            with col1:
                st.markdown(f"**DATA_START_ROW:** {detected_row or 'Not detected'}")
                st.caption("(2nd text block = DEVIATION data)")
                if blocks:
                    blocks_text = ", ".join([f"Block {i+1}: Row {s}-{e}" for i, (s, e) in enumerate(blocks)])
                    st.caption(f"Text blocks: {blocks_text}")
            with col2:
                st.markdown(f"**CORR_COL_START:** {detected_col or 'Not detected'}")
                st.caption("(First large column block >50 cols in row 5)")

            col3, col4 = st.columns(2)
            with col3:
                st.markdown(f"**CORR_THRESHOLD:** {detected_cutoff or 'Not detected'}")
                st.caption("(From 'Cut-off used in columns')")
            with col4:
                rewards = patterns.get('Rewards', 0) if patterns else 0
                nonrewards = patterns.get('Nonrewards', 0) if patterns else 0
                st.markdown(f"**Classification:** {rewards} Rewards, {nonrewards} Nonrewards")
                territories_str = ", ".join(rewards_factors[:6])
                if len(rewards_factors) > 6:
                    territories_str += f", +{len(rewards_factors) - 6} more"
                st.caption(f"Detected reward territories: {territories_str}")
                st.caption("(Counts based on auto-detected row; final classification at generation)")

    except Exception as e:
        st.error(f"❌ Error loading file: {str(e)}")
        st.session_state.df = None

st.markdown("---")

# =============================================================================
# 2. PARAMETERS
# =============================================================================
st.header("2. Data Parameters")
st.caption("Adjust auto-detected values if needed")

col1, col2 = st.columns(2)

with col1:
    data_start_row = st.number_input(
        "Data Start Row",
        min_value=1,
        value=st.session_state.detected_values.get('row', 97) or 97,
        help="Excel row number where data starts (1-based)",
    )
    threshold = st.number_input(
        "Correlation Threshold",
        min_value=0.0,
        value=float(st.session_state.detected_values.get('cutoff', 6.0) or 6.0),
        step=0.1,
        format="%.2f",
        help="Higher = fewer connections, Lower = more connections",
    )

with col2:
    corr_col_start = st.number_input(
        "Correlation Column Start",
        min_value=0,
        value=st.session_state.detected_values.get('col', 32) or 32,
        help="Column index where correlation data starts (0-based)",
    )
    max_l1_nodes = st.number_input(
        "Max L1 Connections",
        min_value=1,
        max_value=20,
        value=5,
        help="Maximum number of Level 1 connections per node",
    )
    show_category_index = st.checkbox(
        "Show Category Index in labels",
        value=True,
        help="Display the Category Index number on each node. Uncheck for cleaner labels.",
    )

st.markdown("---")

# =============================================================================
# 3. PROJECT DETAILS
# =============================================================================
st.header("3. Project Details")
st.caption("Optional β€” used for HTML title and output filename. Falls back to uploaded filename.")

col1, col2 = st.columns(2)

with col1:
    client_name = st.text_input("Client Name", placeholder="e.g., P&G")
    brand_name = st.text_input("Brand Name", placeholder="e.g., Oral-B")

with col2:
    country_name = st.text_input("Country Code", placeholder="e.g., UK, MX, US")
    category_name = st.text_input("Category", placeholder="e.g., OralCare")

st.markdown("---")

# =============================================================================
# 4. GENERATE
# =============================================================================
st.header("4. Generate Network")

can_generate = st.session_state.df is not None

if not can_generate:
    st.warning("⚠️ Please upload a file")

if st.button("πŸš€ Generate HTML Network", disabled=not can_generate, type="primary"):
    with st.spinner("Generating network..."):
        try:
            rewards_factors = st.session_state.detected_values.get(
                'rewards_factors', detect_reward_territories(st.session_state.df)
            )
            network_data = extract_network_data(
                st.session_state.df, data_start_row, corr_col_start, rewards_factors
            )

            # Derive fallback name from uploaded filename
            upload_name = uploaded_file.name if uploaded_file else ""
            fallback_name = upload_name.rsplit('.', 1)[0] if upload_name else ""

            html_content, stats, filename = generate_network_html(
                network_data,
                threshold,
                max_l1_nodes,
                client_name.strip(),
                country_name.strip(),
                brand_name.strip(),
                category_name.strip(),
                show_category_index=show_category_index,
                fallback_name=fallback_name,
            )

            st.success("βœ… Network generated successfully!")

            col1, col2, col3, col4 = st.columns(4)
            col1.metric("Drivers", stats['drivers'])
            col2.metric("Rewards (red)", stats['rewards'])
            col3.metric("Nonrewards (blue)", stats['nonrewards'])
            col4.metric("Correlations", stats['positive_correlations'])

            st.download_button(
                label="πŸ“₯ Download HTML File",
                data=html_content,
                file_name=filename,
                mime="text/html",
                type="primary",
            )
            st.caption(f"Filename: `{filename}`")

        except Exception as e:
            st.error(f"❌ Error generating network: {str(e)}")
            import traceback
            st.code(traceback.format_exc())

# Footer
st.markdown("---")
st.caption("DECODE Correlation Network Generator | Uses DEVIATION data (normalized values)")