Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Enhance SeedDataManager with robust CSV/JSON support and improved validation
KaifAhmad18b6e8608c34c
diff --git a/semantica/seed/seed_manager.py b/semantica/seed/seed_manager.pyindex ea2380af..2f20463c 100644--- a/semantica/seed/seed_manager.py+++ b/semantica/seed/seed_manager.py@@ -194,18 +194,21 @@ class SeedDataManager:entity_type: Optional[str] = None,relationship_type: Optional[str] = None,source_name: Optional[str] = None,+ delimiter: Optional[str] = None,) -> List[Dict[str, Any]]:"""Load seed data from CSV file.Reads a CSV file and converts rows to dictionaries. Automaticallyadds entity_type, relationship_type, and source metadata if provided.+ Supports automatic delimiter detection if not provided.Args:file_path: Path to CSV fileentity_type: Optional entity type to add to all recordsrelationship_type: Optional relationship type to add to all recordssource_name: Optional source name for tracking+ delimiter: Optional CSV delimiter. If None, attempts to detect it.Returns:List of loaded data records as dictionaries@@ -215,7 +218,7 @@ class SeedDataManager:Example:>>> records = manager.load_from_csv("data/entities.csv", entity_type="Person")- >>> print(f"Loaded {len(records)} records")+ >>> records = manager.load_from_csv("data/data.csv", delimiter=";")"""tracking_id = self.progress_tracker.start_tracking(module="seed",@@ -239,7 +242,21 @@ class SeedDataManager:tracking_id, message="Reading CSV file...")with open(file_path, "r", encoding="utf-8") as f:- reader = csv.DictReader(f)+ # Detect delimiter if not provided+ if delimiter is None:+ try:+ sample = f.read(1024)+ f.seek(0)+ dialect = csv.Sniffer().sniff(sample)+ delimiter = dialect.delimiter+ self.logger.debug(f"Detected CSV delimiter: '{delimiter}'")+ except csv.Error:+ # Fallback to comma if sniffing fails+ f.seek(0)+ delimiter = ","+ self.logger.debug("Could not detect delimiter, defaulting to ','")++ reader = csv.DictReader(f, delimiter=delimiter)for row in reader:# Clean up row datarecord = {k: v for k, v in row.items() if v}@@ -316,6 +333,11 @@ class SeedDataManager:elif "records" in data:records = data["records"]else:+ self.logger.warning(+ f"JSON file {file_path} is a dictionary but contains none of the "+ "expected keys: 'entities', 'data', 'records'. "+ "Treating entire object as a single record."+ )records = [data]else:records = []diff --git a/semantica/seed/seed_usage.md b/semantica/seed/seed_usage.mdindex bda4d816..d69ba826 100644--- a/semantica/seed/seed_usage.md+++ b/semantica/seed/seed_usage.md@@ -48,6 +48,17 @@ records = manager.load_from_csv(entity_type="Person")+# Load from CSV with custom delimiter+records_pipe = manager.load_from_csv(+ "data/entities_pipe.csv",+ delimiter="|"+)++# Load from CSV with auto-detection (supported for common delimiters like ;, \t, etc.)+records_auto = manager.load_from_csv(+ "data/entities_semicolon.csv"+)+print(f"Loaded {len(records)} records from CSV")# CSV should have columns like: id, name, type, etc.@@ -74,6 +85,10 @@ print(f"Loaded {len(records)} records from JSON")# - List: [{"id": "1", "name": "John"}, ...]# - Dict with 'entities': {"entities": [...]}# - Dict with 'data': {"data": [...]}+# - Dict with 'records': {"records": [...]}+#+# Note: Ensure JSON seed files follow these supported top-level structures.+# Unsupported structures will trigger a warning and may be loaded as a single record.```### Loading from Database@@ -553,11 +568,15 @@ manager.export_seed_data("output/custom_seed.json", format="json")**Algorithm**: Row-by-row CSV processing with metadata injection1. **File Reading**: Open CSV file with UTF-8 encoding-2. **Header Detection**: Use csv.DictReader() for automatic header detection-3. **Row Processing**: Iterate through rows, convert to dictionaries-4. **Data Cleaning**: Remove empty values, clean whitespace-5. **Metadata Injection**: Add entity_type, relationship_type, source metadata-6. **Type Conversion**: Convert string values to appropriate types+2. **Delimiter Detection**:+ - Use provided delimiter if specified+ - If not, attempt to auto-detect delimiter using `csv.Sniffer`+ - Fallback to comma (`,`) if detection fails+3. **Header Detection**: Use csv.DictReader() for automatic header detection+4. **Row Processing**: Iterate through rows, convert to dictionaries+5. **Data Cleaning**: Remove empty values, clean whitespace+6. **Metadata Injection**: Add entity_type, relationship_type, source metadata+7. **Type Conversion**: Convert string values to appropriate types**Time Complexity**: O(n) where n = number of rows**Space Complexity**: O(n) for records storage