File size: 8,340 Bytes
aa893a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd


def load_data(file):
    """
    Load a CSV or Excel file into a pandas DataFrame.

    This function should work both with:
    - a file path string
    - a Gradio UploadedFile object (has .name)
    """
    try:
        # If "file" is a Gradio upload, it has a .name attribute.
        if hasattr(file, "name"):
            path = file.name
        else:
            path = file

        if path.endswith(".csv"):
            df = pd.read_csv(path)
        elif path.endswith(".xlsx") or path.endswith(".xls"):
            df = pd.read_excel(path)
        else:
            raise ValueError("Only .csv, .xlsx, or .xls files are supported.")

        # Try to parse any column that already looks like a date.
        # For your Tesla data, "Date" will be parsed correctly.
        for col in df.columns:
            if "date" in col.lower():
                try:
                    df[col] = pd.to_datetime(df[col])
                except Exception:
                    # If parsing fails, just keep it as is.
                    pass

        return df, None

    except Exception as e:
        # Return None and an error message so Gradio can display it.
        return None, f"Error loading data: {e}"


def get_basic_info(df):
    """
    Return basic information about the dataset:
    - number of rows and columns
    - column names
    - data types as strings
    """
    shape = df.shape
    columns = list(df.columns)
    dtypes = df.dtypes.astype(str).to_dict()

    info = {
        "n_rows": shape[0],
        "n_cols": shape[1],
        "columns": columns,
        "dtypes": dtypes,
    }
    return info


def detect_column_types(df):
    """
    Split columns into:
    - numeric_cols
    - categorical_cols
    - date_cols

    This will be used for:
    - summary statistics
    - filters
    - visualizations
    """
    numeric_cols = df.select_dtypes(include=["number"]).columns.tolist()
    date_cols = df.select_dtypes(include=["datetime64[ns]", "datetime64[ns, UTC]"]).columns.tolist()

    # Everything else is treated as categorical for this project.
    categorical_cols = [col for col in df.columns if col not in numeric_cols + date_cols]

    col_types = {
        "numeric": numeric_cols,
        "categorical": categorical_cols,
        "date": date_cols,
    }
    return col_types


def numeric_summary(df, numeric_cols):
    """
    Calculate summary statistics for numeric columns.

    Returns a DataFrame where each row is a column and
    columns include: count, mean, std, min, 25%, 50%, 75%, max
    """
    if not numeric_cols:
        return pd.DataFrame()

    summary = df[numeric_cols].describe().T  # transpose so each row is a column
    summary = summary.reset_index().rename(columns={"index": "column"})
    return summary


def categorical_summary(df, categorical_cols, max_unique_to_show=20):
    """
    Create a summary for categorical columns.

    For each categorical column we will show:
    - number of unique values
    - the most frequent value (mode)
    - frequency of the mode
    - up to 'max_unique_to_show' value counts (for display if needed)
    """
    rows = []

    for col in categorical_cols:
        series = df[col].astype("object")

        n_unique = series.nunique(dropna=False)

        # Mode (most common value)
        if not series.mode(dropna=False).empty:
            mode_value = series.mode(dropna=False).iloc[0]
        else:
            mode_value = None

        value_counts = series.value_counts(dropna=False)
        mode_freq = int(value_counts.iloc[0]) if len(value_counts) > 0 else 0

        # We keep the top value counts as a JSON-like string to show in a table if needed.
        top_values = value_counts.head(max_unique_to_show).to_dict()

        rows.append(
            {
                "column": col,
                "unique_values": int(n_unique),
                "mode": mode_value,
                "mode_freq": mode_freq,
                "top_values": str(top_values),
            }
        )

    if not rows:
        return pd.DataFrame()

    summary_df = pd.DataFrame(rows)
    return summary_df


def missing_values_report(df):
    """
    Return a DataFrame with:
    - column name
    - number of missing values
    - percentage of missing values
    """
    total_rows = len(df)
    missing_counts = df.isna().sum()

    rows = []
    for col, count in missing_counts.items():
        if total_rows > 0:
            pct = (count / total_rows) * 100
        else:
            pct = 0.0
        rows.append(
            {
                "column": col,
                "missing_count": int(count),
                "missing_pct": round(pct, 2),
            }
        )

    report_df = pd.DataFrame(rows)
    return report_df


def correlation_matrix(df, numeric_cols):
    """
    Compute the correlation matrix for numeric columns.
    """
    if len(numeric_cols) < 2:
        return pd.DataFrame()
    corr = df[numeric_cols].corr()
    return corr


def build_filter_metadata(df, col_types):
    """
    Prepare simple metadata that the Gradio UI can use to build filters.

    For numeric columns:
        min and max value

    For categorical columns:
        sorted list of unique values

    For date columns:
        min and max date
    """
    meta = {
        "numeric": {},
        "categorical": {},
        "date": {},
    }

    # Numeric ranges
    for col in col_types["numeric"]:
        col_series = df[col].dropna()
        if col_series.empty:
            continue
        meta["numeric"][col] = {
            "min": float(col_series.min()),
            "max": float(col_series.max()),
        }

    # Categorical unique values
    for col in col_types["categorical"]:
        unique_vals = df[col].dropna().unique().tolist()
        # Convert numpy types to plain Python for safety
        unique_vals = [str(v) for v in unique_vals]
        meta["categorical"][col] = sorted(unique_vals)

    # Date min/max
    for col in col_types["date"]:
        col_series = df[col].dropna()
        if col_series.empty:
            continue
        meta["date"][col] = {
            "min": col_series.min(),
            "max": col_series.max(),
        }

    return meta


def apply_filters(df, numeric_filters=None, categorical_filters=None, date_filters=None):
    """
    Apply simple filters to the DataFrame.

    numeric_filters: dict like
        {
            "Estimated_Deliveries": [min_val, max_val],
            "Production_Units": [min_val, max_val],
        }

    categorical_filters: dict like
        {
            "Region": ["Europe", "Asia"],
            "Model": ["Model 3", "Model Y"],
        }

    date_filters: dict like
        {
            "Date": ["2018-01-01", "2023-12-31"]
        }

    All arguments are optional. If a filter dict is None, it is ignored.
    """
    filtered = df.copy()

    # Numeric ranges
    if numeric_filters:
        for col, bounds in numeric_filters.items():
            if col not in filtered.columns:
                continue
            try:
                min_val, max_val = bounds
                filtered = filtered[
                    (filtered[col] >= min_val) & (filtered[col] <= max_val)
                ]
            except Exception:
                # If something goes wrong, just skip this column filter.
                continue

    # Categorical selections (multi-select)
    if categorical_filters:
        for col, allowed_values in categorical_filters.items():
            if col not in filtered.columns:
                continue
            if not allowed_values:
                # If list is empty, skip this filter.
                continue
            filtered = filtered[filtered[col].astype(str).isin(allowed_values)]

    # Date range filters
    if date_filters:
        for col, bounds in date_filters.items():
            if col not in filtered.columns:
                continue
            try:
                start, end = bounds
                # Convert to datetime just in case inputs are strings.
                start = pd.to_datetime(start)
                end = pd.to_datetime(end)
                filtered = filtered[
                    (filtered[col] >= start) & (filtered[col] <= end)
                ]
            except Exception:
                continue

    return filtered