Files
planet/backend/app/services/private_data_ingest.py
T
linkong 1c0066edc6
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.85.0
2026-12-06 22:47:23 +08:00

298 lines
12 KiB
Python

"""Private CSV/JSON/REST upload-to-globe ingestion reusing mapping DSL (§4.4)."""
from __future__ import annotations
import csv
from datetime import UTC, datetime
import io
import json
import os
from typing import Any
import httpx
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.models.earth_interactable import EarthInteractable
from app.services.datasource_mapping import build_heuristic_mapping, execute_mapping
logger = get_logger(__name__, service="private_data_ingest")
def get_private_upload_limits() -> tuple[int, int]:
"""Return `(max_bytes, max_rows)` (defaults: 20 MB / 100,000 rows)."""
max_mb = int(os.getenv("PRIVATE_UPLOAD_MAX_MB", "20") or "20")
max_rows = int(os.getenv("PRIVATE_UPLOAD_MAX_ROWS", "100000") or "100000")
return max(1024, max_mb * 1024 * 1024), max(1, max_rows)
def parse_tabular_or_json_bytes(
raw_bytes: bytes,
*,
fmt: str,
) -> list[dict[str, Any]]:
"""Parse CSV or JSON bytes into a list of flat dicts, enforcing size and row caps."""
max_bytes, max_rows = get_private_upload_limits()
if len(raw_bytes) > max_bytes:
raise ValueError(
f"文件体积超出上限 ({len(raw_bytes)} bytes > {max_bytes} bytes),请分批上传"
)
fmt_clean = str(fmt or "json").strip().lower()
records: list[dict[str, Any]] = []
if fmt_clean == "csv":
text_content = raw_bytes.decode("utf-8-sig", errors="replace")
reader = csv.DictReader(io.StringIO(text_content))
for row in reader:
records.append(dict(row))
if len(records) > max_rows:
raise ValueError(
f"数据行数超出上限 ({max_rows} 行),请拆分为多个批次导入"
)
elif fmt_clean == "json":
parsed = json.loads(raw_bytes.decode("utf-8-sig", errors="replace"))
if isinstance(parsed, list):
items = parsed
elif isinstance(parsed, dict):
items = (
parsed.get("items")
or parsed.get("records")
or parsed.get("features")
or parsed.get("data")
or [parsed]
)
else:
raise ValueError("JSON 必须为对象数组或包含 records/items 的对象")
if len(items) > max_rows:
raise ValueError(f"数据行数超出上限 ({max_rows} 行),请拆分为多个批次导入")
records = [dict(it) for it in items if isinstance(it, dict)]
else:
raise ValueError(f"Unsupported upload format: {fmt}")
return records
async def fetch_rest_records_for_upload(url: str, *, root_path: str | None = None) -> list[dict[str, Any]]:
"""Fetch a JSON REST endpoint into normalized candidate dicts within upload limits."""
max_bytes, max_rows = get_private_upload_limits()
async with httpx.AsyncClient(timeout=15.0) as client:
resp = await client.get(url)
resp.raise_for_status()
raw = resp.content
if len(raw) > max_bytes:
raise ValueError(f"REST 响应体超出上限 ({max_bytes} bytes),请分页读取")
payload = json.loads(raw.decode("utf-8-sig", errors="replace"))
if root_path and isinstance(payload, dict):
for seg in root_path.split("."):
if isinstance(payload, dict):
payload = payload.get(seg)
if isinstance(payload, list):
items = payload
elif isinstance(payload, dict):
items = payload.get("items") or payload.get("records") or payload.get("data") or [payload]
else:
items = []
if len(items) > max_rows:
raise ValueError(f"REST 数据行数超出上限 ({max_rows} 行),请分页读取")
return [dict(it) for it in items if isinstance(it, dict)]
_ALIAS_FIELD_MAP = {
"latitude": ("lat", "float"),
"lat": ("lat", "float"),
"longitude": ("lon", "float"),
"lon": ("lon", "float"),
"name": ("name", "string"),
"label": ("name", "string"),
"id": ("source_id", "string"),
"source_id": ("source_id", "string"),
"kind": ("type", "string"),
"type": ("type", "string"),
"category": ("type", "string"),
"observed_at": ("observed_at", "string"),
}
def _normalize_geo_mapping_json(custom_mapping: dict[str, Any]) -> dict[str, Any]:
"""Convert flat field_mapping or full DSL dict into `execute_mapping(..., 'geo_points')` format."""
if isinstance(custom_mapping.get("fields"), dict) and custom_mapping["fields"]:
return custom_mapping
raw_fields = (
custom_mapping.get("field_mapping")
if isinstance(custom_mapping.get("field_mapping"), dict)
else custom_mapping
)
fields: dict[str, Any] = {}
for src_key, spec in raw_fields.items():
if src_key in ("source", "items_path", "meta"):
continue
target_name, default_type = _ALIAS_FIELD_MAP.get(str(src_key), (str(src_key), "string"))
if isinstance(spec, dict) and spec.get("path"):
fields[target_name] = dict(spec)
elif isinstance(spec, str) and spec.strip():
col = spec.strip()
path = col if col.startswith("$") else f"$.{col}"
fields[target_name] = {"path": path, "type": default_type}
return {"source": {"items_path": "$"}, "fields": fields}
def preview_private_mapping(records: list[dict[str, Any]], *, custom_mapping: dict[str, Any] | None = None) -> dict[str, Any]:
"""Generate heuristic field mapping & preview mapped globe coordinates."""
sample = records[:5]
suggested = build_heuristic_mapping(sample, target_schema_key="geo_points")
if custom_mapping:
mapping_json = _normalize_geo_mapping_json(custom_mapping)
else:
mapping_json = suggested
fields = dict(mapping_json.get("fields") or {})
cols = list(sample[0].keys()) if sample else []
for target_name, default_type, candidates in (
("source_id", "string", ("source_id", "id", "uid", "code", "object_id", "asset_id")),
("name", "string", ("name", "title", "label", "facility")),
("type", "string", ("type", "kind", "category")),
("lat", "float", ("lat", "latitude", "y")),
("lon", "float", ("lon", "lng", "longitude", "x")),
):
existing = fields.get(target_name)
existing_col = (
existing.get("path", "").removeprefix("$.")
if isinstance(existing, dict)
else ""
)
if not existing_col or existing_col not in cols:
for col in cols:
if col.lower() in candidates:
fields[target_name] = {"path": f"$.{col}", "type": default_type}
break
mapping_json = {"source": mapping_json.get("source") or {"items_path": "$"}, "fields": fields}
preview_items = (
execute_mapping(sample, mapping_json, "geo_points")
if mapping_json.get("fields")
else {"records": sample, "errors": []}
)
columns = list(sample[0].keys()) if sample else []
flat_mapping = {
k: (v.get("path", "").removeprefix("$.") if isinstance(v, dict) else v)
for k, v in (mapping_json.get("fields") or {}).items()
}
return {
"total_records": len(records),
"columns": columns,
"field_mapping": flat_mapping,
"mapping_json": mapping_json,
"preview": preview_items.get("records") or sample,
"errors": preview_items.get("errors") or [],
}
async def commit_private_records_to_globe(
db: AsyncSession,
*,
records: list[dict[str, Any]],
field_mapping: dict[str, Any],
default_kind: str = "private_asset",
layer_name: str = "interactables",
source_label: str = "private_upload",
) -> dict[str, Any]:
"""Map records via DSL and upsert into `earth_interactables` (`interactable:{id}`)."""
mapping_json = _normalize_geo_mapping_json(field_mapping or {})
mapped_res = (
execute_mapping(records, mapping_json, "geo_points")
if mapping_json.get("fields")
else {"records": records, "errors": []}
)
mapped_rows = mapped_res.get("records") or []
dialect = getattr(getattr(db.get_bind(), "dialect", None), "name", "")
now = datetime.now(UTC)
upserted = 0
skipped = 0
created_ids: list[str] = []
for idx, row in enumerate(mapped_rows):
raw_src = records[idx] if idx < len(records) else {}
lat_val = row.get("lat") if row.get("lat") is not None else row.get("latitude")
lon_val = row.get("lon") if row.get("lon") is not None else row.get("longitude")
try:
lat = float(lat_val)
lon = float(lon_val)
except (TypeError, ValueError):
skipped += 1
continue
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
skipped += 1
continue
obj_id = str(row.get("source_id") or row.get("id") or raw_src.get("id") or f"{default_kind}-{idx+1}").strip()[:160]
label = str(row.get("name") or row.get("label") or obj_id).strip()[:255]
kind = str(row.get("type") or row.get("kind") or row.get("category") or default_kind).strip()[:80]
props = {
**raw_src,
"source": source_label,
"observed_at": row.get("observed_at") or raw_src.get("observed_at") or now.isoformat(),
"category": row.get("category") or kind,
}
values = {
"id": obj_id,
"layer": layer_name,
"kind": kind,
"label": label,
"description": str(row.get("description") or raw_src.get("description") or ""),
"latitude": lat,
"longitude": lon,
"altitude": float(row["altitude"]) if row.get("altitude") is not None else None,
"revision": 1,
"properties": props,
"is_deleted": False,
}
if dialect == "postgresql":
stmt = pg_insert(EarthInteractable).values(**values)
stmt = stmt.on_conflict_do_update(
index_elements=["id"],
set_={
"layer": stmt.excluded.layer,
"kind": stmt.excluded.kind,
"label": stmt.excluded.label,
"description": stmt.excluded.description,
"latitude": stmt.excluded.latitude,
"longitude": stmt.excluded.longitude,
"altitude": stmt.excluded.altitude,
"properties": stmt.excluded.properties,
"is_deleted": False,
"deleted_at": None,
"updated_at": now,
},
)
await db.execute(stmt)
else:
stmt = sqlite_insert(EarthInteractable).values(**values)
stmt = stmt.on_conflict_do_update(
index_elements=["id"],
set_={
"layer": stmt.excluded.layer,
"kind": stmt.excluded.kind,
"label": stmt.excluded.label,
"description": stmt.excluded.description,
"latitude": stmt.excluded.latitude,
"longitude": stmt.excluded.longitude,
"altitude": stmt.excluded.altitude,
"properties": stmt.excluded.properties,
"is_deleted": False,
"deleted_at": None,
},
)
await db.execute(stmt)
upserted += 1
created_ids.append(f"interactable:{obj_id}")
await db.commit()
return {
"upserted": upserted,
"skipped": skipped,
"object_ids": created_ids,
"mapping_errors": mapped_res.get("errors") or [],
}