Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

CSV ingestion: fix header handling and duplicate header kwarg; add edge-case tests (tab, quoted, multiline, chunksize, NaN)

KaifAhmad195ea8de45582
diff --git a/semantica/ingest/pandas_ingestor.py b/semantica/ingest/pandas_ingestor.py
index b699eb91..073c07d1 100644
--- a/semantica/ingest/pandas_ingestor.py
+++ b/semantica/ingest/pandas_ingestor.py
@@ -192,8 +192,7 @@ class PandasIngestor:
self.logger.error(f"Failed to ingest DataFrame: {e}")
raise ProcessingError(f"Failed to ingest DataFrame: {e}") from e
-
- def from_csv(
+ def from_csv(
self,
file_path: Union[str, Path],
chunksize: Optional[int] = None,
@@ -212,8 +211,6 @@ class PandasIngestor:
)
try:
- import csv
- import chardet
# ---------- Encoding Detection ----------
with open(file_path, "rb") as f:
@@ -235,20 +232,38 @@ class PandasIngestor:
delimiter = ","
quotechar = '"'
- has_header = True # Always treat first row as header
+ # Header handling: default to True (treat first row as header)
+ # unless user explicitly overrides via pandas_options['header'].
+ has_header = True
+ header_opt = pandas_options.get("header", None)
+ if header_opt is None:
+ has_header = True
+ elif header_opt == 0 or header_opt == "infer":
+ has_header = True
+ else:
+ # Any explicit non-header setting (e.g., None or int>0) implies no header
+ try:
+ has_header = False if header_opt is None or int(header_opt) != 0 else True
+ except Exception:
+ has_header = False
skipped_rows = 0
dataframes = []
# ---------- CSV Reading (Chunked if needed) ----------
+ # Preserve explicit header setting (including None) if user provided it.
+ has_explicit_header = "header" in pandas_options
+ explicit_header = pandas_options.pop("header", None) if has_explicit_header else None
+ header_arg = explicit_header if has_explicit_header else (0 if has_header else None)
+
reader = pd.read_csv(
file_path,
sep=delimiter,
encoding=encoding,
encoding_errors="replace",
quoting=csv.QUOTE_MINIMAL,
- header=0 if has_header else None,
+ header=header_arg,
quotechar=quotechar,
escapechar="\\",
engine="python",
diff --git a/tests/ingest/test_ingest_from_csv().py b/tests/ingest/test_ingest_from_csv().py
index a05ad271..3810d94f 100644
--- a/tests/ingest/test_ingest_from_csv().py
+++ b/tests/ingest/test_ingest_from_csv().py
@@ -6,10 +6,6 @@ import pytest
from semantica.ingest.pandas_ingestor import PandasIngestor
-# -------------------------------------------------------
-# Helper to write temporary CSV
-# -------------------------------------------------------
-
def write_temp_csv(content: str, encoding="utf-8"):
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
tmp.close()
@@ -42,6 +38,115 @@ def test_from_csv_detects_encoding():
os.remove(path)
+def test_from_csv_detects_tab_delimiter():
+ content = (
+ "user_id\trole\n"
+ "1\tadmin\n"
+ "2\tuser\n"
+ )
+
+ path = write_temp_csv(content)
+
+ ingestor = PandasIngestor()
+ data = ingestor.from_csv(path)
+
+ assert data.row_count == 2
+ assert data.columns == ["user_id", "role"]
+ assert data.dataframe.iloc[0]["role"] == "admin"
+
+ os.remove(path)
+
+
+def test_from_csv_handles_quoted_fields_with_commas():
+ content = (
+ "company,revenue\n"
+ '"Acme, Inc.",100\n'
+ '"Widgets, LLC",200\n'
+ )
+
+ path = write_temp_csv(content)
+
+ ingestor = PandasIngestor()
+ data = ingestor.from_csv(path)
+
+ assert data.row_count == 2
+ assert data.columns == ["company", "revenue"]
+ assert data.dataframe.iloc[0]["company"] == "Acme, Inc."
+ assert int(data.dataframe.iloc[1]["revenue"]) == 200
+
+ os.remove(path)
+
+
+def test_from_csv_handles_multiline_quoted_fields():
+ # Embed actual newlines within quoted fields
+ content = "id,notes\n1,\"line1\nline2\"\n2,\"alpha\nbeta\"\n"
+
+ path = write_temp_csv(content)
+
+ ingestor = PandasIngestor()
+ data = ingestor.from_csv(path)
+
+ assert data.row_count == 2
+ assert "\n" in data.dataframe.iloc[0]["notes"]
+ assert data.dataframe.iloc[1]["notes"].split("\n")[1] == "beta"
+
+ os.remove(path)
+
+
+def test_from_csv_no_header_override():
+ content = (
+ "colA,colB\n"
+ "x,1\n"
+ "y,2\n"
+ )
+
+ path = write_temp_csv(content)
+
+ ingestor = PandasIngestor()
+ data = ingestor.from_csv(path, header=None)
+
+ assert data.row_count == 3
+ assert data.columns == [0, 1]
+ assert list(data.dataframe.iloc[0]) == ["colA", "colB"]
+
+ os.remove(path)
+
+
+def test_from_csv_with_chunksize_concatenates():
+ rows = ["a,b", "1,x", "2,y", "3,z", "4,w"]
+ content = "\n".join(rows) + "\n"
+
+ path = write_temp_csv(content)
+
+ ingestor = PandasIngestor()
+ data = ingestor.from_csv(path, chunksize=2)
+
+ assert data.row_count == 4
+ assert data.metadata.get("chunksize") == 2
+ assert list(data.dataframe["a"]) == [1, 2, 3, 4]
+
+ os.remove(path)
+
+
+def test_from_csv_preserves_nan_values():
+ content = (
+ "name,score\n"
+ "alice,\n"
+ "bob,10\n"
+ )
+
+ path = write_temp_csv(content)
+
+ ingestor = PandasIngestor()
+ data = ingestor.from_csv(path)
+
+ assert data.row_count == 2
+ assert pd.isna(data.dataframe.iloc[0]["score"]) is True
+ assert int(data.dataframe.iloc[1]["score"]) == 10
+
+ os.remove(path)
+
+
# -------------------------------------------------------
# Test 2: Delimiter Detection (semicolon separated)
# -------------------------------------------------------