cwicr-data-loader
Load and parse DDC CWICR construction cost database from multiple formats: Parquet, Excel, CSV, Qdrant snapshots. Foundation for all CWICR operations.
What this skill does
# CWICR Data Loader
## Business Case
### Problem Statement
DDC CWICR database is distributed in multiple formats:
- Apache Parquet (optimized for analytics)
- Excel workbooks (human-readable)
- CSV files (universal exchange)
- Qdrant snapshots (vector search)
Applications need unified data access regardless of source format.
### Solution
Universal data loader supporting all CWICR formats with automatic schema detection, validation, and pandas DataFrame conversion.
### Business Value
- **Format agnostic** - Load from any CWICR distribution
- **Validated data** - Automatic schema validation
- **Memory efficient** - Lazy loading for large datasets
- **Type-safe** - Proper data types preserved
## Technical Implementation
### Prerequisites
```bash
pip install pandas pyarrow openpyxl qdrant-client
```
### Python Implementation
```python
import pandas as pd
import pyarrow.parquet as pq
from pathlib import Path
from typing import Optional, Dict, Any, List, Union
from dataclasses import dataclass, field
from enum import Enum
import json
class CWICRFormat(Enum):
"""Supported CWICR data formats."""
PARQUET = "parquet"
EXCEL = "excel"
CSV = "csv"
QDRANT = "qdrant"
JSON = "json"
class CWICRLanguage(Enum):
"""Supported languages in CWICR database."""
ARABIC = "ar"
CHINESE = "zh"
GERMAN = "de"
ENGLISH = "en"
SPANISH = "es"
FRENCH = "fr"
HINDI = "hi"
PORTUGUESE = "pt"
RUSSIAN = "ru"
@dataclass
class CWICRSchema:
"""CWICR database schema definition."""
# Core fields
work_item_code: str = "work_item_code"
description: str = "description"
unit: str = "unit"
category: str = "category"
# Cost fields
unit_price: str = "unit_price"
labor_cost: str = "labor_cost"
material_cost: str = "material_cost"
equipment_cost: str = "equipment_cost"
overhead_cost: str = "overhead_cost"
# Norm fields
labor_norm: str = "labor_norm"
material_norm: str = "material_norm"
equipment_norm: str = "equipment_norm"
# Metadata
language: str = "language"
region: str = "region"
currency: str = "currency"
last_updated: str = "last_updated"
# Optional embedding
embedding: str = "embedding"
@dataclass
class CWICRWorkItem:
"""Represents a single work item from CWICR database."""
work_item_code: str
description: str
unit: str
category: str
unit_price: float = 0.0
labor_cost: float = 0.0
material_cost: float = 0.0
equipment_cost: float = 0.0
overhead_cost: float = 0.0
labor_norm: float = 0.0
labor_unit: str = "h"
resources: List[Dict[str, Any]] = field(default_factory=list)
language: str = "en"
region: str = ""
currency: str = "USD"
@dataclass
class CWICRResource:
"""Represents a resource (material, labor, equipment)."""
resource_code: str
description: str
unit: str
unit_price: float
resource_type: str # 'labor', 'material', 'equipment'
category: str = ""
class CWICRDataLoader:
"""Universal loader for CWICR database formats."""
REQUIRED_COLUMNS = ['work_item_code', 'description', 'unit']
NUMERIC_COLUMNS = ['unit_price', 'labor_cost', 'material_cost',
'equipment_cost', 'labor_norm']
def __init__(self):
self.schema = CWICRSchema()
self._cache: Dict[str, pd.DataFrame] = {}
def load(self, source: str,
format: Optional[CWICRFormat] = None,
language: Optional[CWICRLanguage] = None,
use_cache: bool = True) -> pd.DataFrame:
"""Load CWICR data from any supported source."""
cache_key = f"{source}_{language}"
if use_cache and cache_key in self._cache:
return self._cache[cache_key]
# Auto-detect format if not specified
if format is None:
format = self._detect_format(source)
# Load based on format
if format == CWICRFormat.PARQUET:
df = self._load_parquet(source)
elif format == CWICRFormat.EXCEL:
df = self._load_excel(source)
elif format == CWICRFormat.CSV:
df = self._load_csv(source)
elif format == CWICRFormat.JSON:
df = self._load_json(source)
else:
raise ValueError(f"Unsupported format: {format}")
# Validate and normalize
df = self._validate_schema(df)
df = self._normalize_types(df)
# Filter by language if specified
if language and 'language' in df.columns:
df = df[df['language'] == language.value]
# Cache result
if use_cache:
self._cache[cache_key] = df
return df
def _detect_format(self, source: str) -> CWICRFormat:
"""Auto-detect data format from source."""
path = Path(source)
if path.suffix.lower() == '.parquet':
return CWICRFormat.PARQUET
elif path.suffix.lower() in ['.xlsx', '.xls']:
return CWICRFormat.EXCEL
elif path.suffix.lower() == '.csv':
return CWICRFormat.CSV
elif path.suffix.lower() == '.json':
return CWICRFormat.JSON
else:
raise ValueError(f"Cannot detect format: {source}")
def _load_parquet(self, source: str) -> pd.DataFrame:
"""Load from Parquet file."""
return pd.read_parquet(source)
def _load_excel(self, source: str,
sheet_name: str = "WorkItems") -> pd.DataFrame:
"""Load from Excel workbook."""
try:
return pd.read_excel(source, sheet_name=sheet_name)
except:
# Try first sheet if named sheet doesn't exist
return pd.read_excel(source, sheet_name=0)
def _load_csv(self, source: str) -> pd.DataFrame:
"""Load from CSV file."""
# Try different encodings
for encoding in ['utf-8', 'latin-1', 'cp1252']:
try:
return pd.read_csv(source, encoding=encoding)
except UnicodeDecodeError:
continue
raise ValueError(f"Cannot read CSV with any encoding: {source}")
def _load_json(self, source: str) -> pd.DataFrame:
"""Load from JSON file."""
with open(source, 'r', encoding='utf-8') as f:
data = json.load(f)
if isinstance(data, list):
return pd.DataFrame(data)
elif isinstance(data, dict) and 'items' in data:
return pd.DataFrame(data['items'])
else:
return pd.DataFrame([data])
def _validate_schema(self, df: pd.DataFrame) -> pd.DataFrame:
"""Validate DataFrame against CWICR schema."""
# Check required columns
missing = set(self.REQUIRED_COLUMNS) - set(df.columns)
if missing:
raise ValueError(f"Missing required columns: {missing}")
return df
def _normalize_types(self, df: pd.DataFrame) -> pd.DataFrame:
"""Normalize column types."""
for col in self.NUMERIC_COLUMNS:
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0)
# Ensure string columns
for col in ['work_item_code', 'description', 'unit', 'category']:
if col in df.columns:
df[col] = df[col].astype(str)
return df
def load_resources(self, source: str,
format: Optional[CWICRFormat] = None) -> pd.DataFrame:
"""Load resources separately."""
if format is None:
format = self._detect_format(source)
if format == CWICRFormat.EXCEL:
try:
return pd.read_excel(source, sheet_name="Resources")
except:
return pd.DataFrame()
else:
return self.load(source, format)
def get_work_item(self, df: pd.DataFrame,
code: str) -> Optional[CWICRWorkItem]:
"""Get single work item by code."""
Related in Data & Analytics
clawarr-suite
IncludedComprehensive management for self-hosted media stacks (Sonarr, Radarr, Lidarr, Readarr, Prowlarr, Bazarr, Overseerr, Plex, Tautulli, SABnzbd, Recyclarr, Unpackerr, Notifiarr, Maintainerr, Kometa, FlareSolverr). Deep library exploration, analytics, dashboard generation, content management, request handling, subtitle management, indexer control, download monitoring, quality profile sync, library cleanup automation, notification routing, collection/overlay management, and media tracker integration (Trakt, Letterboxd, Simkl).
querying-soql
IncludedSOQL query generation, optimization, and analysis with 100-point scoring. Use this skill when the user needs SOQL/SOSL authoring or optimization: natural-language-to-query generation, relationship queries, aggregates, query-plan analysis, and performance or safety improvements for Salesforce queries. TRIGGER when: user writes, optimizes, or debugs SOQL/SOSL queries, touches .soql files, or asks about relationship queries, aggregates, or query performance. DO NOT TRIGGER when: bulk data operations (use handling-sf-data), Apex DML logic (use generating-apex), or report/dashboard queries.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
habit-flow
IncludedAI-powered atomic habit tracker with natural language logging, streak tracking, smart reminders, and coaching. Use for creating habits, logging completions naturally ("I meditated today"), viewing progress, and getting personalized coaching.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
visualizing-data
IncludedBuilds dashboards, reports, and data-driven interfaces requiring charts, graphs, or visual analytics. Provides systematic framework for selecting appropriate visualizations based on data characteristics and analytical purpose. Includes 24+ visualization types organized by purpose (trends, comparisons, distributions, relationships, flows, hierarchies, geospatial), accessibility patterns (WCAG 2.1 AA compliance), colorblind-safe palettes, and performance optimization strategies. Use when creating visualizations, choosing chart types, displaying data graphically, or designing data interfaces.