File size: 17,640 Bytes
b937f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

CSV to Interactive Web App - Freelance Template

Kaggle Rank #44 - Tassawar Abbas

Use this for every client. Just change the title and instructions.

"""

import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from io import StringIO, BytesIO
import base64
import numpy as np

# ========== PAGE CONFIGURATION ==========
st.set_page_config(
    page_title="CSV Data Explorer - Tassawar Abbas",
    page_icon="πŸ“Š",
    layout="wide",
    initial_sidebar_state="expanded"
)

# ========== CUSTOM CSS (Makes it look professional) ==========
st.markdown("""

<style>

    .main-header {

        font-size: 2.5rem;

        color: #1E88E5;

        text-align: center;

        margin-bottom: 1rem;

    }

    .kaggle-badge {

        background-color: #20BEFF;

        padding: 0.5rem;

        border-radius: 10px;

        text-align: center;

        color: white;

        font-weight: bold;

    }

    .insight-box {

        background-color: #F0F2F6;

        padding: 1rem;

        border-radius: 10px;

        margin: 1rem 0;

    }

</style>

""", unsafe_allow_html=True)

# ========== HEADER WITH YOUR CREDENTIAL ==========
st.markdown('<p class="kaggle-badge">πŸ† Kaggle Notebooks Expert - Rank #44 of 61,000+ | Built by Tassawar Abbas</p>', unsafe_allow_html=True)
st.markdown('<h1 class="main-header">πŸ“Š CSV Data Explorer</h1>', unsafe_allow_html=True)
st.markdown("*Upload your CSV file. Filter, sort, visualize, and download insights instantly.*")

# ========== SIDEBAR - INSTRUCTIONS ==========
with st.sidebar:
    st.markdown("### πŸš€ How to Use")
    st.markdown("""

    1. Upload your CSV file (any size)

    2. Use filters to explore data

    3. Click column headers to sort

    4. Download filtered data

    5. Download charts as images

    """)
    st.markdown("---")
    st.markdown(f"**Need a custom app?** [Contact me on LinkedIn](https://www.linkedin.com/in/abbas829pro/)")
    st.markdown(f"**See my work on** [Kaggle](https://www.kaggle.com/abbas829) | [GitHub](https://github.com/abbas829)")
    st.markdown("---")
    st.markdown("### πŸ“Š Quick Stats")
    st.markdown("- **Kaggle Rank:** #44 Notebooks")
    st.markdown("- **Kaggle Rank:** #122 Datasets")
    st.markdown("- **Experience:** 2+ Years")

# ========== FILE UPLOAD ==========
uploaded_file = st.file_uploader(
    "πŸ“ Choose a CSV or Excel file",
    type=['csv', 'xlsx', 'xls'],
    help="Upload any CSV or Excel file. Your data stays private - processed in your browser."
)

# ========== MAIN APP LOGIC ==========
if uploaded_file is not None:
    # Load data based on file type
    try:
        if uploaded_file.name.endswith('.csv'):
            df = pd.read_csv(uploaded_file)
        else:
            df = pd.read_excel(uploaded_file)
        
        # Show basic info
        st.success(f"βœ… Successfully loaded {df.shape[0]} rows and {df.shape[1]} columns")
        
        # ========== DATA PREVIEW SECTION ==========
        with st.expander("πŸ” View Raw Data (click to expand)"):
            st.dataframe(df.head(100), use_container_width=True)
            st.caption(f"Showing first 100 rows of {df.shape[0]} total rows")
        
        # ========== FILTER SECTION ==========
        st.markdown("### 🎯 Filter Your Data")
        
        # Create filters in columns
        col1, col2, col3 = st.columns(3)
        
        filtered_df = df.copy()
        
        # Column selector for filtering
        with col1:
            filter_column = st.selectbox(
                "Select column to filter",
                options=df.columns.tolist(),
                key="filter_col"
            )
        
        # Dynamic filter based on column type
        with col2:
            if filter_column:
                if df[filter_column].dtype in ['int64', 'float64']:
                    min_val = float(df[filter_column].min())
                    max_val = float(df[filter_column].max())
                    filter_range = st.slider(
                        f"Range for {filter_column}",
                        min_val, max_val, (min_val, max_val)
                    )
                    filtered_df = filtered_df[
                        (filtered_df[filter_column] >= filter_range[0]) & 
                        (filtered_df[filter_column] <= filter_range[1])
                    ]
                else:
                    unique_vals = df[filter_column].dropna().unique().tolist()
                    selected_vals = st.multiselect(
                        f"Select values for {filter_column}",
                        options=unique_vals,
                        default=unique_vals[:5] if len(unique_vals) > 5 else unique_vals
                    )
                    if selected_vals:
                        filtered_df = filtered_df[filtered_df[filter_column].isin(selected_vals)]
        
        # Search box for text columns
        with col3:
            search_col = st.selectbox("Search in column", options=["None"] + df.columns.tolist())
            if search_col != "None":
                search_term = st.text_input(f"Search in {search_col}")
                if search_term:
                    filtered_df = filtered_df[
                        filtered_df[search_col].astype(str).str.contains(search_term, case=False)
                    ]
        
        # ========== RESULTS SUMMARY ==========
        st.info(f"πŸ“Œ **Showing {filtered_df.shape[0]} rows** out of {df.shape[0]} total")
        
        # ========== INTERACTIVE TABLE ==========
        st.markdown("### πŸ“‹ Filtered Data (click column headers to sort)")
        st.dataframe(filtered_df, use_container_width=True, height=400)
        
        # ========== DOWNLOAD BUTTONS ==========
        st.markdown("### πŸ’Ύ Download Data")
        col_dl1, col_dl2, col_dl3 = st.columns(3)
        
        with col_dl1:
            csv = filtered_df.to_csv(index=False).encode('utf-8')
            st.download_button(
                label="πŸ“₯ Download as CSV",
                data=csv,
                file_name='filtered_data.csv',
                mime='text/csv',
                use_container_width=True
            )
        
        with col_dl2:
            # For Excel download
            output = BytesIO()
            with pd.ExcelWriter(output, engine='openpyxl') as writer:
                filtered_df.to_excel(writer, index=False, sheet_name='Filtered Data')
            excel_data = output.getvalue()
            st.download_button(
                label="πŸ“₯ Download as Excel",
                data=excel_data,
                file_name='filtered_data.xlsx',
                mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                use_container_width=True
            )
        
        with col_dl3:
            # Summary stats download
            if len(filtered_df) > 0:
                summary = filtered_df.describe().to_csv()
                st.download_button(
                    label="πŸ“Š Download Summary Stats",
                    data=summary,
                    file_name='summary_statistics.csv',
                    mime='text/csv',
                    use_container_width=True
                )
        
        # ========== AI INSIGHTS ==========
        st.markdown("### πŸ€– Data Insights")
        st.markdown('<div class="insight-box">', unsafe_allow_html=True)
        
        insight_col1, insight_col2 = st.columns(2)
        
        with insight_col1:
            # Find numeric columns for insights
            numeric_cols = filtered_df.select_dtypes(include=['int64', 'float64']).columns.tolist()
            if numeric_cols and len(filtered_df) > 0:
                selected_num = st.selectbox("πŸ“ˆ Select column for detailed stats", numeric_cols)
                if selected_num:
                    col_data = filtered_df[selected_num].dropna()
                    if len(col_data) > 0:
                        st.metric(
                            label=f"{selected_num} - Average",
                            value=f"{col_data.mean():.2f}",
                            delta=f"Std: {col_data.std():.2f}"
                        )
                        st.write(f"- **Minimum:** {col_data.min():.2f}")
                        st.write(f"- **Maximum:** {col_data.max():.2f}")
                        st.write(f"- **Missing Values:** {filtered_df[selected_num].isnull().sum()} rows")
                    else:
                        st.warning("No valid numeric data in this column")
            else:
                st.info("No numeric columns found for statistical insights")
        
        with insight_col2:
            if filtered_df.shape[0] > 0 and df.shape[0] > 0:
                reduction = df.shape[0] - filtered_df.shape[0]
                reduction_pct = (reduction / df.shape[0]) * 100
                st.info(f"πŸ’‘ **Quick Insight:**\n\n- Original rows: {df.shape[0]}\n- After filtering: {filtered_df.shape[0]}\n- Filtered out: {reduction} rows ({reduction_pct:.1f}%)")
                
                # Check for missing values
                missing_cols = df.isnull().sum()
                missing_cols = missing_cols[missing_cols > 0]
                if len(missing_cols) > 0:
                    st.warning(f"⚠️ Found {len(missing_cols)} columns with missing values")
                else:
                    st.success("βœ… No missing values found in original data")
        
        st.markdown('</div>', unsafe_allow_html=True)
        
        # ========== VISUALIZATION SECTION ==========
        st.markdown("### πŸ“Š Create Custom Charts")
        
        if len(filtered_df) > 0:
            viz_col1, viz_col2, viz_col3 = st.columns(3)
            
            with viz_col1:
                chart_type = st.selectbox(
                    "Chart Type",
                    ["Scatter Plot", "Line Chart", "Bar Chart", "Histogram", "Box Plot"]
                )
            
            numeric_cols = filtered_df.select_dtypes(include=['int64', 'float64']).columns.tolist()
            text_cols = filtered_df.select_dtypes(include=['object']).columns.tolist()
            
            with viz_col2:
                if chart_type in ["Scatter Plot", "Line Chart"]:
                    x_axis = st.selectbox("X-Axis", numeric_cols if numeric_cols else df.columns.tolist())
                    y_axis = st.selectbox("Y-Axis", numeric_cols if numeric_cols else df.columns.tolist())
                elif chart_type == "Bar Chart":
                    x_axis = st.selectbox("Category (X-Axis)", text_cols if text_cols else df.columns.tolist())
                    y_axis = st.selectbox("Value (Y-Axis)", numeric_cols if numeric_cols else df.columns.tolist())
                elif chart_type == "Histogram":
                    x_axis = st.selectbox("Column for Histogram", numeric_cols if numeric_cols else df.columns.tolist())
                    y_axis = None
                else:  # Box Plot
                    x_axis = st.selectbox("Numeric Column", numeric_cols if numeric_cols else df.columns.tolist())
                    y_axis = None
            
            with viz_col3:
                chart_height = st.slider("Chart Height (pixels)", 300, 800, 500)
            
            # Generate chart
            try:
                fig = None
                if chart_type == "Scatter Plot" and x_axis and y_axis:
                    fig = px.scatter(filtered_df, x=x_axis, y=y_axis, title=f"{y_axis} vs {x_axis}")
                elif chart_type == "Line Chart" and x_axis and y_axis:
                    fig = px.line(filtered_df, x=x_axis, y=y_axis, title=f"{y_axis} over {x_axis}")
                elif chart_type == "Bar Chart" and x_axis and y_axis:
                    fig = px.bar(filtered_df, x=x_axis, y=y_axis, title=f"{y_axis} by {x_axis}")
                elif chart_type == "Histogram" and x_axis:
                    fig = px.histogram(filtered_df, x=x_axis, title=f"Distribution of {x_axis}")
                elif chart_type == "Box Plot" and x_axis:
                    fig = px.box(filtered_df, y=x_axis, title=f"Box Plot of {x_axis}")
                
                if fig:
                    fig.update_layout(height=chart_height)
                    st.plotly_chart(fig, use_container_width=True)
                    st.caption("πŸ’‘ **Tip:** Hover over chart β†’ Click camera icon to save as PNG")
                else:
                    st.warning("Please select valid columns for this chart type")
                    
            except Exception as e:
                st.warning(f"Could not create chart. Error: {str(e)[:150]}")
        else:
            st.warning("No data available after filtering. Adjust your filters to see charts.")
        
        # ========== MISSING VALUES REPORT ==========
        with st.expander("⚠️ Data Quality Report (Missing Values)"):
            missing_df = pd.DataFrame({
                'Column': df.columns,
                'Missing Count': df.isnull().sum().values,
                'Missing %': (df.isnull().sum() / len(df) * 100).round(2).values
            })
            missing_df = missing_df[missing_df['Missing Count'] > 0]
            if len(missing_df) > 0:
                st.dataframe(missing_df, use_container_width=True)
                st.info("πŸ’‘ **Recommendations:** Fill missing values with mean/median for numeric columns, or mode for categorical columns. Drop columns with >50% missing values.")
            else:
                st.success("βœ… No missing values found! Your data is clean and ready to use.")
        
        # ========== COLUMN INFORMATION ==========
        with st.expander("πŸ“‹ Column Information"):
            col_info = pd.DataFrame({
                'Column Name': df.columns,
                'Data Type': df.dtypes.values,
                'Unique Values': [df[col].nunique() for col in df.columns],
                'Missing %': (df.isnull().sum() / len(df) * 100).round(2).values
            })
            st.dataframe(col_info, use_container_width=True)
        
    except Exception as e:
        st.error(f"❌ Error loading file: {str(e)}")
        st.info("Make sure your file is a valid CSV or Excel file. Check for special characters or encoding issues.")

else:
    # Show example when no file is uploaded
    st.markdown("### πŸ“Œ Try it with sample data")
    
    # Sample dataset options using reliable datasets
    col_sample1, col_sample2, col_sample3 = st.columns(3)
    
    with col_sample1:
        if st.button("🌸 Iris Dataset", use_container_width=True):
            df_sample = px.data.iris()
            st.session_state['sample_df'] = df_sample
            st.rerun()
    
    with col_sample2:
        if st.button("πŸ“Š Gapminder Dataset", use_container_width=True):
            df_sample = px.data.gapminder()
            st.session_state['sample_df'] = df_sample
            st.rerun()
    
    with col_sample3:
        if st.button("πŸ’³ Tips Dataset", use_container_width=True):
            df_sample = px.data.tips()
            st.session_state['sample_df'] = df_sample
            st.rerun()
    
    # Show sample data preview if loaded
    if 'sample_df' in st.session_state:
        st.markdown("### πŸ“‹ Sample Data Preview")
        st.dataframe(st.session_state['sample_df'].head(10), use_container_width=True)
        st.info("✨ This is just a preview. Upload your own CSV or Excel file above to analyze your data!")
        
        # Option to clear sample
        if st.button("πŸ”„ Clear Sample Data"):
            del st.session_state['sample_df']
            st.rerun()
    
    st.markdown("---")
    st.markdown("""

    ### πŸ“ About This Tool

    

    **Built by Tassawar Abbas** - Kaggle Notebooks Expert (Rank #44 out of 61,000+)

    

    **Features:**

    - πŸ”’ **Privacy first:** Your data never leaves your browser. All processing happens locally.

    - πŸ“Š **Interactive filtering:** Filter by any column, search text, or select ranges.

    - πŸ“ˆ **Custom charts:** Create scatter plots, bar charts, histograms, box plots, and line charts.

    - πŸ’Ύ **Download data:** Export filtered results as CSV or Excel files.

    - πŸ€– **Automatic insights:** Get statistics, missing value reports, and data quality checks.

    - 🎯 **Column information:** View data types, unique values, and completeness.

    

    **Why choose this tool?**

    - βœ… Kaggle Rank #44 (Top 0.07% globally)

    - βœ… 2+ years data science experience

    - βœ… Built by a Kaggle Datasets Expert (#122)

    

    **Need a custom version for your business?** Contact me for:

    - Branded dashboard with your logo

    - Custom calculations and business logic

    - Automated reporting

    - Integration with your existing workflow

    

    [πŸ“§ Contact on LinkedIn](https://www.linkedin.com/in/abbas829pro/) | [πŸ™ GitHub](https://github.com/abbas829) | [πŸ† Kaggle](https://www.kaggle.com/abbas829)

    """)

# ========== FOOTER ==========
st.markdown("---")
st.markdown(
    "<p style='text-align: center; color: gray; font-size: 12px;'>Built with Streamlit | Kaggle Rank #44 (Notebooks) & #122 (Datasets) | Data Scientist @ DataforAI | Β© 2024 Tassawar Abbas</p>",
    unsafe_allow_html=True
)