简介
建筑历史数据治理方案,支持老旧Excel/Access格式迁移与成本指数化,助力企业挖掘历史项目数据价值用于成本基准与风险识别。
原始描述
Extract, clean, and organize legacy construction data from archives. Migrate historical project data, cost records, and schedules into modern formats.
中文使用说明 来自收录源
核心用法
Historical Data Manager 是专为建筑行业设计的遗留数据治理工具,核心工作流程分为四个阶段:首先通过 HistoricalDataManager 类初始化并扫描归档目录,自动识别 PDF、Excel、CSV、Access MDB 等异构文件格式;其次利用专用提取器解析不同来源数据,包括使用 xlrd/openpyxl 处理早期 Excel 格式、pyodbc 连接 Access 数据库、以及解析 Primavera P6 XER 和 Timberline 等专业施工管理软件导出文件;随后进行数据规范化,通过正则映射统一列名命名规范,并基于 RSMeans 历史成本指数将历年成本数据通胀调整至基准年(如 2026 年);最后生成包含数据质量评分、类型分布和年份统计的迁移报告,并导出为现代 Excel 格式供 BI 工具分析。
显著优点
该技能最大优势在于对建筑行业遗留系统的深度兼容,不仅支持从 Lotus 1-2-3 到现代 Office 的 Excel 全版本,还能解析 Sage Timberline(现 Sage 300)和 Primavera P6 等专业工程软件导出格式。内置的智能数据类型检测可基于列名自动识别成本、进度、人工、材料四类数据,配合正则表达式实现列名标准化(如将 "Proj.ID"、"Project Name" 统一映射)。成本指数化功能内置 RSMeans 历史指数表,支持将数十年历史成本一键折算为当前币值,这对成本基准测试和趋势分析至关重要。此外,数据质量评估体系(完整性、列名规范性、数据量)可帮助用户优先处理高价值档案。
潜在缺点与局限性
作为 T3 来源的社区项目,代码虽通过安全审计但缺乏顶级开源基金会的长期维护背书。功能上属于批处理工具,不支持实时数据流处理或增量同步,面对 TB 级超大规模档案时性能可能受限。对于仅存在纸质扫描件(非结构化 PDF)的历史记录,该工具缺乏 OCR 内容提取能力,需配合其他预处理步骤。依赖方面,连接 Access 数据库需要系统安装对应的 ODBC 驱动(如 Microsoft Access Driver),在 Linux 或 macOS 环境下配置较为复杂,且 pyodbc 等依赖的版本兼容性可能引发异常。
适合的目标群体
主要面向建筑承包商、工程咨询公司的数据管理团队,特别是负责企业数字化转型的档案管理员和成本数据库建设者。适合需要整合 10-30 年历史项目数据的成本估算师,以及进行生产力趋势分析和风险模式识别的项目分析师。对于使用 Sage 300、Primavera P6 等遗留系统且面临数据迁移压力的中大型建筑企业尤为实用。
使用风险与注意事项
尽管代码本身无恶意行为,但使用仍需注意:首先,工具需要读取整个归档文件系统的权限,建议在生产环境部署前在沙箱中测试,并严格遵循最小权限原则(仅授予归档目录只读权限)。其次,处理旧版 Excel 或 Access 文件时可能存在宏病毒或恶意代码嵌入风险,建议先进行病毒扫描。数据库连接方面,pyodbc 的错误配置可能导致连接字符串信息泄露,需确保连接参数安全存储。最后,成本指数化依赖内置的 RSMeans 示例数据,实际生产环境应更新为官方最新指数表,避免通胀计算偏差影响商业决策。
技能正文
slug: "historical-data-manager" display_name: "Historical Data Manager" description: "Extract, clean, and organize legacy construction data from archives. Migrate historical project data, cost records, and schedules into modern formats."
Historical Data Manager for Construction
Overview
Manage legacy construction data from archives, old systems, and historical records. Extract, clean, normalize, and migrate data into modern formats for analysis and benchmarking.
Business Case
Construction companies accumulate decades of project data in various formats:
- Paper records scanned to PDF
- Legacy database exports (Access, dBase, FoxPro)
- Old spreadsheet formats (Lotus 1-2-3, early Excel)
- Proprietary software exports
- Project closeout documentation
This skill helps extract value from historical data for:
- Cost benchmarking and trending
- Productivity analysis over time
- Risk pattern identification
- Estimating improvement
Technical Implementation
Historical Data Extractor
from dataclasses import dataclass, field
from typing import List, Dict, Any, Optional
from datetime import datetime
from pathlib import Path
import pandas as pd
import re
import json
@dataclass
class HistoricalRecord:
project_id: str
project_name: str
year: int
data_type: str # cost, schedule, labor, material
original_format: str
extracted_data: Dict[str, Any]
quality_score: float
notes: List[str] = field(default_factory=list)
class HistoricalDataManager:
"""Manage extraction and normalization of historical construction data."""
def __init__(self, archive_path: str):
self.archive_path = Path(archive_path)
self.records: List[HistoricalRecord] = []
self.normalization_rules = self._load_normalization_rules()
def scan_archive(self) -> Dict[str, int]:
"""Scan archive and categorize files by type."""
file_types = {}
for file_path in self.archive_path.rglob('*'):
if file_path.is_file():
ext = file_path.suffix.lower()
file_types[ext] = file_types.get(ext, 0) + 1
return file_types
def extract_from_legacy_excel(self, file_path: str, year: int) -> List[HistoricalRecord]:
"""Extract data from legacy Excel files."""
records = []
try:
# Try different engines for old formats
try:
df = pd.read_excel(file_path, engine='openpyxl')
except:
df = pd.read_excel(file_path, engine='xlrd')
# Detect data type from content
data_type = self._detect_data_type(df)
# Normalize column names
df = self._normalize_columns(df)
# Extract project info
project_info = self._extract_project_info(df, file_path)
record = HistoricalRecord(
project_id=project_info.get('id', f'LEGACY-{year}-{hash(file_path) % 10000}'),
project_name=project_info.get('name', Path(file_path).stem),
year=year,
data_type=data_type,
original_format='excel',
extracted_data=df.to_dict('records'),
quality_score=self._assess_quality(df)
)
records.append(record)
except Exception as e:
print(f"Error extracting {file_path}: {e}")
return records
def extract_from_csv(self, file_path: str, year: int) -> HistoricalRecord:
"""Extract data from CSV files with encoding detection."""
# Try different encodings
encodings = ['utf-8', 'latin-1', 'cp1252', 'iso-8859-1']
for encoding in encodings:
try:
df = pd.read_csv(file_path, encoding=encoding)
break
except:
continue
df = self._normalize_columns(df)
data_type = self._detect_data_type(df)
return HistoricalRecord(
project_id=f'CSV-{year}-{hash(file_path) % 10000}',
project_name=Path(file_path).stem,
year=year,
data_type=data_type,
original_format='csv',
extracted_data=df.to_dict('records'),
quality_score=self._assess_quality(df)
)
def extract_from_database_export(self, file_path: str, db_type: str) -> List[HistoricalRecord]:
"""Extract data from legacy database exports."""
records = []
if db_type == 'access':
# Read Access MDB/ACCDB files
import pyodbc
conn_str = f'DRIVER={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ={file_path}'
conn = pyodbc.connect(conn_str)
# Get all tables
cursor = conn.cursor()
tables = [row.table_name for row in cursor.tables(tableType='TABLE')]
for table in tables:
df = pd.read_sql(f'SELECT * FROM [{table}]', conn)
# Process each table...
conn.close()
return records
def normalize_cost_data(self, records: List[HistoricalRecord], base_year: int = 2026) -> pd.DataFrame:
"""Normalize historical cost data to current dollars."""
# RSMeans historical cost indices (example values)
cost_indices = {
2015: 0.82, 2016: 0.84, 2017: 0.87, 2018: 0.90,
2019: 0.93, 2020: 0.95, 2021: 0.98, 2022: 1.02,
2023: 1.06, 2024: 1.10, 2025: 1.14, 2026: 1.18
}
normalized_data = []
for record in records:
if record.data_type == 'cost':
year_index = cost_indices.get(record.year, 1.0)
base_index = cost_indices.get(base_year, 1.18)
escalation_factor = base_index / year_index
for item in record.extracted_data:
if 'amount' in item or 'cost' in item:
original_cost = item.get('amount') or item.get('cost', 0)
normalized_item = item.copy()
normalized_item['original_cost'] = original_cost
normalized_item['normalized_cost'] = original_cost * escalation_factor
normalized_item['escalation_factor'] = escalation_factor
normalized_item['original_year'] = record.year
normalized_item['project_id'] = record.project_id
normalized_data.append(normalized_item)
return pd.DataFrame(normalized_data)
def _detect_data_type(self, df: pd.DataFrame) -> str:
"""Detect type of data from column names and content."""
columns_lower = [c.lower() for c in df.columns]
if any(c in columns_lower for c in ['cost', 'amount', 'price', 'total', 'budget']):
return 'cost'
elif any(c in columns_lower for c in ['start', 'finish', 'duration', 'task', 'activity']):
return 'schedule'
elif any(c in columns_lower for c in ['hours', 'labor', 'worker', 'crew']):
return 'labor'
elif any(c in columns_lower for c in ['material', 'quantity', 'unit', 'supplier']):
return 'material'
else:
return 'unknown'
def _normalize_columns(self, df: pd.DataFrame) -> pd.DataFrame:
"""Normalize column names to standard format."""
column_mapping = {
r'proj.*id': 'project_id',
r'proj.*name': 'project_name',
r'desc.*': 'description',
r'qty|quantity': 'quantity',
r'unit.*cost|unit.*price': 'unit_cost',
r'total|amount': 'amount',
r'start.*date': 'start_date',
r'end.*date|finish.*date': 'end_date',
r'dur.*': 'duration',
}
new_columns = {}
for col in df.columns:
col_lower = col.lower().strip()
for pattern, new_name in column_mapping.items():
if re.match(pattern, col_lower):
new_columns[col] = new_name
break
return df.rename(columns=new_columns)
def _assess_quality(self, df: pd.DataFrame) -> float:
"""Assess data quality score (0-1)."""
if df.empty:
return 0.0
scores = []
# Completeness: % of non-null values
completeness = 1 - (df.isnull().sum().sum() / df.size)
scores.append(completeness)
# Column quality: has meaningful column names
meaningful_cols = sum(1 for c in df.columns if len(c) > 2 and not c.startswith('Unnamed'))
col_quality = meaningful_cols / len(df.columns)
scores.append(col_quality)
# Row count: more data is better (capped at 1.0)
row_score = min(len(df) / 100, 1.0)
scores.append(row_score)
return sum(scores) / len(scores)
def _extract_project_info(self, df: pd.DataFrame, file_path: str) -> Dict[str, str]:
"""Extract project info from data or filename."""
info = {}
# Try to find project info in data
for col in df.columns:
if 'project' in col.lower() and 'id' in col.lower():
info['id'] = str(df[col].iloc[0]) if not df[col].empty else None
if 'project' in col.lower() and 'name' in col.lower():
info['name'] = str(df[col].iloc[0]) if not df[col].empty else None
# Fallback to filename
if 'name' not in info:
info['name'] = Path(file_path).stem
return info
def _load_normalization_rules(self) -> Dict:
"""Load rules for normalizing legacy data."""
return {
'unit_conversions': {
'M': 1000, # Thousand
'C': 100, # Hundred
'LF': 1, # Linear Foot
'SF': 1, # Square Foot
'CY': 1, # Cubic Yard
},
'date_formats': [
'%m/%d/%Y', '%m/%d/%y', '%Y-%m-%d',
'%d-%b-%Y', '%B %d, %Y'
]
}
def generate_migration_report(self) -> str:
"""Generate report on migrated data."""
report = ["# Historical Data Migration Report", ""]
# Summary
report.append("## Summary")
report.append(f"- Total Records: {len(self.records)}")
by_type = {}
by_year = {}
for r in self.records:
by_type[r.data_type] = by_type.get(r.data_type, 0) + 1
by_year[r.year] = by_year.get(r.year, 0) + 1
report.append("\n### By Data Type")
for dt, count in sorted(by_type.items()):
report.append(f"- {dt}: {count}")
report.append("\n### By Year")
for year, count in sorted(by_year.items()):
report.append(f"- {year}: {count}")
# Quality Assessment
report.append("\n## Data Quality")
avg_quality = sum(r.quality_score for r in self.records) / len(self.records) if self.records else 0
report.append(f"- Average Quality Score: {avg_quality:.2%}")
low_quality = [r for r in self.records if r.quality_score < 0.5]
if low_quality:
report.append(f"\n### Low Quality Records ({len(low_quality)})")
for r in low_quality[:10]:
report.append(f"- {r.project_name} ({r.year}): {r.quality_score:.2%}")
return "\n".join(report)
Legacy System Connectors
class LegacySystemConnector:
"""Connect to various legacy construction systems."""
@staticmethod
def read_timberline_export(file_path: str) -> pd.DataFrame:
"""Read Sage Timberline (now Sage 300) export files."""
# Timberline exports typically have specific format
df = pd.read_csv(file_path, encoding='cp1252')
# Map Timberline columns to standard
column_map = {
'JOB': 'project_id',
'PHASE': 'phase_code',
'CATEGORY': 'cost_code',
'DESCRIPTION': 'description',
'ESTIMATE': 'estimated_cost',
'ACTUAL': 'actual_cost',
'COMMITTED': 'committed_cost'
}
return df.rename(columns=column_map)
@staticmethod
def read_primavera_xer(file_path: str) -> Dict[str, pd.DataFrame]:
"""Read Primavera P6 XER export files."""
tables = {}
current_table = None
current_data = []
columns = []
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line.startswith('%T'):
# Save previous table
if current_table and current_data:
tables[current_table] = pd.DataFrame(current_data, columns=columns)
# Start new table
current_table = line.split('\t')[1] if '\t' in line else None
current_data = []
columns = []
elif line.startswith('%F'):
# Field definitions
columns = line.split('\t')[1:]
elif line.startswith('%R'):
# Data row
current_data.append(line.split('\t')[1:])
# Save last table
if current_table and current_data:
tables[current_table] = pd.DataFrame(current_data, columns=columns)
return tables
@staticmethod
def read_mc2_ice(file_path: str) -> pd.DataFrame:
"""Read MC2 ICE estimating export."""
# MC2 ICE format handling
pass
Quick Start
# Initialize manager
manager = HistoricalDataManager('/archive/projects')
# Scan archive
file_types = manager.scan_archive()
print(f"Found: {file_types}")
# Extract from legacy Excel files
for year in range(2015, 2024):
year_path = f'/archive/projects/{year}'
for file in Path(year_path).glob('*.xls*'):
records = manager.extract_from_legacy_excel(str(file), year)
manager.records.extend(records)
# Normalize cost data to 2026 dollars
cost_records = [r for r in manager.records if r.data_type == 'cost']
normalized_costs = manager.normalize_cost_data(cost_records, base_year=2026)
# Generate migration report
report = manager.generate_migration_report()
print(report)
# Export for analysis
normalized_costs.to_excel('historical_costs_normalized.xlsx', index=False)
Common Use Cases
- Cost Benchmarking: Normalize historical costs for comparison
- Productivity Analysis: Track labor productivity over time
- Risk Identification: Find patterns in historical project issues
- Estimating Calibration: Improve estimates with historical data
Dependencies
pip install pandas openpyxl xlrd pyodbc
Resources
- RSMeans Historical Cost Index: For cost escalation
- ENR Construction Cost Index: Alternative escalation source
- Legacy Format Documentation: Vendor-specific export formats
正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。
其他来源收录
同一技能在不同目录的原始页面: