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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import seaborn as sns
import matplotlib.pyplot as plt
import io
import base64
from scipy import stats
import warnings
import google.generativeai as genai
import os
from dotenv import load_dotenv
import logging
from datetime import datetime
import tempfile
import json
warnings.filterwarnings('ignore')

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# Load environment variables
#load_dotenv()

# Gemini API configuration
# Set your API key as environment variable: GEMINI_API_KEY
#genai.configure(api_key=os.getenv("GEMINI_API_KEY"))

def analyze_dataset_overview(file_obj, api_key) -> tuple:
    """
    Analyzes dataset using Gemini AI and provides storytelling overview.
    
    Args:
        file_obj: Gradio file object
        api_key: Gemini API key from user input
        
    Returns:
        story_text (str): AI-generated data story
        basic_info_text (str): Dataset basic information
        data_quality_score (float): Data quality percentage
    """
    if file_obj is None:
        return "โŒ Please upload a CSV file first.", "", 0
    
    if not api_key or api_key.strip() == "":
        return "โŒ Please enter your Gemini API key first.", "", 0
    
    try:
        df = pd.read_csv(file_obj.name)
        
        # Extract dataset metadata
        metadata = extract_dataset_metadata(df)
        
        # Create prompt for Gemini
        gemini_prompt = create_insights_prompt(metadata)
        
        # Generate story with Gemini
        story = generate_insights_with_gemini(gemini_prompt, api_key)
        
        # Create basic info summary
        basic_info = create_basic_info_summary(metadata)
        
        # Calculate data quality score
        quality_score = metadata['data_quality']
        
        return story, basic_info, quality_score
        
    except Exception as e:
        return f"โŒ Error loading data: {str(e)}", "", 0

def extract_dataset_metadata(df: pd.DataFrame) -> dict:
    """
    Extracts metadata from dataset.
    
    Args:
        df (pd.DataFrame): DataFrame to analyze
        
    Returns:
        dict: Dataset metadata
    """
    rows, cols = df.shape
    columns = df.columns.tolist()
    
    # Data types
    numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
    categorical_cols = df.select_dtypes(include=['object']).columns.tolist()
    datetime_cols = df.select_dtypes(include=['datetime64']).columns.tolist()
    
    # Missing values
    missing_data = df.isnull().sum()
    missing_percentage = (missing_data / len(df) * 100).round(2)
    
    # Basic statistics
    numeric_stats = {}
    if numeric_cols:
        numeric_stats = df[numeric_cols].describe().to_dict()
    
    # Categorical variable information
    categorical_info = {}
    for col in categorical_cols[:5]:  # First 5 categorical columns
        unique_count = df[col].nunique()
        top_values = df[col].value_counts().head(3).to_dict()
        categorical_info[col] = {
            'unique_count': unique_count,
            'top_values': top_values
        }
    
    # Potential relationships
    correlations = {}
    if len(numeric_cols) > 1:
        corr_matrix = df[numeric_cols].corr()
        # Find highest correlations
        high_corr = []
        for i in range(len(corr_matrix.columns)):
            for j in range(i+1, len(corr_matrix.columns)):
                corr_val = abs(corr_matrix.iloc[i, j])
                if corr_val > 0.7:
                    high_corr.append({
                        'var1': corr_matrix.columns[i],
                        'var2': corr_matrix.columns[j],
                        'correlation': round(corr_val, 3)
                    })
        correlations = high_corr[:5]  # Top 5 correlations
    
    return {
        'shape': (rows, cols),
        'columns': columns,
        'numeric_cols': numeric_cols,
        'categorical_cols': categorical_cols,
        'datetime_cols': datetime_cols,
        'missing_data': missing_data.to_dict(),
        'missing_percentage': missing_percentage.to_dict(),
        'numeric_stats': numeric_stats,
        'categorical_info': categorical_info,
        'correlations': correlations,
        'data_quality': round((df.notna().sum().sum() / (rows * cols)) * 100, 1)
    }

def create_insights_prompt(metadata: dict) -> str:
    """
    Creates data insights prompt for Gemini.
    
    Args:
        metadata (dict): Dataset metadata
        
    Returns:
        str: Gemini prompt
    """
    prompt = f"""
    You are an expert data analyst and storyteller. Using the following dataset information,
    predict what this dataset is about and tell a story about it.
    
    DATASET INFORMATION:
    - Size: {metadata['shape'][0]:,} rows, {metadata['shape'][1]} columns
    - Columns: {', '.join(metadata['columns'])}
    - Numeric columns: {', '.join(metadata['numeric_cols'])}
    - Categorical columns: {', '.join(metadata['categorical_cols'])}
    - Data quality: {metadata['data_quality']}%
    
    CATEGORICAL VARIABLE DETAILS:
    {metadata['categorical_info']}
    
    HIGH CORRELATIONS:
    {metadata['correlations']}
    
    Please create a story in the following format:
    
    # Dataset Overview
    
    ## What is this dataset about?
    [Your prediction about the dataset]
    
    ## Which sector/domain does it belong to?
    [Your sector analysis]
    
    ## Potential Use Cases
    - [Use case 1]
    - [Use case 2]
    - [Use case 3]
    
    ## Interesting Findings
    - [Finding 1]
    - [Finding 2]
    - [Finding 3]
    
    ## What Can We Do With This Data?
    - [Potential analysis 1]
    - [Potential analysis 2]
    - [Potential analysis 3]
    
    Make your story visual and engaging using emojis!
    Keep it in English and make it professional yet accessible.
    Use proper markdown formatting for headers and lists.
    """
    
    return prompt

def generate_insights_with_gemini(prompt: str, api_key: str) -> str:
    """
    Generates data insights using Gemini AI.
    
    Args:
        prompt (str): Prepared prompt for Gemini
        api_key (str): Gemini API key
        
    Returns:
        str: Story generated by Gemini
    """
    try:
        genai.configure(api_key=api_key)
        model = genai.GenerativeModel('gemini-1.5-flash')
        response = model.generate_content(prompt)
        return response.text
        
    except Exception as e:
        # Fallback story if Gemini API fails
        return f"""
        ๐Ÿ” **DATA DISCOVERY STORY**
        
        โš ๏ธ Gemini API Error: {str(e)}
        
        ๐Ÿ“Š **Fallback Analysis**:
        This dataset appears to be a fascinating collection of information! 
        
        ๐ŸŽฏ **Prediction**: Based on the structure, this could be business, e-commerce, or customer behavior data.
        
        ๐Ÿข **Sector**: Likely used in retail, digital marketing, or analytics domain.
        
        โœจ **Potential Stories**:
        โ€ข ๐Ÿ›’ Customer journey analysis
        โ€ข ๐Ÿ“ˆ Seasonal trends and patterns  
        โ€ข ๐Ÿ‘ฅ Customer segmentation
        โ€ข ๐Ÿ’ก Recommendation systems
        โ€ข ๐ŸŽฏ Marketing campaign optimization
        
        ๐Ÿ”ฎ **What We Can Do**:
        โ€ข Customer lifetime value prediction
        โ€ข Churn prediction modeling
        โ€ข Pricing strategy optimization
        โ€ข Market basket analysis
        โ€ข A/B testing insights
        
        ๐Ÿ“Š The data quality looks promising for analysis!
        """

def create_basic_info_summary(metadata: dict) -> str:
    """Creates basic information summary text"""
    summary = f"""
    ๐Ÿ“‹ **Dataset Overview**
    
    ๐Ÿ“Š **Size**: {metadata['shape'][0]:,} rows ร— {metadata['shape'][1]} columns
    
    ๐Ÿ”ข **Data Types**:
    โ€ข Numeric variables: {len(metadata['numeric_cols'])}
    โ€ข Categorical variables: {len(metadata['categorical_cols'])}
    โ€ข DateTime variables: {len(metadata['datetime_cols'])}
    
    ๐ŸŽฏ **Data Quality**: {metadata['data_quality']}%
    
    ๐Ÿ“ˆ **Missing Data**: {sum(metadata['missing_data'].values())} total missing values
    
    ๐Ÿ”— **High Correlations Found**: {len(metadata['correlations'])} pairs
    """
    return summary

def generate_data_profiling(file_obj) -> tuple:
    """
    Generates detailed data profiling report.
    
    Args:
        file_obj: Gradio file object
        
    Returns:
        missing_data_df (DataFrame): Missing data analysis
        numeric_stats_df (DataFrame): Numeric statistics
        categorical_stats_df (DataFrame): Categorical statistics
    """
    if file_obj is None:
        return None, None, None
    
    try:
        df = pd.read_csv(file_obj.name)
        
        # Missing data analysis
        missing_data = df.isnull().sum()
        missing_pct = (missing_data / len(df) * 100).round(2)
        missing_df = pd.DataFrame({
            'Column': missing_data.index,
            'Missing Count': missing_data.values,
            'Missing Percentage': missing_pct.values
        }).sort_values('Missing Count', ascending=False)
        
        # Numeric statistics
        numeric_cols = df.select_dtypes(include=[np.number]).columns
        numeric_stats_df = None
        if len(numeric_cols) > 0:
            numeric_stats_df = df[numeric_cols].describe().round(3).reset_index()
        
        # Categorical statistics
        cat_cols = df.select_dtypes(include=['object']).columns
        categorical_stats = []
        for col in cat_cols:
            categorical_stats.append({
                'Column': col,
                'Unique Values': df[col].nunique(),
                'Most Frequent': df[col].mode().iloc[0] if len(df[col].mode()) > 0 else 'N/A',
                'Frequency': df[col].value_counts().iloc[0] if len(df[col].value_counts()) > 0 else 0
            })
        
        categorical_stats_df = pd.DataFrame(categorical_stats) if categorical_stats else None
        
        return missing_df, numeric_stats_df, categorical_stats_df
        
    except Exception as e:
        error_df = pd.DataFrame({'Error': [f"Error in profiling: {str(e)}"]})
        return error_df, None, None

def create_smart_visualizations(file_obj) -> tuple:
    """
    Creates smart visualizations.
    
    Args:
        file_obj: Gradio file object
        
    Returns:
        dtype_fig (Plot): Data type distribution chart
        missing_fig (Plot): Missing data bar chart
        correlation_fig (Plot): Correlation heatmap
        distribution_fig (Plot): Variable distributions
    """
    if file_obj is None:
        return None, None, None, None
    
    try:
        df = pd.read_csv(file_obj.name)
        
        # 1. Data type distribution
        dtype_counts = df.dtypes.value_counts()
        dtype_fig = px.pie(
            values=dtype_counts.values,
            names=[str(dtype) for dtype in dtype_counts.index],  # Convert dtype objects to strings
            title="๐Ÿ” Data Type Distribution"
        )
        dtype_fig.update_traces(textposition='inside', textinfo='percent+label')
        
        # 2. Missing data heatmap
        missing_data = df.isnull().sum()
        missing_fig = px.bar(
            x=missing_data.index,
            y=missing_data.values,
            title="๐Ÿ”ด Missing Data by Column",
            labels={'x': 'Columns', 'y': 'Missing Count'}
        )
        missing_fig.update_xaxes(tickangle=45)
        
        # 3. Correlation heatmap
        numeric_cols = df.select_dtypes(include=[np.number]).columns
        correlation_fig = None
        if len(numeric_cols) > 1:
            corr_matrix = df[numeric_cols].corr()
            correlation_fig = px.imshow(
                corr_matrix,
                text_auto=True,
                aspect="auto",
                title="๐Ÿ”— Correlation Matrix",
                color_continuous_scale='RdBu'
            )
        
        # 4. Distribution plots for numeric variables
        distribution_fig = None
        if len(numeric_cols) > 0:
            # Select first 4 numeric columns for distribution
            cols_to_plot = numeric_cols[:4]
            
            if len(cols_to_plot) == 1:
                distribution_fig = px.histogram(
                    df, x=cols_to_plot[0], 
                    title=f"๐Ÿ“Š Distribution of {cols_to_plot[0]}"
                )
            else:
                # Create subplots for multiple columns
                fig = make_subplots(
                    rows=2, cols=2,
                    subplot_titles=[f"{col} Distribution" for col in cols_to_plot]
                )
                
                for i, col in enumerate(cols_to_plot):
                    row = (i // 2) + 1
                    col_pos = (i % 2) + 1
                    
                    fig.add_trace(
                        go.Histogram(x=df[col].values, name=str(col), showlegend=False),  # Convert to numpy array and string
                        row=row, col=col_pos
                    )
                
                fig.update_layout(title="๐Ÿ“Š Numeric Variable Distributions")
                distribution_fig = fig
        
        return dtype_fig, missing_fig, correlation_fig, distribution_fig
        
    except Exception as e:
        # Return error plot
        error_fig = px.scatter(title=f"โŒ Visualization Error: {str(e)}")
        return error_fig, None, None, None

# Create Gradio interface
def create_gradio_interface():
    """Creates main Gradio interface"""
    
    with gr.Blocks(title="๐Ÿš€ AI Data Explorer", theme=gr.themes.Soft()) as demo:
        gr.Markdown("# ๐Ÿš€ AutoEDA")
        gr.Markdown("Upload your CSV file and get AI-powered analysis reports!")
        
        with gr.Row():
            file_input = gr.File(
                label="๐Ÿ“ Upload CSV File",
                file_types=[".csv"]
            )
        
        with gr.Tabs():
            # Overview tab
            with gr.Tab("๐Ÿ” Overview"):
                gr.Markdown("### AI-Powered Data Insights")
                
                with gr.Row():
                    api_key_input = gr.Textbox(
                        label="๐Ÿ”‘ Gemini API Key",
                        placeholder="Enter your Gemini API key here...",
                        type="password"
                    )
                
                with gr.Row():
                    overview_btn = gr.Button("๐ŸŽฏ Generate Story", variant="primary")
                
                with gr.Row():
                    with gr.Column():
                        story_output = gr.Markdown(
                            label="๐Ÿ“– Data Insights",
                            value=""
                        )
                    with gr.Column():
                        basic_info_output = gr.Markdown(
                            label="๐Ÿ“‹ Basic Information",
                            value=""
                        )
                
                with gr.Row():
                    quality_score = gr.Number(
                        label="๐ŸŽฏ Data Quality Score (%)",
                        precision=1
                    )
                
                overview_btn.click(
                    fn=analyze_dataset_overview,
                    inputs=[file_input, api_key_input],
                    outputs=[story_output, basic_info_output, quality_score]
                )
            
            # Profiling tab  
            with gr.Tab("๐Ÿ“Š Data Profiling"):
                gr.Markdown("### Automated Data Profiling")
                
                with gr.Row():
                    profiling_btn = gr.Button("๐Ÿ” Generate Profiling", variant="secondary")
                
                with gr.Row():
                    with gr.Column():
                        missing_data_table = gr.Dataframe(
                            label="๐Ÿ”ด Missing Data Analysis",
                            interactive=False
                        )
                    with gr.Column():
                        numeric_stats_table = gr.Dataframe(
                            label="๐Ÿ”ข Numeric Statistics",
                            interactive=False
                        )
                
                with gr.Row():
                    categorical_stats_table = gr.Dataframe(
                        label="๐Ÿ“ Categorical Statistics",
                        interactive=False
                    )
                
                profiling_btn.click(
                    fn=generate_data_profiling,
                    inputs=[file_input],
                    outputs=[missing_data_table, numeric_stats_table, categorical_stats_table]
                )
            
            # Visualization tab
            with gr.Tab("๐Ÿ“ˆ Smart Visualizations"):
                gr.Markdown("### Automated Data Visualizations")
                
                with gr.Row():
                    viz_btn = gr.Button("๐ŸŽจ Create Visualizations", variant="secondary")
                
                with gr.Row():
                    with gr.Column():
                        dtype_plot = gr.Plot(label="๐Ÿ” Data Types")
                        missing_plot = gr.Plot(label="๐Ÿ”ด Missing Data")
                    with gr.Column():
                        correlation_plot = gr.Plot(label="๐Ÿ”— Correlations")
                        distribution_plot = gr.Plot(label="๐Ÿ“Š Distributions")
                
                viz_btn.click(
                    fn=create_smart_visualizations,
                    inputs=[file_input],
                    outputs=[dtype_plot, missing_plot, correlation_plot, distribution_plot]
                )
        
        # Footer
        gr.Markdown("---")
        gr.Markdown("๐Ÿ’ก **Tip**: Get your free Gemini API key from [Google AI Studio](https://aistudio.google.com/)")
    
    return demo

# Main application
if __name__ == "__main__":
    demo = create_gradio_interface()
    demo.launch(
        mcp_server=True
    )