Spaces:
Running
Running
Update tools/csv_parser.py
Browse files- tools/csv_parser.py +78 -46
tools/csv_parser.py
CHANGED
@@ -1,67 +1,99 @@
|
|
1 |
-
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
def parse_csv_tool(file: Union[str, bytes]) -> str:
|
6 |
"""
|
7 |
-
|
8 |
-
Supports large files by sampling if necessary and handles common parsing errors.
|
9 |
-
"""
|
10 |
-
# Determine extension
|
11 |
-
try:
|
12 |
-
filename = getattr(file, 'name', file)
|
13 |
-
ext = os.path.splitext(filename)[1].lower()
|
14 |
-
except Exception:
|
15 |
-
ext = ".csv"
|
16 |
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
try:
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
df = pd.read_csv(file)
|
23 |
-
except Exception as e:
|
24 |
-
return f"❌ Failed to load data ({ext}): {e}"
|
25 |
|
26 |
-
# Basic dimensions
|
27 |
n_rows, n_cols = df.shape
|
28 |
|
29 |
-
#
|
30 |
-
|
31 |
-
|
|
|
|
|
32 |
|
33 |
-
#
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
if
|
39 |
-
|
40 |
-
missing_md = "\n".join(missing_lines) or "None"
|
41 |
|
42 |
-
#
|
43 |
-
|
44 |
-
|
|
|
|
|
45 |
|
46 |
-
#
|
47 |
-
mem_mb = df.memory_usage(deep=True).sum() /
|
48 |
|
49 |
-
#
|
50 |
-
|
51 |
-
# 📊
|
52 |
|
53 |
-
|
54 |
-
|
55 |
-
|
|
|
|
|
56 |
|
57 |
-
## 🗂
|
58 |
{schema_md}
|
59 |
|
60 |
-
## 🛠
|
61 |
{missing_md}
|
62 |
|
63 |
-
## 📈
|
64 |
{desc_md}
|
65 |
""".strip()
|
66 |
-
|
67 |
-
return report
|
|
|
1 |
+
# tools/csv_parser.py
|
2 |
+
# ------------------------------------------------------------
|
3 |
+
# Reads CSV / Excel, samples for very large files, and returns a
|
4 |
+
# Markdown‑formatted “quick‑scan” report: dimensions, schema,
|
5 |
+
# missing‑value profile, numeric describe(), and memory footprint.
|
6 |
+
|
7 |
+
from __future__ import annotations
|
8 |
+
|
9 |
import os
|
10 |
+
from typing import Union
|
11 |
+
|
12 |
+
import pandas as pd
|
13 |
+
|
14 |
+
|
15 |
+
def _safe_read(path_or_buf: Union[str, bytes], sample_rows: int = 1_000_000) -> pd.DataFrame:
|
16 |
+
"""Read CSV or Excel. If the file has > sample_rows, read only a sample."""
|
17 |
+
# Determine extension (best‑effort)
|
18 |
+
ext = ".csv"
|
19 |
+
if isinstance(path_or_buf, str):
|
20 |
+
ext = os.path.splitext(path_or_buf)[1].lower()
|
21 |
+
|
22 |
+
if ext in (".xls", ".xlsx"):
|
23 |
+
# Excel — read first sheet
|
24 |
+
df = pd.read_excel(path_or_buf, engine="openpyxl")
|
25 |
+
else: # CSV family
|
26 |
+
# First row‑count check: pandas 1.5+ uses memory map ⇒ cheap for header only
|
27 |
+
nrows_total = sum(1 for _ in open(path_or_buf, "rb")) if isinstance(path_or_buf, str) else None
|
28 |
+
if nrows_total and nrows_total > sample_rows:
|
29 |
+
# sample uniformly without loading everything
|
30 |
+
skip = sorted(
|
31 |
+
pd.np.random.choice(range(1, nrows_total), nrows_total - sample_rows, replace=False)
|
32 |
+
)
|
33 |
+
df = pd.read_csv(path_or_buf, skiprows=skip)
|
34 |
+
else:
|
35 |
+
df = pd.read_csv(path_or_buf)
|
36 |
+
|
37 |
+
return df
|
38 |
+
|
39 |
|
40 |
def parse_csv_tool(file: Union[str, bytes]) -> str:
|
41 |
"""
|
42 |
+
Return a **Markdown** report describing the dataset.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
+
Sections:
|
45 |
+
• Dimensions
|
46 |
+
• Schema (+ dtypes)
|
47 |
+
• Missing‑value counts + %
|
48 |
+
• Numeric descriptive statistics
|
49 |
+
• Memory usage
|
50 |
+
"""
|
51 |
try:
|
52 |
+
df = _safe_read(file)
|
53 |
+
except Exception as exc:
|
54 |
+
return f"❌ Failed to load data: {exc}"
|
|
|
|
|
|
|
55 |
|
|
|
56 |
n_rows, n_cols = df.shape
|
57 |
|
58 |
+
# ---------- schema ----------
|
59 |
+
schema_md = "\n".join(
|
60 |
+
f"- **{col}** – `{dtype}`"
|
61 |
+
for col, dtype in df.dtypes.items()
|
62 |
+
)
|
63 |
|
64 |
+
# ---------- missing ----------
|
65 |
+
miss_ct = df.isna().sum()
|
66 |
+
miss_pct = (miss_ct / len(df) * 100).round(1)
|
67 |
+
missing_md = "\n".join(
|
68 |
+
f"- **{c}**: {miss_ct[c]} ({miss_pct[c]} %)"
|
69 |
+
for c in df.columns if miss_ct[c] > 0
|
70 |
+
) or "None"
|
|
|
71 |
|
72 |
+
# ---------- descriptive stats (numeric only) ----------
|
73 |
+
if df.select_dtypes("number").shape[1]:
|
74 |
+
desc_md = df.describe().T.round(2).to_markdown()
|
75 |
+
else:
|
76 |
+
desc_md = "_No numeric columns_"
|
77 |
|
78 |
+
# ---------- memory ----------
|
79 |
+
mem_mb = df.memory_usage(deep=True).sum() / 1024**2
|
80 |
|
81 |
+
# ---------- assemble ----------
|
82 |
+
return f"""
|
83 |
+
# 📊 Dataset Overview
|
84 |
|
85 |
+
| metric | value |
|
86 |
+
| ------ | ----- |
|
87 |
+
| Rows | {n_rows:,} |
|
88 |
+
| Columns| {n_cols} |
|
89 |
+
| Memory | {mem_mb:.2f} MB |
|
90 |
|
91 |
+
## 🗂 Schema
|
92 |
{schema_md}
|
93 |
|
94 |
+
## 🛠 Missing Values
|
95 |
{missing_md}
|
96 |
|
97 |
+
## 📈 Descriptive Statistics (numeric)
|
98 |
{desc_md}
|
99 |
""".strip()
|
|
|
|