File size: 11,145 Bytes
9101d7e |
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 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
#!/usr/bin/env python3
"""
Step 1: Data Unification Script
================================
Reads various data formats (XML, JSON, CSV, MBOX) and
combines them into a single standardized DataFrame.
Output Schema: ['timestamp', 'sender', 'body', 'source']
Usage:
python step1_unify.py --input /path/to/raw/data --output step1_unified.csv
"""
import argparse
import json
import csv
import os
import re
import pandas as pd
from pathlib import Path
from datetime import datetime
from typing import List, Dict, Any, Optional
import mailbox
import email
from email.utils import parsedate_to_datetime
import xml.etree.ElementTree as ET
def parse_mbox(filepath: Path) -> List[Dict[str, Any]]:
"""Parse Gmail MBOX export."""
records = []
try:
mbox = mailbox.mbox(str(filepath))
for message in mbox:
try:
# Get timestamp
date_str = message.get('Date', '')
try:
timestamp = parsedate_to_datetime(date_str).isoformat()
except:
timestamp = date_str
# Get sender
sender = message.get('From', '')
# Get body
body = ''
if message.is_multipart():
for part in message.walk():
if part.get_content_type() == 'text/plain':
payload = part.get_payload(decode=True)
if payload:
body = payload.decode('utf-8', errors='ignore')
break
else:
payload = message.get_payload(decode=True)
if payload:
body = payload.decode('utf-8', errors='ignore')
if body.strip():
records.append({
'timestamp': timestamp,
'sender': sender,
'body': body.strip(),
'source': 'mbox'
})
except Exception as e:
continue
except Exception as e:
print(f" โ ๏ธ Error parsing MBOX {filepath}: {e}")
return records
def parse_json(filepath: Path) -> List[Dict[str, Any]]:
"""Parse JSON exports (Google Takeout format)."""
records = []
try:
with open(filepath, 'r', encoding='utf-8') as f:
data = json.load(f)
# Handle different JSON structures
if isinstance(data, list):
items = data
elif isinstance(data, dict):
# Common Google Takeout patterns
items = data.get('messages', []) or \
data.get('transactions', []) or \
data.get('items', []) or \
data.get('data', []) or \
[data]
else:
items = []
for item in items:
if not isinstance(item, dict):
continue
# Try common field names
timestamp = item.get('timestamp') or item.get('date') or \
item.get('time') or item.get('created_at') or ''
sender = item.get('sender') or item.get('from') or \
item.get('source') or item.get('merchant') or ''
body = item.get('body') or item.get('message') or \
item.get('text') or item.get('content') or \
item.get('description') or item.get('title') or ''
# For Google Pay transactions
if 'amount' in item:
amount = item.get('amount', '')
merchant = item.get('merchant', {})
if isinstance(merchant, dict):
merchant_name = merchant.get('name', '')
else:
merchant_name = str(merchant)
body = f"Transaction: Rs.{amount} to {merchant_name}"
if body and str(body).strip():
records.append({
'timestamp': str(timestamp),
'sender': str(sender),
'body': str(body).strip(),
'source': f'json:{filepath.name}'
})
except Exception as e:
print(f" โ ๏ธ Error parsing JSON {filepath}: {e}")
return records
def parse_csv(filepath: Path) -> List[Dict[str, Any]]:
"""Parse CSV exports."""
records = []
try:
df = pd.read_csv(filepath, encoding='utf-8', on_bad_lines='skip')
# Find relevant columns (case-insensitive)
cols = {c.lower(): c for c in df.columns}
timestamp_col = None
for name in ['timestamp', 'date', 'time', 'datetime', 'created_at']:
if name in cols:
timestamp_col = cols[name]
break
sender_col = None
for name in ['sender', 'from', 'source', 'bank', 'merchant']:
if name in cols:
sender_col = cols[name]
break
body_col = None
for name in ['body', 'message', 'text', 'content', 'description', 'sms']:
if name in cols:
body_col = cols[name]
break
if body_col:
for _, row in df.iterrows():
body = str(row.get(body_col, ''))
if body.strip() and body != 'nan':
records.append({
'timestamp': str(row.get(timestamp_col, '')) if timestamp_col else '',
'sender': str(row.get(sender_col, '')) if sender_col else '',
'body': body.strip(),
'source': f'csv:{filepath.name}'
})
except Exception as e:
print(f" โ ๏ธ Error parsing CSV {filepath}: {e}")
return records
def parse_xml(filepath: Path) -> List[Dict[str, Any]]:
"""Parse XML exports (SMS Backup format)."""
records = []
try:
tree = ET.parse(filepath)
root = tree.getroot()
# Common SMS backup format
for sms in root.findall('.//sms') or root.findall('.//message'):
body = sms.get('body') or sms.text or ''
timestamp = sms.get('date') or sms.get('timestamp') or ''
sender = sms.get('address') or sms.get('sender') or sms.get('from') or ''
if body.strip():
# Convert timestamp if it's milliseconds
if timestamp.isdigit() and len(timestamp) > 10:
try:
timestamp = datetime.fromtimestamp(int(timestamp)/1000).isoformat()
except:
pass
records.append({
'timestamp': timestamp,
'sender': sender,
'body': body.strip(),
'source': f'xml:{filepath.name}'
})
except Exception as e:
print(f" โ ๏ธ Error parsing XML {filepath}: {e}")
return records
def find_all_files(input_dir: Path) -> Dict[str, List[Path]]:
"""Find all data files recursively."""
files = {
'mbox': [],
'json': [],
'csv': [],
'xml': []
}
for filepath in input_dir.rglob('*'):
if filepath.is_file():
ext = filepath.suffix.lower()
if ext == '.mbox':
files['mbox'].append(filepath)
elif ext == '.json':
files['json'].append(filepath)
elif ext == '.csv':
files['csv'].append(filepath)
elif ext == '.xml':
files['xml'].append(filepath)
return files
def unify_data(input_dir: Path) -> pd.DataFrame:
"""Main function to unify all data sources."""
print("=" * 60)
print("๐ STEP 1: DATA UNIFICATION")
print("=" * 60)
all_records = []
# Find all files
print(f"\n๐ Scanning: {input_dir}")
files = find_all_files(input_dir)
total_files = sum(len(v) for v in files.values())
print(f" Found {total_files} files to process")
# Parse MBOX files
if files['mbox']:
print(f"\n๐ง Processing {len(files['mbox'])} MBOX files...")
for f in files['mbox']:
print(f" Processing: {f.name}")
records = parse_mbox(f)
all_records.extend(records)
print(f" โ
Extracted {len(records)} messages")
# Parse JSON files
if files['json']:
print(f"\n๐ Processing {len(files['json'])} JSON files...")
for f in files['json']:
print(f" Processing: {f.name}")
records = parse_json(f)
all_records.extend(records)
print(f" โ
Extracted {len(records)} records")
# Parse CSV files
if files['csv']:
print(f"\n๐ Processing {len(files['csv'])} CSV files...")
for f in files['csv']:
print(f" Processing: {f.name}")
records = parse_csv(f)
all_records.extend(records)
print(f" โ
Extracted {len(records)} records")
# Parse XML files
if files['xml']:
print(f"\n๐ Processing {len(files['xml'])} XML files...")
for f in files['xml']:
print(f" Processing: {f.name}")
records = parse_xml(f)
all_records.extend(records)
print(f" โ
Extracted {len(records)} records")
# Create DataFrame
df = pd.DataFrame(all_records, columns=['timestamp', 'sender', 'body', 'source'])
# Remove exact duplicates
original_count = len(df)
df = df.drop_duplicates(subset=['body'])
dedup_count = len(df)
print(f"\n๐ SUMMARY:")
print(f" Total records: {original_count}")
print(f" After dedup: {dedup_count}")
print(f" Removed: {original_count - dedup_count} duplicates")
return df
def main():
parser = argparse.ArgumentParser(description="Step 1: Unify data sources")
parser.add_argument("--input", "-i", required=True, help="Input directory with raw data")
parser.add_argument("--output", "-o", default="data/pipeline/step1_unified.csv",
help="Output CSV path")
args = parser.parse_args()
input_dir = Path(args.input)
if not input_dir.exists():
print(f"โ Input directory not found: {input_dir}")
return
# Unify data
df = unify_data(input_dir)
if len(df) == 0:
print("\nโ No data extracted! Check your input directory.")
return
# Save output
output_path = Path(args.output)
output_path.parent.mkdir(parents=True, exist_ok=True)
df.to_csv(output_path, index=False)
print(f"\nโ
Saved to: {output_path}")
print(f" Records: {len(df)}")
print("\nNext: python scripts/data_pipeline/step2_filter.py")
if __name__ == "__main__":
main()
|