Download app.py from DecodeMarketing/Correlation-network: direct link, hf CLI and curl.
- Browser
- Download file 8.85 kB
-
https://huggingface.co/spaces/DecodeMarketing/Correlation-network/resolve/main/app.py
- Command line
-
hf download hf://spaces/DecodeMarketing/Correlation-network/app.py
-
curl -L -o app.py https://huggingface.co/spaces/DecodeMarketing/Correlation-network/resolve/main/app.py
8.85 kB
| """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)") | |