diff --git a/.dockerignore b/.dockerignore index 77c6d116..d7772c7f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -14,7 +14,7 @@ !config/ !config/earth-boundary-pov-policy.china-v1.json !scripts/ -!scripts/build_earth_boundary_china_pov_geojson.py +!scripts/earth_boundary_geometry.py !scripts/build_earth_boundary_pmtiles.py !scripts/db_migrate.py !scripts/earth_boundary_policy.py diff --git a/.gitignore b/.gitignore index 83d627a1..f7ef8d67 100644 --- a/.gitignore +++ b/.gitignore @@ -170,10 +170,14 @@ temp/ # ---------------------- data/ai/bgp-briefs/ data/earth-boundary-sources/ +data/earth-clouds/ +data/earth-tiles/ +data/earth-wind/ -# Generated Earth boundary tile artifacts. Keep source configs and builders in -# Git; publish PMTiles/MVT artifacts through release/deploy storage instead of -# committing thousands of generated tile files. +# Earth boundary sources and generated PMTiles artifacts live in the backend +# boundary data volume (built by the Earth "高精" rebuild), never in Git or in +# the desktop Earth bundle. +backend/data/earth-boundaries/ frontend/public/earth/data/boundaries/ # Offline comparison originals; runtime 8K maps and provenance remain versioned. diff --git a/VERSION b/VERSION index 83dcd12c..09c49413 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.83.0 +0.84.0 diff --git a/aiprovider/provider_service.py b/aiprovider/provider_service.py index 86a54f04..07cba3f2 100644 --- a/aiprovider/provider_service.py +++ b/aiprovider/provider_service.py @@ -126,6 +126,7 @@ class ProviderService: native_web_search = bool(getattr(payload, "native_web_search", False)) images = self._normalize_images(getattr(payload, "images", None)) tool_calls: list[ToolCallRecord] = [] + citation_urls: list[str] = [] stop_reason: str | None = None if provider_api == "openai-completions": @@ -160,6 +161,7 @@ class ProviderService: content_blocks = self._extract_responses_blocks(data) content = "".join(block.text for block in content_blocks if block.text) tool_calls = self._extract_responses_tool_calls(data) + citation_urls = self._extract_responses_citations(data) stop_reason = str(data.get("status") or "") or None elif provider_api == "anthropic-messages": data = await self._request_anthropic_messages( @@ -177,6 +179,7 @@ class ProviderService: content = self._extract_anthropic_content(data) content_blocks = self._extract_anthropic_blocks(data) tool_calls = self._extract_anthropic_tool_calls(data) + citation_urls = self._extract_anthropic_citations(data) stop_reason = str(data.get("stop_reason") or "") or None elif provider_api == "ollama-generate": data = await self._request_ollama( @@ -207,6 +210,7 @@ class ProviderService: text_blocks=text_blocks, thinking_blocks=thinking_blocks, tool_calls=tool_calls, + citation_urls=citation_urls, stop_reason=stop_reason, raw_response=data, ) @@ -332,7 +336,17 @@ class ProviderService: anthropic_messages: list[dict[str, Any]] = [] source_messages = ( conversation_messages - if (conversation_messages and (len(conversation_messages) > 1 or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages))) + if ( + conversation_messages + and ( + len(conversation_messages) > 1 + or bool(tools) + or any( + m.get("role") == "tool" or m.get("tool_calls") or m.get("thinking_blocks") + for m in conversation_messages + ) + ) + ) else [{"role": "user", "content": prompt}] ) for msg in source_messages: @@ -354,8 +368,15 @@ class ProviderService: else: anthropic_messages.append({"role": "user", "content": [block]}) continue - if role == "assistant" and msg.get("tool_calls"): + if role == "assistant" and (msg.get("tool_calls") or msg.get("thinking_blocks")): blocks: list[dict[str, Any]] = [] + for tb in msg.get("thinking_blocks") or []: + if not isinstance(tb, dict): + continue + t_text = str(tb.get("thinking") or "") + sig = str(tb.get("signature") or "") + if t_text and sig: + blocks.append({"type": "thinking", "thinking": t_text, "signature": sig}) text = str(msg.get("content") or "").strip() if text: blocks.append({"type": "text", "text": text}) @@ -424,9 +445,12 @@ class ProviderService: for tool in tools or []: if not isinstance(tool, dict) or not tool.get("name"): continue + tool_name = str(tool["name"]) + if native_web_search and tool_name == "web_search": + continue anthropic_tools.append( { - "name": str(tool["name"]), + "name": tool_name, "description": str(tool.get("description") or ""), "input_schema": tool.get("parameters") or {"type": "object", "properties": {}}, } @@ -437,13 +461,15 @@ class ProviderService: request_body["tools"] = anthropic_tools if isinstance(tool_choice, str): if tool_choice == "required": - request_body["tool_choice"] = {"type": "any"} + request_body["tool_choice"] = {"type": "auto"} if thinking_active else {"type": "any"} elif tool_choice == "auto": request_body["tool_choice"] = {"type": "auto"} elif tool_choice not in {"none", ""}: - request_body["tool_choice"] = {"type": "tool", "name": tool_choice} + request_body["tool_choice"] = {"type": "auto"} if thinking_active else {"type": "tool", "name": tool_choice} elif isinstance(tool_choice, dict) and tool_choice.get("name"): - request_body["tool_choice"] = {"type": "tool", "name": str(tool_choice["name"])} + request_body["tool_choice"] = ( + {"type": "auto"} if thinking_active else {"type": "tool", "name": str(tool_choice["name"])} + ) path = "/v1/messages" if self.provider == "minimax" and self.base_url.endswith("/anthropic") else "/messages" headers = { @@ -751,10 +777,15 @@ class ProviderService: if not isinstance(item, dict) else item.get("tool_calls") ) + or bool( + getattr(item, "thinking_blocks", None) + if not isinstance(item, dict) + else item.get("thinking_blocks") + ) ) for item in raw_items ) - if has_tool_turns: + if raw_items and (has_tool_turns or getattr(payload, "tools", None)): preserved: list[dict[str, Any]] = [] for item in raw_items: if isinstance(item, dict): @@ -763,12 +794,14 @@ class ProviderService: tool_call_id = item.get("tool_call_id") name = item.get("name") tool_calls = item.get("tool_calls") + thinking_blocks = item.get("thinking_blocks") else: role = str(getattr(item, "role", "") or "").strip().lower() content = str(getattr(item, "content", "") or "") tool_call_id = getattr(item, "tool_call_id", None) name = getattr(item, "name", None) tool_calls = getattr(item, "tool_calls", None) + thinking_blocks = getattr(item, "thinking_blocks", None) if role not in {"user", "assistant", "tool"}: continue entry: dict[str, Any] = {"role": role, "content": content} @@ -778,6 +811,8 @@ class ProviderService: entry["name"] = str(name) if tool_calls: entry["tool_calls"] = list(tool_calls) + if thinking_blocks: + entry["thinking_blocks"] = list(thinking_blocks) preserved.append(entry) return preserved or [{"role": "user", "content": final_prompt}] @@ -943,7 +978,14 @@ class ProviderService: messages.append({"role": "system", "content": resolved_system_prompt}) source_messages = ( conversation_messages - if (conversation_messages and (len(conversation_messages) > 1 or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages))) + if ( + conversation_messages + and ( + len(conversation_messages) > 1 + or bool(tools) + or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages) + ) + ) else [{"role": "user", "content": prompt}] ) for msg in source_messages: @@ -1046,6 +1088,7 @@ class ProviderService: conversation_messages and ( len(conversation_messages) > 1 + or bool(tools) or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages) ) ) @@ -1480,3 +1523,52 @@ class ProviderService: args = self._parse_tool_arguments(item.get("input")) records.append(ToolCallRecord(id=call_id, name=name, arguments=args)) return records + + @staticmethod + def _dedupe_urls(urls: list[str]) -> list[str]: + seen: set[str] = set() + out: list[str] = [] + for raw in urls: + url = str(raw or "").strip() + if url.startswith(("http://", "https://")) and url not in seen: + seen.add(url) + out.append(url) + return out + + def _extract_responses_citations(self, payload: dict[str, Any]) -> list[str]: + urls: list[str] = [] + for item in payload.get("output") or []: + if not isinstance(item, dict): + continue + if item.get("type") == "message": + for part in item.get("content") or []: + if not isinstance(part, dict): + continue + for ann in part.get("annotations") or []: + if isinstance(ann, dict) and ann.get("type") == "url_citation" and ann.get("url"): + urls.append(str(ann["url"])) + elif item.get("type") == "web_search_call": + action = item.get("action") if isinstance(item.get("action"), dict) else {} + for src in action.get("sources") or []: + if isinstance(src, dict) and src.get("url"): + urls.append(str(src["url"])) + return self._dedupe_urls(urls) + + def _extract_anthropic_citations(self, payload: dict[str, Any]) -> list[str]: + content = payload.get("content") + if not isinstance(content, list): + return [] + urls: list[str] = [] + for item in content: + if not isinstance(item, dict): + continue + item_type = str(item.get("type") or "") + if item_type == "web_search_tool_result": + for res in item.get("content") or []: + if isinstance(res, dict) and res.get("url"): + urls.append(str(res["url"])) + elif item_type == "text": + for cite in item.get("citations") or []: + if isinstance(cite, dict) and cite.get("url"): + urls.append(str(cite["url"])) + return self._dedupe_urls(urls) diff --git a/aiprovider/schemas.py b/aiprovider/schemas.py index d859c302..8511b8d4 100644 --- a/aiprovider/schemas.py +++ b/aiprovider/schemas.py @@ -9,6 +9,7 @@ class ChatMessage(BaseModel): tool_call_id: str | None = Field(default=None, max_length=200) name: str | None = Field(default=None, max_length=200) tool_calls: list[dict[str, Any]] | None = None + thinking_blocks: list[dict[str, Any]] | None = None class ToolCallRecord(BaseModel): @@ -56,6 +57,7 @@ class SituationalAnalysisResponse(BaseModel): text_blocks: list[str] = Field(default_factory=list) thinking_blocks: list[str] = Field(default_factory=list) tool_calls: list[ToolCallRecord] = Field(default_factory=list) + citation_urls: list[str] = Field(default_factory=list) stop_reason: str | None = None raw_response: dict[str, Any] = Field(default_factory=dict) diff --git a/backend/Dockerfile b/backend/Dockerfile index 0743aaca..d0ccb8c4 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -4,6 +4,17 @@ ARG PYTHON_IMAGE=python:3.14-slim ARG UV_IMAGE=ghcr.io/astral-sh/uv:latest FROM ${UV_IMAGE} AS uv + +# Earth boundary PMTiles builder (used by the Earth "高精" rebuild job). +FROM ${PYTHON_IMAGE} AS tippecanoe-build +ARG TIPPECANOE_REF=2.79.0 +RUN apt-get update \ + && apt-get install -y --no-install-recommends build-essential ca-certificates git libsqlite3-dev zlib1g-dev \ + && rm -rf /var/lib/apt/lists/* +RUN git clone --depth 1 --branch "${TIPPECANOE_REF}" https://github.com/felt/tippecanoe.git /src/tippecanoe \ + && make -C /src/tippecanoe -j"$(nproc)" tippecanoe \ + && install -m 0755 /src/tippecanoe/tippecanoe /usr/local/bin/tippecanoe + FROM ${PYTHON_IMAGE} COPY --from=uv /uv /uvx /bin/ @@ -20,8 +31,13 @@ RUN mkdir -p /root/.config/uv RUN apt-get update && apt-get install -y --no-install-recommends \ curl \ + libsqlite3-0 \ + libstdc++6 \ + zlib1g \ && rm -rf /var/lib/apt/lists/* +COPY --from=tippecanoe-build /usr/local/bin/tippecanoe /usr/local/bin/tippecanoe + COPY pyproject.toml uv.lock /app/ RUN --mount=type=cache,target=/root/.cache/uv \ --mount=type=secret,id=planet_uv_config,target=/root/.config/uv/uv.toml,required=false \ @@ -29,8 +45,8 @@ RUN --mount=type=cache,target=/root/.cache/uv \ COPY backend /app/backend COPY config/earth-boundary-pov-policy.china-v1.json /app/config/earth-boundary-pov-policy.china-v1.json -COPY scripts/build_earth_boundary_china_pov_geojson.py /app/scripts/build_earth_boundary_china_pov_geojson.py COPY scripts/build_earth_boundary_pmtiles.py /app/scripts/build_earth_boundary_pmtiles.py +COPY scripts/earth_boundary_geometry.py /app/scripts/earth_boundary_geometry.py COPY scripts/db_migrate.py /app/scripts/db_migrate.py COPY scripts/earth_boundary_policy.py /app/scripts/earth_boundary_policy.py COPY resources/earth/boundary-pov-geometry.china-v1.json /app/resources/earth/boundary-pov-geometry.china-v1.json diff --git a/backend/app/ai_tasks/default_prompts.json b/backend/app/ai_tasks/default_prompts.json index bb21787f..b35ece05 100644 --- a/backend/app/ai_tasks/default_prompts.json +++ b/backend/app/ai_tasks/default_prompts.json @@ -31,21 +31,13 @@ "system_prompt": "你是 BGP 值班分析师。请直接输出面向值班人员的中文 Markdown 简报,只写最终研判内容;不要复述用户需求、提示词、写作计划、字段清单或“我将如何回答”。", "prompt": "基于当前 BGP incidents、anomalies、原始观测事件、观测站覆盖与 prefix geography 证据,生成一份面向操作员的简明态势简报,突出区域热点、观测偏差、当前风险、证据和优先动作。" }, - { - "key": "location.factcheck.normalize", - "label": "位置事实核查结构化", - "group": "位置解析", - "version": "2026-05-16.1", - "system_prompt": "", - "prompt": "Convert the supplied location factcheck text into exactly one strict JSON object. Extract only facts present in the text or original query." - }, { "key": "location.factcheck.resolve", - "label": "位置事实核查兜底", + "label": "位置事实核查单轮研判", "group": "位置解析", - "version": "2026-05-16.1", + "version": "2026-12-03.3", "system_prompt": "", - "prompt": "Return exactly one JSON object for the most likely physical location. Use only fact-checkable public knowledge; return null fields rather than guessing when evidence is weak." + "prompt": "严格基于输入的 evidence_items(编号 E1..En)与目标元数据判断物理部署城市与园区,输出严格 JSON 对象,禁止编造坐标或证据列表外的引用;reasoning 与 country_override_reason 必须使用不超过 120 字的简洁简体中文,严禁出现 E1、E6 等内部证据编号。" }, { "key": "datasource.mapping", diff --git a/backend/app/api/main.py b/backend/app/api/main.py index fc131df8..6630bd0e 100644 --- a/backend/app/api/main.py +++ b/backend/app/api/main.py @@ -15,7 +15,9 @@ from app.api.v1 import ( alerts, settings, collected_data, + cloud_analysis, compute_intelligence, + data_ledger, data_products, layers, visualization, @@ -28,6 +30,7 @@ from app.api.v1 import ( situational_awareness, system_control, tv, + wind_analysis, ) api_router = APIRouter() @@ -40,6 +43,7 @@ api_router.include_router( ) api_router.include_router(datasources.router, prefix="/datasources", tags=["datasources"]) api_router.include_router(collected_data.router, prefix="/collected", tags=["collected-data"]) +api_router.include_router(data_ledger.router, prefix="/data-ledger", tags=["data-ledger"]) api_router.include_router(docs.router, prefix="/docs", tags=["docs"]) api_router.include_router(earth.router, prefix="/earth", tags=["earth"]) api_router.include_router(client_updates.router, prefix="/client", tags=["client-updates"]) @@ -50,6 +54,8 @@ api_router.include_router(settings.router, prefix="/settings", tags=["settings"] api_router.include_router(system_control.router, prefix="/system", tags=["system"]) api_router.include_router(api_keys.router, prefix="/system/api-keys", tags=["api-keys"]) api_router.include_router(data_products.router, prefix="/data-products", tags=["data-products"]) +api_router.include_router(cloud_analysis.router, prefix="/data-products/clouds", tags=["clouds"]) +api_router.include_router(wind_analysis.router, prefix="/data-products/wind", tags=["wind"]) api_router.include_router(compute_intelligence.router, prefix="/data-products/compute", tags=["compute"]) api_router.include_router( situational_awareness.router, diff --git a/backend/app/api/v1/ai_workflows.py b/backend/app/api/v1/ai_workflows.py index 98684133..3e3d1e44 100644 --- a/backend/app/api/v1/ai_workflows.py +++ b/backend/app/api/v1/ai_workflows.py @@ -63,12 +63,8 @@ from app.services.ai_client import get_ai_provider_client from app.services.alert_ai_brief import build_alert_brief_request from app.services.bgp_ai_brief import build_bgp_brief_request from app.services.compute_center_locations import build_compute_center_location_query -from app.services.location.agent_resolver import ( - run_controlled_location_agent, - run_l1_structured_facility_resolvers, -) +from app.services.location.workflow_tools import run_location_workflow from app.services.situational_alert_ai_brief import build_situational_alert_brief_request -from app.api.v1.settings import get_web_search_client router = APIRouter() logger = get_logger(__name__, service="ai_workflows") @@ -701,41 +697,20 @@ async def _resolve_playground_slash_or_workflow( active_wf = "location.resolve_unknown" target_name = trimmed[len("/locate") :].strip() or "Unknown Facility" query = build_compute_center_location_query(name=target_name) - l1_candidates, _, _ = await run_l1_structured_facility_resolvers(query, db=db) - tool_trace.extend(["l0_normalize", "l1_knowledge"]) - if l1_candidates: - c0 = l1_candidates[0] - extra_meta["direct_reply"] = ( - f"已通过 **L1 设施知识库** (`{c0.source}`) 定位到 **{c0.display_name}**:\n\n" - f"- 国家/地区:{c0.country or '-'}\n" - f"- 坐标:`{c0.latitude:.5f}, {c0.longitude:.5f}`(精度 `{c0.precision}`,置信度 `{c0.confidence:.2f}`)\n" - f"- 说明:{c0.source_note}" - ) - return active_wf, tool_trace, None, extra_meta try: - provider_client = await get_ai_provider_client(db) - web_search_client = await get_web_search_client(db) - res, term = await run_controlled_location_agent( - provider_client=provider_client, - web_search_client=web_search_client, + res = await run_location_workflow( + db=db, query=query, entity_type="compute_center", - db=db, + earth_context=earth_context if isinstance(earth_context, dict) else {}, + use_draft=use_draft, + record_run=False, + trigger_evolution=False, ) - tool_trace.extend(["l2_agent_research", "l3_geo_guardrail"]) - if res.candidates: - c0 = res.candidates[0] - extra_meta["direct_reply"] = ( - f"已通过 **L2/L3 位置 Agent** 核验 **{c0.display_name}**:\n\n" - f"- 坐标:`{c0.latitude:.5f}, {c0.longitude:.5f}`(精度 `{c0.precision}`)\n" - f"- 结论:{c0.source_note}" - ) - elif term: - extra_meta["direct_reply"] = f"位置 Agent 判定该目标属于终态 `{term}`:{res.failure_reason or ''}" - else: - extra_meta["direct_reply"] = f"未能定位目标「{target_name}」:{res.failure_reason or '暂无可核验公开证据'}。" + tool_trace.extend(res.get("tool_trace") or ["l0_normalize"]) + extra_meta["direct_reply"] = res.get("answer_markdown") or f"未能定位目标「{target_name}」。" except Exception as exc: - extra_meta["direct_reply"] = f"位置 Agent 调试执行失败:{exc}" + extra_meta["direct_reply"] = f"位置工作流调试执行失败:{exc}" extra_meta["direct_reply_error"] = str(exc) return active_wf, tool_trace, None, extra_meta diff --git a/backend/app/api/v1/auth.py b/backend/app/api/v1/auth.py index 06a8882b..92cf8aee 100644 --- a/backend/app/api/v1/auth.py +++ b/backend/app/api/v1/auth.py @@ -528,7 +528,8 @@ async def create_earth_session( detail="Too many desktop Earth session requests", ) client_header = await verify_desktop_handshake(request) - token, ttl_seconds = create_earth_session_token("desktop", client_id=client_header) + desktop_client_id = f"{client_ip}:{client_header}" + token, ttl_seconds = create_earth_session_token("desktop", client_id=desktop_client_id) return { "token": token, "expires_in": ttl_seconds, diff --git a/backend/app/api/v1/bgp.py b/backend/app/api/v1/bgp.py index b10c1aac..e0738891 100644 --- a/backend/app/api/v1/bgp.py +++ b/backend/app/api/v1/bgp.py @@ -15,16 +15,10 @@ from app.models.bgp_observation import BGPObservation from app.models.user import User from app.services.bgp_collector_locations import ( build_bgp_collector_location_query, - collect_bgp_collector_location_candidates, get_bgp_collector_location_dict, ) from app.services.bgp_collectors import build_bgp_collector_coverage -from app.services.ai_client import get_ai_provider_client -from app.api.v1.settings import get_web_search_client -from app.services.location.llm_fallback import ( - collect_llm_location_fallback_candidate, - collect_location_search_evidence, -) +from app.services.location.workflow_tools import run_location_workflow router = APIRouter() @@ -307,56 +301,56 @@ async def collect_bgp_collector_location( city = payload.city or legacy.get("city") country = payload.country or legacy.get("country") operator = payload.operator or "RIPE NCC" - - candidates, attempted_queries = collect_bgp_collector_location_candidates( + query = build_bgp_collector_location_query( collector=collector_id, site=site, city=city, country=country, operator=operator, ) - llm_failure_reason = None - if not candidates: - query = build_bgp_collector_location_query( - collector=collector_id, - site=site, - city=city, - country=country, - operator=operator, - ) - llm_result = None - try: - web_search_client = await get_web_search_client(db) - search_result = await collect_location_search_evidence( - web_search_client=web_search_client, - query=query, - entity_type="bgp_collector", - ) - attempted_queries = [*attempted_queries, *search_result.attempted_queries] - if not search_result.evidence: - llm_failure_reason = search_result.failure_reason - raise RuntimeError(search_result.failure_reason or "no WebSearch evidence") - provider_client = await get_ai_provider_client(db) - llm_result = await collect_llm_location_fallback_candidate( - provider_client=provider_client, - query=query, - entity_type="bgp_collector", - db=db, - attempted_queries=attempted_queries, - search_evidence=search_result.evidence, - ) - except Exception as exc: - if llm_failure_reason is None: - llm_failure_reason = f"LLM location factcheck unavailable: {exc}" - attempted_queries = [ - *attempted_queries, - f"llm_factcheck:bgp_collector:{collector_id or 'unknown'}", - ] - if llm_result is not None: - attempted_queries = [*attempted_queries, *llm_result.attempted_queries] - candidates = llm_result.candidates - llm_failure_reason = llm_result.failure_reason + try: + res = await run_location_workflow( + db=db, + query=query, + entity_type="bgp_collector", + earth_context={ + "collector_id": collector_id, + "name": collector_id, + "site": site, + "city": city, + "country": country, + "operator": operator, + }, + record_run=True, + trigger_evolution=True, + ) + except Exception as exc: + return { + "collector_id": collector_id, + "name": collector_id, + "success": False, + "failure_reason": ( + "No source coordinates or online geocoding result reached" + " city-level precision for this collector." + ), + "candidates": [], + "attempted_queries": [], + "llm_failure_reason": f"Location workflow unavailable: {exc}", + "workflow_run_id": None, + "context": { + "collector": collector_id, + "site": site, + "city": city, + "country": country, + "operator": operator, + }, + } + + candidates = res.get("candidates") or [] + attempted_queries = list(res.get("attempted_queries") or []) + llm_failure_reason = res.get("failure_reason") + workflow_run_id = res.get("workflow_run_id") context = { "collector": collector_id, "site": site, @@ -375,8 +369,9 @@ async def collect_bgp_collector_location( " city-level precision for this collector." ), "candidates": [], - "attempted_queries": list(attempted_queries), + "attempted_queries": attempted_queries, "llm_failure_reason": llm_failure_reason, + "workflow_run_id": workflow_run_id, "context": context, } @@ -386,7 +381,8 @@ async def collect_bgp_collector_location( "success": True, "candidates": [candidate.to_dict() for candidate in candidates], "best_candidate": candidates[0].to_dict(), - "attempted_queries": list(attempted_queries), + "attempted_queries": attempted_queries, + "workflow_run_id": workflow_run_id, "context": context, } diff --git a/backend/app/api/v1/cloud_analysis.py b/backend/app/api/v1/cloud_analysis.py new file mode 100644 index 00000000..4c5a96c0 --- /dev/null +++ b/backend/app/api/v1/cloud_analysis.py @@ -0,0 +1,56 @@ +"""Real-time cloud map spatial analytics & asset correlation APIs.""" + +from __future__ import annotations + +from fastapi import APIRouter, Depends, HTTPException, Query +from pydantic import BaseModel, Field +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.access_gate import require_earth_or_api_access +from app.core.security import get_current_user +from app.db.session import get_db +from app.models.user import User +from app.services.earth_clouds import ( + correlate_cloud_with_assets, + get_cloud_analysis_summary, + query_cloud_point, +) + +router = APIRouter() + + +class CloudAssetCorrelateRequest(BaseModel): + domain: str = Field(default="vessels") + min_density: float = Field(default=55.0, ge=0.0, le=100.0) + limit: int = Field(default=25, ge=1, le=100) + + +@router.get("/summary", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) +async def get_clouds_summary(db: AsyncSession = Depends(get_db)): + return await get_cloud_analysis_summary(db) + + +@router.get("/point", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) +async def get_clouds_point( + lat: float = Query(..., ge=-90.0, le=90.0), + lon: float = Query(..., ge=-180.0, le=180.0), + db: AsyncSession = Depends(get_db), +): + return await query_cloud_point(lat, lon, db=db) + + +@router.post("/correlate") +async def post_clouds_correlate( + payload: CloudAssetCorrelateRequest, + _current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), +): + try: + return await correlate_cloud_with_assets( + db, + domain=payload.domain, + min_density=payload.min_density, + limit=payload.limit, + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc diff --git a/backend/app/api/v1/collected_data.py b/backend/app/api/v1/collected_data.py index bc027162..26b80c28 100644 --- a/backend/app/api/v1/collected_data.py +++ b/backend/app/api/v1/collected_data.py @@ -1,23 +1,32 @@ -from typing import Optional -from fastapi import APIRouter, Depends, HTTPException, Query, status, Response -from fastapi.responses import StreamingResponse -from sqlalchemy import select, func, text -from sqlalchemy.ext.asyncio import AsyncSession -import json import csv +import hashlib import io +import json +from typing import Optional +from fastapi import APIRouter, Depends, HTTPException, Query, status +from fastapi.responses import StreamingResponse +from sqlalchemy import select, text +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.cache import cache from app.core.collected_data_fields import get_metadata_field from app.core.countries import COUNTRY_OPTIONS, get_country_search_variants, normalize_country +from app.core.security import get_current_user from app.core.time import to_iso8601_utc from app.db.session import get_db -from app.models.user import User -from app.core.security import get_current_user -from app.models.collected_data import CollectedData from app.models.datasource import DataSource +from app.models.user import User router = APIRouter() +DEFAULT_EXCLUDED_DATA_TYPES: tuple[str, ...] = ("prefix_geography",) +DEFAULT_EXCLUDED_SOURCES: frozenset[str] = frozenset( + {"iptoasn_prefix_geo", "opengeofeed_prefix_geo", "nro_delegated_prefix_geo"} +) +COLLECTED_FACETS_CACHE_KEY = "collected:facets:v1" +COLLECTED_FACETS_TTL_SECONDS = 300 +COLLECTED_SUMMARY_TTL_SECONDS = 60 COUNTRY_SQL = "metadata->>'country'" SEARCHABLE_SQL = [ @@ -46,6 +55,50 @@ def build_in_condition(field_sql: str, values: list[str], param_prefix: str, par return f"{field_sql} IN ({', '.join(placeholders)})" +def build_not_in_condition(field_sql: str, values: tuple[str, ...], param_prefix: str, params: dict) -> str: + placeholders = [] + for index, value in enumerate(values): + key = f"{param_prefix}_{index}" + params[key] = value + placeholders.append(f":{key}") + return f"{field_sql} NOT IN ({', '.join(placeholders)})" + + +def _includes_default_excluded(source_values: list[str], data_type_values: list[str]) -> bool: + if any(dt in DEFAULT_EXCLUDED_DATA_TYPES for dt in data_type_values): + return True + if any(src in DEFAULT_EXCLUDED_SOURCES for src in source_values): + return True + return False + + +def _facets_cache_key(mode: str) -> str: + return COLLECTED_FACETS_CACHE_KEY if mode != "history" else f"{COLLECTED_FACETS_CACHE_KEY}:history" + + +def _summary_cache_key( + *, + mode: str, + source: Optional[str], + data_type: Optional[str], + country: Optional[str], + search: Optional[str], +) -> str: + payload = json.dumps( + { + "mode": "history" if mode == "history" else "current", + "source": source or "", + "data_type": data_type or "", + "country": country or "", + "search": (search or "").strip(), + }, + sort_keys=True, + ensure_ascii=False, + ) + digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()[:24] + return f"collected:summary:v1:{digest}" + + def build_search_condition(search: Optional[str], params: dict) -> Optional[str]: if not search: return None @@ -108,7 +161,14 @@ def serialize_collected_row( *, include_metadata: bool = True, ) -> dict: - metadata = row[7] + raw_metadata = row[7] + if isinstance(raw_metadata, str): + try: + metadata = json.loads(raw_metadata) + except json.JSONDecodeError: + metadata = None + else: + metadata = raw_metadata source = row[1] return { "id": row[0], @@ -141,6 +201,43 @@ async def get_source_name_map(db: AsyncSession) -> dict[str, str]: return {row[0]: row[1] for row in result.fetchall()} +async def _load_collected_facets( + db: AsyncSession, + *, + mode: str, + source_name_map: dict[str, str] | None = None, +) -> list[dict]: + cache_key = _facets_cache_key(mode) + cached_facets = cache.get(cache_key) + if isinstance(cached_facets, list): + return cached_facets + + where_sql = "is_current IS TRUE" if mode != "history" else "1=1" + result = await db.execute( + text( + f""" + SELECT source, data_type, COUNT(*) AS count + FROM collected_data + WHERE {where_sql} + GROUP BY source, data_type + ORDER BY source, data_type + """ + ) + ) + names = source_name_map if source_name_map is not None else await get_source_name_map(db) + facets = [ + { + "source": row[0], + "source_name": names.get(row[0], row[0]), + "data_type": row[1], + "count": int(row[2] or 0), + } + for row in result.fetchall() + ] + cache.set(cache_key, facets, expire_seconds=COLLECTED_FACETS_TTL_SECONDS) + return facets + + @router.get("") async def list_collected_data( mode: str = Query("current", description="查询模式: current/history"), @@ -155,55 +252,64 @@ async def list_collected_data( db: AsyncSession = Depends(get_db), ): """查询采集的数据列表""" - normalized_country = normalize_country(country) if country else None - source_values = parse_multi_values(source) - data_type_values = parse_multi_values(data_type) - - # Build WHERE clause - conditions = [] - params = {} - - if mode != "history": - conditions.append("COALESCE(is_current, TRUE) = TRUE") - - if source_values: - conditions.append(build_in_condition("source", source_values, "source", params)) - if data_type_values: - conditions.append(build_in_condition("data_type", data_type_values, "data_type", params)) - if normalized_country: - conditions.append(f"{COUNTRY_SQL} = :country") - params["country"] = normalized_country - search_condition = build_search_condition(search, params) - if search_condition: - conditions.append(search_condition) - - where_sql = " AND ".join(conditions) if conditions else "1=1" - search_rank_sql = build_search_rank_sql(search) + where_sql, params, include_excluded = build_where_clause( + source, + data_type, + country, + search, + mode=mode, + ) + has_search = bool(search and search.strip()) # Calculate offset offset = (page - 1) * page_size + source_name_map = await get_source_name_map(db) - # Query total count - count_query = text(f"SELECT COUNT(*) FROM collected_data WHERE {where_sql}") - count_result = await db.execute(count_query, params) - total = count_result.scalar() + if not country and not has_search: + facets = await _load_collected_facets(db, mode=mode, source_name_map=source_name_map) + source_set = set(parse_multi_values(source)) + type_set = set(parse_multi_values(data_type)) + total = sum( + item["count"] + for item in facets + if (include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES) + and (not source_set or item["source"] in source_set) + and (not type_set or item["data_type"] in type_set) + ) + else: + count_query = text(f"SELECT COUNT(*) FROM collected_data WHERE {where_sql}") + count_result = await db.execute(count_query, params) + total = int(count_result.scalar() or 0) - # Query data - query = text(f""" - SELECT id, source, source_id, data_type, name, title, description, - metadata, collected_at, reference_date, is_valid, - {search_rank_sql} AS search_rank - FROM collected_data - WHERE {where_sql} - ORDER BY search_rank DESC, collected_at DESC - LIMIT :limit OFFSET :offset - """) params["limit"] = page_size params["offset"] = offset + if has_search: + search_rank_sql = build_search_rank_sql(search) + query = text( + f""" + SELECT id, source, source_id, data_type, name, title, description, + metadata, collected_at, reference_date, is_valid, + {search_rank_sql} AS search_rank + FROM collected_data + WHERE {where_sql} + ORDER BY search_rank DESC, collected_at DESC + LIMIT :limit OFFSET :offset + """ + ) + else: + query = text( + f""" + SELECT id, source, source_id, data_type, name, title, description, + metadata, collected_at, reference_date, is_valid + FROM collected_data + WHERE {where_sql} + ORDER BY collected_at DESC + LIMIT :limit OFFSET :offset + """ + ) result = await db.execute(query, params) rows = result.fetchall() - source_name_map = await get_source_name_map(db) data = [] for row in rows: @@ -217,6 +323,40 @@ async def list_collected_data( } +def _aggregate_summary_from_facets(facets: list[dict], *, overall_total: int) -> dict: + by_source: dict[str, dict[str, int]] = {} + source_acc: dict[str, dict] = {} + type_acc: dict[str, int] = {} + total = 0 + + for item in facets: + src = str(item["source"]) + src_name = str(item.get("source_name") or src) + dt = str(item["data_type"]) + cnt = int(item["count"] or 0) + if cnt <= 0: + continue + by_source.setdefault(src_name, {})[dt] = by_source.get(src_name, {}).get(dt, 0) + cnt + if src not in source_acc: + source_acc[src] = {"source": src, "source_name": src_name, "count": 0} + source_acc[src]["count"] += cnt + type_acc[dt] = type_acc.get(dt, 0) + cnt + total += cnt + + source_totals = sorted(source_acc.values(), key=lambda x: (-x["count"], x["source"])) + type_totals = [ + {"data_type": dt, "count": cnt} + for dt, cnt in sorted(type_acc.items(), key=lambda item: (-item[1], item[0])) + ] + return { + "total_records": total, + "overall_total_records": overall_total, + "by_source": by_source, + "source_totals": source_totals, + "type_totals": type_totals, + } + + @router.get("/summary") async def get_data_summary( mode: str = Query("current", description="查询模式: current/history"), @@ -228,89 +368,76 @@ async def get_data_summary( db: AsyncSession = Depends(get_db), ): """获取数据汇总统计""" - where_sql, params = build_where_clause(source, data_type, country, search) - if mode != "history": - where_sql = f"({where_sql}) AND COALESCE(is_current, TRUE) = TRUE" - - overall_where_sql = "COALESCE(is_current, TRUE) = TRUE" if mode != "history" else "1=1" - - overall_total_result = await db.execute( - text(f"SELECT COUNT(*) FROM collected_data WHERE {overall_where_sql}") + cache_key = _summary_cache_key( + mode=mode, + source=source, + data_type=data_type, + country=country, + search=search, ) - overall_total = overall_total_result.scalar() or 0 + cached_summary = cache.get(cache_key) + if isinstance(cached_summary, dict): + return cached_summary - # By source and data_type - result = await db.execute( - text(f""" - SELECT source, data_type, COUNT(*) as count - FROM collected_data - WHERE {where_sql} - GROUP BY source, data_type - ORDER BY source, data_type - """), - params, - ) - rows = result.fetchall() source_name_map = await get_source_name_map(db) - - by_source = {} - total = 0 - for row in rows: - source = row[0] - data_type = row[1] - count = row[2] - - source_key = source_name_map.get(source, source) - if source_key not in by_source: - by_source[source_key] = {} - by_source[source_key][data_type] = count - total += count - - # Total by source - source_totals = await db.execute( - text(f""" - SELECT source, COUNT(*) as count - FROM collected_data - WHERE {where_sql} - GROUP BY source - ORDER BY count DESC - """), - params, + unfiltered_facets = await _load_collected_facets( + db, mode=mode, source_name_map=source_name_map ) - source_rows = source_totals.fetchall() - - type_totals = await db.execute( - text(f""" - SELECT data_type, COUNT(*) as count - FROM collected_data - WHERE {where_sql} - GROUP BY data_type - ORDER BY count DESC, data_type - """), - params, + source_values = parse_multi_values(source) + data_type_values = parse_multi_values(data_type) + include_excluded = _includes_default_excluded(source_values, data_type_values) + overall_total = sum( + int(item["count"] or 0) + for item in unfiltered_facets + if include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES ) - type_rows = type_totals.fetchall() - return { - "total_records": total, - "overall_total_records": overall_total, - "by_source": by_source, - "source_totals": [ + normalized_country = normalize_country(country) if country else None + has_search = bool(search and search.strip()) + + if not normalized_country and not has_search: + source_set = set(source_values) + type_set = set(data_type_values) + filtered_facets = [ + item + for item in unfiltered_facets + if (include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES) + and (not source_set or item["source"] in source_set) + and (not type_set or item["data_type"] in type_set) + ] + else: + where_sql, params, _ = build_where_clause( + source, + data_type, + country, + search, + mode=mode, + ) + result = await db.execute( + text( + f""" + SELECT source, data_type, COUNT(*) AS count + FROM collected_data + WHERE {where_sql} + GROUP BY source, data_type + ORDER BY source, data_type + """ + ), + params, + ) + filtered_facets = [ { "source": row[0], "source_name": source_name_map.get(row[0], row[0]), - "count": row[1], + "data_type": row[1], + "count": int(row[2] or 0), } - for row in source_rows - ], - "type_totals": [ - { - "data_type": row[0], - "count": row[1], - } - for row in type_rows - ], - } + for row in result.fetchall() + ] + + payload = _aggregate_summary_from_facets(filtered_facets, overall_total=overall_total) + cache.set(cache_key, payload, expire_seconds=COLLECTED_SUMMARY_TTL_SECONDS) + return payload @router.get("/sources") @@ -320,21 +447,17 @@ async def get_data_sources( db: AsyncSession = Depends(get_db), ): """获取所有数据源列表""" - - result = await db.execute( - text(""" - SELECT DISTINCT source FROM collected_data - """ + ("WHERE COALESCE(is_current, TRUE) = TRUE " if mode != "history" else "") + """ - ORDER BY source - """) - ) - rows = result.fetchall() - source_name_map = await get_source_name_map(db) + facets = await _load_collected_facets(db, mode=mode) + seen: dict[str, str] = {} + for item in facets: + src = str(item["source"]) + if src not in seen: + seen[src] = str(item.get("source_name") or src) return { "sources": [ - {"source": row[0], "source_name": source_name_map.get(row[0], row[0])} - for row in rows + {"source": src, "source_name": seen[src]} + for src in sorted(seen.keys()) ], } @@ -346,18 +469,10 @@ async def get_data_types( db: AsyncSession = Depends(get_db), ): """获取所有数据类型列表""" - - result = await db.execute( - text(""" - SELECT DISTINCT data_type FROM collected_data - """ + ("WHERE COALESCE(is_current, TRUE) = TRUE " if mode != "history" else "") + """ - ORDER BY data_type - """) - ) - rows = result.fetchall() - + facets = await _load_collected_facets(db, mode=mode) + types = sorted({str(item["data_type"]) for item in facets if item.get("data_type")}) return { - "data_types": [row[0] for row in rows], + "data_types": types, } @@ -403,20 +518,31 @@ async def get_collected_data( def build_where_clause( - source: Optional[str], data_type: Optional[str], country: Optional[str], search: Optional[str] -): - """Build WHERE clause and params for queries""" + source: Optional[str], + data_type: Optional[str], + country: Optional[str], + search: Optional[str], + *, + mode: str = "current", +) -> tuple[str, dict, bool]: + """Build WHERE clause and params for queries.""" conditions = [] - params = {} + params: dict = {} + if mode != "history": + conditions.append("is_current IS TRUE") + source_values = parse_multi_values(source) data_type_values = parse_multi_values(data_type) + include_excluded = _includes_default_excluded(source_values, data_type_values) if source_values: conditions.append(build_in_condition("source", source_values, "source", params)) if data_type_values: conditions.append(build_in_condition("data_type", data_type_values, "data_type", params)) - normalized_country = normalize_country(country) if country else None + if not include_excluded and DEFAULT_EXCLUDED_DATA_TYPES: + conditions.append(build_not_in_condition("data_type", DEFAULT_EXCLUDED_DATA_TYPES, "excl_dt", params)) + normalized_country = normalize_country(country) if country else None if normalized_country: conditions.append(f"{COUNTRY_SQL} = :country") params["country"] = normalized_country @@ -425,7 +551,7 @@ def build_where_clause( conditions.append(search_condition) where_sql = " AND ".join(conditions) if conditions else "1=1" - return where_sql, params + return where_sql, params, include_excluded @router.get("/export/json") @@ -441,9 +567,7 @@ async def export_json( ): """导出数据为 JSON 格式""" - where_sql, params = build_where_clause(source, data_type, country, search) - if mode != "history": - where_sql = f"({where_sql}) AND COALESCE(is_current, TRUE) = TRUE" + where_sql, params, _ = build_where_clause(source, data_type, country, search, mode=mode) params["limit"] = limit query = text(f""" @@ -486,9 +610,7 @@ async def export_csv( ): """导出数据为 CSV 格式""" - where_sql, params = build_where_clause(source, data_type, country, search) - if mode != "history": - where_sql = f"({where_sql}) AND COALESCE(is_current, TRUE) = TRUE" + where_sql, params, _ = build_where_clause(source, data_type, country, search, mode=mode) params["limit"] = limit query = text(f""" diff --git a/backend/app/api/v1/compute_intelligence.py b/backend/app/api/v1/compute_intelligence.py index b7cb4c7c..94cbe298 100644 --- a/backend/app/api/v1/compute_intelligence.py +++ b/backend/app/api/v1/compute_intelligence.py @@ -1,6 +1,6 @@ """Compute observations, administrator configuration and independent facility samples.""" -from datetime import UTC, datetime +from datetime import UTC, date, datetime from app.core.compute_types import COMPUTE_SITE_TYPES, compute_record_filter, compute_site_type_expression from app.api.v1.visualization import convert_compute_centers_to_geojson @@ -8,10 +8,11 @@ from app.core.access_gate import require_earth_or_api_access from app.core.earth_geography_policy import display_country from app.core.enums import UserRole from app.core.logging import get_logger -from app.core.security import get_current_user +from app.core.security import get_current_user, get_optional_current_user from app.core.websocket.broadcaster import broadcaster from app.db.session import get_db from app.models.collected_data import CollectedData +from app.models.compute_configuration_revision import ComputeConfigurationRevision from app.models.data_snapshot import DataSnapshot from app.models.user import User from app.schemas.compute_configuration import ( @@ -29,10 +30,12 @@ from app.services.compute_center_locations import refresh_compute_center_locatio from app.services.compute_configuration import ( DEFAULT_CONFIGURATION, configuration_response, + list_configuration_revisions, publish_configuration, read_configuration, ) from app.services.compute_history import ComputeSeriesMode, compute_history +from app.services.compute_lineage import build_observation_lineage, is_admin_user from fastapi import APIRouter, Depends, HTTPException, Query, Response from sqlalchemy import and_, case, func, or_, select from sqlalchemy.ext.asyncio import AsyncSession @@ -70,13 +73,35 @@ async def get_series( countries: str = "CN,US", mode: ComputeSeriesMode = "global_share", db: AsyncSession = Depends(get_db), + as_of: str | None = None, + publish_id: str | None = None, ): codes = selected_countries(countries) - envelope = await read_configuration(db) + envelope = await read_configuration(db, as_of=as_of, publish_id=publish_id) response.headers["Cache-Control"] = "no-store" + if envelope.get("snapshot_unavailable"): + empty_cfg = ComputeConfiguration( + reviewed_at=date.today(), sources=[], observations=[], innovation=[] + ) + result = compute_history(codes, mode, empty_cfg) + result.update( + version=None, + publish_id=None, + published_at=None, + as_of=envelope.get("as_of"), + snapshot_unavailable=True, + notice=envelope.get("notice"), + provenance="snapshot_unavailable", + ) + return result result = compute_history(codes, mode, ComputeConfiguration.model_validate(envelope["config"])) + effective_pid = envelope.get("publish_id") or envelope["revision"] result.update( - version=envelope["revision"], + version=effective_pid, + publish_id=effective_pid, + published_at=envelope.get("published_at"), + as_of=envelope.get("as_of"), + snapshot_unavailable=False, provenance="bundled_reports" if envelope["is_default"] else "admin_curated_reports", ) return result @@ -98,6 +123,108 @@ async def get_configuration( return configuration_response(await read_configuration(db)) +@router.get("/revisions") +async def get_configuration_revisions( + response: Response, + limit: int = Query(20, ge=1, le=100), + _actor: User = Depends(configuration_admin), + db: AsyncSession = Depends(get_db), +): + response.headers["Cache-Control"] = "no-store" + items = await list_configuration_revisions(db, limit=limit, redact=False) + return {"items": items} + + +@router.get( + "/revisions/public", + dependencies=[Depends(require_earth_or_api_access("data_products:read"))], +) +async def get_public_configuration_revisions( + response: Response, + limit: int = Query(20, ge=1, le=50), + db: AsyncSession = Depends(get_db), +): + response.headers["Cache-Control"] = "no-store" + items = await list_configuration_revisions(db, limit=limit, redact=True) + return {"items": items} + + +@router.get( + "/lineage", + dependencies=[Depends(require_earth_or_api_access("data_products:read"))], +) +async def get_compute_observation_lineage( + response: Response, + code: str = Query(..., min_length=2, max_length=32), + metric: ComputeSeriesMode = "global_share", + year: int = Query(..., ge=2000, le=2100), + publish_id: str | None = None, + as_of: str | None = None, + current_user: User | None = Depends(get_optional_current_user), + db: AsyncSession = Depends(get_db), +): + response.headers["Cache-Control"] = "no-store" + return await build_observation_lineage( + db, + code=code, + metric=metric, + year=year, + publish_id=publish_id, + as_of=as_of, + redact=not is_admin_user(current_user), + ) + + +async def _deliver_revision_presentation( + db: AsyncSession, + envelope: dict, +) -> dict: + """Trigger revision-driven presentation after commit; record failures for scheduled retry.""" + publish_id = envelope.get("publish_id") or envelope.get("revision") + if not publish_id or envelope.get("no_changes"): + return envelope + rev_row = ( + await db.execute( + select(ComputeConfigurationRevision).where( + ComputeConfigurationRevision.publish_id == publish_id + ) + ) + ).scalar_one_or_none() + if not isinstance(rev_row, ComputeConfigurationRevision): + return envelope + if rev_row.presentation_status == "skipped": + envelope["presentation_status"] = "skipped" + return envelope + + from app.services.ai.proactive_pipeline import process_compute_revision_presentation + + try: + res = await process_compute_revision_presentation(db, rev_row.id) + await db.commit() + envelope["presentation_status"] = str(res.get("status") or rev_row.presentation_status) + except Exception as exc: + await db.rollback() + logger.warning_event( + "Compute revision presentation failed; queued for retry", + event="compute.revision.presentation_failed", + context={"publish_id": publish_id, "revision_id": rev_row.id, "error": str(exc)}, + ) + failed_row = ( + await db.execute( + select(ComputeConfigurationRevision).where( + ComputeConfigurationRevision.publish_id == publish_id + ) + ) + ).scalar_one_or_none() + if isinstance(failed_row, ComputeConfigurationRevision): + failed_row.presentation_status = "failed" + failed_row.presentation_attempts = int(failed_row.presentation_attempts or 0) + 1 + failed_row.presentation_error = str(exc)[:1000] + await db.commit() + envelope["presentation_status"] = "failed" + return envelope + + @router.put("/configuration") async def update_configuration( payload: ComputeConfigurationWrite, @@ -105,16 +232,16 @@ async def update_configuration( db: AsyncSession = Depends(get_db), ): envelope = await publish_configuration( - db, revision=payload.revision, config=payload.config, actor=actor, + db, + revision=payload.revision, + config=payload.config, + actor=actor, + publish_note=payload.publish_note, + source_candidate_ids=payload.source_candidate_ids, ) - try: - from app.services.ai.proactive_pipeline import process_compute_config_proactive_delta - - await process_compute_config_proactive_delta(db) - await db.commit() - except Exception: - pass - await _broadcast_compute_configuration_update() + if not envelope.get("no_changes"): + envelope = await _deliver_revision_presentation(db, envelope) + await _broadcast_compute_configuration_update() return configuration_response(envelope) @@ -125,16 +252,16 @@ async def reset_configuration( db: AsyncSession = Depends(get_db), ): envelope = await publish_configuration( - db, revision=payload.revision, config=DEFAULT_CONFIGURATION, actor=actor, reset=True, + db, + revision=payload.revision, + config=DEFAULT_CONFIGURATION, + actor=actor, + reset=True, + publish_note=payload.publish_note, ) - try: - from app.services.ai.proactive_pipeline import process_compute_config_proactive_delta - - await process_compute_config_proactive_delta(db) - await db.commit() - except Exception: - pass - await _broadcast_compute_configuration_update() + if not envelope.get("no_changes"): + envelope = await _deliver_revision_presentation(db, envelope) + await _broadcast_compute_configuration_update() return configuration_response(envelope) diff --git a/backend/app/api/v1/data_ledger.py b/backend/app/api/v1/data_ledger.py new file mode 100644 index 00000000..df3f13b2 --- /dev/null +++ b/backend/app/api/v1/data_ledger.py @@ -0,0 +1,958 @@ +"""Admin layer-based data ledger APIs (read-only per-layer views + compute review).""" + +from __future__ import annotations + +from dataclasses import dataclass +import re +from typing import Any, Optional + +from fastapi import APIRouter, Depends, HTTPException, Query +from sqlalchemy import desc, func, or_, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.v1.collected_data import DEFAULT_EXCLUDED_DATA_TYPES, _load_collected_facets +from app.api.v1.data_products import PRODUCT_DEFINITIONS +from app.core.cache import cache +from app.core.collected_data_fields import get_record_field +from app.core.compute_types import COMPUTE_SITE_TYPES, compute_record_filter, compute_site_type +from app.core.countries import normalize_country +from app.core.security import get_current_user +from app.core.time import to_iso8601_utc +from app.db.session import get_db +from app.models.bgp_collector_location import BGPCollectorLocation +from app.models.bgp_incident import BGPIncident +from app.models.collected_data import CollectedData +from app.models.compute_center_location import ComputeCenterLocationRecord +from app.models.datasource import DataSource +from app.models.earth_news import EarthNewsItem +from app.models.situational_assessment import WorkflowRun +from app.models.vessel import VesselCurrentState +from app.services.compute_center_locations import resolve_compute_center_location_full +from app.services.location.workflow_tools import ( + TERMINAL_UNLOCATABLE_STATUSES, + sanitize_user_facing_reasoning, +) + +router = APIRouter(dependencies=[Depends(get_current_user)]) + +DATA_LEDGER_LAYERS_CACHE_KEY = "data_ledger:layers:v2" +DATA_LEDGER_LAYERS_TTL_SECONDS = 60 + +LAYER_ORDER: tuple[str, ...] = ( + "compute", + "satellites", + "cables", + "vessels", + "bgp", + "news", + "weather", + "geo", +) + +LAYER_KINDS: dict[str, tuple[dict[str, str], ...]] = { + "cables": ( + {"id": "submarine_cable", "label": "海缆系统"}, + {"id": "landing_point", "label": "登陆点"}, + {"id": "cable_landing_relation", "label": "海缆登陆关系"}, + ), + "bgp": ( + {"id": "collectors", "label": "观测站"}, + {"id": "incidents", "label": "BGP 事件"}, + ), + "news": ( + {"id": "items", "label": "新闻条目"}, + {"id": "live_streams", "label": "Live 直播源"}, + ), + "weather": ( + {"id": "all", "label": "气象图层"}, + {"id": "cloud_map_record", "label": "云图记录"}, + {"id": "wind_field_record", "label": "风场记录"}, + ), +} + + +@dataclass(frozen=True) +class _CollectedLayerSpec: + data_types: tuple[str, ...] + columns: tuple[dict[str, str], ...] + include_data_type_col: bool = False + + +_COLLECTED_LAYER_SPECS: dict[str, _CollectedLayerSpec] = { + "satellites": _CollectedLayerSpec( + data_types=("satellite_tle",), + columns=( + {"key": "name", "label": "名称"}, + {"key": "source_id", "label": "NORAD ID"}, + {"key": "international_designator", "label": "国际编号"}, + {"key": "constellation_group", "label": "星座分组"}, + {"key": "inclination", "label": "轨道倾角"}, + {"key": "source", "label": "数据源"}, + {"key": "collected_at", "label": "采集时间"}, + ), + ), + "cables": _CollectedLayerSpec( + data_types=("submarine_cable", "landing_point", "cable_landing_relation"), + columns=( + {"key": "name", "label": "名称"}, + {"key": "source_id", "label": "原始 ID"}, + {"key": "source", "label": "数据源"}, + {"key": "country", "label": "国家/地区"}, + {"key": "collected_at", "label": "采集时间"}, + ), + ), + "news:live_streams": _CollectedLayerSpec( + data_types=("news_live_stream",), + columns=( + {"key": "name", "label": "频道名称"}, + {"key": "source", "label": "数据源"}, + {"key": "region", "label": "区域"}, + {"key": "language", "label": "语言"}, + {"key": "collected_at", "label": "采集时间"}, + ), + ), + "weather": _CollectedLayerSpec( + data_types=("cloud_map_record", "wind_field_record"), + include_data_type_col=True, + columns=( + {"key": "name", "label": "名称"}, + {"key": "data_type", "label": "数据类型"}, + {"key": "source", "label": "数据源"}, + {"key": "reference_date", "label": "观测时间"}, + {"key": "collected_at", "label": "采集时间"}, + ), + ), + "geo": _CollectedLayerSpec( + data_types=("earth_tile_pyramid",), + columns=( + {"key": "name", "label": "瓦片数据集"}, + {"key": "source", "label": "数据源"}, + {"key": "reference_date", "label": "参考日期"}, + {"key": "collected_at", "label": "采集时间"}, + ), + ), +} + + +_US_CA_STATE_ZIP_RE = re.compile(r"^[A-Z]{2}(?:\s+\d{5}(?:-\d{4})?)?$") +_POSTAL_PREFIX_RE = re.compile(r"^\d{4,6}(?:-\d{3,4})?\s+") +_POSTAL_SUFFIX_RE = re.compile(r"\s+\d{4,6}(?:-\d{3,4})?$") +_STREET_ADDRESS_RE = re.compile( + r"^\d+\s+.*\b(rd|road|ave|avenue|st|street|blvd|dr|drive|way|lane|pkwy|hwy|floor|suite|building)\b", + re.IGNORECASE, +) +_VAGUE_LOCATION_TOKENS = ( + "on prem", + "various", + "multiple", + "global", + "nordics", + "europe", + "asia", + "unknown", +) +_US_STATE_NAMES = frozenset( + { + "alabama", + "alaska", + "arizona", + "arkansas", + "california", + "colorado", + "connecticut", + "delaware", + "florida", + "georgia", + "hawaii", + "idaho", + "illinois", + "indiana", + "iowa", + "kansas", + "kentucky", + "louisiana", + "maine", + "maryland", + "massachusetts", + "michigan", + "minnesota", + "mississippi", + "missouri", + "montana", + "nebraska", + "nevada", + "new hampshire", + "new jersey", + "new mexico", + "new york", + "north carolina", + "north dakota", + "ohio", + "oklahoma", + "oregon", + "pennsylvania", + "rhode island", + "south carolina", + "south dakota", + "tennessee", + "texas", + "utah", + "vermont", + "virginia", + "washington", + "west virginia", + "wisconsin", + "wyoming", + "district of columbia", + } +) + + +def _normalize_ledger_country(value: Any) -> str | None: + if value is None: + return None + text = str(value).strip() + if not text: + return None + return normalize_country(text) or text + + +def _extract_city_from_location(location: Any, country: str | None = None) -> str | None: + if not isinstance(location, str): + return None + text = location.strip() + if not text: + return None + normalized_country = _normalize_ledger_country(country) if country else None + lines = [line.strip() for line in text.splitlines() if line.strip()] + for line in reversed(lines): + if "°" in line or '"' in line: + continue + lowered_line = line.casefold() + if any(token in lowered_line for token in _VAGUE_LOCATION_TOKENS): + continue + if "," not in line: + continue + parts = [part.strip() for part in line.split(",") if part.strip()] + while parts and normalize_country(parts[-1]) is not None: + parts.pop() + if not parts: + continue + if len(parts) >= 2: + tail = parts[-1] + if _US_CA_STATE_ZIP_RE.fullmatch(tail) or tail.casefold() in _US_STATE_NAMES: + parts.pop() + if not parts: + continue + candidate = parts[-1].strip() + candidate = _POSTAL_PREFIX_RE.sub("", candidate).strip() + candidate = _POSTAL_SUFFIX_RE.sub("", candidate).strip() + if not candidate or len(candidate) > 48: + continue + if candidate.isdigit(): + continue + if _STREET_ADDRESS_RE.search(candidate): + continue + if normalize_country(candidate) is not None: + continue + if normalized_country and _normalize_ledger_country(candidate) == normalized_country: + continue + return candidate + return None + + +def _format_satellite_inclination(value: Any) -> str: + if value is None or value == "": + return "-" + try: + return f"{float(value):.2f}°" + except (TypeError, ValueError): + return "-" + + +async def _load_source_name_map(db: AsyncSession) -> dict[str, str]: + rows = (await db.execute(select(DataSource.source, DataSource.name))).all() + return { + str(source): str(name) + for source, name in rows + if source and name and str(name).strip() + } + + +def _has_valid_coords(latitude: Any, longitude: Any) -> bool: + try: + lat = float(latitude) + lon = float(longitude) + except (TypeError, ValueError): + return False + if lat == 0.0 or lon == 0.0: + return False + return -90.0 <= lat <= 90.0 and -180.0 <= lon <= 180.0 + + +def _classify_compute_row( + record: CollectedData, + loc: ComputeCenterLocationRecord | None, + fallback_wf_run_id: str | None = None, +) -> dict[str, Any]: + metadata = record.extra_data if isinstance(record.extra_data, dict) else {} + site_type = compute_site_type(record) + operator = ( + (loc.operator if loc else None) + or metadata.get("organization") + or metadata.get("operator") + or metadata.get("owner") + or metadata.get("manufacturer") + ) + country = _normalize_ledger_country( + (loc.country if loc else None) + or get_record_field(record, "country") + or metadata.get("raw_country") + ) + city = (loc.city if loc else None) or get_record_field(record, "city") + if not city: + city = _extract_city_from_location(metadata.get("location"), country) + + lat = loc.latitude if loc else None + lon = loc.longitude if loc else None + precision = (loc.precision if loc else None) or "unknown" + confidence = loc.confidence if loc else None + location_source = (loc.location_source if loc else None) or "" + source_url = loc.source_url if loc else (metadata.get("source_url") or metadata.get("detail_url")) + raw_note = loc.source_note if loc else None + verification_status = str(loc.verification_status if loc else "").strip().lower() + raw_payload = (loc.raw_payload if loc and isinstance(loc.raw_payload, dict) else {}) or {} + workflow_run_id = raw_payload.get("workflow_run_id") or fallback_wf_run_id + + terminal_status: str | None = None + if verification_status in TERMINAL_UNLOCATABLE_STATUSES: + status_bucket = "terminal" + terminal_status = verification_status + elif loc is None and metadata.get("compute_contract") == "v1" and metadata.get("anonymous"): + status_bucket = "terminal" + terminal_status = "anonymous" + verification_status = "anonymous" + location_source = "contract_anonymous" + raw_note = raw_note or "源数据声明为匿名集群,不披露具体物理设施。" + elif verification_status == "unverified": + status_bucket = "needs_confirmation" + elif (verification_status == "verified" and _has_valid_coords(lat, lon)) or ( + verification_status == "source_provided" and _has_valid_coords(lat, lon) + ): + status_bucket = "located" + elif loc is None: + resolved = resolve_compute_center_location_full(record, metadata) + if resolved.is_resolved and resolved.location and resolved.location.is_renderable: + res_loc = resolved.location + status_bucket = "needs_confirmation" if res_loc.needs_confirmation else "located" + lat = res_loc.latitude + lon = res_loc.longitude + precision = res_loc.location_precision + confidence = res_loc.location_confidence + location_source = res_loc.location_source or "source_coordinates" + verification_status = "unverified" if res_loc.needs_confirmation else "source_provided" + city = city or res_loc.city + country = country or _normalize_ledger_country(res_loc.country) + raw_note = res_loc.location_source_note or res_loc.estimated_reason + else: + status_bucket = "pending" + verification_status = "pending" + else: + status_bucket = "pending" if not _has_valid_coords(lat, lon) else "located" + if not verification_status: + verification_status = "pending" + + sources_list = metadata.get("sources") if isinstance(metadata.get("sources"), list) else [] + has_clues = bool(operator or city or sources_list) + is_anonymous_placeholder = bool(metadata.get("anonymous")) and not has_clues + + updated_ts = (loc.verified_at or loc.updated_at if loc else None) or record.reference_date or record.collected_at + return { + "id": record.id, + "source": record.source, + "source_id": record.source_id, + "name": record.name or record.title or record.source_id, + "site_type": site_type, + "operator": operator, + "country": country, + "city": city, + "latitude": float(lat) if _has_valid_coords(lat, lon) else None, + "longitude": float(lon) if _has_valid_coords(lat, lon) else None, + "precision": precision, + "confidence": confidence, + "verification_status": verification_status, + "status_bucket": status_bucket, + "terminal_status": terminal_status, + "is_anonymous_placeholder": is_anonymous_placeholder, + "location_source": location_source or None, + "source_url": source_url, + "source_note": sanitize_user_facing_reasoning(raw_note) or None, + "workflow_run_id": workflow_run_id, + "updated_at": to_iso8601_utc(updated_ts), + } + + +def _compute_review_priority_tier(item: dict[str, Any]) -> int: + bucket = str(item.get("status_bucket") or "") + if bucket == "pending": + return 0 + if bucket == "needs_confirmation": + return 1 + if bucket == "located": + return 2 + if item.get("is_anonymous_placeholder"): + return 4 + return 3 + + +async def _count_collected_types(db: AsyncSession, data_types: tuple[str, ...]) -> int: + stmt = ( + select(func.count(CollectedData.id)) + .where(CollectedData.is_current.is_(True)) + .where(CollectedData.deleted_at.is_(None)) + .where(CollectedData.data_type.in_(data_types)) + ) + if "satellite_tle" in data_types: + stmt = stmt.where(CollectedData.source_id.is_not(None)).where(CollectedData.source_id != "") + return int((await db.scalar(stmt)) or 0) + + +@router.get("/layers") +async def list_data_ledger_layers(db: AsyncSession = Depends(get_db)): + """Return layer categories and item counts reusing `PRODUCT_DEFINITIONS`.""" + cached = cache.get(DATA_LEDGER_LAYERS_CACHE_KEY) + if isinstance(cached, dict) and isinstance(cached.get("layers"), list): + return cached + + compute_cnt = int( + ( + await db.scalar( + select(func.count(CollectedData.id)) + .where(CollectedData.is_current.is_(True)) + .where(CollectedData.deleted_at.is_(None)) + .where(compute_record_filter(CollectedData)) + ) + ) + or 0 + ) + sat_cnt = await _count_collected_types(db, ("satellite_tle",)) + cable_cnt = await _count_collected_types( + db, ("submarine_cable", "landing_point", "cable_landing_relation") + ) + vessel_cnt = int((await db.scalar(select(func.count(VesselCurrentState.mmsi)))) or 0) + bgp_col_cnt = int((await db.scalar(select(func.count(BGPCollectorLocation.id)))) or 0) + bgp_inc_cnt = int((await db.scalar(select(func.count(BGPIncident.id)))) or 0) + news_items_cnt = int((await db.scalar(select(func.count(EarthNewsItem.id)))) or 0) + news_live_cnt = await _count_collected_types(db, ("news_live_stream",)) + weather_cnt = await _count_collected_types(db, ("cloud_map_record", "wind_field_record")) + geo_cnt = await _count_collected_types(db, ("earth_tile_pyramid",)) + + facets = await _load_collected_facets(db, mode="current") + raw_cnt = sum( + int(item.get("count") or 0) + for item in facets + if item.get("data_type") not in DEFAULT_EXCLUDED_DATA_TYPES + ) + + counts_map = { + "compute": compute_cnt, + "satellites": sat_cnt, + "cables": cable_cnt, + "vessels": vessel_cnt, + "bgp": bgp_col_cnt + bgp_inc_cnt, + "news": news_items_cnt + news_live_cnt, + "weather": weather_cnt, + "geo": geo_cnt, + } + + layers = [ + { + "id": layer_id, + "name": str(PRODUCT_DEFINITIONS[layer_id]["name"]), + "count": counts_map[layer_id], + "kinds": list(LAYER_KINDS.get(layer_id, ())), + } + for layer_id in LAYER_ORDER + if layer_id in PRODUCT_DEFINITIONS + ] + layers.append( + { + "id": "raw", + "name": "原始采集记录", + "count": raw_cnt, + "kinds": [], + } + ) + + payload = {"layers": layers} + cache.set( + DATA_LEDGER_LAYERS_CACHE_KEY, + payload, + expire_seconds=DATA_LEDGER_LAYERS_TTL_SECONDS, + ) + return payload + + +@router.get("/compute-centers") +async def list_compute_center_ledger( + site_type: Optional[str] = Query(None), + status: Optional[str] = Query(None), + country: Optional[str] = Query(None), + search: Optional[str] = Query(None), + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=200), + db: AsyncSession = Depends(get_db), +): + """Return compute center review ledger with site-type and status bucket counts.""" + records = ( + await db.execute( + select(CollectedData) + .where(CollectedData.is_current.is_(True)) + .where(CollectedData.deleted_at.is_(None)) + .where(compute_record_filter(CollectedData)) + .order_by(desc(CollectedData.collected_at), desc(CollectedData.id)) + ) + ).scalars().all() + + loc_rows = (await db.execute(select(ComputeCenterLocationRecord))).scalars().all() + loc_map = {(r.source, r.source_id): r for r in loc_rows} + + wf_rows = ( + await db.execute( + select(WorkflowRun) + .where(WorkflowRun.workflow_id == "location.resolve_unknown") + .order_by(desc(WorkflowRun.started_at)) + ) + ).scalars().all() + latest_wf_by_sid: dict[str, str] = {} + for wf in wf_rows: + sid = None + if isinstance(wf.input_params, dict): + sid = wf.input_params.get("source_id") + if not sid and isinstance(wf.budget_used, dict): + sid = wf.budget_used.get("source_id") + if sid and str(sid) not in latest_wf_by_sid: + latest_wf_by_sid[str(sid)] = wf.id + + all_rows = [ + _classify_compute_row( + rec, + loc_map.get((rec.source, rec.source_id)), + fallback_wf_run_id=latest_wf_by_sid.get(str(rec.source_id)), + ) + for rec in records + ] + + search_needle = (search or "").strip().lower() + country_needle = _normalize_ledger_country(country) or "" + + def _matches_base(item: dict[str, Any]) -> bool: + if country_needle and str(item.get("country") or "") != country_needle: + return False + if search_needle: + haystack = " ".join( + str(item.get(k) or "") + for k in ("name", "source_id", "operator", "city", "country", "source_note") + ).lower() + if search_needle not in haystack: + return False + return True + + base_filtered = [item for item in all_rows if _matches_base(item)] + + status_filter = (status or "").strip() + site_type_filter = (site_type or "").strip() + + by_site_type = dict.fromkeys(COMPUTE_SITE_TYPES, 0) + for item in base_filtered: + if status_filter and item["status_bucket"] != status_filter: + continue + st = item["site_type"] + if st in by_site_type: + by_site_type[st] += 1 + + by_status = { + "located": 0, + "needs_confirmation": 0, + "terminal": 0, + "pending": 0, + } + for item in base_filtered: + if site_type_filter and item["site_type"] != site_type_filter: + continue + bucket = item["status_bucket"] + if bucket in by_status: + by_status[bucket] += 1 + + filtered = [ + item + for item in base_filtered + if (not site_type_filter or item["site_type"] == site_type_filter) + and (not status_filter or item["status_bucket"] == status_filter) + ] + filtered = [ + item + for _, item in sorted( + enumerate(filtered), + key=lambda pair: (_compute_review_priority_tier(pair[1]), pair[0]), + ) + ] + + countries = sorted({str(item["country"]) for item in all_rows if item.get("country")}) + total = len(filtered) + start = (page - 1) * page_size + paginated = filtered[start : start + page_size] + + return { + "items": paginated, + "total": total, + "page": page, + "page_size": page_size, + "counts": { + "total": len(all_rows), + "by_site_type": by_site_type, + "by_status": by_status, + }, + "countries": countries, + } + + +async def _query_collected_layer_items( + db: AsyncSession, + *, + layer: str, + spec: _CollectedLayerSpec, + kind: str, + kinds: list[dict[str, str]], + search: str, + page: int, + page_size: int, +) -> dict[str, Any]: + target_types = spec.data_types + if kind and kind != "all" and kind in spec.data_types: + target_types = (kind,) + + stmt = ( + select(CollectedData) + .where(CollectedData.is_current.is_(True)) + .where(CollectedData.deleted_at.is_(None)) + .where(CollectedData.data_type.in_(target_types)) + ) + if "satellite_tle" in target_types: + stmt = stmt.where(CollectedData.source_id.is_not(None)).where(CollectedData.source_id != "") + if search: + pat = f"%{search}%" + stmt = stmt.where( + or_( + CollectedData.name.ilike(pat), + CollectedData.title.ilike(pat), + CollectedData.source_id.ilike(pat), + CollectedData.source.ilike(pat), + ) + ) + + total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0) + rows_orm = ( + await db.execute( + stmt.order_by(desc(CollectedData.collected_at), desc(CollectedData.id)) + .limit(page_size) + .offset((page - 1) * page_size) + ) + ).scalars().all() + + source_name_map = await _load_source_name_map(db) + rows = [] + for rec in rows_orm: + meta = rec.extra_data if isinstance(rec.extra_data, dict) else {} + country_val = _normalize_ledger_country(get_record_field(rec, "country")) or "-" + constellation = meta.get("constellation_group") or meta.get("celestrak_query_group") or "-" + rows.append( + { + "id": rec.id, + "name": rec.name or rec.title or rec.source_id, + "source_id": rec.source_id, + "source": source_name_map.get(rec.source, rec.source), + "data_type": rec.data_type, + "country": country_val, + "international_designator": meta.get("international_designator") or "-", + "constellation_group": constellation, + "inclination": _format_satellite_inclination(meta.get("inclination")), + "region": meta.get("region") or meta.get("country") or "-", + "language": meta.get("language") or meta.get("lang") or "-", + "reference_date": to_iso8601_utc(rec.reference_date), + "collected_at": to_iso8601_utc(rec.collected_at), + } + ) + + return { + "layer": layer, + "kind": kind or (kinds[0]["id"] if kinds else "all"), + "kinds": kinds, + "columns": list(spec.columns), + "rows": rows, + "total": total, + "page": page, + "page_size": page_size, + } + + +async def _query_vessels_items( + db: AsyncSession, *, search: str, page: int, page_size: int +) -> dict[str, Any]: + stmt = select(VesselCurrentState) + if search: + pat = f"%{search}%" + stmt = stmt.where( + or_( + VesselCurrentState.name.ilike(pat), + VesselCurrentState.callsign.ilike(pat), + VesselCurrentState.flag.ilike(pat), + VesselCurrentState.vessel_type_name.ilike(pat), + ) + ) + total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0) + rows_orm = ( + await db.execute( + stmt.order_by(desc(VesselCurrentState.observed_at), desc(VesselCurrentState.mmsi)) + .limit(page_size) + .offset((page - 1) * page_size) + ) + ).scalars().all() + source_name_map = await _load_source_name_map(db) + rows = [ + { + "id": str(v.mmsi), + "mmsi": str(v.mmsi), + "name": v.name or f"MMSI {v.mmsi}", + "vessel_type_name": v.vessel_type_name or "-", + "flag": v.flag or "-", + "coordinates": f"{v.lat:.4f}, {v.lon:.4f}", + "sog": f"{v.sog:.1f} kn" if v.sog is not None else "-", + "source": source_name_map.get(v.source, v.source), + "observed_at": to_iso8601_utc(v.observed_at), + } + for v in rows_orm + ] + return { + "layer": "vessels", + "kind": "all", + "kinds": [], + "columns": [ + {"key": "name", "label": "船名"}, + {"key": "mmsi", "label": "MMSI"}, + {"key": "vessel_type_name", "label": "船型"}, + {"key": "flag", "label": "船旗"}, + {"key": "coordinates", "label": "坐标"}, + {"key": "sog", "label": "航速"}, + {"key": "source", "label": "数据源"}, + {"key": "observed_at", "label": "观测时间"}, + ], + "rows": rows, + "total": total, + "page": page, + "page_size": page_size, + } + + +async def _query_bgp_items( + db: AsyncSession, *, kind: str, kinds: list[dict[str, str]], search: str, page: int, page_size: int +) -> dict[str, Any]: + active_kind = kind if kind in {"collectors", "incidents"} else "collectors" + if active_kind == "collectors": + stmt = select(BGPCollectorLocation) + if search: + pat = f"%{search}%" + stmt = stmt.where( + or_( + BGPCollectorLocation.collector_id.ilike(pat), + BGPCollectorLocation.operator.ilike(pat), + BGPCollectorLocation.city.ilike(pat), + BGPCollectorLocation.country.ilike(pat), + ) + ) + total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0) + rows_orm = ( + await db.execute( + stmt.order_by(desc(BGPCollectorLocation.updated_at), desc(BGPCollectorLocation.id)) + .limit(page_size) + .offset((page - 1) * page_size) + ) + ).scalars().all() + rows = [ + { + "id": r.id, + "collector_id": r.collector_id, + "operator": r.operator or "-", + "country": r.country or "-", + "city": r.city or "-", + "verification_status": r.verification_status, + "updated_at": to_iso8601_utc(r.updated_at or r.verified_at), + } + for r in rows_orm + ] + columns = [ + {"key": "collector_id", "label": "观测站 ID"}, + {"key": "operator", "label": "运营机构"}, + {"key": "country", "label": "国家/地区"}, + {"key": "city", "label": "城市"}, + {"key": "verification_status", "label": "核验状态"}, + {"key": "updated_at", "label": "更新时间"}, + ] + else: + stmt = select(BGPIncident) + if search: + pat = f"%{search}%" + stmt = stmt.where( + or_( + BGPIncident.title.ilike(pat), + BGPIncident.incident_type.ilike(pat), + BGPIncident.source.ilike(pat), + ) + ) + total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0) + rows_orm = ( + await db.execute( + stmt.order_by(desc(BGPIncident.started_at), desc(BGPIncident.id)) + .limit(page_size) + .offset((page - 1) * page_size) + ) + ).scalars().all() + rows = [ + { + "id": r.id, + "title": r.title, + "incident_type": r.incident_type, + "severity": r.severity, + "status": r.status, + "source": r.source, + "started_at": to_iso8601_utc(r.started_at), + } + for r in rows_orm + ] + columns = [ + {"key": "title", "label": "事件标题"}, + {"key": "incident_type", "label": "事件类型"}, + {"key": "severity", "label": "级别"}, + {"key": "status", "label": "状态"}, + {"key": "source", "label": "数据源"}, + {"key": "started_at", "label": "开始时间"}, + ] + + return { + "layer": "bgp", + "kind": active_kind, + "kinds": kinds, + "columns": columns, + "rows": rows, + "total": total, + "page": page, + "page_size": page_size, + } + + +async def _query_news_items( + db: AsyncSession, *, kind: str, kinds: list[dict[str, str]], search: str, page: int, page_size: int +) -> dict[str, Any]: + active_kind = kind if kind in {"items", "live_streams"} else "items" + if active_kind == "live_streams": + return await _query_collected_layer_items( + db, + layer="news", + spec=_COLLECTED_LAYER_SPECS["news:live_streams"], + kind=active_kind, + kinds=kinds, + search=search, + page=page, + page_size=page_size, + ) + + stmt = select(EarthNewsItem) + if search: + pat = f"%{search}%" + stmt = stmt.where( + or_( + EarthNewsItem.title.ilike(pat), + EarthNewsItem.source.ilike(pat), + EarthNewsItem.region.ilike(pat), + EarthNewsItem.location_label.ilike(pat), + ) + ) + total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0) + rows_orm = ( + await db.execute( + stmt.order_by( + desc(func.coalesce(EarthNewsItem.published_at, EarthNewsItem.last_seen_at)), + desc(EarthNewsItem.id), + ) + .limit(page_size) + .offset((page - 1) * page_size) + ) + ).scalars().all() + rows = [ + { + "id": r.id, + "title": r.title, + "source": r.source or r.feed_name or "-", + "region": r.region, + "location_label": r.location_label, + "enrichment_status": r.enrichment_status, + "published_at": to_iso8601_utc(r.published_at or r.last_seen_at), + } + for r in rows_orm + ] + return { + "layer": "news", + "kind": "items", + "kinds": kinds, + "columns": [ + {"key": "title", "label": "新闻标题"}, + {"key": "source", "label": "来源"}, + {"key": "region", "label": "区域"}, + {"key": "location_label", "label": "地理落点"}, + {"key": "enrichment_status", "label": "处理状态"}, + {"key": "published_at", "label": "发布时间"}, + ], + "rows": rows, + "total": total, + "page": page, + "page_size": page_size, + } + + +@router.get("/{layer}/items") +async def list_layer_ledger_items( + layer: str, + kind: Optional[str] = Query(None), + search: Optional[str] = Query(None), + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=200), + db: AsyncSession = Depends(get_db), +): + """Return paginated read-only ledger rows for non-compute Earth layers.""" + kinds = list(LAYER_KINDS.get(layer, ())) + resolved_kind = (kind or "").strip() or (kinds[0]["id"] if kinds else "all") + search_str = (search or "").strip() + + if layer == "vessels": + return await _query_vessels_items(db, search=search_str, page=page, page_size=page_size) + if layer == "bgp": + return await _query_bgp_items( + db, kind=resolved_kind, kinds=kinds, search=search_str, page=page, page_size=page_size + ) + if layer == "news": + return await _query_news_items( + db, kind=resolved_kind, kinds=kinds, search=search_str, page=page, page_size=page_size + ) + if layer in _COLLECTED_LAYER_SPECS: + return await _query_collected_layer_items( + db, + layer=layer, + spec=_COLLECTED_LAYER_SPECS[layer], + kind=resolved_kind, + kinds=kinds, + search=search_str, + page=page, + page_size=page_size, + ) + + raise HTTPException(status_code=404, detail=f"Unknown ledger layer: {layer}") diff --git a/backend/app/api/v1/data_products.py b/backend/app/api/v1/data_products.py index 2ae696a6..34d0190e 100644 --- a/backend/app/api/v1/data_products.py +++ b/backend/app/api/v1/data_products.py @@ -1,12 +1,20 @@ from datetime import UTC, datetime +from typing import Any from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from app.api.v1.visualization import get_visualization_geo_summary from app.core.access_gate import require_earth_or_api_access from app.core.time import to_iso8601_utc from app.db.session import get_db +from app.models.collected_data import CollectedData +from app.models.datasource import DataSource +from app.models.earth_news import EarthNewsItem +from app.models.task import CollectionTask +from app.services.data_jobs import JOB_STATUS_CANCELLING, JOB_STATUS_QUEUED, JOB_STATUS_RUNNING +from app.services.earth_clouds import get_cloud_map_runtime_meta router = APIRouter(dependencies=[Depends(require_earth_or_api_access("data_products:read"))]) @@ -55,20 +63,131 @@ PRODUCT_DEFINITIONS: dict[str, dict] = { "primary_stat_key": "compute_center_count", "stat_keys": ["compute_center_count", "supercomputer_count", "gpu_cluster_count", "data_center_count", "cloud_center_count", "edge_node_count"], }, + "weather": { + "name": "气象", + "sources": ["global_cloud_map", "cloud_hd_tiles", "global_wind_gfs"], + "primary_stat_key": "cloud_frame_count", + "stat_keys": ["cloud_frame_count", "cloud_record_count", "wind_available_flag"], + }, + "geo": { + "name": "地理/底图", + "sources": ["earth_imagery_sentinel2", "earth_imagery_viirs_daily"], + "primary_stat_key": "cached_tile_count", + "stat_keys": ["cached_tile_count"], + }, + "news": { + "name": "新闻与直播", + "sources": ["earth_news", "news_live_streams"], + "primary_stat_key": "news_count", + "stat_keys": ["news_count"], + }, } -def _build_product_status(product_id: str, summary: dict) -> dict: +async def _load_collector_product_states( + db: AsyncSession, + source_names: list[str], +) -> tuple[dict[str, bool], set[str]]: + if not source_names: + return {}, set() + ds_rows = ( + await db.execute( + select(DataSource.id, DataSource.source, DataSource.is_active).where( + DataSource.source.in_(source_names) + ) + ) + ).all() + active_by_source = {str(source): bool(is_active) for _, source, is_active in ds_rows} + id_to_source = {int(ds_id): str(source) for ds_id, source, _ in ds_rows} + running_sources: set[str] = set() + if id_to_source: + task_rows = ( + await db.execute( + select(CollectionTask.datasource_id, func.count(CollectionTask.id)) + .where(CollectionTask.datasource_id.in_(list(id_to_source.keys()))) + .where( + CollectionTask.status.in_( + (JOB_STATUS_QUEUED, JOB_STATUS_RUNNING, JOB_STATUS_CANCELLING) + ) + ) + .group_by(CollectionTask.datasource_id) + ) + ).all() + for ds_id, cnt in task_rows: + if int(cnt or 0) > 0 and int(ds_id) in id_to_source: + running_sources.add(id_to_source[int(ds_id)]) + return active_by_source, running_sources + + +def _build_product_status( + product_id: str, + summary: dict, + *, + active_by_source: dict[str, bool], + running_sources: set[str], + weather_meta: dict[str, Any] | None = None, + wind_meta: dict[str, Any] | None = None, + basemap_meta: dict[str, Any] | None = None, + news_count: int | None = None, +) -> dict: definition = PRODUCT_DEFINITIONS[product_id] - stats = summary.get("stats", {}) - product_stats = {key: stats.get(key, 0) for key in definition["stat_keys"]} - total_count = int(product_stats.get(definition["primary_stat_key"]) or 0) + sources = definition["sources"] + total_collector_count = len(sources) + active_collector_count = sum(1 for src in sources if active_by_source.get(src, False)) + running_collector_count = sum(1 for src in sources if src in running_sources) + + if product_id == "weather": + meta = weather_meta or {} + w_meta = wind_meta or {} + frames = meta.get("frames") if isinstance(meta.get("frames"), list) else [] + frame_count = len(frames) + clusters = meta.get("convective_clusters") if isinstance(meta.get("convective_clusters"), list) else [] + regions = meta.get("regions") if isinstance(meta.get("regions"), list) else [] + wind_has_data = bool(w_meta.get("has_data")) + product_stats = { + "cloud_frame_count": frame_count, + "cloud_record_count": (1 + len(regions) + len(clusters)) if frame_count > 0 else 0, + "wind_available_flag": 1 if wind_has_data else 0, + } + total_count = frame_count + (1 if wind_has_data else 0) + has_data = frame_count > 0 or wind_has_data + captured_at = meta.get("captured_at") or w_meta.get("captured_at") + elif product_id == "geo": + b_meta = basemap_meta or {} + tile_sources = [ + item for item in (b_meta.get("sources") or []) + if isinstance(item, dict) and item.get("source") in sources + ] + cached_tiles = sum(int(item.get("cached_tiles") or 0) for item in tile_sources) + product_stats = {"cached_tile_count": cached_tiles} + total_count = cached_tiles + has_data = cached_tiles > 0 + captured_at = None + elif product_id == "news": + resolved_news_count = int(news_count or 0) + product_stats = {"news_count": resolved_news_count} + total_count = resolved_news_count + has_data = resolved_news_count > 0 + captured_at = None + else: + stats = summary.get("stats", {}) + product_stats = {key: stats.get(key, 0) for key in definition["stat_keys"]} + total_count = int(product_stats.get(definition["primary_stat_key"]) or 0) + has_data = total_count > 0 + captured_at = None + return { "product_id": product_id, "name": definition["name"], - "sources": definition["sources"], + "sources": sources, "generated_at": summary.get("generated_at") or to_iso8601_utc(datetime.now(UTC)), + "captured_at": captured_at, "total_count": total_count, + "has_data": has_data, + "total_collector_count": total_collector_count, + "active_collector_count": active_collector_count, + "running_collector_count": running_collector_count, + "datasources_url": f"/datasources?product={product_id}", "stats": product_stats, "build_state": "ready", "stats_scope": "global", @@ -76,13 +195,48 @@ def _build_product_status(product_id: str, summary: dict) -> dict: } +async def _load_news_product_count(db: AsyncSession) -> int: + try: + items_cnt = await db.scalar(select(func.count(EarthNewsItem.id))) + except Exception: + items_cnt = 0 + try: + live_cnt = await db.scalar( + select(func.count(CollectedData.id)) + .where(CollectedData.is_current.is_(True)) + .where(CollectedData.deleted_at.is_(None)) + .where(CollectedData.data_type == "news_live_stream") + ) + except Exception: + live_cnt = 0 + return int(items_cnt or 0) + int(live_cnt or 0) + + @router.get("") async def list_data_products(db: AsyncSession = Depends(get_db)): + from app.services.earth_tiles import get_basemap_runtime_meta + from app.services.earth_wind import get_wind_runtime_meta + summary = await get_visualization_geo_summary(db) + all_sources = [src for definition in PRODUCT_DEFINITIONS.values() for src in definition["sources"]] + active_by_source, running_sources = await _load_collector_product_states(db, all_sources) + weather_meta = await get_cloud_map_runtime_meta(db) + wind_meta = await get_wind_runtime_meta(db) + basemap_meta = await get_basemap_runtime_meta(db) + news_count = await _load_news_product_count(db) return { "generated_at": summary.get("generated_at"), "data": [ - _build_product_status(product_id, summary) + _build_product_status( + product_id, + summary, + active_by_source=active_by_source, + running_sources=running_sources, + weather_meta=weather_meta if product_id == "weather" else None, + wind_meta=wind_meta if product_id == "weather" else None, + basemap_meta=basemap_meta if product_id == "geo" else None, + news_count=news_count if product_id == "news" else None, + ) for product_id in PRODUCT_DEFINITIONS ], } @@ -93,7 +247,25 @@ async def get_data_product_status( product_id: str, db: AsyncSession = Depends(get_db), ): + from app.services.earth_tiles import get_basemap_runtime_meta + from app.services.earth_wind import get_wind_runtime_meta + if product_id not in PRODUCT_DEFINITIONS: raise HTTPException(status_code=404, detail="Unknown data product") summary = await get_visualization_geo_summary(db) - return _build_product_status(product_id, summary) + sources = PRODUCT_DEFINITIONS[product_id]["sources"] + active_by_source, running_sources = await _load_collector_product_states(db, sources) + weather_meta = await get_cloud_map_runtime_meta(db) if product_id == "weather" else None + wind_meta = await get_wind_runtime_meta(db) if product_id == "weather" else None + basemap_meta = await get_basemap_runtime_meta(db) if product_id == "geo" else None + news_count = await _load_news_product_count(db) if product_id == "news" else None + return _build_product_status( + product_id, + summary, + active_by_source=active_by_source, + running_sources=running_sources, + weather_meta=weather_meta, + wind_meta=wind_meta, + basemap_meta=basemap_meta, + news_count=news_count, + ) diff --git a/backend/app/api/v1/datasource_config.py b/backend/app/api/v1/datasource_config.py index e2723706..62e4da8a 100644 --- a/backend/app/api/v1/datasource_config.py +++ b/backend/app/api/v1/datasource_config.py @@ -44,8 +44,9 @@ from app.services.custom_datasource_runtime import ( ) from app.services.datasource_connectivity import ( _resolve_aisstream_api_key, - resolve_spacetrack_credentials, get_builtin_connection_status, + get_connectivity_store, + resolve_spacetrack_credentials, save_connectivity_success, strip_connectivity_validation, test_builtin_connectivity, @@ -64,6 +65,70 @@ def _user_role_value(user: User) -> str: return str(getattr(role, "value", role) or "").lower() +def mask_credential_value(value: Any, *, secret: bool = False, reveal_edges: bool = False) -> str: + """Return a strictly non-plaintext masked representation of a credential or identifier.""" + raw = str(value or "").strip() + if not raw: + return "" + if secret: + if reveal_edges and len(raw) >= 8: + return f"{raw[:3]}••••{raw[-4:]}" + return "••••••" + if len(raw) >= 6: + return f"{raw[:2]}•••{raw[-2:]}" + return "•••" + + +def build_masked_credential_preview( + *, + requires_credentials: bool, + auth_type: str | None, + auth_config: dict[str, Any] | None, + resolved_provider: str | None = None, + resolved_values: dict[str, str] | None = None, +) -> tuple[bool, str]: + """Compute `(has_credentials, masked_preview)` without exposing plaintext secrets.""" + cfg = auth_config if isinstance(auth_config, dict) else {} + resolved = resolved_values if isinstance(resolved_values, dict) else {} + norm_auth = str(auth_type or "none").strip().lower() + provider = str(resolved_provider or "").strip().lower() + + if not requires_credentials and norm_auth in {"", "none"}: + return True, "" + + if provider == "barentswatch" or "oauth" in norm_auth or cfg.get("client_id") or cfg.get("client_secret"): + client_id = str(resolved.get("client_id") or cfg.get("client_id") or "").strip() + client_secret = str(resolved.get("client_secret") or cfg.get("client_secret") or "").strip() + has_creds = bool(client_id and client_secret) + parts = [ + mask_credential_value(client_id, secret=False), + mask_credential_value(client_secret, secret=True), + ] + return has_creds, " · ".join(part for part in parts if part) + + if provider == "spacetrack" or "basic" in norm_auth or cfg.get("username") or cfg.get("password"): + username = str(resolved.get("username") or cfg.get("username") or "").strip() + password = str(resolved.get("password") or cfg.get("password") or "").strip() + has_creds = bool(username and password) + parts = [ + mask_credential_value(username, secret=False), + mask_credential_value(password, secret=True), + ] + return has_creds, " · ".join(part for part in parts if part) + + api_key = str( + resolved.get("api_key") + or cfg.get("api_key") + or cfg.get("token") + or cfg.get("bearer_token") + or "" + ).strip() + if provider == "aisstream" or norm_auth in {"api_key", "bearer"} or api_key: + return bool(api_key), mask_credential_value(api_key, secret=True, reveal_edges=True) + + return False, "" + + def _user_display_name(user: User) -> str: return str(getattr(user, "username", None) or getattr(user, "email", None) or getattr(user, "id", "")) @@ -109,6 +174,45 @@ async def _ensure_datasource_secret_reveal_allowed( ) def _default_builtin_config(name: str) -> dict[str, Any]: + if name == "global_cloud_map": + from app.services.earth_clouds import DEFAULT_CLOUD_CONFIG + + return { + "primary_source": DEFAULT_CLOUD_CONFIG.primary_source, + "fallback_source": DEFAULT_CLOUD_CONFIG.fallback_source, + "resolution": DEFAULT_CLOUD_CONFIG.resolution, + "ir_threshold": DEFAULT_CLOUD_CONFIG.ir_threshold, + "contrast_gamma": DEFAULT_CLOUD_CONFIG.contrast_gamma, + "convective_threshold": DEFAULT_CLOUD_CONFIG.convective_threshold, + "min_cluster_area_km2": DEFAULT_CLOUD_CONFIG.min_cluster_area_km2, + "polar_feather_enabled": DEFAULT_CLOUD_CONFIG.polar_feather_enabled, + "max_history_frames": DEFAULT_CLOUD_CONFIG.max_history_frames, + "request_timeout_seconds": DEFAULT_CLOUD_CONFIG.request_timeout_seconds, + "geocolor_enabled": DEFAULT_CLOUD_CONFIG.geocolor_enabled, + "relief_shading_strength": DEFAULT_CLOUD_CONFIG.relief_shading_strength, + "optical_flow_enabled": DEFAULT_CLOUD_CONFIG.optical_flow_enabled, + } + if name == "cloud_hd_tiles": + return { + "warmup_max_zoom": 2, + "max_zoom": 6, + "max_cache_mb": 512, + "request_timeout_seconds": 15, + } + if name in {"earth_imagery_sentinel2", "earth_imagery_viirs_daily"}: + return { + "warmup_max_zoom": 3, + "max_zoom": 10 if name == "earth_imagery_sentinel2" else 9, + "max_cache_mb": 1024 if name == "earth_imagery_sentinel2" else 768, + "request_timeout_seconds": 15, + } + if name == "global_wind_gfs": + return { + "grid_step_deg": 2.0, + "gale_threshold_ms": 17.2, + "request_timeout_seconds": 25, + "max_history_runs": 12, + } return {"timeout": 30, "retry": 3} @@ -377,6 +481,8 @@ async def list_configs( db: AsyncSession = Depends(get_db), ): """List all user-defined data source configurations""" + from app.api.v1.datasources import infer_datasource_product_key + query = select(DataSourceConfig) if active_only: query = query.where(DataSourceConfig.is_active) @@ -391,10 +497,24 @@ async def list_configs( { "id": c.id, "name": c.name, + "product": infer_datasource_product_key(c.name, c.description or "", c.name), "description": c.description, "source_type": c.source_type, "endpoint": c.endpoint, "auth_type": c.auth_type, + "requires_credentials": (c.auth_type or "none") != "none", + **( + lambda cred_state: { + "has_credentials": cred_state[0], + "credential_preview": cred_state[1], + } + )( + build_masked_credential_preview( + requires_credentials=(c.auth_type or "none") != "none", + auth_type=c.auth_type, + auth_config=c.auth_config, + ) + ), "headers": c.headers, "config": c.config, "is_active": c.is_active, @@ -412,12 +532,30 @@ async def list_all_datasources( db: AsyncSession = Depends(get_db), ): """List all data sources: YAML defaults + DB overrides""" + from app.api.v1.datasources import infer_datasource_product_key from app.core.data_sources import get_data_sources_config config = get_data_sources_config() db_query = await db.execute(select(DataSourceConfig)) db_configs = {c.name: c for c in db_query.scalars().all()} + connectivity_store = await get_connectivity_store(db) + + resolved_provider_values: dict[str, dict[str, str]] = {} + bw_cfg = await resolve_barentswatch_config(db) + resolved_provider_values["barentswatch"] = { + "client_id": bw_cfg.client_id, + "client_secret": bw_cfg.client_secret, + } + st_user, st_pass, _ = await resolve_spacetrack_credentials(db) + resolved_provider_values["spacetrack"] = { + "username": st_user, + "password": st_pass, + } + ais_key, _ = await _resolve_aisstream_api_key(db) + resolved_provider_values["aisstream"] = { + "api_key": ais_key, + } result = [] for name, metadata in DEFAULT_DATASOURCES.items(): @@ -426,13 +564,47 @@ async def list_all_datasources( default_config = _default_builtin_config(name) default_url = yaml_url db_auth_config = db_config.auth_config or {} if db_config else {} + product = infer_datasource_product_key(name, str(metadata.get("name") or ""), name) + requires_credentials = bool(metadata.get("requires_credentials", False)) + credential_provider = metadata.get("credential_provider") + provider_key = str(credential_provider or "").strip().lower() + effective_auth_type = db_config.auth_type if db_config else ( + "oauth2" if provider_key == "barentswatch" else ( + "basic" if provider_key == "spacetrack" else ( + "api_key" if provider_key == "aisstream" else "none" + ) + ) + ) + has_credentials, credential_preview = build_masked_credential_preview( + requires_credentials=requires_credentials, + auth_type=effective_auth_type, + auth_config=db_auth_config, + resolved_provider=provider_key, + resolved_values=resolved_provider_values.get(provider_key), + ) + validation = connectivity_store.get(name) if isinstance(connectivity_store, dict) else None + connectivity_status = ( + "missing_credentials" + if requires_credentials and not has_credentials + else ( + "connected" + if isinstance(validation, dict) and validation.get("status") == "success" + else "unverified" + ) + ) result.append( { "name": name, - "requires_credentials": bool(metadata.get("requires_credentials", False)), - "credential_provider": metadata.get("credential_provider"), + "display_name": metadata.get("display_name") or metadata.get("name") or name, + "product": product, + "requires_credentials": requires_credentials, + "credential_provider": credential_provider, "credential_status": metadata.get("credential_status", "none"), + "has_credentials": has_credentials, + "credential_preview": credential_preview, + "connectivity_status": connectivity_status, + "connectivity_checked_at": validation.get("checked_at") if isinstance(validation, dict) else None, "default_url": default_url, "endpoint": db_config.endpoint if db_config else default_url, "is_overridden": db_config is not None and db_config.endpoint != yaml_url diff --git a/backend/app/api/v1/datasources.py b/backend/app/api/v1/datasources.py index f3b584e1..c7ebfa04 100644 --- a/backend/app/api/v1/datasources.py +++ b/backend/app/api/v1/datasources.py @@ -43,6 +43,8 @@ DATASOURCE_ADMIN_ROLES = {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value} PRODUCT_SOURCE_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = ( + ("geo", ("earth_imagery", "sentinel2", "viirs", "basemap", "imagery")), + ("weather", ("cloud", "weather", "meteorolog", "atmosphere", "ir108", "wind", "gfs")), ("vessels", ("vessel", "ais")), ("cables", ("cable", "landing", "telegeography", "arcgis", "fao")), ("satellites", ("tle", "satellite", "spacetrack", "celestrak")), @@ -99,12 +101,16 @@ def datasource_metadata(source: str) -> dict: } -def datasource_product_key(datasource: DataSource) -> str: +def infer_datasource_product_key( + source: str = "", + name: str = "", + collector_class: str = "", +) -> str: haystack = " ".join( [ - datasource.source or "", - datasource.name or "", - datasource.collector_class or "", + source or "", + name or "", + collector_class or "", ] ).lower() for product, keywords in PRODUCT_SOURCE_KEYWORDS: @@ -113,6 +119,14 @@ def datasource_product_key(datasource: DataSource) -> str: return "other" +def datasource_product_key(datasource: DataSource) -> str: + return infer_datasource_product_key( + datasource.source or "", + datasource.name or "", + datasource.collector_class or "", + ) + + def is_due_for_collection(datasource: DataSource, now: datetime) -> bool: if datasource.last_run_at is None: return True diff --git a/backend/app/api/v1/earth.py b/backend/app/api/v1/earth.py index f523f237..15801a8f 100644 --- a/backend/app/api/v1/earth.py +++ b/backend/app/api/v1/earth.py @@ -6,7 +6,8 @@ from pathlib import Path from typing import Any from uuid import uuid4 -from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile, status +from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, Response, UploadFile, status +from fastapi.responses import FileResponse from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from pydantic import BaseModel, Field from sqlalchemy import delete, func, select, text @@ -14,6 +15,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.core.access_gate import require_earth_or_api_access from app.core.config import settings as app_settings +from app.core.enums import UserRole from app.core.logging import get_logger from app.core.security import ( decode_token, @@ -53,6 +55,8 @@ from app.services.earth_boundaries import ( EarthBoundaryBuildError, get_boundary_build_status, get_boundary_status, + get_public_boundary_manifest, + resolve_boundary_artifact, save_boundary_config, start_boundary_build_job, ) @@ -676,6 +680,38 @@ async def get_earth_oobe_status( async def get_earth_boundary_status(): return get_boundary_status() + +@router.get("/boundaries/manifest", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) +async def get_earth_boundary_manifest(response: Response): + manifest = get_public_boundary_manifest() + if manifest is None: + raise HTTPException(status_code=404, detail="Verified Earth boundary artifact not built") + response.headers["Cache-Control"] = "no-cache" + return manifest + + +BOUNDARY_ARTIFACT_MEDIA_TYPES = {".pmtiles": "application/vnd.pmtiles", ".json": "application/json"} + + +_boundary_file_access = Depends( + require_earth_or_api_access("earth:read", rate_limit_tier="tile") +) + + +@router.get("/boundaries/files/{name}", dependencies=[_boundary_file_access]) +@router.head("/boundaries/files/{name}", include_in_schema=False, dependencies=[_boundary_file_access]) +async def get_earth_boundary_file(name: str): + path = resolve_boundary_artifact(name) + if path is None: + raise HTTPException(status_code=404, detail="Earth boundary artifact not found") + # Artifact names embed the build hash, so clients may cache them forever. + # FileResponse answers Range requests with 206 for PMTiles reads. + return FileResponse( + path, + media_type=BOUNDARY_ARTIFACT_MEDIA_TYPES.get(path.suffix, "application/octet-stream"), + headers={"Cache-Control": "public, max-age=31536000, immutable"}, + ) + def _is_loopback_request(request: Request) -> bool: host = request.client.host if request.client else "" return host in {"127.0.0.1", "::1", "localhost"} or host.startswith("127.") @@ -722,3 +758,370 @@ async def build_earth_boundary_assets( @router.get("/boundaries/build/status", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) async def get_earth_boundary_build_status(): return get_boundary_build_status() + + +def _require_cloud_admin(user: User) -> None: + role = getattr(user.role, "value", user.role) + if str(role).lower() not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Only administrators can modify cloud map configuration", + ) + + +def _require_cloud_operator(user: User) -> None: + role = getattr(user.role, "value", user.role) + if str(role).lower() not in { + UserRole.ADMIN.value, + UserRole.SUPER_ADMIN.value, + }: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Administrator access required", + ) + + +class CloudMapConfigUpdatePayload(BaseModel): + revision: str = Field(..., min_length=4, max_length=128) + config: dict[str, Any] = Field(default_factory=dict) + + +class CloudMapSourceTestPayload(BaseModel): + source_id: str = Field(default="multi_sat_ir", max_length=64) + timeout_seconds: int = Field(default=15, ge=5, le=45) + + +@router.get("/clouds/meta", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) +async def get_earth_clouds_meta(db: AsyncSession = Depends(get_db)): + from app.services.earth_clouds import get_cloud_map_runtime_meta + + return await get_cloud_map_runtime_meta(db) + + +@router.get("/clouds/frames/{version}", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) +async def get_earth_cloud_frame(version: str): + from app.services.earth_clouds import read_cloud_frame_bytes + + content = read_cloud_frame_bytes(version) + if content is None: + raise HTTPException(status_code=404, detail="Cloud frame not found") + return Response( + content=content, + media_type="image/webp", + headers={"Cache-Control": "public, max-age=86400, immutable"}, + ) + + +@router.get("/clouds/configuration") +async def get_earth_cloud_configuration( + _current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), +): + from app.services.earth_clouds import ( + get_cloud_datasource_summary, + get_cloud_map_runtime_meta, + read_cloud_map_configuration, + ) + + envelope = await read_cloud_map_configuration(db) + meta = await get_cloud_map_runtime_meta(db) + datasource = await get_cloud_datasource_summary(db) + return { + **envelope, + "meta": meta, + "datasource": datasource, + } + + +@router.put("/clouds/configuration") +async def put_earth_cloud_configuration( + payload: CloudMapConfigUpdatePayload, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), +): + from pydantic import ValidationError + from app.services.earth_clouds import ( + CloudMapConfig, + CloudMapRevisionConflictError, + get_cloud_datasource_summary, + get_cloud_map_runtime_meta, + save_cloud_map_configuration, + ) + + _require_cloud_admin(current_user) + try: + validated = CloudMapConfig.model_validate(payload.config) + envelope = await save_cloud_map_configuration( + db, + revision=payload.revision, + config=validated, + actor=current_user, + reset=False, + ) + except ValidationError as exc: + raise HTTPException(status_code=422, detail=exc.errors()) from exc + except CloudMapRevisionConflictError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc + + await _broadcast_earth_config_update("clouds") + return { + **envelope, + "meta": await get_cloud_map_runtime_meta(db), + "datasource": await get_cloud_datasource_summary(db), + } + + +@router.post("/clouds/configuration/reset") +async def reset_earth_cloud_configuration( + payload: CloudMapConfigUpdatePayload, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), +): + from app.services.earth_clouds import ( + CloudMapRevisionConflictError, + DEFAULT_CLOUD_CONFIG, + get_cloud_datasource_summary, + get_cloud_map_runtime_meta, + save_cloud_map_configuration, + ) + + _require_cloud_admin(current_user) + try: + envelope = await save_cloud_map_configuration( + db, + revision=payload.revision, + config=DEFAULT_CLOUD_CONFIG, + actor=current_user, + reset=True, + ) + except CloudMapRevisionConflictError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc + + await _broadcast_earth_config_update("clouds") + return { + **envelope, + "meta": await get_cloud_map_runtime_meta(db), + "datasource": await get_cloud_datasource_summary(db), + } + + +@router.post("/clouds/test") +async def test_earth_cloud_source( + payload: CloudMapSourceTestPayload, + current_user: User = Depends(get_current_user), +): + from app.services.earth_clouds import test_cloud_map_source + + _require_cloud_operator(current_user) + try: + return await test_cloud_map_source(payload.source_id, timeout_seconds=payload.timeout_seconds) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + +@router.delete("/clouds/cache") +async def clear_earth_cloud_cache( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), +): + from app.services.earth_clouds import clear_all_cloud_map_artifacts, get_cloud_map_runtime_meta + + _require_cloud_admin(current_user) + removed = clear_all_cloud_map_artifacts() + await _broadcast_earth_config_update("clouds") + return { + "removed_files": removed, + "meta": await get_cloud_map_runtime_meta(db), + } + + +@router.get("/clouds/frames/{version}/visual", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) +async def get_earth_cloud_visual_frame(version: str): + from app.services.earth_clouds import read_cloud_visual_frame_bytes + + content = read_cloud_visual_frame_bytes(version) + if content is None: + raise HTTPException(status_code=404, detail="Cloud visual frame not found") + return Response( + content=content, + media_type="image/webp", + headers={"Cache-Control": "public, max-age=86400, immutable"}, + ) + + +@router.get("/clouds/flows/{version}", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) +async def get_earth_cloud_flow_map(version: str): + from app.services.earth_clouds import read_cloud_flow_bytes + + content = read_cloud_flow_bytes(version) + if content is None: + raise HTTPException(status_code=404, detail="Cloud optical flow map not found") + return Response( + content=content, + media_type="image/webp", + headers={"Cache-Control": "public, max-age=86400, immutable"}, + ) + + +class BasemapConfigUpdatePayload(BaseModel): + revision: str = Field(..., min_length=4, max_length=128) + config: dict[str, Any] = Field(default_factory=dict) + + +@router.get( + "/tiles/{source_key}/{z}/{x}/{y}.webp", + dependencies=[Depends(require_earth_or_api_access("earth:read", rate_limit_tier="tile"))], +) +async def get_earth_managed_tile( + source_key: str, + z: int, + x: int, + y: int, + db: AsyncSession = Depends(get_db), +): + from app.services.earth_tiles import get_or_fetch_tile + + try: + content, allowed = await get_or_fetch_tile(source_key, z, x, y, db=db) + except ValueError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + if not allowed: + raise HTTPException(status_code=403, detail=f"Tile source '{source_key}' is disabled") + if content is None: + raise HTTPException(status_code=404, detail="Tile not available") + cache_max_age = 300 if source_key == "cloud_hd_tiles" else 86400 + return Response( + content=content, + media_type="image/webp", + headers={"Cache-Control": f"public, max-age={cache_max_age}"}, + ) + + +@router.get("/basemap/meta", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) +async def get_earth_basemap_meta(db: AsyncSession = Depends(get_db)): + from app.services.earth_tiles import get_basemap_runtime_meta + + return await get_basemap_runtime_meta(db) + + +@router.get("/basemap/configuration") +async def get_earth_basemap_configuration( + _current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), +): + from app.services.earth_tiles import get_basemap_runtime_meta, read_basemap_configuration + + envelope = await read_basemap_configuration(db) + return { + **envelope, + "meta": await get_basemap_runtime_meta(db), + } + + +@router.put("/basemap/configuration") +async def put_earth_basemap_configuration( + payload: BasemapConfigUpdatePayload, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), +): + from pydantic import ValidationError + from app.services.earth_tiles import ( + BasemapConfig, + BasemapRevisionConflictError, + get_basemap_runtime_meta, + save_basemap_configuration, + ) + + _require_cloud_admin(current_user) + try: + validated = BasemapConfig.model_validate(payload.config) + envelope = await save_basemap_configuration( + db, + revision=payload.revision, + config=validated, + actor=current_user, + reset=False, + ) + except ValidationError as exc: + raise HTTPException(status_code=422, detail=exc.errors()) from exc + except BasemapRevisionConflictError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc + + await _broadcast_earth_config_update("basemap") + return { + **envelope, + "meta": await get_basemap_runtime_meta(db), + } + + +@router.post("/basemap/configuration/reset") +async def reset_earth_basemap_configuration( + payload: BasemapConfigUpdatePayload, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), +): + from app.services.earth_tiles import ( + BasemapRevisionConflictError, + DEFAULT_BASEMAP_CONFIG, + get_basemap_runtime_meta, + save_basemap_configuration, + ) + + _require_cloud_admin(current_user) + try: + envelope = await save_basemap_configuration( + db, + revision=payload.revision, + config=DEFAULT_BASEMAP_CONFIG, + actor=current_user, + reset=True, + ) + except BasemapRevisionConflictError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc + + await _broadcast_earth_config_update("basemap") + return { + **envelope, + "meta": await get_basemap_runtime_meta(db), + } + + +@router.delete("/tiles/{source_key}/cache") +async def clear_earth_tile_cache_route( + source_key: str, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), +): + from app.services.earth_tiles import ( + TILE_SOURCES, + clear_tile_source_cache, + get_basemap_runtime_meta, + ) + + _require_cloud_admin(current_user) + if source_key not in TILE_SOURCES: + raise HTTPException(status_code=404, detail="Unknown tile source") + removed = clear_tile_source_cache(source_key) + await _broadcast_earth_config_update("basemap") + return { + "source": source_key, + "removed_files": removed, + "meta": await get_basemap_runtime_meta(db), + } + + +@router.get("/wind/meta", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) +async def get_earth_wind_meta(db: AsyncSession = Depends(get_db)): + from app.services.earth_wind import get_wind_runtime_meta + + return await get_wind_runtime_meta(db) + + +@router.get("/wind/grid/{version}", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) +async def get_earth_wind_grid(version: str): + from app.services.earth_wind import read_wind_grid_payload + + payload = read_wind_grid_payload(version) + if payload is None: + raise HTTPException(status_code=404, detail="Wind grid snapshot not found") + return payload diff --git a/backend/app/api/v1/situational_awareness.py b/backend/app/api/v1/situational_awareness.py index 88f412be..e40c6523 100644 --- a/backend/app/api/v1/situational_awareness.py +++ b/backend/app/api/v1/situational_awareness.py @@ -4,12 +4,14 @@ from __future__ import annotations from dataclasses import replace from datetime import UTC, datetime +import hashlib +import json import uuid -from typing import Any, Literal +from typing import Any, Literal, Self from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response from fastapi.responses import StreamingResponse -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, model_validator from sqlalchemy import desc, select from sqlalchemy.ext.asyncio import AsyncSession @@ -18,12 +20,16 @@ from app.core.access_gate import require_earth_or_api_access from app.db.session import get_db from app.models.situational_assessment import ( ComputeEvidenceCandidate, + EvidenceRecord, InvestigationSession, TopicWatch, WorkflowRun, ) from app.models.system_log import AuditLog from app.models.user import User +from app.schemas.compute_configuration import ComputeConfiguration, source_for +from app.services.compute_configuration import read_configuration +from app.services.compute_history import MODE_DENOMINATOR, ComputeSeriesMode from app.services.ai.access_policy import ( AccessContext, enforce_paid_research_gate, @@ -44,7 +50,7 @@ from app.services.ai.presentation_compiler import ( from app.services.ai.proactive_pipeline import ( audit_situational_hygiene, process_bgp_snapshot_proactive_delta, - process_compute_config_proactive_delta, + retry_pending_compute_presentations, ) from app.services.ai.semantic_delta import extract_compute_candidates_deterministic from app.services.ai.tool_registry import TimeBasis, query_compute_posture_tool @@ -57,7 +63,6 @@ from app.services.ai.workflow_runtime import ( ) from app.services.ai.stream_turn import stream_session_turn from app.services.ai_client import AIProviderClient, get_ai_provider_client -from app.services.compute_history import ComputeSeriesMode router = APIRouter() @@ -73,6 +78,8 @@ class SessionCreateRequest(BaseModel): visible_layers: dict[str, bool] = Field(default_factory=dict) time_basis: TimeBasis = "retrospective" cutoff_at: str | None = Field(default=None, max_length=40) + publish_id: str | None = Field(default=None, max_length=64) + as_of: str | None = Field(default=None, max_length=64) include_drill: bool = False @@ -116,6 +123,8 @@ class SessionTurnRequest(BaseModel): visible_layers: dict[str, bool] | None = None time_basis: TimeBasis | None = None cutoff_at: str | None = Field(default=None, max_length=40) + publish_id: str | None = Field(default=None, max_length=64) + as_of: str | None = Field(default=None, max_length=64) include_drill: bool | None = None preset: ViewPreset | None = None prefer_llm: bool | Literal["auto"] = False @@ -160,6 +169,8 @@ class SpatialInvestigateRequest(BaseModel): question: str = Field(min_length=2, max_length=1000) time_basis: TimeBasis = "retrospective" cutoff_at: str | None = Field(default=None, max_length=40) + publish_id: str | None = Field(default=None, max_length=64) + as_of: str | None = Field(default=None, max_length=64) include_drill: bool = False external_urls: list[str] = Field(default_factory=list, max_length=3) @@ -177,6 +188,25 @@ class ReportExportRequest(BaseModel): cutoff_at: str | None = Field(default=None, max_length=40) +APPROVE_REASON_CODES = frozenset( + { + "newer_authoritative_report", + "corrects_prior_error", + "adds_missing_observation", + "methodology_update", + } +) +REJECT_REASON_CODES = frozenset( + { + "unverifiable_source", + "denominator_mismatch", + "extraction_error", + "superseded", + "duplicate", + } +) + + class CandidateExtractRequest(BaseModel): model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) @@ -187,12 +217,36 @@ class CandidateExtractRequest(BaseModel): source_url: str = Field(min_length=8, max_length=2000) publisher: str = Field(default="Research Institute", max_length=200) locator: str = Field(default="Extracted excerpt", max_length=300) + period_label: str | None = Field(default=None, max_length=40) + published_at: str | None = Field(default=None, max_length=40) + report_year: int | None = Field(default=None, ge=2000, le=2100) class CandidateReviewRequest(BaseModel): - model_config = ConfigDict(extra="forbid") + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) decision: Literal["approved", "rejected"] + reason_code: Literal[ + "newer_authoritative_report", + "corrects_prior_error", + "adds_missing_observation", + "methodology_update", + "unverifiable_source", + "denominator_mismatch", + "extraction_error", + "superseded", + "duplicate", + ] + reason: str = Field(min_length=2, max_length=1000) + + @model_validator(mode="after") + def matching_reason_code(self) -> Self: + allowed = APPROVE_REASON_CODES if self.decision == "approved" else REJECT_REASON_CODES + if self.reason_code not in allowed: + raise ValueError( + f"reason_code '{self.reason_code}' is not valid for decision '{self.decision}'" + ) + return self # ============================================================================ @@ -219,6 +273,8 @@ async def create_investigation_session( "visible_layers": dict(payload.visible_layers or {}), "time_basis": payload.time_basis, "cutoff_at": payload.cutoff_at, + "publish_id": payload.publish_id, + "as_of": payload.as_of, "include_drill": payload.include_drill, "active_result_id": None, "active_revision": None, @@ -349,6 +405,8 @@ async def create_session_turn( "visible_layers": payload.visible_layers, "time_basis": payload.time_basis, "cutoff_at": payload.cutoff_at, + "publish_id": payload.publish_id, + "as_of": payload.as_of, "include_drill": payload.include_drill, } turn_result = await execute_session_turn( @@ -404,6 +462,8 @@ async def stream_investigation_session_turn( "visible_layers": payload.visible_layers, "time_basis": payload.time_basis, "cutoff_at": payload.cutoff_at, + "publish_id": payload.publish_id, + "as_of": payload.as_of, "include_drill": payload.include_drill, } headers = { @@ -702,7 +762,7 @@ async def evaluate_proactive_snapshot( db: AsyncSession = Depends(get_db), ) -> dict[str, Any]: if payload.domain == "compute": - res = await process_compute_config_proactive_delta(db) + res = await retry_pending_compute_presentations(db) else: res = await process_bgp_snapshot_proactive_delta( db, @@ -723,6 +783,8 @@ async def get_compute_posture( mode: ComputeSeriesMode = "global_share", time_basis: TimeBasis = "retrospective", cutoff_at: str | None = None, + as_of: str | None = None, + publish_id: str | None = None, prefer_llm: bool = False, access: AccessContext = Depends(resolve_access_context), db: AsyncSession = Depends(get_db), @@ -733,7 +795,13 @@ async def get_compute_posture( codes = selected_countries(countries) response.headers["Cache-Control"] = "no-store" series = await query_compute_posture_tool( - db, codes, mode=mode, time_basis=time_basis, cutoff_at=cutoff_at + db, + codes, + mode=mode, + time_basis=time_basis, + cutoff_at=cutoff_at, + as_of=as_of, + publish_id=publish_id, ) # GET is strictly 100% read-only (`persist=False`) when `prefer_llm=False` return await generate_or_get_compute_posture( @@ -779,6 +847,8 @@ async def investigate_spatial_context( question=payload.question, time_basis=payload.time_basis, cutoff_at=payload.cutoff_at, + publish_id=payload.publish_id, + as_of=payload.as_of, allow_drill=payload.include_drill, ai_client=ai_client, ) @@ -819,48 +889,190 @@ async def list_compute_candidates( return {"items": [row.to_dict() for row in rows]} +def _candidate_dedupe_fingerprint( + *, + source_id: str, + metric: str, + year: int, + period_label: str | None, + values: dict[str, Any], +) -> str: + sorted_vals = { + str(k): round(float(v), 6) + for k, v in sorted((values or {}).items(), key=lambda kv: str(kv[0])) + } + raw = f"{source_id}|{metric}|{year}|{period_label or ''}|{json.dumps(sorted_vals, sort_keys=True, separators=(',', ':'))}" + return hashlib.sha256(raw.encode("utf-8")).hexdigest() + + +def _build_candidate_comparison( + *, + current_config: ComputeConfiguration, + current_publish_id: str, + proposed: dict[str, Any], +) -> dict[str, Any]: + metric = str(proposed.get("metric") or "global_share") + year = int(proposed.get("year") or 0) + proposed_period = (proposed.get("period_label") or None) + existing_row = next( + (obs for obs in current_config.observations if obs.metric == metric and obs.year == year), + None, + ) + existing_period = existing_row.period_label if existing_row is not None else None + period_conflict = bool( + existing_row is not None and (existing_period or None) != (proposed_period or None) + ) + codes_comparison: dict[str, dict[str, Any]] = {} + has_historical_revision = False + for code, raw_new in sorted((proposed.get("values") or {}).items()): + new_val = float(raw_new) + if existing_row is not None and code in existing_row.values: + old_val = float(existing_row.values[code]) + old_src = source_for(existing_row, code) + delta = round(new_val - old_val, 4) + change_kind = "historical_revision" if delta != 0 else "unchanged" + if change_kind == "historical_revision": + has_historical_revision = True + else: + old_val = None + old_src = None + delta = round(new_val, 4) + change_kind = "new_observation" + codes_comparison[code] = { + "old_value": old_val, + "new_value": new_val, + "delta": delta, + "change_kind": change_kind, + "old_source_id": old_src, + } + return { + "publish_id": current_publish_id, + "metric": metric, + "year": year, + "period_label": proposed_period, + "existing_period_label": existing_period, + "period_conflict": period_conflict, + "denominator": MODE_DENOMINATOR.get(metric), + "codes": codes_comparison, + "has_historical_revision": has_historical_revision, + } + + @router.post("/candidates/extract") async def extract_compute_candidates( payload: CandidateExtractRequest, actor: User = Depends(configuration_admin), db: AsyncSession = Depends(get_db), ) -> dict[str, Any]: - source_meta = { + effective_report_year = payload.report_year or payload.year + source_meta: dict[str, Any] = { "id": payload.source_id, "title": payload.source_title, "url": payload.source_url, "publisher": payload.publisher, - "report_year": payload.year, + "report_year": effective_report_year, + "published_at": payload.published_at, "locator": payload.locator, } extracted = extract_compute_candidates_deterministic( - payload.excerpt, year=payload.year, source_meta=source_meta + payload.excerpt, + year=payload.year, + source_meta=source_meta, + period_label=payload.period_label, ) + envelope = await read_configuration(db) + current_config = ComputeConfiguration.model_validate(envelope["config"]) + current_publish_id = str(envelope.get("publish_id") or envelope["revision"]) + + # Upsert immutable EvidenceRecord without overwriting existing record. + if extracted and hasattr(db, "execute") and hasattr(db, "add"): + existing_ev = ( + await db.execute(select(EvidenceRecord).where(EvidenceRecord.id == payload.source_id)) + ).scalar_one_or_none() + if existing_ev is None: + db.add( + EvidenceRecord( + id=payload.source_id, + source_type="curated_report", + title=payload.source_title, + publisher=payload.publisher, + url=payload.source_url, + locator=payload.locator, + excerpt=payload.excerpt, + content_sha256=hashlib.sha256(payload.excerpt.encode("utf-8")).hexdigest(), + published_at=payload.published_at or str(effective_report_year), + metadata_json={ + "report_year": effective_report_year, + "period_label": payload.period_label, + }, + ) + ) + created: list[ComputeEvidenceCandidate] = [] + ordered_entries: list[tuple[ComputeEvidenceCandidate, bool]] = [] for item in extracted: + proposed = item["proposed_payload"] + fp = _candidate_dedupe_fingerprint( + source_id=str(proposed.get("source_id") or payload.source_id), + metric=str(proposed.get("metric") or "global_share"), + year=int(proposed.get("year") or payload.year), + period_label=proposed.get("period_label"), + values=proposed.get("values") or {}, + ) + existing_cand = ( + await db.execute( + select(ComputeEvidenceCandidate) + .where(ComputeEvidenceCandidate.dedupe_fingerprint == fp) + .order_by(desc(ComputeEvidenceCandidate.id)) + .limit(1) + ) + ).scalar_one_or_none() + if existing_cand is not None: + ordered_entries.append((existing_cand, True)) + continue + + comparison = _build_candidate_comparison( + current_config=current_config, + current_publish_id=current_publish_id, + proposed=proposed, + ) record = ComputeEvidenceCandidate( status="pending", candidate_type=item["candidate_type"], - proposed_payload=item["proposed_payload"], + proposed_payload=proposed, source_payload=item["source_payload"], + comparison=comparison, + dedupe_fingerprint=fp, confidence=item["confidence"], extractor_note=item["extractor_note"], ) db.add(record) created.append(record) + ordered_entries.append((record, False)) + db.add( AuditLog( actor_id=actor.id, + actor_name=actor.username, action="compute_candidates.extract", target_type="compute_evidence_candidates", target_id=payload.source_id, - details={"count": len(created), "year": payload.year}, + details={ + "count": len(created), + "duplicates": sum(1 for _, is_dup in ordered_entries if is_dup), + "year": payload.year, + }, ) ) await db.commit() for rec in created: await db.refresh(rec) - return {"items": [rec.to_dict() for rec in created]} + return { + "items": [ + {**rec.to_dict(), "duplicate": is_dup} + for rec, is_dup in ordered_entries + ] + } @router.post("/candidates/{candidate_id}/review") @@ -877,17 +1089,30 @@ async def review_compute_candidate( ).scalar_one_or_none() if record is None: raise HTTPException(status_code=404, detail="Candidate not found") + if record.published_publish_id: + raise HTTPException( + status_code=409, + detail="Candidate has already been published and cannot be modified.", + ) previous_status = record.status record.status = payload.decision + record.review_reason_code = payload.reason_code + record.review_reason = payload.reason record.reviewed_by = actor.username record.reviewed_at = datetime.now(UTC) db.add( AuditLog( actor_id=actor.id, + actor_name=actor.username, action=f"compute_candidates.{payload.decision}", target_type="compute_evidence_candidates", target_id=str(candidate_id), - details={"before_status": previous_status, "after_status": payload.decision}, + details={ + "before_status": previous_status, + "after_status": payload.decision, + "reason_code": payload.reason_code, + "reason": payload.reason, + }, ) ) await db.commit() diff --git a/backend/app/api/v1/visualization.py b/backend/app/api/v1/visualization.py index c5ac959e..51e22b37 100644 --- a/backend/app/api/v1/visualization.py +++ b/backend/app/api/v1/visualization.py @@ -37,23 +37,17 @@ from app.services.cable_graph import build_graph_from_data, CableGraph, haversin from app.services.compute_center_locations import ( RENDERABLE_PRECISIONS, ResolutionDiagnostic, - build_compute_center_location_query, - collect_location_candidates, get_compute_center_location_dict, refresh_compute_center_location_cache, resolve_compute_center_location_full, upsert_compute_center_location, ) -from app.services.ai_client import get_ai_provider_client -from app.api.v1.settings import get_runtime_web_search_config, get_web_search_client +from app.api.v1.settings import get_runtime_web_search_config +from app.services.ai_tools.web_search import normalize_web_search_provider from app.services.collectors.bgp_common import RIPE_RIS_COLLECTOR_COORDS -from app.services.location.llm_fallback import ( - collect_llm_location_fallback_candidate, - collect_location_search_evidence, -) -from app.services.location.agent_resolver import ( - run_controlled_location_agent, - run_l1_structured_facility_resolvers, +from app.services.location.workflow_tools import ( + TERMINAL_UNLOCATABLE_STATUSES, + run_location_workflow, ) from app.services.persistent_logs import record_system_log from app.services.vessel_ais_aggregation import ( @@ -79,6 +73,9 @@ from app.core.logging import get_logger router = APIRouter() logger = get_logger(__name__, service="api") _vis_read_dep = Depends(require_earth_or_api_access("visualization:read")) +_vis_tile_read_dep = Depends( + require_earth_or_api_access("visualization:read", rate_limit_tier="tile") +) TERRAIN_TILE_URL_TEMPLATE = ( "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png" ) @@ -296,7 +293,14 @@ def _extract_satellite_record(record: CollectedData) -> tuple[dict[str, Any], An tle_line1 = metadata.get("tle_line1") tle_line2 = metadata.get("tle_line2") - if not tle_line1 or not tle_line2: + # Stored 6-digit NORAD TLE lines (70+ chars) shift orbital element columns; regenerate using Alpha-5. + valid_tle = ( + isinstance(tle_line1, str) + and isinstance(tle_line2, str) + and len(tle_line1.rstrip()) == 69 + and len(tle_line2.rstrip()) == 69 + ) + if not valid_tle: tle_line1, tle_line2 = build_tle_lines_from_elements( norad_cat_id=norad_id, epoch=metadata.get("epoch"), @@ -719,16 +723,27 @@ def convert_compute_centers_to_geojson(records: List[CollectedData]) -> Dict[str features: List[Dict[str, Any]] = [] unresolved: List[Dict[str, Any]] = [] withheld_count = 0 + withheld_by_status: Dict[str, int] = {} for record in records: metadata = record.extra_data or {} if metadata.get("compute_contract") == "v1" and metadata.get("anonymous"): withheld_count += 1 + withheld_by_status["anonymous"] = withheld_by_status.get("anonymous", 0) + 1 continue result = resolve_compute_center_location_full(record, metadata) site_type = compute_site_type(record) if not result.is_resolved: + stored_loc = get_compute_center_location_dict( + getattr(record, "source", None), + getattr(record, "source_id", None), + ) + stored_status = str(stored_loc.get("verification_status") or "").strip().lower() + if stored_status in TERMINAL_UNLOCATABLE_STATUSES: + withheld_count += 1 + withheld_by_status[stored_status] = withheld_by_status.get(stored_status, 0) + 1 + continue diagnostic = result.diagnostic or ResolutionDiagnostic( failure_reason="Unknown resolver failure", attempted_queries=(), @@ -816,7 +831,13 @@ def convert_compute_centers_to_geojson(records: List[CollectedData]) -> Dict[str } ) - return {"type": "FeatureCollection", "features": features, "unresolved": unresolved, "withheld_count": withheld_count} + return { + "type": "FeatureCollection", + "features": features, + "unresolved": unresolved, + "withheld_count": withheld_count, + "withheld_by_status": withheld_by_status, + } VESSEL_TYPE_FILTERS = { @@ -1693,7 +1714,7 @@ async def _build_landing_points_geojson(db: AsyncSession) -> dict[str, Any]: raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}") -@router.get("/terrain/terrarium/{z}/{x}/{y}.png", dependencies=[_vis_read_dep]) +@router.get("/terrain/terrarium/{z}/{x}/{y}.png", dependencies=[_vis_tile_read_dep]) async def get_terrarium_tile(z: int, x: int, y: int): """Proxy Terrarium elevation tiles through the backend to avoid browser CORS issues.""" if not _is_valid_terrain_tile(z, x, y): @@ -1783,7 +1804,7 @@ async def _fetch_terrain_tile( return content, content_type, dict(headers) -@router.post("/terrain/terrarium/batch", dependencies=[_vis_read_dep]) +@router.post("/terrain/terrarium/batch", dependencies=[_vis_tile_read_dep]) async def get_terrarium_tile_batch(payload: TerrariumTileBatchRequest): """Fetch Terrarium elevation tiles in batches so the browser avoids many tiny requests.""" unique_tiles: list[TerrariumTileRequest] = [] @@ -2095,6 +2116,8 @@ async def _build_compute_centers_geojson( "type": "FeatureCollection", "features": [], "unresolved": [], + "withheld_count": 0, + "withheld_by_status": {}, "count": 0, "stats": { "total": 0, @@ -2140,6 +2163,8 @@ async def _build_compute_centers_geojson( "type": "FeatureCollection", "features": sanitized_features, "unresolved": unresolved, + "withheld_count": int(geojson.get("withheld_count") or 0), + "withheld_by_status": geojson.get("withheld_by_status") or {}, "count": len(sanitized_features), "stats": { "total": len(sanitized_features), @@ -2188,6 +2213,8 @@ class SaveComputeCenterLocationRequest(BaseModel): raw_payload: Dict[str, Any] = Field(default_factory=dict) needs_confirmation: bool = False verification_status: Optional[str] = None + workflow_run_id: Optional[str] = None + feedback_rating: Optional[int] = None model_config = {"populate_by_name": True} @@ -2202,7 +2229,11 @@ async def _compute_center_location_web_search_capability(db: AsyncSession) -> Di "reason": f"WebSearch 配置读取失败:{exc}", } provider_config = config.active_provider_config - has_api_key = bool((provider_config.api_key or "").strip()) or not provider_config.api_key_env + provider_name = normalize_web_search_provider(provider_config.provider) + has_api_key = ( + provider_name == "searxng" + or bool((provider_config.api_key or "").strip()) + ) if not config.enabled: return { "enabled": False, @@ -2230,9 +2261,6 @@ async def get_compute_center_location_capability( return await _compute_center_location_web_search_capability(db) -_TERMINAL_UNLOCATABLE_STATUSES = frozenset({"undisclosed", "multi_site", "anonymous"}) - - @router.post("/compute-centers/{source_id}/collect-location") async def collect_compute_center_location( source_id: str, @@ -2240,155 +2268,78 @@ async def collect_compute_center_location( _admin: User = Depends(require_admin_user), db: AsyncSession = Depends(get_db), ): - """Run deterministic facility lookups, Wikidata/PeeringDB, and controlled Tool-Calling location resolution.""" + """Run the unified `location.resolve_unknown` DAG workflow to locate a compute facility.""" if not source_id or not source_id.strip(): raise HTTPException(status_code=400, detail="source_id is required") record = await _load_compute_center_record(db, source_id) name = payload.name or (record.name if record else None) metadata = (record.extra_data or {}) if record else {} - operator = payload.operator or metadata.get("operator") or metadata.get("organization") or metadata.get("owner") site = payload.site or metadata.get("site") organization = payload.organization or metadata.get("organization") - city = payload.city or get_record_field(record, "city") if record else payload.city + city = payload.city or (get_record_field(record, "city") if record else None) country = payload.country or (get_record_field(record, "country") if record else None) source = payload.source or (record.source if record else None) record_id = payload.record_id or (record.id if record else None) - raw_sources = metadata.get("sources") if isinstance(metadata.get("sources"), list) else [] + raw_sources = list(metadata.get("sources") if isinstance(metadata.get("sources"), list) else []) source_url = metadata.get("source_url") or metadata.get("detail_url") builds_upon = metadata.get("builds_upon") source_raw_country = metadata.get("raw_country") - if not payload.force and source and source_id: - cached = get_compute_center_location_dict(source, source_id) - cached_status = str(cached.get("verification_status") or "").strip().lower() - if cached_status in _TERMINAL_UNLOCATABLE_STATUSES: - return { - "source_id": source_id, - "record_id": record_id, - "name": name, - "success": False, - "terminal_status": cached_status, - "failure_reason": cached.get("source_note") or f"Marked as {cached_status}", - "candidates": [], - "attempted_queries": [], - "llm_failure_reason": None, - "context": { - "name": name, - "operator": operator, - "site": site, - "city": city, - "country": country, - }, - } + earth_ctx = { + "entity_type": "compute_center", + "source_id": source_id, + "record_id": record_id, + "source": source, + "name": name, + "operator": operator, + "site": site, + "organization": organization, + "city": city, + "country": country, + "sources": raw_sources, + "source_url": source_url, + "builds_upon": builds_upon, + "source_raw_country": source_raw_country, + "force": bool(payload.force), + } - candidates, attempted_queries = await asyncio.to_thread( - collect_location_candidates, - name=name, - source=source, - source_id=source_id, - operator=operator, - site=site, - organization=organization, - city=city, - country=country, - record_id=record_id, - sources=raw_sources, - source_url=source_url, - builds_upon=builds_upon, - source_raw_country=source_raw_country, + res = await run_location_workflow( + db=db, + entity_type="compute_center", + earth_context=earth_ctx, + targets=[{"entity_type": "compute_center", "entity_id": source_id, "label": name or source_id}], + record_run=True, + trigger_evolution=True, ) - llm_failure_reason = None - terminal_status: str | None = None - query = build_compute_center_location_query( - name=name, - source=source, - source_id=source_id, - operator=operator, - site=site, - organization=organization, - city=city, - country=country, - sources=raw_sources, - source_url=source_url, - builds_upon=builds_upon, - source_raw_country=source_raw_country, - ) - if not candidates: - l1_candidates, l1_queries, _allow_low_short_circuit = await run_l1_structured_facility_resolvers( - query, db=db - ) - if l1_candidates: - candidates = l1_candidates - attempted_queries = [*attempted_queries, *l1_queries] - if not candidates: - capability = await _compute_center_location_web_search_capability(db) - llm_result = None - if not capability.get("enabled") and not raw_sources and not source_url: - llm_failure_reason = str(capability.get("reason") or "WebSearch unavailable") - else: - try: - provider_client = await get_ai_provider_client(db) - web_search_client = await get_web_search_client(db) - if hasattr(provider_client, "analyze"): - llm_result, terminal_status = await run_controlled_location_agent( - provider_client=provider_client, - web_search_client=web_search_client, - query=query, - entity_type="compute_center", - db=db, - attempted_queries=[], - ) - else: - search_result = await collect_location_search_evidence( - web_search_client=web_search_client, - query=query, - entity_type="compute_center", - ) - attempted_queries = [*attempted_queries, *search_result.attempted_queries] - if not search_result.evidence: - llm_failure_reason = search_result.failure_reason - raise RuntimeError(search_result.failure_reason or "no WebSearch evidence") - llm_result = await collect_llm_location_fallback_candidate( - provider_client=provider_client, - query=query, - entity_type="compute_center", - db=db, - attempted_queries=attempted_queries, - search_evidence=search_result.evidence, - ) - except Exception as exc: - if llm_failure_reason is None: - llm_failure_reason = f"LLM location factcheck unavailable: {exc}" - attempted_queries = [ - *attempted_queries, - f"llm_factcheck:compute_center:{name or source_id or 'unknown'}", - ] - if llm_result is not None: - attempted_queries = [*attempted_queries, *llm_result.attempted_queries] - candidates = llm_result.candidates - llm_failure_reason = llm_result.failure_reason + candidates = res.get("candidates") or [] + terminal_status = res.get("terminal_status") + failure_reason = res.get("failure_reason") + attempted_queries = list(res.get("attempted_queries") or []) + workflow_run_id = res.get("workflow_run_id") + context = { + "name": name, + "operator": operator, + "site": site, + "city": city, + "country": country, + } - if terminal_status in _TERMINAL_UNLOCATABLE_STATUSES: + if terminal_status in TERMINAL_UNLOCATABLE_STATUSES: return { "source_id": source_id, "record_id": record_id, "name": name, "success": False, "terminal_status": terminal_status, - "failure_reason": llm_failure_reason or f"Marked as {terminal_status}", + "failure_reason": failure_reason or f"Marked as {terminal_status}", "candidates": [], - "attempted_queries": list(attempted_queries), - "llm_failure_reason": llm_failure_reason, - "context": { - "name": name, - "operator": operator, - "site": site, - "city": city, - "country": country, - }, + "attempted_queries": attempted_queries, + "llm_failure_reason": failure_reason, + "workflow_run_id": workflow_run_id, + "context": context, } if not candidates: @@ -2400,8 +2351,9 @@ async def collect_compute_center_location( "record_id": record_id, "name": name, "success": False, - "llm_failure_reason": llm_failure_reason, - "attempted_queries": list(attempted_queries), + "llm_failure_reason": failure_reason, + "attempted_queries": attempted_queries, + "workflow_run_id": workflow_run_id, "context": { "operator": operator, "site": site, @@ -2420,15 +2372,10 @@ async def collect_compute_center_location( " result reached city-level precision." ), "candidates": [], - "attempted_queries": list(attempted_queries), - "llm_failure_reason": llm_failure_reason, - "context": { - "name": name, - "operator": operator, - "site": site, - "city": city, - "country": country, - }, + "attempted_queries": attempted_queries, + "llm_failure_reason": failure_reason, + "workflow_run_id": workflow_run_id, + "context": context, } best_candidate = candidates[0].to_dict() @@ -2442,8 +2389,9 @@ async def collect_compute_center_location( "success": True, "candidate_count": len(candidates), "best_candidate": best_candidate, - "llm_failure_reason": llm_failure_reason, - "attempted_queries": list(attempted_queries), + "llm_failure_reason": failure_reason, + "attempted_queries": attempted_queries, + "workflow_run_id": workflow_run_id, "context": { "operator": operator, "site": site, @@ -2459,14 +2407,9 @@ async def collect_compute_center_location( "success": True, "candidates": [candidate.to_dict() for candidate in candidates], "best_candidate": best_candidate, - "attempted_queries": list(attempted_queries), - "context": { - "name": name, - "operator": operator, - "site": site, - "city": city, - "country": country, - }, + "attempted_queries": attempted_queries, + "workflow_run_id": workflow_run_id, + "context": context, } @@ -2521,6 +2464,21 @@ async def save_compute_center_location( or ("unverified" if payload.needs_confirmation else "verified"), ) + if payload.workflow_run_id: + try: + from app.services.ai.workflow_evolver import record_run_feedback + + rating = payload.feedback_rating if payload.feedback_rating in (-1, 0, 1) else 1 + await record_run_feedback( + db, + payload.workflow_run_id, + rating=rating, + note=f"Adopted compute-center location for {source_id}", + actor=f"admin:{getattr(_admin, 'username', 'admin')}", + ) + except Exception: + pass + return { "success": True, "source": saved.source, diff --git a/backend/app/api/v1/wind_analysis.py b/backend/app/api/v1/wind_analysis.py new file mode 100644 index 00000000..93095396 --- /dev/null +++ b/backend/app/api/v1/wind_analysis.py @@ -0,0 +1,26 @@ +"""Real-time global 10m wind field analytics & spatial point query APIs.""" + +from __future__ import annotations + +from fastapi import APIRouter, Depends, Query +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.access_gate import require_earth_or_api_access +from app.db.session import get_db +from app.services.earth_wind import get_wind_analysis_summary, query_wind_point + +router = APIRouter() + + +@router.get("/summary", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) +async def get_wind_summary(db: AsyncSession = Depends(get_db)): + return await get_wind_analysis_summary(db) + + +@router.get("/point", dependencies=[Depends(require_earth_or_api_access("earth:read"))]) +async def get_wind_point( + lat: float = Query(..., ge=-90.0, le=90.0), + lon: float = Query(..., ge=-180.0, le=180.0), + db: AsyncSession = Depends(get_db), +): + return await query_wind_point(lat, lon, db=db) diff --git a/backend/app/core/access_gate.py b/backend/app/core/access_gate.py index 3a9db9e0..1624ff71 100644 --- a/backend/app/core/access_gate.py +++ b/backend/app/core/access_gate.py @@ -47,6 +47,14 @@ TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverif _EARTH_SESSION_TOKEN_TYPE = "earth_session" _MAX_DESKTOP_CLOCK_SKEW_SECONDS = 300 _EARTH_SESSION_RATE_LIMIT_PER_MIN = 600 +_EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN = 3000 +_RATE_LIMIT_LUA = """ +local count = redis.call('INCR', KEYS[1]) +if count == 1 or redis.call('TTL', KEYS[1]) < 0 then + redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1])) +end +return count +""" _LOCAL_SLIDING_WINDOWS: dict[str, deque[float]] = defaultdict(deque) _LOCAL_NONCES: dict[str, float] = {} _MAX_LOCAL_ENTRIES = 20_000 @@ -91,15 +99,31 @@ async def check_sliding_rate_limit( redis_key = f"access_gate:{bucket}" try: client = _AsyncRedisClient.get_client() - count = await asyncio.wait_for( - client.incr(redis_key), - timeout=REDIS_OP_TIMEOUT_SECONDS, - ) - if int(count) == 1: - await asyncio.wait_for( - client.expire(redis_key, window_seconds), + if callable(getattr(client, "eval", None)): + count = await asyncio.wait_for( + client.eval(_RATE_LIMIT_LUA, 1, redis_key, window_seconds), timeout=REDIS_OP_TIMEOUT_SECONDS, ) + else: + count = await asyncio.wait_for( + client.incr(redis_key), + timeout=REDIS_OP_TIMEOUT_SECONDS, + ) + if int(count) == 1: + await asyncio.wait_for( + client.expire(redis_key, window_seconds), + timeout=REDIS_OP_TIMEOUT_SECONDS, + ) + elif callable(getattr(client, "ttl", None)): + ttl = await asyncio.wait_for( + client.ttl(redis_key), + timeout=REDIS_OP_TIMEOUT_SECONDS, + ) + if int(ttl) < 0: + await asyncio.wait_for( + client.expire(redis_key, window_seconds), + timeout=REDIS_OP_TIMEOUT_SECONDS, + ) if int(count) > limit: raise HTTPException( status_code=status.HTTP_429_TOO_MANY_REQUESTS, @@ -386,13 +410,43 @@ async def _validate_bearer_api_user( return user +EarthRateLimitTier = Literal["default", "tile"] + + +def _resolve_earth_session_rate_limit(tier: EarthRateLimitTier) -> int: + if tier == "tile": + return max( + 1, + int( + getattr( + settings, + "EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN", + _EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN, + ) + ), + ) + return max( + 1, + int( + getattr( + settings, + "EARTH_SESSION_RATE_LIMIT_PER_MIN", + _EARTH_SESSION_RATE_LIMIT_PER_MIN, + ) + ), + ) + + def require_earth_or_api_access( scope: str, *, allow_query_api_key: bool = False, + rate_limit_tier: EarthRateLimitTier = "default", ): """Build a FastAPI dependency allowing API Keys, authorized JWT users, or Earth sessions.""" + bucket_suffix = ":tile" if rate_limit_tier == "tile" else "" + async def _dependency( request: Request, credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer), @@ -425,9 +479,10 @@ def require_earth_or_api_access( if claims is not None: channel = "earth_desktop" if claims.get("channel") == "desktop" else "earth_web" cid = str(claims.get("cid") or "anon") + effective_limit = _resolve_earth_session_rate_limit(rate_limit_tier) await check_sliding_rate_limit( - f"earth:{channel}:{cid}", - limit=_EARTH_SESSION_RATE_LIMIT_PER_MIN, + f"earth:{channel}:{cid}{bucket_suffix}", + limit=effective_limit, window_seconds=60, detail="Earth session rate limit exceeded", ) diff --git a/backend/app/core/config.py b/backend/app/core/config.py index ad694cb9..1d24246c 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -94,6 +94,8 @@ class Settings(BaseSettings): EARTH_API_AUTH_MODE: str = "" EARTH_SESSION_TTL_MINUTES: int = 30 + EARTH_SESSION_RATE_LIMIT_PER_MIN: int = 600 + EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN: int = 3000 EARTH_WEB_ALLOWED_ORIGINS: List[str] = [] EARTH_DESKTOP_HANDSHAKE_SECRET: str = "" TURNSTILE_SECRET_KEY: str = "" diff --git a/backend/app/core/countries.py b/backend/app/core/countries.py index 409717d7..e1c48537 100644 --- a/backend/app/core/countries.py +++ b/backend/app/core/countries.py @@ -12,14 +12,14 @@ COUNTRY_ENTRIES = [ ("阿根廷", ["Argentina", "AR", "ARG"]), ("亚美尼亚", ["Armenia", "AM", "ARM"]), ("澳大利亚", ["Australia", "AU", "AUS"]), - ("奥地利", ["Austria", "AT", "AUT"]), + ("奥地利", ["Austria", "AT", "AUT", "Österreich"]), ("阿塞拜疆", ["Azerbaijan", "AZ", "AZE"]), ("巴哈马", ["Bahamas", "BS", "BHS"]), ("巴林", ["Bahrain", "BH", "BHR"]), ("孟加拉国", ["Bangladesh", "BD", "BGD"]), ("巴巴多斯", ["Barbados", "BB", "BRB"]), ("白俄罗斯", ["Belarus", "BY", "BLR"]), - ("比利时", ["Belgium", "BE", "BEL"]), + ("比利时", ["Belgium", "BE", "BEL", "België", "Belgique"]), ("伯利兹", ["Belize", "BZ", "BLZ"]), ("贝宁", ["Benin", "BJ", "BEN"]), ("不丹", ["Bhutan", "BT", "BTN"]), @@ -51,8 +51,8 @@ COUNTRY_ENTRIES = [ ("克罗地亚", ["Croatia", "HR", "HRV"]), ("古巴", ["Cuba", "CU", "CUB"]), ("塞浦路斯", ["Cyprus", "CY", "CYP"]), - ("捷克", ["Czech Republic", "Czechia", "CZ", "CZE"]), - ("丹麦", ["Denmark", "DK", "DNK"]), + ("捷克", ["Czech Republic", "Czechia", "CZ", "CZE", "Česko"]), + ("丹麦", ["Denmark", "DK", "DNK", "Danmark"]), ("吉布提", ["Djibouti", "DJ", "DJI"]), ("多米尼克", ["Dominica", "DM", "DMA"]), ("多米尼加", ["Dominican Republic", "DO", "DOM"]), @@ -65,14 +65,14 @@ COUNTRY_ENTRIES = [ ("埃斯瓦蒂尼", ["Eswatini", "SZ", "SWZ", "Swaziland"]), ("埃塞俄比亚", ["Ethiopia", "ET", "ETH"]), ("斐济", ["Fiji", "FJ", "FJI"]), - ("芬兰", ["Finland", "FI", "FIN"]), + ("芬兰", ["Finland", "FI", "FIN", "Suomi"]), ("法国", ["France", "FR", "FRA"]), ("加蓬", ["Gabon", "GA", "GAB"]), ("冈比亚", ["Gambia", "GM", "GMB"]), ("格鲁吉亚", ["Georgia", "GE", "GEO"]), - ("德国", ["Germany", "DE", "DEU"]), + ("德国", ["Germany", "DE", "DEU", "Deutschland"]), ("加纳", ["Ghana", "GH", "GHA"]), - ("希腊", ["Greece", "GR", "GRC"]), + ("希腊", ["Greece", "GR", "GRC", "Ελλάς", "Ελλάδα"]), ("格林纳达", ["Grenada", "GD", "GRD"]), ("危地马拉", ["Guatemala", "GT", "GTM"]), ("几内亚", ["Guinea", "GN", "GIN"]), @@ -80,15 +80,15 @@ COUNTRY_ENTRIES = [ ("圭亚那", ["Guyana", "GY", "GUY"]), ("海地", ["Haiti", "HT", "HTI"]), ("洪都拉斯", ["Honduras", "HN", "HND"]), - ("匈牙利", ["Hungary", "HU", "HUN"]), - ("冰岛", ["Iceland", "IS", "ISL"]), + ("匈牙利", ["Hungary", "HU", "HUN", "Magyarország"]), + ("冰岛", ["Iceland", "IS", "ISL", "Ísland", "Island"]), ("印度", ["India", "IN", "IND"]), ("印度尼西亚", ["Indonesia", "ID", "IDN"]), ("伊朗", ["Iran", "IR", "IRN", "Iran (Islamic Republic of)"]), ("伊拉克", ["Iraq", "IQ", "IRQ"]), - ("爱尔兰", ["Ireland", "IE", "IRL"]), - ("以色列", ["Israel", "IL", "ISR"]), - ("意大利", ["Italy", "IT", "ITA"]), + ("爱尔兰", ["Ireland", "IE", "IRL", "Éire"]), + ("以色列", ["Israel", "IL", "ISR", "ישראל"]), + ("意大利", ["Italy", "IT", "ITA", "Italia"]), ("牙买加", ["Jamaica", "JM", "JAM"]), ("日本", ["Japan", "JP", "JPN"]), ("约旦", ["Jordan", "JO", "JOR"]), @@ -96,7 +96,7 @@ COUNTRY_ENTRIES = [ ("肯尼亚", ["Kenya", "KE", "KEN"]), ("基里巴斯", ["Kiribati", "KI", "KIR"]), ("朝鲜", ["North Korea", "Korea, DPRK", "Democratic People's Republic of Korea", "KP", "PRK"]), - ("韩国", ["South Korea", "Republic of Korea", "Korea", "KR", "KOR"]), + ("韩国", ["South Korea", "Republic of Korea", "Korea", "KR", "KOR", "대한민국"]), ("科威特", ["Kuwait", "KW", "KWT"]), ("吉尔吉斯斯坦", ["Kyrgyzstan", "KG", "KGZ"]), ("老挝", ["Laos", "Lao PDR", "Lao People's Democratic Republic", "LA", "LAO"]), @@ -129,13 +129,13 @@ COUNTRY_ENTRIES = [ ("纳米比亚", ["Namibia", "NA", "NAM"]), ("瑙鲁", ["Nauru", "NR", "NRU"]), ("尼泊尔", ["Nepal", "NP", "NPL"]), - ("荷兰", ["Netherlands", "NL", "NLD"]), + ("荷兰", ["Netherlands", "NL", "NLD", "Nederland"]), ("新西兰", ["New Zealand", "NZ", "NZL"]), ("尼加拉瓜", ["Nicaragua", "NI", "NIC"]), ("尼日尔", ["Niger", "NE", "NER"]), ("尼日利亚", ["Nigeria", "NG", "NGA"]), ("北马其顿", ["North Macedonia", "MK", "MKD", "Macedonia"]), - ("挪威", ["Norway", "NO", "NOR"]), + ("挪威", ["Norway", "NO", "NOR", "Norge"]), ("阿曼", ["Oman", "OM", "OMN"]), ("巴基斯坦", ["Pakistan", "PK", "PAK"]), ("帕劳", ["Palau", "PW", "PLW"]), @@ -145,11 +145,11 @@ COUNTRY_ENTRIES = [ ("巴拉圭", ["Paraguay", "PY", "PRY"]), ("秘鲁", ["Peru", "PE", "PER"]), ("菲律宾", ["Philippines", "PH", "PHL"]), - ("波兰", ["Poland", "PL", "POL"]), + ("波兰", ["Poland", "PL", "POL", "Polska"]), ("葡萄牙", ["Portugal", "PT", "PRT"]), ("卡塔尔", ["Qatar", "QA", "QAT"]), ("罗马尼亚", ["Romania", "RO", "ROU"]), - ("俄罗斯", ["Russia", "Russian Federation", "RU", "RUS"]), + ("俄罗斯", ["Russia", "Russian Federation", "RU", "RUS", "Россия"]), ("卢旺达", ["Rwanda", "RW", "RWA"]), ("圣基茨和尼维斯", ["Saint Kitts and Nevis", "KN", "KNA"]), ("圣卢西亚", ["Saint Lucia", "LC", "LCA"]), @@ -169,12 +169,12 @@ COUNTRY_ENTRIES = [ ("索马里", ["Somalia", "SO", "SOM"]), ("南非", ["South Africa", "ZA", "ZAF"]), ("南苏丹", ["South Sudan", "SS", "SSD"]), - ("西班牙", ["Spain", "ES", "ESP"]), + ("西班牙", ["Spain", "ES", "ESP", "España"]), ("斯里兰卡", ["Sri Lanka", "LK", "LKA"]), ("苏丹", ["Sudan", "SD", "SDN"]), ("苏里南", ["Suriname", "SR", "SUR"]), - ("瑞典", ["Sweden", "SE", "SWE"]), - ("瑞士", ["Switzerland", "CH", "CHE"]), + ("瑞典", ["Sweden", "SE", "SWE", "Sverige"]), + ("瑞士", ["Switzerland", "CH", "CHE", "Schweiz", "Suisse", "Svizzera"]), ("叙利亚", ["Syria", "SY", "SYR", "Syrian Arab Republic"]), ("塔吉克斯坦", ["Tajikistan", "TJ", "TJK"]), ("坦桑尼亚", ["Tanzania", "TZ", "TZA", "United Republic of Tanzania"]), @@ -188,7 +188,7 @@ COUNTRY_ENTRIES = [ ("土库曼斯坦", ["Turkmenistan", "TM", "TKM"]), ("图瓦卢", ["Tuvalu", "TV", "TUV"]), ("乌干达", ["Uganda", "UG", "UGA"]), - ("乌克兰", ["Ukraine", "UA", "UKR"]), + ("乌克兰", ["Ukraine", "UA", "UKR", "Україна"]), ("阿联酋", ["United Arab Emirates", "AE", "ARE", "UAE"]), ("英国", ["United Kingdom", "UK", "GB", "GBR", "Great Britain", "Britain", "England"]), ("美国", ["United States", "United States of America", "US", "USA", "U.S.", "U.S.A."]), @@ -292,6 +292,7 @@ def normalize_country(value: Any) -> Optional[str]: normalized = re.sub(r"\s+", " ", value.strip()) normalized = normalized.replace("(", "(").replace(")", ")") + normalized = re.sub(r"\s*(the)$", "", normalized, flags=re.IGNORECASE).strip() if not normalized: return None diff --git a/backend/app/core/data_sources.py b/backend/app/core/data_sources.py index c3b746bb..8c3da868 100644 --- a/backend/app/core/data_sources.py +++ b/backend/app/core/data_sources.py @@ -32,6 +32,11 @@ COLLECTOR_URL_KEYS = { "news_live_streams": "news_live_streams.channels_url", "barentswatch_vessels": "barentswatch_vessels.url", "aisstream_vessels": "aisstream_vessels.url", + "global_cloud_map": "global_cloud_map.wms_url", + "cloud_hd_tiles": "cloud_hd_tiles.wmts_url", + "earth_imagery_sentinel2": "earth_imagery_sentinel2.wmts_url", + "earth_imagery_viirs_daily": "earth_imagery_viirs_daily.wmts_url", + "global_wind_gfs": "global_wind_gfs.erddap_url", } diff --git a/backend/app/core/data_sources.yaml b/backend/app/core/data_sources.yaml index 03880cd3..0e968c52 100644 --- a/backend/app/core/data_sources.yaml +++ b/backend/app/core/data_sources.yaml @@ -102,3 +102,25 @@ barentswatch_vessels: aisstream_vessels: # AISStream realtime WebSocket endpoint. Requires an AISStream API key. url: "wss://stream.aisstream.io/v0/stream" + +global_cloud_map: + # NASA GIBS WMS EPSG:4326 endpoint (multi-satellite IR composite primary) + wms_url: "https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi" + # Matt Eason equirectangular cloud map fallback URL + fallback_url: "https://clouds.matteason.co.uk/images/2048x1024/clouds-alpha.png" + +cloud_hd_tiles: + # NASA GIBS WMTS EPSG:3857 GeoColor / Band13 tile template + wmts_url: "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/GOES-East_ABI_GeoColor/default/default/GoogleMapsCompatible_Level7/{z}/{y}/{x}.png" + +earth_imagery_sentinel2: + # EOX Sentinel-2 Cloudless 2024 global WMTS template + wmts_url: "https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2024_3857/default/GoogleMapsCompatible/{z}/{y}/{x}.jpg" + +earth_imagery_viirs_daily: + # NASA GIBS VIIRS SNPP Daily TrueColor WMTS template + wmts_url: "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_CorrectedReflectance_TrueColor/default/default/GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg" + +global_wind_gfs: + # PacIOOS ERDDAP NCEP GFS global 0.5-deg 10m wind CSV0 endpoint + erddap_url: "https://pae-paha.pacioos.hawaii.edu/erddap/griddap/ncep_global.csv0" diff --git a/backend/app/core/datasource_defaults.py b/backend/app/core/datasource_defaults.py index 54c4ff7d..460eeffb 100644 --- a/backend/app/core/datasource_defaults.py +++ b/backend/app/core/datasource_defaults.py @@ -267,6 +267,56 @@ DEFAULT_DATASOURCES = { "is_free": True, "requires_credentials": False, }, + "global_cloud_map": { + "id": 34, + "name": "Global Satellite Cloud Map", + "display_name": "全球卫星红外云图", + "module": "L2", + "priority": "P1", + "frequency_minutes": 30, + "is_free": True, + "requires_credentials": False, + }, + "cloud_hd_tiles": { + "id": 35, + "name": "HD Satellite Cloud Tiles", + "display_name": "高清云图瓦片金字塔", + "module": "L2", + "priority": "P1", + "frequency_minutes": 60, + "is_free": True, + "requires_credentials": False, + }, + "earth_imagery_sentinel2": { + "id": 36, + "name": "Sentinel-2 Cloudless 2024 Imagery", + "display_name": "Sentinel-2 无云高分底图", + "module": "L1", + "priority": "P2", + "frequency_minutes": 1440, + "is_free": True, + "requires_credentials": False, + }, + "earth_imagery_viirs_daily": { + "id": 37, + "name": "NASA GIBS Daily TrueColor Imagery", + "display_name": "NASA 每日真彩色卫星底图", + "module": "L1", + "priority": "P2", + "frequency_minutes": 720, + "is_free": True, + "requires_credentials": False, + }, + "global_wind_gfs": { + "id": 38, + "name": "NOAA GFS Global 10m Wind Field", + "display_name": "全球 10m 风场 (NOAA GFS)", + "module": "L2", + "priority": "P1", + "frequency_minutes": 180, + "is_free": True, + "requires_credentials": False, + }, } ID_TO_COLLECTOR = {info["id"]: name for name, info in DEFAULT_DATASOURCES.items()} diff --git a/backend/app/core/satellite_tle.py b/backend/app/core/satellite_tle.py index a4392aff..51105bcc 100644 --- a/backend/app/core/satellite_tle.py +++ b/backend/app/core/satellite_tle.py @@ -29,10 +29,30 @@ def _parse_epoch(value: Any) -> Optional[datetime]: return None +_ALPHA5_PREFIX = "ABCDEFGHJKLMNPQRSTUVWXYZ" + + +def format_tle_norad_id(norad_cat_id: Any) -> Optional[str]: + """Encode a NORAD catalog id into a 5-character TLE field (Alpha-5 for >= 100000).""" + try: + norad = int(norad_cat_id) + except (TypeError, ValueError): + return None + if norad <= 0: + return None + if norad < 100000: + return f"{norad:05d}" + lead = norad // 10000 + if 10 <= lead <= 33: + return f"{_ALPHA5_PREFIX[lead - 10]}{norad % 10000:04d}" + return f"{norad % 100000:05d}" + + def build_tle_line1(norad_cat_id: Any, epoch: Any) -> Optional[str]: """Build a valid TLE line 1 from the NORAD id and epoch.""" epoch_date = _parse_epoch(epoch) - if not norad_cat_id or epoch_date is None: + norad_field = format_tle_norad_id(norad_cat_id) + if not norad_field or epoch_date is None: return None epoch_year = epoch_date.year % 100 @@ -49,7 +69,7 @@ def build_tle_line1(norad_cat_id: Any, epoch: Any) -> Optional[str]: epoch_str = f"{epoch_year:02d}{day_of_year:03d}{decimal_fraction}" core = ( - f"1 {int(norad_cat_id):05d}U 00001A {epoch_str}" + f"1 {norad_field}U 00001A {epoch_str}" " .00000000 00000-0 00000-0 0 999" ) return core + compute_tle_checksum(core) @@ -65,8 +85,9 @@ def build_tle_line2( mean_motion: Any, ) -> Optional[str]: """Build a valid TLE line 2 from the standard orbital elements.""" + norad_field = format_tle_norad_id(norad_cat_id) required = [ - norad_cat_id, + norad_field, inclination, raan, eccentricity, @@ -79,7 +100,7 @@ def build_tle_line2( eccentricity_digits = str(round(float(eccentricity) * 10_000_000)).zfill(7) core = ( - f"2 {int(norad_cat_id):05d}" + f"2 {norad_field}" f" {float(inclination):8.4f}" f" {float(raan):8.4f}" f" {eccentricity_digits}" diff --git a/backend/app/core/security.py b/backend/app/core/security.py index 76d6da95..ceae41ac 100644 --- a/backend/app/core/security.py +++ b/backend/app/core/security.py @@ -21,6 +21,7 @@ from app.models.user import User logger = get_logger(__name__, service="security") oauth2_scheme = HTTPBearer() +optional_oauth2_scheme = HTTPBearer(auto_error=False) REVOKED_KEY_PREFIX = "revoked_jwt:" LOCAL_REVOKED_MAX_ENTRIES = 10_000 @@ -297,6 +298,28 @@ async def get_current_user( return await _load_active_user(user_id, db) +async def get_optional_current_user( + credentials: HTTPAuthorizationCredentials | None = Depends(optional_oauth2_scheme), + db: AsyncSession = Depends(get_db), +) -> User | None: + """Resolve the active authenticated user when a valid Bearer token is present; otherwise return None.""" + if credentials is None or not credentials.credentials: + return None + token = credentials.credentials + if await is_token_blacklisted(token): + return None + payload = decode_token(token) + if payload is None or payload.get("type") != "access": + return None + user_id = payload.get("sub") + if user_id is None: + return None + try: + return await _load_active_user(user_id, db) + except HTTPException: + return None + + async def get_current_user_refresh( credentials: HTTPAuthorizationCredentials = Depends(oauth2_scheme), db: AsyncSession = Depends(get_db), diff --git a/backend/app/core/time.py b/backend/app/core/time.py index 0e6a1303..463373af 100644 --- a/backend/app/core/time.py +++ b/backend/app/core/time.py @@ -5,15 +5,20 @@ from __future__ import annotations from datetime import UTC, datetime -def ensure_utc(value: datetime | None) -> datetime | None: +def ensure_utc(value: datetime | str | None) -> datetime | None: if value is None: return None + if isinstance(value, str): + stripped = value.strip() + if not stripped: + return None + value = datetime.fromisoformat(stripped.replace("Z", "+00:00")) if value.tzinfo is None: return value.replace(tzinfo=UTC) return value.astimezone(UTC) -def to_iso8601_utc(value: datetime | None) -> str | None: +def to_iso8601_utc(value: datetime | str | None) -> str | None: normalized = ensure_utc(value) if normalized is None: return None diff --git a/backend/app/db/migration_steps/0007_add_compute_configuration_revisions.py b/backend/app/db/migration_steps/0007_add_compute_configuration_revisions.py new file mode 100644 index 00000000..787474eb --- /dev/null +++ b/backend/app/db/migration_steps/0007_add_compute_configuration_revisions.py @@ -0,0 +1,177 @@ +"""Create compute_configuration_revisions table and extend compute_evidence_candidates columns.""" + +from __future__ import annotations + +from sqlalchemy import text + +VERSION = "0007" +NAME = "add_compute_configuration_revisions" + + +async def upgrade(conn) -> None: + """Apply compute revision ledger table and candidate review/comparison columns idempotently.""" + dialect = getattr(getattr(conn, "dialect", None), "name", "") + if dialect == "postgresql": + await conn.execute( + text( + """ + CREATE TABLE IF NOT EXISTS compute_configuration_revisions ( + id SERIAL PRIMARY KEY, + publish_id VARCHAR(64) NOT NULL UNIQUE, + parent_publish_id VARCHAR(64), + action VARCHAR(16) NOT NULL DEFAULT 'publish', + content_fingerprint VARCHAR(64) NOT NULL, + is_default_content BOOLEAN NOT NULL DEFAULT FALSE, + config_payload JSONB NOT NULL DEFAULT '{}'::jsonb, + diff_summary JSONB NOT NULL DEFAULT '[]'::jsonb, + source_candidate_ids JSONB NOT NULL DEFAULT '[]'::jsonb, + publish_note TEXT NOT NULL DEFAULT '', + published_by_id INTEGER, + published_by_name VARCHAR(120), + published_by_role VARCHAR(40), + published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + presentation_status VARCHAR(16) NOT NULL DEFAULT 'pending', + presentation_attempts INTEGER NOT NULL DEFAULT 0, + presentation_error TEXT NOT NULL DEFAULT '', + presentation_delivered_at TIMESTAMPTZ + ) + """ + ) + ) + await conn.execute( + text( + """ + CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_published_at + ON compute_configuration_revisions (published_at) + """ + ) + ) + await conn.execute( + text( + """ + CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_fingerprint + ON compute_configuration_revisions (content_fingerprint) + """ + ) + ) + await conn.execute( + text( + """ + CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_pres_status + ON compute_configuration_revisions (presentation_status, id) + """ + ) + ) + await conn.execute( + text( + """ + ALTER TABLE compute_evidence_candidates + ADD COLUMN IF NOT EXISTS comparison JSONB NOT NULL DEFAULT '{}'::jsonb, + ADD COLUMN IF NOT EXISTS dedupe_fingerprint VARCHAR(64), + ADD COLUMN IF NOT EXISTS review_reason_code VARCHAR(40), + ADD COLUMN IF NOT EXISTS review_reason TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS published_publish_id VARCHAR(64) + """ + ) + ) + await conn.execute( + text( + """ + CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_dedupe_fp + ON compute_evidence_candidates (dedupe_fingerprint) + """ + ) + ) + await conn.execute( + text( + """ + CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_published_pid + ON compute_evidence_candidates (published_publish_id) + """ + ) + ) + return + + # SQLite path + await conn.execute( + text( + """ + CREATE TABLE IF NOT EXISTS compute_configuration_revisions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + publish_id VARCHAR(64) NOT NULL UNIQUE, + parent_publish_id VARCHAR(64), + action VARCHAR(16) NOT NULL DEFAULT 'publish', + content_fingerprint VARCHAR(64) NOT NULL, + is_default_content BOOLEAN NOT NULL DEFAULT 0, + config_payload JSON NOT NULL DEFAULT '{}', + diff_summary JSON NOT NULL DEFAULT '[]', + source_candidate_ids JSON NOT NULL DEFAULT '[]', + publish_note TEXT NOT NULL DEFAULT '', + published_by_id INTEGER, + published_by_name VARCHAR(120), + published_by_role VARCHAR(40), + published_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + presentation_status VARCHAR(16) NOT NULL DEFAULT 'pending', + presentation_attempts INTEGER NOT NULL DEFAULT 0, + presentation_error TEXT NOT NULL DEFAULT '', + presentation_delivered_at TIMESTAMP + ) + """ + ) + ) + await conn.execute( + text( + """ + CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_published_at + ON compute_configuration_revisions (published_at) + """ + ) + ) + await conn.execute( + text( + """ + CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_fingerprint + ON compute_configuration_revisions (content_fingerprint) + """ + ) + ) + await conn.execute( + text( + """ + CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_pres_status + ON compute_configuration_revisions (presentation_status, id) + """ + ) + ) + + res = await conn.execute(text("PRAGMA table_info(compute_evidence_candidates)")) + columns = {str(row[1]) for row in res.fetchall()} + if columns: + alter_specs = [ + ("comparison", "JSON NOT NULL DEFAULT '{}'"), + ("dedupe_fingerprint", "VARCHAR(64)"), + ("review_reason_code", "VARCHAR(40)"), + ("review_reason", "TEXT NOT NULL DEFAULT ''"), + ("published_publish_id", "VARCHAR(64)"), + ] + for col_name, col_ddl in alter_specs: + if col_name not in columns: + await conn.execute( + text(f"ALTER TABLE compute_evidence_candidates ADD COLUMN {col_name} {col_ddl}") + ) + await conn.execute( + text( + """ + CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_dedupe_fp + ON compute_evidence_candidates (dedupe_fingerprint) + """ + ) + ) + await conn.execute( + text( + """ + CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_published_pid + ON compute_evidence_candidates (published_publish_id) + """ + ) + ) diff --git a/backend/app/db/session.py b/backend/app/db/session.py index 7c6d22b4..671d6e57 100644 --- a/backend/app/db/session.py +++ b/backend/app/db/session.py @@ -484,6 +484,7 @@ async def init_db(): import app.models.bgp_observation # noqa: F401 import app.models.collected_data # noqa: F401 import app.models.compute_center_location # noqa: F401 + import app.models.compute_configuration_revision # noqa: F401 import app.models.system_setting # noqa: F401 import app.models.playground_session # noqa: F401 import app.models.playground_message # noqa: F401 @@ -919,6 +920,34 @@ async def _init_db_ddl_and_seed(): """ ) ) + await conn.execute( + text( + """ + ALTER TABLE compute_evidence_candidates + ADD COLUMN IF NOT EXISTS comparison JSONB NOT NULL DEFAULT '{}'::jsonb, + ADD COLUMN IF NOT EXISTS dedupe_fingerprint VARCHAR(64), + ADD COLUMN IF NOT EXISTS review_reason_code VARCHAR(40), + ADD COLUMN IF NOT EXISTS review_reason TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS published_publish_id VARCHAR(64) + """ + ) + ) + await conn.execute( + text( + """ + CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_dedupe_fp + ON compute_evidence_candidates (dedupe_fingerprint) + """ + ) + ) + await conn.execute( + text( + """ + CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_published_pid + ON compute_evidence_candidates (published_publish_id) + """ + ) + ) await conn.execute( text( """ @@ -1116,6 +1145,28 @@ async def _init_db_ddl_and_seed(): await ensure_baseline_stamped(conn) + if engine.dialect.name == "postgresql": + async with engine.connect() as base_conn: + auto_conn = await base_conn.execution_options(isolation_level="AUTOCOMMIT") + await auto_conn.execute( + text( + """ + CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_collected_data_current_collected_at + ON collected_data (collected_at DESC) + WHERE is_current IS TRUE + """ + ) + ) + await auto_conn.execute( + text( + """ + CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_collected_data_current_source_type + ON collected_data (source, data_type) + WHERE is_current IS TRUE + """ + ) + ) + async with async_session_factory() as session: from app.services.bgp_collector_locations import ( seed_default_bgp_collector_locations, @@ -1131,6 +1182,19 @@ async def _init_db_ddl_and_seed(): await purge_legacy_earth_boundary_datasources(session) await ensure_default_admin_user(session) await ensure_default_storage_policy(session) + from app.services.ai.proactive_pipeline import retry_pending_compute_presentations from app.services.ai.workflow_registry import ensure_builtin_workflows + from app.services.compute_configuration import ensure_compute_revision_baseline await ensure_builtin_workflows(session) + await ensure_compute_revision_baseline(session) + try: + await retry_pending_compute_presentations(session) + await session.commit() + except Exception as exc: + await session.rollback() + logger.warning_event( + "Startup retry of pending compute presentations failed", + event="compute.revision.presentation_failed", + context={"phase": "startup", "error": str(exc)}, + ) diff --git a/backend/app/main.py b/backend/app/main.py index dbde743e..cc231c41 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -201,6 +201,10 @@ class NonStreamingGZipMiddleware: if path.endswith("/stream") or b"text/event-stream" in accept: await self.app(scope, receive, send) return + # PMTiles clients read byte ranges; re-encoding would break Content-Range. + if path.endswith(".pmtiles"): + await self.app(scope, receive, send) + return await self.gzip_app(scope, receive, send) diff --git a/backend/app/models/collected_data.py b/backend/app/models/collected_data.py index 507141f7..99df94ea 100644 --- a/backend/app/models/collected_data.py +++ b/backend/app/models/collected_data.py @@ -1,6 +1,6 @@ """Collected Data model for storing data from all collectors""" -from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text, JSON, Index +from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text, JSON, Index, text from sqlalchemy.sql import func from app.core.collected_data_fields import get_record_field @@ -39,7 +39,7 @@ class CollectedData(Base): # Status is_valid = Column(Integer, default=1) # 1=valid, 0=invalid - is_current = Column(Boolean, default=True, index=True) + is_current = Column(Boolean, default=True, nullable=False, server_default=text("true"), index=True) previous_record_id = Column(Integer, ForeignKey("collected_data.id"), nullable=True, index=True) change_type = Column(String(20), nullable=True) change_summary = Column(JSON, default={}) diff --git a/backend/app/models/compute_configuration_revision.py b/backend/app/models/compute_configuration_revision.py new file mode 100644 index 00000000..0c12f3c2 --- /dev/null +++ b/backend/app/models/compute_configuration_revision.py @@ -0,0 +1,62 @@ +"""Versioned history table for curated compute comparison configurations.""" + +from __future__ import annotations + +from sqlalchemy import Boolean, Column, DateTime, Index, Integer, JSON, String, Text +from sqlalchemy.sql import func + +from app.core.time import to_iso8601_utc +from app.db.session import Base + + +class ComputeConfigurationRevision(Base): + """Immutable snapshot ledger of published compute comparison configurations.""" + + __tablename__ = "compute_configuration_revisions" + + id = Column(Integer, primary_key=True, autoincrement=True, index=True) + publish_id = Column(String(64), unique=True, nullable=False, index=True) + parent_publish_id = Column(String(64), nullable=True, index=True) + action = Column(String(16), nullable=False, default="publish") + content_fingerprint = Column(String(64), nullable=False, index=True) + is_default_content = Column(Boolean, nullable=False, default=False) + config_payload = Column(JSON, nullable=False, default=dict) + diff_summary = Column(JSON, nullable=False, default=list) + source_candidate_ids = Column(JSON, nullable=False, default=list) + publish_note = Column(Text, nullable=False, default="") + published_by_id = Column(Integer, nullable=True) + published_by_name = Column(String(120), nullable=True) + published_by_role = Column(String(40), nullable=True) + published_at = Column( + DateTime(timezone=True), server_default=func.now(), nullable=False, index=True + ) + presentation_status = Column(String(16), nullable=False, default="pending", index=True) + presentation_attempts = Column(Integer, nullable=False, default=0) + presentation_error = Column(Text, nullable=False, default="") + presentation_delivered_at = Column(DateTime(timezone=True), nullable=True) + + __table_args__ = ( + Index("idx_compute_config_revisions_published_at", "published_at"), + Index("idx_compute_config_revisions_pres_status", "presentation_status", "id"), + ) + + def to_dict(self) -> dict: + return { + "id": self.id, + "publish_id": self.publish_id, + "parent_publish_id": self.parent_publish_id, + "action": self.action, + "content_fingerprint": self.content_fingerprint, + "is_default_content": bool(self.is_default_content), + "diff_summary": list(self.diff_summary or []), + "source_candidate_ids": list(self.source_candidate_ids or []), + "publish_note": self.publish_note or "", + "published_by_id": self.published_by_id, + "published_by_name": self.published_by_name, + "published_by_role": self.published_by_role, + "published_at": to_iso8601_utc(self.published_at), + "presentation_status": self.presentation_status, + "presentation_attempts": int(self.presentation_attempts or 0), + "presentation_error": self.presentation_error or "", + "presentation_delivered_at": to_iso8601_utc(self.presentation_delivered_at), + } diff --git a/backend/app/models/situational_assessment.py b/backend/app/models/situational_assessment.py index dfd2d924..6e8bedb4 100644 --- a/backend/app/models/situational_assessment.py +++ b/backend/app/models/situational_assessment.py @@ -235,8 +235,13 @@ class ComputeEvidenceCandidate(Base): candidate_type = Column(String(40), nullable=False, default="observation") proposed_payload = Column(JSON, nullable=False, default=dict) source_payload = Column(JSON, nullable=False, default=dict) + comparison = Column(JSON, nullable=False, default=dict) + dedupe_fingerprint = Column(String(64), nullable=True, index=True) confidence = Column(Float, nullable=False, default=0.8) extractor_note = Column(Text, nullable=False, default="") + review_reason_code = Column(String(40), nullable=True) + review_reason = Column(Text, nullable=False, default="") + published_publish_id = Column(String(64), nullable=True, index=True) reviewed_by = Column(String(120), nullable=True) reviewed_at = Column(DateTime(timezone=True), nullable=True) created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True) @@ -248,8 +253,13 @@ class ComputeEvidenceCandidate(Base): "candidate_type": self.candidate_type, "proposed_payload": self.proposed_payload or {}, "source_payload": self.source_payload or {}, + "comparison": self.comparison or {}, + "dedupe_fingerprint": self.dedupe_fingerprint, "confidence": self.confidence, "extractor_note": self.extractor_note, + "review_reason_code": self.review_reason_code, + "review_reason": self.review_reason or "", + "published_publish_id": self.published_publish_id, "reviewed_by": self.reviewed_by, "reviewed_at": to_iso8601_utc(self.reviewed_at), "created_at": to_iso8601_utc(self.created_at), diff --git a/backend/app/schemas/ai.py b/backend/app/schemas/ai.py index 6013480f..64998492 100644 --- a/backend/app/schemas/ai.py +++ b/backend/app/schemas/ai.py @@ -11,6 +11,7 @@ class ChatMessage(BaseModel): tool_call_id: str | None = Field(default=None, max_length=200) name: str | None = Field(default=None, max_length=200) tool_calls: list[dict[str, Any]] | None = None + thinking_blocks: list[dict[str, Any]] | None = None class ToolCallRecord(BaseModel): @@ -77,6 +78,7 @@ class SituationalAnalysisResponse(BaseModel): text_blocks: list[str] = Field(default_factory=list) thinking_blocks: list[str] = Field(default_factory=list) tool_calls: list[ToolCallRecord] = Field(default_factory=list) + citation_urls: list[str] = Field(default_factory=list) stop_reason: str | None = None raw_response: dict[str, Any] = Field(default_factory=dict) diff --git a/backend/app/schemas/compute_configuration.py b/backend/app/schemas/compute_configuration.py index f38f6b45..b04c8c07 100644 --- a/backend/app/schemas/compute_configuration.py +++ b/backend/app/schemas/compute_configuration.py @@ -56,6 +56,7 @@ class ComputeObservation(ConfigurationModel): metric: ComputeMetric source_id: Identifier values: dict[str, Value] = Field(min_length=1, max_length=250) + value_sources: dict[str, Identifier] | None = None period_label: PeriodLabel | None = None global_total: Value | None = None @@ -65,11 +66,36 @@ class ComputeObservation(ConfigurationModel): raise ValueError( "Use countries from the canonical compute catalog, not regional totals" ) + if self.value_sources is not None: + invalid_keys = [code for code in self.value_sources if code not in self.values] + if invalid_keys: + raise ValueError( + "Per-country value_sources keys must be a subset of observation values" + ) if self.metric in SHARE_METRICS and sum(self.values.values()) > 100.000001: raise ValueError("Global shares for one year must total at most 100 percent") return self +def source_for(row: ComputeObservation, code: str) -> str: + """Resolve the authoritative source_id for one country inside an observation row.""" + if row.value_sources and code in row.value_sources: + return row.value_sources[code] + return row.source_id + + +def row_source_ids(row: ComputeObservation) -> list[str]: + """Return deduplicated source IDs referenced across all countries in an observation row.""" + if not row.values: + return [row.source_id] + return list(dict.fromkeys(source_for(row, code) for code in row.values)) + + +def has_mixed_sources(row: ComputeObservation) -> bool: + """Return True when countries in one observation row cite more than one distinct source.""" + return len(row_source_ids(row)) > 1 + + class ComputeStructureObservation(ConfigurationModel): scope: str = Field(min_length=2, max_length=16) year: Year @@ -176,6 +202,14 @@ class ComputeConfiguration(ConfigurationModel): raise ValueError(f"Missing report source: {row.source_id}") if row.year > source.report_year: raise ValueError("Observation year must not be after its report year") + for obs in self.observations: + if obs.value_sources: + for code, src_id in obs.value_sources.items(): + source = sources.get(src_id) + if source is None: + raise ValueError(f"Missing report source: {src_id}") + if obs.year > source.report_year: + raise ValueError("Observation year must not be after its report year") hub_id_set = set(hub_ids) for hub in self.national_hubs: if hub.source_id not in sources: @@ -190,7 +224,10 @@ class ComputeConfiguration(ConfigurationModel): class ComputeConfigurationWrite(ConfigurationModel): revision: str = Field(min_length=1, max_length=80) config: ComputeConfiguration + publish_note: str = Field(default="", max_length=1000) + source_candidate_ids: list[int] = Field(default_factory=list, max_length=50) class ComputeConfigurationReset(ConfigurationModel): revision: str = Field(min_length=1, max_length=80) + publish_note: str = Field(default="", max_length=1000) diff --git a/backend/app/services/ai/copilot_agent.py b/backend/app/services/ai/copilot_agent.py index 32c29a9f..3535477c 100644 --- a/backend/app/services/ai/copilot_agent.py +++ b/backend/app/services/ai/copilot_agent.py @@ -7,7 +7,7 @@ from datetime import UTC, datetime import hashlib import json import re -from typing import Any, Literal +from typing import Any from fastapi import HTTPException from pydantic import BaseModel, ConfigDict, Field @@ -38,6 +38,10 @@ from app.services.ai.thinking_sanitizer import ( ) from app.services.ai.tool_registry import TimeBasis, query_compute_posture_tool from app.services.ai_client import AIProviderClient +from app.services.compute_lineage import ( + build_revision_change_context, + is_revision_question, +) logger = get_logger(__name__, service="ai_copilot") @@ -82,6 +86,7 @@ def _deterministic_compute_copilot_reply( *, codes: list[str] | None = None, mode: str = "global_share", + revision_context: dict[str, Any] | None = None, ) -> CopilotInvestigationReply: evidence = series.get("evidence") or {} rpi = series.get("bilateral_rpi") or {} @@ -95,6 +100,7 @@ def _deterministic_compute_copilot_reply( time_basis = series.get("time_basis") or "retrospective" cutoff_at = series.get("cutoff_at") withheld_sources = series.get("withheld_source_ids") or [] + publish_id = series.get("publish_id") or series.get("version") fallback_eid = next(iter(evidence.keys()), "unconfigured") q_lower = question.lower() @@ -102,6 +108,19 @@ def _deterministic_compute_copilot_reply( if entity_id: highlights.append(entity_id) + if series.get("snapshot_unavailable"): + notice = str( + series.get("notice") + or "当前所选历史发布时间早于版本库基线时间,历史快照不完整,无法恢复当时台账。" + ) + return CopilotInvestigationReply( + answer_markdown=f"### 历史快照不完整\n\n- {notice}", + key_points=[], + highlight_entities=list(dict.fromkeys([*(codes or []), *highlights]))[:8], + suggested_followups=["回到当前已发布的最新版本"], + evidence_ids=["unconfigured"], + ) + cutoff_note = ( f"\n\n> **历史回放截点**:当前按 `as_known_then`(截至 `{cutoff_at}`)过滤,已隔离 `{len(withheld_sources)}` 份截点后发布报告。" if time_basis == "as_known_then" and cutoff_at @@ -121,6 +140,83 @@ def _deterministic_compute_copilot_reply( evidence_ids=["unconfigured"], ) + if is_revision_question(question) and isinstance(revision_context, dict): + diff_entries = [ + entry + for entry in (revision_context.get("diff_summary") or []) + if isinstance(entry, dict) and entry.get("kind") == "observation_value" + ] + rev_pid = str(revision_context.get("publish_id") or publish_id or "") + rev_eids: list[str] = [] + for entry in diff_entries: + for k in ("new_source_id", "old_source_id"): + sid = entry.get(k) + if isinstance(sid, str) and sid in evidence and sid not in rev_eids: + rev_eids.append(sid) + for cr in revision_context.get("candidate_reasons") or []: + sid = cr.get("source_id") if isinstance(cr, dict) else None + if isinstance(sid, str) and sid in evidence and sid not in rev_eids: + rev_eids.append(sid) + if not rev_eids: + rev_eids = [fallback_eid] + + if diff_entries: + has_hist = any(e.get("change_kind") == "historical_revision" for e in diff_entries) + bullet_lines = [f"- {e.get('summary') or ''}" for e in diff_entries[:8] if e.get("summary")] + reason_lines: list[str] = [] + for cr in (revision_context.get("candidate_reasons") or [])[:4]: + if not isinstance(cr, dict): + continue + r_label = cr.get("review_reason_label") or cr.get("review_reason_code") or "人工复核采纳" + r_detail = cr.get("review_reason") + if r_detail: + reason_lines.append(f"- **复核理由({r_label})**:{r_detail}") + else: + reason_lines.append(f"- **复核理由类别**:{r_label}") + note_line = ( + f"- **发布说明**:{revision_context['publish_note']}" + if revision_context.get("publish_note") + else "" + ) + hist_banner = ( + "\n\n> **性质说明**:本次变动属于对历史统计观测的修订,不代表当期算力规模跃升。" + if has_hist + else "" + ) + changed_codes = [ + str(e.get("code")) + for e in diff_entries + if isinstance(e.get("code"), str) + ] + highlights.extend(changed_codes or (codes or ["CN", "US"])) + md_parts = [ + f"### 算力台账修订说明(版本 `{rev_pid}`)", + "", + *bullet_lines, + *reason_lines, + *([note_line] if note_line else []), + ] + return CopilotInvestigationReply( + answer_markdown=("\n".join(md_parts) + hist_banner + cutoff_note).strip(), + key_points=[ + CopilotKeyPoint( + claim=str(e.get("summary") or f"版本 {rev_pid} 发生观测值修订"), + evidence_ids=[ + e["new_source_id"] + if isinstance(e.get("new_source_id"), str) and e["new_source_id"] in evidence + else rev_eids[0] + ], + ) + for e in diff_entries[:4] + ], + highlight_entities=list(dict.fromkeys(highlights))[:8], + suggested_followups=[ + "切回修订前的系统发布版本对比旧值", + "查看该数值的完整血缘与报告原文出处", + ], + evidence_ids=rev_eids, + ) + if any(kw in q_lower for kw in ("枢纽", "东数西算", "绿电", "pue", "hub", "west")) and hubs: hub_ids = [h["id"] for h in hubs] highlights.extend(["CN", *hub_ids[:8]]) @@ -174,11 +270,34 @@ def _deterministic_compute_copilot_reply( ) highlights.extend(codes or ["CN", "US"]) - eids = [ + chip_eids = [ eid - for eid in ("caict-2025", "caict-2024", "caict-2023", "epoch-chip-imports-2026", "innovation-2026") - if eid in evidence - ] or [fallback_eid] + for eid in ( + chip.get("cn_evidence_id"), + chip.get("us_evidence_id"), + chip.get("evidence_id"), + ) + if isinstance(eid, str) and eid in evidence + ] + eids = list( + dict.fromkeys( + [ + *(chip_eids if mode == "chip_inflow_share" else []), + *( + eid + for eid in ( + "caict-2025", + "caict-2024", + "caict-2023", + "epoch-chip-imports-2026", + "innovation-2026", + ) + if eid in evidence + ), + *chip_eids, + ] + ) + ) or [fallback_eid] if not tot: # Multilateral or non-CN/US comparison (e.g. JP / EUROPE / DE) @@ -204,11 +323,18 @@ def _deterministic_compute_copilot_reply( evidence_ids=eids[:2], ) - mode_banner = ( - f"当前聚焦口径:**智能算力全球份额**(中国 `{intel['cn_value']}%` vs 美国 `{intel['us_value']}%`,RPI `{intel['rpi_percent']}%`)。" - if mode == "intelligent_share" and intel - else f"当前聚焦口径:**{tot.get('year')} 年全球总算力份额**(中国 `{tot.get('cn_value')}%` vs 美国 `{tot.get('us_value')}%`,RPI `{tot.get('rpi_percent')}%`)。" - ) + if mode == "chip_inflow_share" and chip: + mode_banner = ( + f"当前聚焦口径:**{chip.get('year')} 年高端 AI 算力卡新增流向占比**(中国 `{chip['cn_value']}%` vs 美国 `{chip['us_value']}%`,RPI `{chip['rpi_percent']}%`)。" + ) + elif mode == "intelligent_share" and intel: + mode_banner = ( + f"当前聚焦口径:**智能算力全球份额**(中国 `{intel['cn_value']}%` vs 美国 `{intel['us_value']}%`,RPI `{intel['rpi_percent']}%`)。" + ) + else: + mode_banner = ( + f"当前聚焦口径:**{tot.get('year')} 年全球总算力份额**(中国 `{tot.get('cn_value')}%` vs 美国 `{tot.get('us_value')}%`,RPI `{tot.get('rpi_percent')}%`)。" + ) denom_line = ( f"- **分母膨胀数学分解**:我国绝对总算力由 `{attr['country_from']:.0f}` 跃升至 `{attr['country_to']:.0f}` EFlops(`+{attr['country_growth_pct']}%`),全球总算力由 `{attr['global_from']:.0f}` 增至 `{attr['global_to']:.0f}` EFlops(`+{attr['global_growth_pct']}%`),相对份额回落源于全球分母扩张更快。\n" if attr and attr.get("global_to") @@ -259,9 +385,12 @@ async def run_contextual_copilot( question: str, time_basis: TimeBasis = "retrospective", cutoff_at: str | None = None, + publish_id: str | None = None, + as_of: str | None = None, allow_drill: bool = False, series_override: dict[str, Any] | None = None, posture_override: dict[str, Any] | None = None, + revision_context: dict[str, Any] | None = None, ai_client: AIProviderClient | None = None, cancel_event: asyncio.Event | None = None, ) -> dict[str, Any]: @@ -388,9 +517,26 @@ async def run_contextual_copilot( } series = series_override or await query_compute_posture_tool( - db, codes, mode=mode, time_basis=time_basis, cutoff_at=cutoff_at + db, + codes, + mode=mode, + time_basis=time_basis, + cutoff_at=cutoff_at, + as_of=as_of, + publish_id=publish_id, ) _raise_if_cancelled(cancel_event) + effective_revision_context = revision_context + if ( + effective_revision_context is None + and is_revision_question(question) + and not series.get("snapshot_unavailable") + ): + effective_revision_context = await build_revision_change_context( + db, + publish_id=series.get("publish_id") or publish_id, + redact=True, + ) posture = posture_override or await generate_or_get_compute_posture( db, countries=codes, @@ -421,6 +567,26 @@ async def run_contextual_copilot( } for eid, ev in evidence_map.items() } + llm_context: dict[str, Any] = { + "domain": domain, + "selected_codes": codes, + "focus_year": focus_year, + "mode": mode, + "publish_id": series.get("publish_id") or series.get("version"), + "published_at": series.get("published_at"), + "as_of": series.get("as_of") or as_of, + "time_basis": time_basis, + "cutoff_at": cutoff_at, + "entity_id": entity_id, + "bilateral_rpi": series.get("bilateral_rpi"), + "denominator_attribution": series.get("denominator_attribution"), + "structures": series.get("structures"), + "innovation_summary": series.get("innovation_summary"), + "national_hubs": series.get("national_hubs"), + "evidence": compact_evidence, + } + if effective_revision_context: + llm_context["revision_context"] = effective_revision_context llm_resp = await effective_ai_client.analyze( SituationalAnalysisRequest( title="地球空间上下文追问", @@ -432,21 +598,7 @@ async def run_contextual_copilot( '"highlight_entities": [str], "suggested_followups": [str], "evidence_ids": [str]}' ), system_prompt=prompt_def.system_prompt, - context={ - "domain": domain, - "selected_codes": codes, - "focus_year": focus_year, - "mode": mode, - "time_basis": time_basis, - "cutoff_at": cutoff_at, - "entity_id": entity_id, - "bilateral_rpi": series.get("bilateral_rpi"), - "denominator_attribution": series.get("denominator_attribution"), - "structures": series.get("structures"), - "innovation_summary": series.get("innovation_summary"), - "national_hubs": series.get("national_hubs"), - "evidence": compact_evidence, - }, + context=llm_context, constraints=[ "Return strict JSON matching CopilotInvestigationReply.", "Every evidence_id must exist in context.evidence.", @@ -480,7 +632,12 @@ async def run_contextual_copilot( if reply_obj is None: reply_obj = _deterministic_compute_copilot_reply( - question, series, entity_id, codes=codes, mode=mode + question, + series, + entity_id, + codes=codes, + mode=mode, + revision_context=effective_revision_context, ) return { @@ -488,6 +645,9 @@ async def run_contextual_copilot( "subject_key": posture["subject_key"], "revision": posture["revision"], "config_version": series.get("version"), + "publish_id": series.get("publish_id") or series.get("version"), + "published_at": series.get("published_at"), + "as_of": series.get("as_of") or as_of, "generation_mode": generation_mode, "usage": llm_usage, "reply": reply_obj.model_dump(mode="json"), diff --git a/backend/app/services/ai/dag_evidence.py b/backend/app/services/ai/dag_evidence.py new file mode 100644 index 00000000..0e3303ac --- /dev/null +++ b/backend/app/services/ai/dag_evidence.py @@ -0,0 +1,143 @@ +"""Shared URL-normalized evidence ledger for workflow DAG nodes and guardrails.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Sequence +from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit + +_TRACKING_QUERY_PARAMS: frozenset[str] = frozenset({"fbclid", "gclid", "mc_cid", "mc_eid"}) +_IGNORED_DOC_EXTENSIONS: tuple[str, ...] = (".csv", ".tsv", ".xlsx", ".xls", ".parquet", ".json") + + +def normalize_evidence_url(url: Any) -> str: + """Canonicalize an HTTP(S) URL for deduplication and anti-hallucination matching.""" + raw = str(url or "").strip() + if not raw: + return "" + try: + parts = urlsplit(raw) + except ValueError: + return raw.rstrip("/").lower() + scheme = (parts.scheme or "https").lower() + if scheme == "http": + scheme = "https" + netloc = parts.netloc.lower() + path = parts.path.rstrip("/") + kept_query = sorted( + (k, v) + for k, v in parse_qsl(parts.query, keep_blank_values=True) + if not k.lower().startswith("utm_") and k.lower() not in _TRACKING_QUERY_PARAMS + ) + return urlunsplit((scheme, netloc, path, urlencode(kept_query), "")) + + +def is_tabular_dataset_url(url: Any) -> bool: + """Return True for raw bulk-data files (e.g. Epoch csv exports) unsuitable for webpage fetch.""" + raw = str(url or "").strip() + if not raw: + return False + try: + path = urlsplit(raw).path.lower() + except ValueError: + path = raw.lower() + return path.endswith(_IGNORED_DOC_EXTENSIONS) + + +@dataclass +class EvidenceLedger: + """Assigns sequential ``E1..En`` IDs to tool-observed URLs and resolves citations safely.""" + + items: list[dict[str, Any]] = field(default_factory=list) + by_id: dict[str, dict[str, Any]] = field(default_factory=dict) + by_norm_url: dict[str, dict[str, Any]] = field(default_factory=dict) + evidence_calls: int = 0 + + def record_call(self) -> None: + self.evidence_calls += 1 + + def add( + self, + *, + url: str, + title: str = "", + snippet: str = "", + tool: str = "", + query: str = "", + ) -> str | None: + cleaned_url = str(url or "").strip() + if not cleaned_url: + return None + norm = normalize_evidence_url(cleaned_url) + if not norm: + return None + existing = self.by_norm_url.get(norm) + cleaned_snippet = str(snippet or "").strip() + cleaned_title = str(title or "").strip() + if existing is not None: + if len(cleaned_snippet) > len(str(existing.get("snippet") or "")): + existing["snippet"] = cleaned_snippet[:1500] + if cleaned_title and not existing.get("title"): + existing["title"] = cleaned_title[:200] + return str(existing["id"]) + + eid = f"E{len(self.items) + 1}" + entry = { + "id": eid, + "url": cleaned_url, + "norm_url": norm, + "title": cleaned_title[:200], + "snippet": cleaned_snippet[:1500], + "tool": tool, + "query": query, + } + self.items.append(entry) + self.by_id[eid] = entry + self.by_norm_url[norm] = entry + return eid + + def resolve_refs(self, refs: Sequence[Any]) -> tuple[list[str], list[str]]: + """Map ``['E1', 'https://...']`` references back to verified IDs and original URLs.""" + verified_ids: list[str] = [] + verified_urls: list[str] = [] + seen_urls: set[str] = set() + for raw in refs: + token = str(raw or "").strip() + if not token: + continue + entry = self.by_id.get(token.upper()) + if entry is None: + entry = self.by_norm_url.get(normalize_evidence_url(token)) + if entry is None: + continue + eid = str(entry["id"]) + url = str(entry["url"]) + norm = str(entry["norm_url"]) + if eid not in verified_ids: + verified_ids.append(eid) + if norm not in seen_urls: + seen_urls.add(norm) + verified_urls.append(url) + return verified_ids, verified_urls + + def to_prompt_items(self, limit: int = 14) -> list[dict[str, str]]: + return [ + { + "id": str(item["id"]), + "title": str(item.get("title") or ""), + "url": str(item.get("url") or ""), + "tool": str(item.get("tool") or ""), + "excerpt": str(item.get("snippet") or "")[:900], + } + for item in self.items[:limit] + ] + + def to_evidence_dict(self) -> dict[str, dict[str, str]]: + return { + str(item["id"]): { + "url": str(item.get("url") or ""), + "title": str(item.get("title") or ""), + "source": str(item.get("tool") or "web"), + } + for item in self.items + } diff --git a/backend/app/services/ai/dag_executor.py b/backend/app/services/ai/dag_executor.py index 0cb496c5..81a495c3 100644 --- a/backend/app/services/ai/dag_executor.py +++ b/backend/app/services/ai/dag_executor.py @@ -4,12 +4,14 @@ from __future__ import annotations import asyncio from collections import defaultdict, deque +from datetime import UTC, datetime import json import re from typing import Any, AsyncIterator from app.core.logging import get_logger from app.schemas.ai import ChatMessage, ImageAttachment, SituationalAnalysisRequest +from app.services.ai.dag_evidence import EvidenceLedger from app.services.ai.scene_directives import ( INFLUENCE_ZONE_GUIDANCE, consume_text_holding_scene_tag, @@ -22,16 +24,16 @@ from app.services.ai.tool_registry import ( isolate_untrusted_external_text, query_bgp_incidents_tool, query_cable_posture_tool, + query_cloud_posture_tool, query_compute_posture_tool, query_global_situational_tool, query_recent_earth_news_tool, query_satellite_posture_tool, query_vessel_posture_tool, + query_wind_posture_tool, safe_web_fetch, ) from app.services.ai.workflow_registry import MAX_WORKFLOW_NODES, _extract_first_json_object -from app.services.compute_center_locations import build_compute_center_location_query -from app.services.location.agent_resolver import run_l1_structured_facility_resolvers logger = get_logger(__name__, service="ai_dag_executor") @@ -65,6 +67,8 @@ def render_workflow_template( question: str = "", targets: list[dict[str, Any]] | None = None, node_outputs: dict[str, str] | None = None, + node_data: dict[str, dict[str, Any]] | None = None, + workflow_state: dict[str, Any] | None = None, ) -> str: """Interpolate `{{...}}` placeholders safely without Python `.format` or eval.""" raw = str(template or "") @@ -72,8 +76,17 @@ def render_workflow_template( return raw first = targets[0] if targets else {} outputs = node_outputs or {} + structured = node_data or {} + state = workflow_state or {} targets_summary = summarize_targets(targets) + def _serialize_val(val: Any) -> str: + if val is None: + return "" + if isinstance(val, (dict, list)): + return json.dumps(val, ensure_ascii=False, default=str)[:4000] + return str(val)[:4000] + def _lookup(key: str) -> str: if key == "question": return question @@ -96,9 +109,17 @@ def render_workflow_template( if sub in {"kind", "layer"}: return str(first.get(sub) or "") return "" + if key.startswith("state."): + skey = key[len("state.") :] + return _serialize_val(state.get(skey)) if key.startswith("node."): - nid = key[len("node.") :] - return str(outputs.get(nid) or "")[:4000] + rest = key[len("node.") :] + if "." in rest: + nid, sub = rest.split(".", 1) + nd = structured.get(nid) or {} + if sub in nd: + return _serialize_val(nd.get(sub)) + return str(outputs.get(rest) or "")[:4000] if key.endswith(".output"): nid = key[: -len(".output")] return str(outputs.get(nid) or "")[:4000] @@ -155,8 +176,58 @@ async def _execute_tool( targets: list[dict[str, Any]], earth_context: dict[str, Any], allow_external_tools: bool, + node_params: dict[str, Any] | None = None, + node_data: dict[str, dict[str, Any]] | None = None, + workflow_state: dict[str, Any] | None = None, ) -> dict[str, Any]: - """Execute one whitelisted read-only or controlled external tool cleanly.""" + """Execute one whitelisted read-only or controlled workflow tool cleanly.""" + state = workflow_state if workflow_state is not None else {} + params = node_params or {} + + if tool_id == "location_normalize_context": + from app.services.location.workflow_tools import tool_location_normalize_context + + return await tool_location_normalize_context( + db, + question=question, + targets=targets, + earth_context=earth_context, + node_params=params, + workflow_state=state, + ) + if tool_id == "location_knowledge_lookup" or tool_id in _L1_KNOWLEDGE_TOOL_IDS: + from app.services.location.workflow_tools import tool_location_knowledge_lookup + + return await tool_location_knowledge_lookup( + db, + question=question, + targets=targets, + earth_context=earth_context, + node_params=params, + workflow_state=state, + ) + if tool_id == "location_web_research": + from app.services.location.workflow_tools import tool_location_web_research + + return await tool_location_web_research( + db, + node_params=params, + workflow_state=state, + allow_external_tools=allow_external_tools, + ) + if tool_id in {"location_geocode_verify", "geocode_verify"}: + from app.services.location.workflow_tools import tool_location_geocode_verify + + return await tool_location_geocode_verify(workflow_state=state) + if tool_id == "location_persist_outcome": + from app.services.location.workflow_tools import tool_location_persist_outcome + + return await tool_location_persist_outcome( + db, + node_params=params, + workflow_state=state, + ) + codes, mode = _extract_codes_and_mode(earth_context) time_basis: TimeBasis = str(earth_context.get("time_basis") or "retrospective") # type: ignore[assignment] if time_basis not in {"live", "as_known_then", "retrospective"}: @@ -174,13 +245,26 @@ async def _execute_tool( cutoff_at=cutoff_at, ) if tool_id == "query_compute_posture": - return await query_compute_posture_tool( + res = await query_compute_posture_tool( db, countries=codes, mode=mode, time_basis=time_basis, cutoff_at=cutoff_at, + as_of=earth_context.get("as_of"), + publish_id=earth_context.get("publish_id"), ) + from app.services.compute_lineage import build_revision_change_context, is_revision_question + + if is_revision_question(question) and not res.get("snapshot_unavailable"): + rev_ctx = await build_revision_change_context( + db, + publish_id=res.get("publish_id") or earth_context.get("publish_id"), + redact=not allow_external_tools, + ) + if rev_ctx: + res["revision_context"] = rev_ctx + return res if tool_id == "query_bgp_incidents": incidents = await query_bgp_incidents_tool( db, @@ -211,43 +295,45 @@ async def _execute_tool( cutoff_at=cutoff_at, entity_id=_target_id_for_types(targets, _VESSEL_ENTITY_TYPES), ) + if tool_id == "query_cloud_posture": + first = targets[0] if targets else {} + return await query_cloud_posture_tool( + db, + time_basis=time_basis, + cutoff_at=cutoff_at, + latitude=first.get("latitude"), + longitude=first.get("longitude"), + ) + if tool_id == "query_wind_posture": + first = targets[0] if targets else {} + return await query_wind_posture_tool( + db, + time_basis=time_basis, + cutoff_at=cutoff_at, + latitude=first.get("latitude"), + longitude=first.get("longitude"), + ) if tool_id == "query_recent_earth_news": news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {} region = str(news_ctx.get("region_key") or "").strip() or None return await query_recent_earth_news_tool(db, region=region, limit=10) - if tool_id in _L1_KNOWLEDGE_TOOL_IDS: - facility = next( - (t for t in targets if _target_entity_type(t) in _COMPUTE_FACILITY_TYPES), - targets[0] if targets else {}, - ) - target_name = str(facility.get("label") or question or "Unknown Facility").strip() - query = build_compute_center_location_query(name=target_name) - candidates, resolver_log, _ = await run_l1_structured_facility_resolvers(query, db=db) - return { - "candidates": [ - { - "display_name": c.display_name, - "country": c.country, - "latitude": c.latitude, - "longitude": c.longitude, - "precision": c.precision, - "confidence": c.confidence, - "source": c.source, - "source_note": c.source_note, - } - for c in candidates[:5] - ], - "resolver_log": resolver_log, - } if tool_id == "web_search": if not allow_external_tools: return {"skipped": "external_web_search_admin_only"} from app.api.v1.settings import get_web_search_client client = await get_web_search_client(db) - search_q = " ".join( - part for part in [summarize_targets(targets) if targets else "", question] if part - ).strip()[:200] + custom_q = render_workflow_template( + str(params.get("query_template") or ""), + question=question, + targets=targets, + node_data=node_data, + workflow_state=state, + ).strip() + search_q = ( + custom_q + or " ".join(part for part in [summarize_targets(targets) if targets else "", question] if part).strip() + )[:200] if not search_q: return {"items": []} hits = await client.search(search_q, max_results=5) @@ -267,7 +353,14 @@ async def _execute_tool( return {"skipped": "external_fetch_admin_only"} news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {} target_props = targets[0].get("properties") if targets and isinstance(targets[0].get("properties"), dict) else {} - url = str(news_ctx.get("url") or target_props.get("url") or "").strip() + custom_u = render_workflow_template( + str(params.get("url_template") or ""), + question=question, + targets=targets, + node_data=node_data, + workflow_state=state, + ).strip() + url = (custom_u or str(news_ctx.get("url") or target_props.get("url") or "")).strip() if not url: return {"skipped": "no_target_url"} fetched = await safe_web_fetch(url) @@ -281,11 +374,15 @@ def _has_meaningful_tool_data(tool_results: dict[str, Any]) -> bool: continue if val.get("skipped") or val.get("error"): continue - for key in ("items", "candidates", "cables", "landing_points", "series", "satellites", "vessels"): + for key in ("items", "candidates", "cables", "landing_points", "series", "satellites", "vessels", "new_ids"): seq = val.get(key) if isinstance(seq, list) and len(seq) > 0: return True - if val.get("excerpt") or val.get("summary"): + if val.get("excerpt") or val.get("summary") or val.get("found") is True or val.get("is_terminal") is True: + return True + if isinstance(val.get("evidence_count"), int) and val["evidence_count"] > 0: + return True + if isinstance(val.get("context"), dict) and val["context"]: return True return False @@ -354,14 +451,45 @@ def _eval_edge_condition( pred_state: dict[str, Any], targets: list[dict[str, Any]], trigger_source: str = "interactive", + pred_data: dict[str, Any] | None = None, ) -> bool: cond = str(edge.get("condition") or "always").strip() + data = pred_data if isinstance(pred_data, dict) else ( + pred_state.get("data") if isinstance(pred_state.get("data"), dict) else {} + ) if cond in TRIGGER_SOURCES: # Background RSS ingest and user-clicked analysis share one graph; only the branch # matching the actual trigger may run (avoids a second model call and leaked JSON). return cond == trigger_source - if cond in {"always", "", "not_terminal", "high_confidence_hit", "fallback_to_agent"}: + if cond in {"always", ""}: return True + if cond == "not_terminal": + return not bool(pred_state.get("is_terminal") or data.get("is_terminal")) + if cond == "on_terminal": + return bool(pred_state.get("is_terminal") or data.get("is_terminal")) + if cond == "high_confidence_hit": + return bool(pred_state.get("high_confidence_hit") or data.get("high_confidence_hit")) + if cond == "fallback_to_agent": + return not bool(pred_state.get("high_confidence_hit") or data.get("high_confidence_hit")) + if cond == "on_guardrail_passed": + return bool(pred_state.get("guardrail_passed", True)) + if cond == "on_guardrail_failed": + return not bool(pred_state.get("guardrail_passed", True)) + if cond == "on_field_equals": + raw_expr = str(edge.get("condition_value") or "").strip() + if "=" not in raw_expr: + return False + field_name, expected_raw = raw_expr.split("=", 1) + field_key = field_name.strip() + wanted = {item.strip().lower() for item in expected_raw.split(",") if item.strip()} + if not field_key or not wanted: + return False + actual = data.get(field_key) + if actual is None: + actual = pred_state.get(field_key) + if actual is None: + return False + return str(actual).strip().lower() in wanted if cond == "on_empty_or_low_confidence": return bool(pred_state.get("is_empty")) or float(pred_state.get("confidence", 1.0)) < 0.6 if cond == "on_entity_type": @@ -500,12 +628,15 @@ def _compile_compute_workbench( from app.services.ai.workflow_runtime import compile_compute_view_spec codes, mode = _extract_codes_and_mode(earth_context) + raw_focus_year = earth_context.get("focus_year") + focus_year = int(raw_focus_year) if isinstance(raw_focus_year, int) else None try: view, scene = compile_compute_view_spec( codes=codes, mode=mode, series=series, posture={"payload": brief.model_dump(mode="json")}, + focus_year=focus_year, ) except Exception as exc: logger.warning_event( @@ -537,6 +668,55 @@ def _build_evidence_gap_markdown(tool_results: dict[str, Any], warnings: list[st return "\n".join(lines) +def _render_output_schema_prompt(schema: dict[str, Any]) -> str: + """Render an inline JSON Schema contract directly into the system prompt for cross-provider reliability.""" + props = schema.get("properties") if isinstance(schema.get("properties"), dict) else {} + required = set(str(k) for k in (schema.get("required") or []) if k) + field_lines: list[str] = [] + for name, spec in props.items(): + if not isinstance(spec, dict): + continue + req_tag = "必填" if name in required else "可选" + enum_vals = spec.get("enum") + type_desc = ( + f"枚举: {' | '.join(str(v) for v in enum_vals)}" + if isinstance(enum_vals, list) and enum_vals + else str(spec.get("type") or "string") + ) + desc = str(spec.get("description") or "").strip() + line = f'- "{name}" ({req_tag}, {type_desc})' + if desc: + line += f": {desc}" + field_lines.append(line) + return ( + "【严格输出要求】仅返回单个合法 JSON 对象(禁止输出 Markdown 围栏外文字或思考过程)。字段契约:\n" + + "\n".join(field_lines) + ) + + +async def _repair_json_once( + *, + ai_client: Any, + schema_hint: str, + prior_text: str, + timeout_sec: int, +) -> dict[str, Any] | None: + """Single no-search JSON format repair pass when a structured llm_agent returns non-JSON.""" + req = SituationalAnalysisRequest( + title="Repair structured workflow JSON", + objective="Convert prior output into one valid JSON object matching the required schema.", + system_prompt=f"{schema_hint}\n严禁新增原始回复中未出现的 URL、evidence_ids 或事实。", + context={"prior_output": prior_text[:2500]}, + thinking={"mode": "off"}, + ) + try: + resp = await asyncio.wait_for(ai_client.analyze(req), timeout=min(timeout_sec, 45)) + except Exception: + return None + clean_text, _ = strip_thinking_text(str(getattr(resp, "content", "") or "")) + return _extract_first_json_object(clean_text or str(getattr(resp, "content", "") or "")) + + async def run_workflow_dag_stream( *, db: Any, @@ -579,6 +759,7 @@ async def run_workflow_dag_stream( clean_targets = [t for t in (targets or []) if isinstance(t, dict)][:8] clean_earth_ctx = dict(earth_context or {}) + location_runtime = clean_earth_ctx.pop("_location_runtime", None) planned_ids = [str(n["id"]) for n in ordered_nodes] yield { @@ -604,19 +785,29 @@ async def run_workflow_dag_stream( ai_ready, provider_name, default_model = await ai_client.is_ready() except Exception: ai_ready = False + elif ai_client is not None and (hasattr(ai_client, "analyze") or hasattr(ai_client, "stream_analyze")): + ai_ready = True node_states: dict[str, dict[str, Any]] = {} node_outputs: dict[str, str] = {} + node_data: dict[str, dict[str, Any]] = {} tool_results: dict[str, Any] = {} evidence: dict[str, Any] = {} executed_trace: list[str] = [] + node_traces: list[dict[str, Any]] = [] + evidence_ledger = EvidenceLedger() + workflow_state: dict[str, Any] = { + "evidence_ledger": evidence_ledger, + "attempted_queries": [], + **(location_runtime if isinstance(location_runtime, dict) else {}), + } effective_question = question.strip() final_answer_md = "" final_reasoning_md = "" generation_mode = "deterministic_baseline" zero_token = True - resolved_provider: str | None = None - resolved_model: str | None = None + resolved_provider: str | None = provider_name or None + resolved_model: str | None = default_model or None scene_spec: dict[str, Any] | None = None parsed_dag_scene: dict[str, Any] | None = None view_spec: dict[str, Any] | None = None @@ -632,26 +823,46 @@ async def run_workflow_dag_stream( nid = str(node["id"]) ntype = str(node.get("node_type") or "llm_agent") ntitle = str(node.get("title") or nid) + node_params = node.get("params") if isinstance(node.get("params"), dict) else {} inc_edges = incoming_map.get(nid) or [] if inc_edges: - passed = False - for edge in inc_edges: - pred_id = str(edge.get("source") or "") - pred_state = node_states.get(pred_id) - if not pred_state or pred_state.get("skipped"): - continue - if _eval_edge_condition(edge, pred_state, clean_targets, trigger_source): - passed = True - break + join_mode = str(node_params.get("join_mode") or "any").strip().lower() + if join_mode == "all": + passed = True + for edge in inc_edges: + pred_id = str(edge.get("source") or "") + pred_state = node_states.get(pred_id) + if not pred_state or pred_state.get("skipped"): + passed = False + break + if not _eval_edge_condition( + edge, pred_state, clean_targets, trigger_source, pred_data=node_data.get(pred_id) + ): + passed = False + break + else: + passed = False + for edge in inc_edges: + pred_id = str(edge.get("source") or "") + pred_state = node_states.get(pred_id) + if not pred_state or pred_state.get("skipped"): + continue + if _eval_edge_condition( + edge, pred_state, clean_targets, trigger_source, pred_data=node_data.get(pred_id) + ): + passed = True + break if not passed: node_states[nid] = {"skipped": True, "confidence": 1.0, "is_empty": False} + node_traces.append({"node_id": nid, "node_type": ntype, "status": "skipped", "duration_ms": 0}) yield { "event": "node", "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "skipped"}, } continue + node_started = datetime.now(UTC) yield { "event": "node", "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "running"}, @@ -665,11 +876,15 @@ async def run_workflow_dag_stream( question=effective_question, targets=clean_targets, node_outputs=node_outputs, + node_data=node_data, + workflow_state=workflow_state, ).strip() summary = summarize_targets(clean_targets) node_outputs[nid] = summary node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False} executed_trace.append(nid) + dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000)) + node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms}) yield { "event": "node", "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"}, @@ -678,6 +893,7 @@ async def run_workflow_dag_stream( if ntype == "deterministic": local_results: dict[str, Any] = {} + merged_data: dict[str, Any] = {} l1_ran = False for tid in node.get("tools") or []: if tid in _L1_KNOWLEDGE_TOOL_IDS: @@ -695,11 +911,16 @@ async def run_workflow_dag_stream( targets=clean_targets, earth_context=clean_earth_ctx, allow_external_tools=allow_external_tools, + node_params=node_params, + node_data=node_data, + workflow_state=workflow_state, ) local_results[result_key] = res tool_results[result_key] = res - if isinstance(res, dict) and isinstance(res.get("evidence"), dict): - evidence.update(res["evidence"]) + if isinstance(res, dict): + merged_data.update(res) + if isinstance(res.get("evidence"), dict): + evidence.update(res["evidence"]) executed_trace.append(f"{nid}:{tid}") except Exception as exc: logger.warning_event( @@ -708,15 +929,23 @@ async def run_workflow_dag_stream( context={"workflow_id": wf_id, "node_id": nid, "tool_id": tid, "error": str(exc)}, ) local_results[result_key] = {"error": str(exc)} + if evidence_ledger.items: + evidence.update(evidence_ledger.to_evidence_dict()) has_data = _has_meaningful_tool_data(local_results) + node_data[nid] = merged_data node_outputs[nid] = json.dumps(local_results, ensure_ascii=False, default=str)[:4000] node_states[nid] = { "skipped": False, "confidence": 0.9 if has_data else 0.4, "is_empty": not has_data, + "is_terminal": bool(merged_data.get("is_terminal")), + "high_confidence_hit": bool(merged_data.get("high_confidence_hit")), + "data": merged_data, } if nid not in executed_trace: executed_trace.append(nid) + dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000)) + node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms}) yield { "event": "node", "data": { @@ -731,28 +960,37 @@ async def run_workflow_dag_stream( if ntype in {"llm_agent", "tool_agent"}: has_next_llm = _has_downstream_llm(nid, adj, node_types) + schema_spec = node_params.get("output_schema") if isinstance(node_params.get("output_schema"), dict) else None sys_prompt = render_workflow_template( str(node.get("system_prompt") or "").strip() or "你是智能星球(Planet)AI 参谋。结合当前地球上下文、选中交互物件与工具证据,给出严谨客观的中文分析。", question=effective_question or question, targets=clean_targets, node_outputs=node_outputs, + node_data=node_data, + workflow_state=workflow_state, ) node_prompt = render_workflow_template( str(node.get("prompt") or "").strip(), question=effective_question or question, targets=clean_targets, node_outputs=node_outputs, + node_data=node_data, + workflow_state=workflow_state, ) objective = ( f"{node_prompt}\n\n用户请求:{effective_question or question}" if node_prompt else (effective_question or question) ) - structured = _node_wants_structured_json(node) + structured = _node_wants_structured_json(node) or bool(schema_spec) is_compute_brief = str(node.get("prompt_key") or "") == COMPUTE_BRIEF_PROMPT_KEY if is_compute_brief: objective = f"{objective}\n\n{_COMPUTE_BRIEF_SCHEMA_HINT}" + schema_hint = _render_output_schema_prompt(schema_spec) if schema_spec else "" + if schema_hint: + sys_prompt = f"{sys_prompt}\n\n{schema_hint}".strip() + wants_scene_zones = ( not has_next_llm and not structured @@ -779,6 +1017,9 @@ async def run_workflow_dag_stream( targets=clean_targets, earth_context=clean_earth_ctx, allow_external_tools=allow_external_tools, + node_params=node_params, + node_data=node_data, + workflow_state=workflow_state, ) node_tool_results[tid] = res tool_results[tid] = res @@ -786,6 +1027,8 @@ async def run_workflow_dag_stream( evidence.update(res["evidence"]) except Exception as exc: node_tool_results[tid] = {"error": str(exc)} + if evidence_ledger.items: + evidence.update(evidence_ledger.to_evidence_dict()) ctx_payload: dict[str, Any] = { "targets": clean_targets, @@ -794,6 +1037,10 @@ async def run_workflow_dag_stream( "upstream_outputs": {k: v[:2000] for k, v in node_outputs.items()}, "evidence": evidence, } + if workflow_state.get("location_ctx"): + ctx_payload["location_target"] = workflow_state["location_ctx"] + if evidence_ledger.items: + ctx_payload["evidence_items"] = evidence_ledger.to_prompt_items() if clean_earth_ctx: ctx_payload["earth_context"] = clean_earth_ctx if wants_scene_zones: @@ -820,6 +1067,7 @@ async def run_workflow_dag_stream( or str(node.get("model_override") or "").strip() or None ) + native_search = bool(node.get("native_web_search", False)) and allow_external_tools req = SituationalAnalysisRequest( title=f"Planet AI Advisor · {wf_name}", objective=objective[:24000], @@ -827,13 +1075,96 @@ async def run_workflow_dag_stream( context=ctx_payload, preferred_model=preferred_model, thinking={"mode": "auto"} if bool(node.get("thinking_enabled", True)) else {"mode": "off"}, - native_web_search=bool(node.get("native_web_search", False)) and allow_external_tools, - messages=[] if has_next_llm else chat_msgs, + native_web_search=native_search, + messages=[] if (has_next_llm or schema_spec) else chat_msgs, images=parsed_images, ) compute_series = _compute_series_from_tools(tool_results) if is_compute_brief else None + if schema_spec is not None: + cap_reason = str(workflow_state.get("capability_reason") or "").strip() + if not ai_ready or ai_client is None: + parsed_schema = { + "decision": "unresolved", + "reasoning": cap_reason or "当前未配置可用 AI Provider", + } + elif ( + cap_reason + and evidence_ledger.evidence_calls == 0 + and not native_search + ): + parsed_schema = {"decision": "unresolved", "reasoning": cap_reason} + else: + timeout_sec = max(5, min(int(node.get("timeout_seconds") or 60), 300)) + try: + resp = await asyncio.wait_for(ai_client.analyze(req), timeout=timeout_sec) + except Exception as exc: + parsed_schema = { + "decision": "unresolved", + "reasoning": f"模型研判请求失败:{exc}", + } + else: + raw_out = str(getattr(resp, "content", "") or "") + clean_text, inline_thoughts = strip_thinking_text(raw_out) + resolved_provider = getattr(resp, "provider", None) or resolved_provider or None + resolved_model = getattr(resp, "model", None) or preferred_model or resolved_model or None + if inline_thoughts: + final_reasoning_md = f"{final_reasoning_md}\n\n" + "\n\n".join(inline_thoughts) + final_reasoning_md = final_reasoning_md.strip() + for cite_u in getattr(resp, "citation_urls", None) or []: + u_str = str(cite_u or "").strip() + if u_str: + evidence_ledger.record_call() + evidence_ledger.add(url=u_str, title="Provider Web Citation", tool="native_web_search") + if evidence_ledger.items: + evidence.update(evidence_ledger.to_evidence_dict()) + generation_mode = "llm_verified" + zero_token = False + parsed_schema = _extract_first_json_object(clean_text or raw_out) + if parsed_schema is None and (clean_text or raw_out).strip(): + parsed_schema = await _repair_json_once( + ai_client=ai_client, + schema_hint=schema_hint, + prior_text=clean_text or raw_out, + timeout_sec=timeout_sec, + ) + if parsed_schema is None: + parsed_schema = { + "decision": "unresolved", + "reasoning": "模型未返回可解析的结构化 JSON 结论", + } + if ( + node_params.get("allow_followup") is False + and str(parsed_schema.get("decision") or "").strip().lower() == "need_followup" + ): + parsed_schema["decision"] = "unresolved" + node_data[nid] = parsed_schema + workflow_state["latest_llm_data"] = parsed_schema + node_outputs[nid] = json.dumps(parsed_schema, ensure_ascii=False, default=str)[:4000] + node_states[nid] = { + "skipped": False, + "confidence": float(parsed_schema.get("confidence") or 0.7), + "is_empty": False, + "data": parsed_schema, + } + executed_trace.append(nid) + dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000)) + node_traces.append( + { + "node_id": nid, + "node_type": ntype, + "status": "completed", + "duration_ms": dur_ms, + "decision": parsed_schema.get("decision"), + } + ) + yield { + "event": "node", + "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"}, + } + continue + if not ai_ready or ai_client is None: if compute_series is not None and not has_next_llm: compute_brief, compute_brief_llm_verified = _resolve_compute_brief(None, compute_series) @@ -855,6 +1186,8 @@ async def run_workflow_dag_stream( if not has_next_llm: final_answer_md = fallback_md yield {"event": "text", "data": {"delta": fallback_md}} + dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000)) + node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms}) yield { "event": "node", "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"}, @@ -882,6 +1215,8 @@ async def run_workflow_dag_stream( zero_token = False if structured and not has_next_llm: parsed = _extract_first_json_object(node_outputs[nid]) + if isinstance(parsed, dict): + node_data[nid] = parsed narrative = "" if compute_series is not None: compute_brief, compute_brief_llm_verified = _resolve_compute_brief(parsed, compute_series) @@ -900,8 +1235,11 @@ async def run_workflow_dag_stream( "skipped": False, "confidence": 0.85 if node_outputs[nid] else 0.4, "is_empty": not bool(node_outputs[nid].strip()), + **({"data": node_data[nid]} if nid in node_data else {}), } executed_trace.append(nid) + dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000)) + node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms}) yield { "event": "node", "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"}, @@ -980,6 +1318,8 @@ async def run_workflow_dag_stream( "is_empty": not bool(final_answer_md), } executed_trace.append(nid) + dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000)) + node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms}) yield { "event": "node", "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"}, @@ -1003,6 +1343,25 @@ async def run_workflow_dag_stream( if hits: passed = False warnings.append("命中禁用表述: " + ", ".join(hits[:5])) + if gr.get("geo_verification") or any( + k in gr + for k in ( + "min_confidence", + "enforce_country_match", + "require_tool_cited_urls", + "downgrade_geocoded_site_to_city", + ) + ): + from app.services.location.workflow_tools import evaluate_location_geo_guardrail + + geo_eval = evaluate_location_geo_guardrail(gr, workflow_state) + node_data[nid] = geo_eval + if not geo_eval.get("passed", False): + passed = False + for gw in geo_eval.get("warnings") or []: + if gw and gw not in warnings: + warnings.append(str(gw)) + disclaimer = str(gr.get("append_disclaimer") or "").strip() if disclaimer and final_answer_md and disclaimer not in final_answer_md: extra_block = f"\n\n> {disclaimer}" @@ -1020,9 +1379,22 @@ async def run_workflow_dag_stream( "skipped": False, "confidence": 0.95 if passed else 0.45, "is_empty": False, + "guardrail_passed": passed, "warnings": warnings, + **({"data": node_data[nid]} if nid in node_data else {}), } executed_trace.append(nid) + dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000)) + node_traces.append( + { + "node_id": nid, + "node_type": ntype, + "status": "completed", + "duration_ms": dur_ms, + "guardrail_passed": passed, + **({"warnings": warnings[:3]} if warnings else {}), + } + ) yield { "event": "node", "data": { @@ -1036,9 +1408,35 @@ async def run_workflow_dag_stream( continue if ntype == "output": - params = node.get("params") if isinstance(node.get("params"), dict) else {} + params = node_params + for tid in node.get("tools") or []: + try: + out_res = await _execute_tool( + db, + tid, + question=effective_question or question, + targets=clean_targets, + earth_context=clean_earth_ctx, + allow_external_tools=allow_external_tools, + node_params=params, + node_data=node_data, + workflow_state=workflow_state, + ) + if isinstance(out_res, dict): + node_data[nid] = out_res + except Exception as exc: + logger.warning_event( + "Output DAG tool failed", + event="ai_dag.output_tool.failed", + context={"workflow_id": wf_id, "node_id": nid, "tool_id": tid, "error": str(exc)}, + ) + if isinstance(workflow_state.get("final_answer_markdown"), str) and workflow_state["final_answer_markdown"]: + final_answer_md = workflow_state["final_answer_markdown"] + yield {"event": "text", "data": {"delta": final_answer_md}} + if isinstance(workflow_state.get("final_scene_spec"), dict): + scene_spec = workflow_state["final_scene_spec"] fly_enabled = bool(params.get("fly_to_target", True)) - if fly_enabled and clean_targets: + if scene_spec is None and fly_enabled and clean_targets: first = clean_targets[0] lat = first.get("latitude") lon = first.get("longitude") @@ -1064,7 +1462,10 @@ async def run_workflow_dag_stream( if scene_spec is None and compute_scene is not None: scene_spec = compute_scene node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False} - executed_trace.append(nid) + outcome_tag = str(workflow_state.get("outcome_tag") or "").strip() + executed_trace.append(f"{nid}:{outcome_tag}" if outcome_tag else nid) + dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000)) + node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms}) yield { "event": "node", "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"}, @@ -1092,7 +1493,11 @@ async def run_workflow_dag_stream( "data": {"run_id": run_id, "domain": "compute", "view_spec": view_spec, "scene_spec": scene_spec}, } - if isinstance(scene_spec, dict) and (scene_spec.get("influence_zones") or parsed_dag_scene): + if isinstance(scene_spec, dict) and ( + scene_spec.get("influence_zones") + or parsed_dag_scene + or isinstance(workflow_state.get("final_scene_spec"), dict) + ): yield {"event": "scene", "data": {"scene_spec": scene_spec}} verification = { @@ -1119,5 +1524,7 @@ async def run_workflow_dag_stream( "answer_markdown": final_answer_md, "reasoning_markdown": final_reasoning_md, "text_length": len(final_answer_md), + **({"structured_output": workflow_state["structured_output"]} if "structured_output" in workflow_state else {}), + "node_traces": node_traces, }, } diff --git a/backend/app/services/ai/posture_agent.py b/backend/app/services/ai/posture_agent.py index c3efbb85..904dafdf 100644 --- a/backend/app/services/ai/posture_agent.py +++ b/backend/app/services/ai/posture_agent.py @@ -116,7 +116,18 @@ def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> Strateg tot = rpi["latest_total"] intel = rpi.get("latest_intelligent") chip = rpi.get("latest_chip_inflow") - tot_ev = tot["evidence_id"] + def _pair_eids(pair: dict[str, Any] | None) -> list[str]: + if not pair: + return [] + candidates = [ + pair.get("cn_evidence_id"), + pair.get("us_evidence_id"), + pair.get("evidence_id"), + ] + return list(dict.fromkeys(str(eid) for eid in candidates if eid and eid in evidence)) + + tot_eids = _pair_eids(tot) + tot_ev = tot_eids[0] if tot_eids else tot["evidence_id"] near_parity = float(tot["rpi_percent"]) >= 85.0 if near_parity: headline = ( @@ -174,7 +185,8 @@ def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> Strateg evidence_ids=[eid for eid in (attribution["evidence_ids"] if attribution else [tot_ev]) if eid in evidence] or [tot_ev], ) ] - if intel and intel.get("evidence_id") in evidence: + intel_eids = _pair_eids(intel) + if intel and intel_eids: causes.append( PostureBullet( label="智能算力竞争成为核心分化面", @@ -184,10 +196,11 @@ def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> Strateg f"高端训练集群供给差异直接拉开了总算力剪刀差。" ), detail_en=f"U.S. holds {intel['us_value']}% of global intelligent compute vs China's {intel['cn_value']}%.", - evidence_ids=[intel["evidence_id"]], + evidence_ids=intel_eids, ) ) - if chip and chip.get("evidence_id") in evidence: + chip_eids = _pair_eids(chip) + if chip and chip_eids: causes.append( PostureBullet( label="先进芯片管制重塑新增算力流向", @@ -196,7 +209,7 @@ def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> Strateg f"公开样本显示高端 AI 加速卡新增算力约 {chip['us_value']}% 流向美国,我国公开可统计流入约 {chip['cn_value']}%。" ), detail_en=f"~{chip['us_value']}% of tracked H100-equivalent compute inflows went to the U.S. vs ~{chip['cn_value']}% to China.", - evidence_ids=[chip["evidence_id"]], + evidence_ids=chip_eids, ) ) @@ -348,12 +361,56 @@ async def generate_or_get_compute_posture( _raise_if_cancelled(cancel_event) effective_basis = str(time_basis or series_payload.get("time_basis") or "retrospective") effective_cutoff = cutoff_at if cutoff_at is not None else series_payload.get("cutoff_at") + effective_publish_id = series_payload.get("publish_id") or series_payload.get("version") + effective_published_at = series_payload.get("published_at") + effective_as_of = series_payload.get("as_of") + snapshot_unavailable = bool(series_payload.get("snapshot_unavailable")) basis_suffix = ( f":as_known_then:{effective_cutoff}" if effective_basis == "as_known_then" and effective_cutoff else "" ) subject_key = f"compute:{','.join(countries)}:{mode}{basis_suffix}" + + if snapshot_unavailable: + notice = str( + series_payload.get("notice") + or "历史快照不完整:所选系统发布时间早于版本库基线时间,无法还原当时的系统台账。" + ) + brief_unavail = StrategicPostureBrief( + headline="历史快照不完整", + headline_en="Incomplete Historical Snapshot", + executive_assertion=notice, + executive_assertion_en=( + "Historical snapshot incomplete: requested system publish timestamp precedes the revision baseline." + ), + causes=[], + breakthrough_levers=[], + blind_spots=[notice], + evidence_ids=["snapshot_unavailable"], + ) + return { + "id": None, + "result_id": subject_key, + "subject_type": "compute_posture", + "subject_key": subject_key, + "input_fingerprint": "snapshot_unavailable", + "revision": 0, + "generation_mode": "deterministic_baseline", + "payload": brief_unavail.model_dump(mode="json"), + "evidence_ids": [], + "cache_hit": False, + "time_basis": effective_basis, + "cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None, + "publish_id": None, + "published_at": None, + "as_of": effective_as_of, + "snapshot_unavailable": True, + "notice": notice, + "usage": {}, + "evidence": {}, + } + fingerprint = compute_posture_fingerprint( countries, mode, @@ -410,6 +467,10 @@ async def generate_or_get_compute_posture( "cache_hit": True, "time_basis": effective_basis, "cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None, + "publish_id": (cached.audit_meta or {}).get("publish_id") or effective_publish_id, + "published_at": (cached.audit_meta or {}).get("published_at") or effective_published_at, + "as_of": effective_as_of, + "snapshot_unavailable": False, "usage": (cached.audit_meta or {}).get("llm_usage") or {}, "evidence": { eid: cached_evidence_map[eid] @@ -424,6 +485,9 @@ async def generate_or_get_compute_posture( frozen_series_snapshot = _freeze_json_snapshot(series_payload) audit_meta: dict[str, Any] = { "fingerprint": fingerprint, + "publish_id": effective_publish_id, + "published_at": effective_published_at, + "as_of": effective_as_of, "time_basis": effective_basis, "cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None, "countries": list(countries), @@ -510,6 +574,10 @@ async def generate_or_get_compute_posture( "cache_hit": True, "time_basis": effective_basis, "cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None, + "publish_id": (fallback_cached.audit_meta or {}).get("publish_id") or effective_publish_id, + "published_at": (fallback_cached.audit_meta or {}).get("published_at") or effective_published_at, + "as_of": effective_as_of, + "snapshot_unavailable": False, "usage": {}, "evidence": { eid: fallback_evidence_map[eid] @@ -557,6 +625,10 @@ async def generate_or_get_compute_posture( "cache_hit": False, "time_basis": effective_basis, "cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None, + "publish_id": effective_publish_id, + "published_at": effective_published_at, + "as_of": effective_as_of, + "snapshot_unavailable": False, "usage": llm_usage, "evidence": {eid: evidence_map[eid] for eid in valid_eids}, } @@ -580,6 +652,10 @@ async def generate_or_get_compute_posture( "cache_hit": False, "time_basis": effective_basis, "cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None, + "publish_id": effective_publish_id, + "published_at": effective_published_at, + "as_of": effective_as_of, + "snapshot_unavailable": False, "usage": llm_usage, "evidence": {eid: evidence_map[eid] for eid in valid_eids}, } diff --git a/backend/app/services/ai/presentation_compiler.py b/backend/app/services/ai/presentation_compiler.py index a298980e..9569c0f0 100644 --- a/backend/app/services/ai/presentation_compiler.py +++ b/backend/app/services/ai/presentation_compiler.py @@ -15,7 +15,6 @@ from app.models.situational_assessment import StagePresentation from app.services.ai.domain_catalog import SPATIAL_POSTURE_DOMAINS, SpatialDomain, WorkbenchDomain from app.services.ai.incident_agent import ( DRILL_INCIDENT_KEY, - HISTORICAL_INCIDENT_SAMPLE, investigate_infrastructure_incident, ) from app.services.ai.spatial_domain_agent import investigate_spatial_domain @@ -84,6 +83,7 @@ class StagePresentationContract(BaseModel): domain: WorkbenchDomain time_basis: TimeBasis cutoff_date: str | None = None + publish_id: str | None = None is_drill: bool = False title: str title_en: str @@ -515,13 +515,185 @@ def _wrap_ephemeral_contract(contract: StagePresentationContract, cursor: int, r } +_COUNTRY_CAMERA_ANCHORS: dict[str, tuple[float, float, float]] = { + "CN": (35.0, 105.0, 1.18), + "US": (39.0, -98.0, 1.12), + "JP": (36.2, 138.2, 1.25), + "DE": (51.1, 10.4, 1.25), + "GB": (54.0, -2.0, 1.25), + "FR": (46.6, 2.2, 1.25), + "KR": (36.5, 127.8, 1.28), + "IN": (21.5, 79.0, 1.18), +} + +_REVISION_METRIC_LABELS_EN: dict[str, str] = { + "global_share": "Global Compute Share", + "intelligent_share": "Global AI Compute Share", + "absolute": "Total Compute Capacity", + "frontier_cluster_share": "Frontier AI Cluster Share", + "chip_inflow_share": "AI Chip Inflow Share", +} + + +def compile_compute_revision_presentation( + *, + publish_id: str, + action: str, + series: dict[str, Any], + value_diffs: list[dict[str, Any]], + time_basis: TimeBasis = "retrospective", +) -> StagePresentationContract: + """Compile a revision-driven stage presentation notice from structured observation diffs.""" + from app.services.compute_revision_diff import COUNTRY_ZH_LABELS, METRIC_ZH_LABELS + + raw_evidence = series.get("evidence") or {} + evidence = dict(raw_evidence) + historical_diffs = [d for d in value_diffs if d.get("change_kind") == "historical_revision"] + has_historical = bool(historical_diffs) + primary = historical_diffs[0] if has_historical else value_diffs[0] + + metric = str(primary.get("metric") or "global_share") + year = int(primary.get("year") or 2024) + metric_zh = METRIC_ZH_LABELS.get(metric, metric) + metric_en = _REVISION_METRIC_LABELS_EN.get(metric, metric) + + spotlight_codes = list( + dict.fromkeys(str(d.get("code")) for d in value_diffs if d.get("code")) + ) or ["CN", "US"] + first_code = spotlight_codes[0] + cam_lat, cam_lon, cam_zoom = _COUNTRY_CAMERA_ANCHORS.get(first_code, (34.5, 110.0, 1.12)) + + change_lines_zh: list[str] = [] + change_lines_en: list[str] = [] + referenced_eids: list[str] = [] + for item in value_diffs[:4]: + code = str(item.get("code") or "") + c_zh = COUNTRY_ZH_LABELS.get(code, code) + item_metric = str(item.get("metric") or metric) + item_unit = " EFlops" if item_metric == "absolute" else "%" + item_delta_unit = " EFlops" if item_metric == "absolute" else "pp" + old_val = item.get("old_value") + new_val = item.get("new_value") + delta = float(item.get("delta") or 0.0) + if old_val is not None and new_val is not None: + change_lines_zh.append( + f"{c_zh} {old_val}{item_unit} → {new_val}{item_unit}({delta:+.2g}{item_delta_unit})" + ) + change_lines_en.append( + f"{code} {old_val}{item_unit} -> {new_val}{item_unit} ({delta:+.2g}{item_delta_unit})" + ) + elif new_val is not None: + change_lines_zh.append(f"{c_zh} 新增 {new_val}{item_unit}") + change_lines_en.append(f"{code} added {new_val}{item_unit}") + elif old_val is not None: + change_lines_zh.append(f"{c_zh} 移除(原 {old_val}{item_unit})") + change_lines_en.append(f"{code} removed (was {old_val}{item_unit})") + for src_key in ("new_source_id", "old_source_id"): + eid = item.get(src_key) + if eid and eid in evidence and eid not in referenced_eids: + referenced_eids.append(str(eid)) + if not referenced_eids: + referenced_eids = list(evidence.keys())[:2] + + changes_zh = ";".join(change_lines_zh) + changes_en = "; ".join(change_lines_en) + if has_historical: + title_zh = f"{year} 年{metric_zh}数据获修订" + title_en = f"{year} {metric_en} Data Revised" + caption_zh = f"{changes_zh}。这是对历史数据的修订,不代表当期算力跃升。" + caption_en = f"{changes_en}. This is a historical data revision, not a current-period jump." + elif action == "reset": + title_zh = f"{year} 年{metric_zh}已恢复内置版本" + title_en = f"{year} {metric_en} Restored to Bundled Baseline" + caption_zh = f"{changes_zh}。台账已恢复至内置权威报告基线。" + caption_en = f"{changes_en}. Ledger restored to bundled authoritative report baseline." + else: + title_zh = f"{year} 年{metric_zh}台账已更新" + title_en = f"{year} {metric_en} Ledger Updated" + caption_zh = f"{changes_zh}。" + caption_en = f"{changes_en}." + + steps = [ + StageStepSpec( + step_id="rev-act-1-notice", + stage="overview", + title=title_zh, + title_en=title_en, + caption=caption_zh, + caption_en=caption_en, + dwell_ms=6400, + camera=StageCameraPose(lat=cam_lat, lon=cam_lon, zoom=cam_zoom), + compute_mode=metric, + focus_year=year, + spotlight_Statistic_codes=spotlight_codes, + evidence_ids=referenced_eids, + ), + StageStepSpec( + step_id="rev-act-2-lineage", + stage="attribution", + title=f"版本 {publish_id[:8]} · 证据溯源与口径校验", + title_en=f"Revision {publish_id[:8]} · Evidence & Denominator Check", + caption=( + f"当前已生效版本 {publish_id[:8]},共更新 {len(value_diffs)} 项观测值(口径:{metric_zh},{year} 年)。" + "点击卡片数值旁溯源按钮可查看报告原文页码、复核记录与历史对比。" + ), + caption_en=( + f"Active revision {publish_id[:8]} updated {len(value_diffs)} observation value(s) " + f"({metric_en}, {year}). Inspect lineage from the compute card for full provenance." + ), + dwell_ms=5600, + camera=StageCameraPose(lat=cam_lat, lon=cam_lon, zoom=max(0.95, cam_zoom - 0.1)), + compute_mode=metric, + focus_year=year, + spotlight_Statistic_codes=spotlight_codes, + evidence_ids=referenced_eids, + ), + ] + + return StagePresentationContract( + presentation_key="compute-revision-notice", + domain="compute", + time_basis=time_basis, + publish_id=publish_id, + is_drill=False, + title=title_zh, + title_en=title_en, + summary=caption_zh, + summary_en=caption_en, + steps=steps, + evidence=evidence, + ) + + async def publish_stage_contract( db: AsyncSession, contract: StagePresentationContract, + *, + explicit_revision: int | None = None, ) -> StagePresentation | None: """Idempotently persist a `StagePresentation` ONLY on explicit write-side snapshot/config pipelines.""" if not hasattr(db, "execute") or not hasattr(db, "add") or not hasattr(db, "flush"): return None + if contract.publish_id: + existing_rows = ( + ( + await db.execute( + select(StagePresentation) + .where( + StagePresentation.presentation_key == contract.presentation_key, + StagePresentation.time_basis == contract.time_basis, + ) + .order_by(desc(StagePresentation.revision), desc(StagePresentation.id)) + .limit(50) + ) + ) + .scalars() + .all() + ) + for row in existing_rows: + if isinstance(row.contract, dict) and row.contract.get("publish_id") == contract.publish_id: + return row + new_fp = _contract_fingerprint(contract) existing = ( await db.execute( @@ -535,7 +707,9 @@ async def publish_stage_contract( ) ).scalar_one_or_none() - if isinstance(existing, StagePresentation) and existing.contract: + if explicit_revision is not None: + next_rev = int(explicit_revision) + elif isinstance(existing, StagePresentation) and existing.contract: old_fp = hashlib.sha256( json.dumps(existing.contract, sort_keys=True, ensure_ascii=False).encode("utf-8") ).hexdigest() diff --git a/backend/app/services/ai/proactive_pipeline.py b/backend/app/services/ai/proactive_pipeline.py index ace703ed..e0b9c867 100644 --- a/backend/app/services/ai/proactive_pipeline.py +++ b/backend/app/services/ai/proactive_pipeline.py @@ -10,6 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.core.logging import get_logger from app.models.bgp_incident import BGPIncident +from app.models.compute_configuration_revision import ComputeConfigurationRevision from app.models.situational_assessment import ( SituationalAssessment, StagePresentation, @@ -19,7 +20,7 @@ from app.models.situational_assessment import ( from app.services.ai.incident_agent import DRILL_INCIDENT_KEY, investigate_infrastructure_incident from app.services.ai.posture_agent import generate_or_get_compute_posture from app.services.ai.presentation_compiler import ( - compile_compute_posture_presentation, + compile_compute_revision_presentation, compile_incident_five_act_presentation, publish_stage_contract, ) @@ -29,7 +30,6 @@ from app.services.ai.tool_registry import query_compute_posture_tool logger = get_logger(__name__, service="ai_proactive") _BGP_STATE_KEY = "situational_bgp_snapshot_state" -_COMPUTE_STATE_KEY = "situational_compute_snapshot_state" async def _load_state_setting(db: AsyncSession, key: str) -> tuple[SituationalAssessment | None, dict[str, Any] | None]: @@ -280,80 +280,227 @@ async def process_bgp_snapshot_proactive_delta( } +async def process_compute_revision_presentation( + db: AsyncSession, + revision_id: int, + *, + countries: list[str] | None = None, +) -> dict[str, Any]: + """Emit an idempotent StagePresentation driven directly by one `ComputeConfigurationRevision`.""" + row = ( + await db.execute( + select(ComputeConfigurationRevision).where( + ComputeConfigurationRevision.id == revision_id + ) + ) + ).scalar_one_or_none() + if not isinstance(row, ComputeConfigurationRevision): + return { + "domain": "compute", + "status": "not_found", + "revision_id": revision_id, + "emitted_presentations": [], + "triggered_watches": [], + } + + if row.presentation_status in {"delivered", "skipped"}: + return { + "domain": "compute", + "status": row.presentation_status, + "publish_id": row.publish_id, + "revision_id": row.id, + "idempotent": True, + "emitted_presentations": [], + "triggered_watches": [], + } + + value_diffs = [ + item + for item in (row.diff_summary or []) + if item.get("kind") == "observation_value" + and item.get("delta") is not None + and float(item["delta"]) != 0.0 + ] + if not value_diffs: + row.presentation_status = "skipped" + row.presentation_error = "" + await db.flush() + return { + "domain": "compute", + "status": "skipped", + "publish_id": row.publish_id, + "revision_id": row.id, + "emitted_presentations": [], + "triggered_watches": [], + } + + historical = [d for d in value_diffs if d.get("change_kind") == "historical_revision"] + primary = historical[0] if historical else value_diffs[0] + primary_mode = str(primary.get("metric") or "global_share") + changed_codes = [str(d["code"]) for d in value_diffs if d.get("code")] + codes = list(dict.fromkeys([*(countries or ["CN", "US"]), *changed_codes])) + + series = await query_compute_posture_tool( + db, codes, mode=primary_mode, publish_id=row.publish_id + ) + posture = await generate_or_get_compute_posture( + db, + countries=codes, + mode=primary_mode, + series_payload=series, + persist=True, + ) + + existing_stage_rows = ( + ( + await db.execute( + select(StagePresentation) + .where( + StagePresentation.presentation_key == "compute-revision-notice", + StagePresentation.time_basis == "retrospective", + ) + .order_by(desc(StagePresentation.id)) + .limit(50) + ) + ) + .scalars() + .all() + ) + existing_for_publish = next( + ( + st + for st in existing_stage_rows + if isinstance(st.contract, dict) and st.contract.get("publish_id") == row.publish_id + ), + None, + ) + + if existing_for_publish is not None: + published = existing_for_publish + else: + contract = compile_compute_revision_presentation( + publish_id=row.publish_id, + action=row.action, + series=series, + value_diffs=value_diffs, + time_basis="retrospective", + ) + published = await publish_stage_contract(db, contract, explicit_revision=int(row.id)) + + row.presentation_status = "delivered" + row.presentation_attempts = int(row.presentation_attempts or 0) + 1 + row.presentation_error = "" + row.presentation_delivered_at = datetime.now(UTC) + await db.flush() + + triggered_watches = await _evaluate_topic_watches( + db, + domain="compute", + target_keys=[posture["subject_key"]], + revision=int(row.id), + ) + return { + "domain": "compute", + "status": "delivered", + "publish_id": row.publish_id, + "revision_id": row.id, + "emitted_presentations": [published.to_dict()] if published is not None else [], + "triggered_watches": triggered_watches, + } + + +async def retry_pending_compute_presentations( + db: AsyncSession, + *, + max_attempts: int = 3, +) -> dict[str, Any]: + """Retry pending or failed compute revision presentations in ascending revision order.""" + if not hasattr(db, "execute"): + return {"domain": "compute", "processed": 0, "delivered": 0, "skipped": 0, "failed": 0, "results": []} + + rows = ( + ( + await db.execute( + select(ComputeConfigurationRevision) + .where( + ComputeConfigurationRevision.presentation_status.in_(["pending", "failed"]), + ComputeConfigurationRevision.presentation_attempts < max_attempts, + ) + .order_by(ComputeConfigurationRevision.id.asc()) + .limit(20) + ) + ) + .scalars() + .all() + ) + delivered = 0 + skipped = 0 + failed = 0 + results: list[dict[str, Any]] = [] + for row in rows: + try: + res = await process_compute_revision_presentation(db, row.id) + results.append(res) + if res.get("status") == "delivered": + delivered += 1 + elif res.get("status") == "skipped": + skipped += 1 + except Exception as exc: + failed += 1 + row.presentation_status = "failed" + row.presentation_attempts = int(row.presentation_attempts or 0) + 1 + row.presentation_error = str(exc)[:1000] + await db.flush() + logger.warning_event( + "Compute revision presentation retry failed", + event="compute.revision.presentation_failed", + context={ + "revision_id": row.id, + "publish_id": row.publish_id, + "attempts": row.presentation_attempts, + "error": str(exc), + }, + ) + results.append( + { + "domain": "compute", + "status": "failed", + "publish_id": row.publish_id, + "revision_id": row.id, + "error": str(exc), + } + ) + return { + "domain": "compute", + "processed": len(rows), + "delivered": delivered, + "skipped": skipped, + "failed": failed, + "results": results, + } + + async def process_compute_config_proactive_delta( db: AsyncSession, *, countries: list[str] | None = None, + publish_id: str | None = None, ) -> dict[str, Any]: - """Evaluate a newly published compute configuration and emit idempotent stage & watch updates.""" - codes = countries or ["CN", "US"] - setting_row, prev_state = await _load_state_setting(db, _COMPUTE_STATE_KEY) - prev_snapshot = prev_state.get("snapshot") if prev_state else None - seen_fps: set[str] = set(prev_state.get("seen_fingerprints") or []) if prev_state else set() - - series = await query_compute_posture_tool(db, codes, mode="global_share") - rpi = series.get("bilateral_rpi") or {} - tot = rpi.get("latest_total") or {} - intel = rpi.get("latest_intelligent") or {} - - curr_snapshot: dict[str, Any] = { - "status": "success", - "completed_at": datetime.now(UTC).isoformat(), - "record_count": len(series.get("evidence") or {}) or 1, - "active_keys": [f"config:{series.get('version')}"], - "metrics": { - "cn_total_share": float(tot.get("cn_value") or 0.0), - "us_total_share": float(tot.get("us_value") or 0.0), - "cn_intel_share": float(intel.get("cn_value") or 0.0), - }, - } - curr_snapshot["fingerprint"] = snapshot_fingerprint(curr_snapshot) - - delta = classify_snapshot_delta( - prev_snapshot, - curr_snapshot, - seen_fingerprints=seen_fps, - ) - - emitted: list[dict[str, Any]] = [] - triggered_watches: list[dict[str, Any]] = [] - - if delta["emit_event"]: - posture = await generate_or_get_compute_posture( - db, - countries=codes, - mode="global_share", - series_payload=series, - persist=True, - ) - for tb in ("live", "retrospective"): - contract = compile_compute_posture_presentation(series, time_basis=tb) - published = await publish_stage_contract(db, contract) - if published is not None and tb == "retrospective": - emitted.append(published.to_dict()) - triggered_watches = await _evaluate_topic_watches( - db, - domain="compute", - target_keys=[posture["subject_key"]], - revision=int(posture.get("revision") or 1), - ) - - await _save_state_setting( - db, - setting_row, - _COMPUTE_STATE_KEY, - { - "snapshot": curr_snapshot, - "seen_fingerprints": sorted(seen_fps)[-32:], - "last_verdict": delta["verdict"], - }, - ) - return { - "domain": "compute", - "delta": delta, - "emitted_presentations": emitted, - "triggered_watches": triggered_watches, - } + """Compatibility wrapper delegating to `process_compute_revision_presentation` for the target/latest revision.""" + stmt = select(ComputeConfigurationRevision) + if publish_id: + stmt = stmt.where(ComputeConfigurationRevision.publish_id == publish_id) + else: + stmt = stmt.order_by(desc(ComputeConfigurationRevision.id)) + row = (await db.execute(stmt.limit(1))).scalar_one_or_none() + if not isinstance(row, ComputeConfigurationRevision): + return { + "domain": "compute", + "status": "skipped", + "emitted_presentations": [], + "triggered_watches": [], + } + return await process_compute_revision_presentation(db, row.id, countries=countries) async def audit_situational_hygiene(db: AsyncSession) -> dict[str, Any]: diff --git a/backend/app/services/ai/semantic_delta.py b/backend/app/services/ai/semantic_delta.py index 78f120dc..9307810e 100644 --- a/backend/app/services/ai/semantic_delta.py +++ b/backend/app/services/ai/semantic_delta.py @@ -174,7 +174,31 @@ def classify_snapshot_delta( _SHARE_PATTERN = re.compile( r"(?P美国|中国|日本)\s*(?:全球)?(?P智能算力|总算力|算力)份额[^\d]{0,10}(?P\d{1,2}(?:\.\d+)?)\s*%" ) -_COUNTRY_MAP = {"美国": "US", "中国": "CN", "日本": "JP"} +_CHIP_INFLOW_ZH_PATTERN = re.compile( + r"(?P美国|中国|日本)\s*(?:高端)?(?:AI)?(?:算力)?芯片(?:新增)?流向(?:算力)?份额[^\d]{0,12}(?P\d{1,2}(?:\.\d+)?)\s*%" +) +_CHIP_INFLOW_CONTEXT_RE = re.compile( + r"\b(?:h100e?|h20|ai\s+chip|chip\s+import|chip\s+inflow|world\s+arrivals|cumulative\s+world\s+arrivals)\b", + re.IGNORECASE, +) +_CHIP_INFLOW_EN_TO_PATTERN = re.compile( + r"\b(?PUnited States|U\.S\.|US|China|Japan)(?:['’]s|['’])?\s+share\b[^,;]{0,90}?\bto\s+(?P\d{1,2}(?:\.\d+)?)\s*%", + re.IGNORECASE, +) +_CHIP_INFLOW_EN_RECEIVED_PATTERN = re.compile( + r"\b(?PUnited States|U\.S\.|US|China|Japan)\s+(?:received|accounted for|captured)\s+(?:about\s+|approximately\s+|roughly\s+)?(?P\d{1,2}(?:\.\d+)?)\s*%\s+of\s+(?:that\s+|global\s+|world\s+)?(?:compute|arrivals|inflow)", + re.IGNORECASE, +) +_COUNTRY_MAP = { + "美国": "US", + "中国": "CN", + "日本": "JP", + "united states": "US", + "u.s.": "US", + "us": "US", + "china": "CN", + "japan": "JP", +} def extract_compute_candidates_deterministic( @@ -182,10 +206,12 @@ def extract_compute_candidates_deterministic( *, year: int, source_meta: dict[str, Any], + period_label: str | None = None, ) -> list[dict[str, Any]]: """Deterministic extractor fallback producing reviewable `ComputeEvidenceCandidate` dicts.""" + text = excerpt or "" by_metric: dict[str, dict[str, float]] = {} - for match in _SHARE_PATTERN.finditer(excerpt or ""): + for match in _SHARE_PATTERN.finditer(text): code = _COUNTRY_MAP.get(match.group("country")) if not code: continue @@ -194,19 +220,41 @@ def extract_compute_candidates_deterministic( if 0 <= value <= 100: by_metric.setdefault(metric_key, {})[code] = value + for match in _CHIP_INFLOW_ZH_PATTERN.finditer(text): + code = _COUNTRY_MAP.get(match.group("country")) + if not code: + continue + value = float(match.group("value")) + if 0 <= value <= 100: + by_metric.setdefault("chip_inflow_share", {})[code] = value + + if _CHIP_INFLOW_CONTEXT_RE.search(text): + for pattern in (_CHIP_INFLOW_EN_TO_PATTERN, _CHIP_INFLOW_EN_RECEIVED_PATTERN): + for match in pattern.finditer(text): + code = _COUNTRY_MAP.get(match.group("country").lower()) + if not code: + continue + value = float(match.group("value")) + if 0 <= value <= 100 and code not in by_metric.get("chip_inflow_share", {}): + by_metric.setdefault("chip_inflow_share", {})[code] = value + + clean_period = (period_label or "").strip() or None candidates: list[dict[str, Any]] = [] for metric_key, values in by_metric.items(): if sum(values.values()) > 100.0: continue + proposed: dict[str, Any] = { + "year": year, + "metric": metric_key, + "source_id": source_meta.get("id") or f"candidate-src-{year}", + "values": values, + } + if clean_period is not None: + proposed["period_label"] = clean_period candidates.append( { "candidate_type": "observation", - "proposed_payload": { - "year": year, - "metric": metric_key, - "source_id": source_meta.get("id") or f"candidate-src-{year}", - "values": values, - }, + "proposed_payload": proposed, "source_payload": source_meta, "confidence": 0.86, "extractor_note": f"从报告摘录自动提取 {year} 年 {metric_key} 候选值,待管理员人工核验后入库。", diff --git a/backend/app/services/ai/stream_turn.py b/backend/app/services/ai/stream_turn.py index bbaadab2..8e49433a 100644 --- a/backend/app/services/ai/stream_turn.py +++ b/backend/app/services/ai/stream_turn.py @@ -47,6 +47,10 @@ from app.services.ai.workflow_runtime import ( unregister_active_run_handle, ) from app.services.ai_client import AIProviderClient +from app.services.compute_lineage import ( + build_revision_change_context, + is_revision_question, +) logger = get_logger(__name__, service="ai_stream") @@ -237,13 +241,19 @@ def _build_telemetry_stream_request( conversation_summary: str = "", memory_notes: list[str] | None = None, pinned_summaries: list[str] | None = None, + revision_context: dict[str, Any] | None = None, ) -> SituationalAnalysisRequest: context: dict[str, Any] = { "domain": domain, "verified_baseline_summary": base_answer_md, "evidence": evidence, "view_headline": (view_spec or {}).get("headline"), + "publish_id": (view_spec or {}).get("publish_id"), + "mode": (view_spec or {}).get("mode"), + "focus_year": (view_spec or {}).get("focus_year"), } + if revision_context: + context["revision_context"] = revision_context if recent_news and recent_news.get("items"): context["recent_news_headlines"] = (recent_news.get("items") or [])[:10] if conversation_summary: @@ -308,6 +318,10 @@ async def stream_session_turn( for k, v in context_override.items(): if v is not None: merged_ctx[k] = v + if context_override.get("publish_id") and not context_override.get("as_of"): + merged_ctx["as_of"] = None + elif context_override.get("as_of") and not context_override.get("publish_id"): + merged_ctx["publish_id"] = None raw_history = history if history else merged_ctx.get("recent_messages") existing_summary = str( @@ -338,6 +352,8 @@ async def stream_session_turn( time_basis: TimeBasis = (context_override or {}).get("time_basis") or merged_ctx.get("time_basis") or "retrospective" cutoff_at: str | None = (context_override or {}).get("cutoff_at") or merged_ctx.get("cutoff_at") + publish_id: str | None = merged_ctx.get("publish_id") + as_of: str | None = merged_ctx.get("as_of") codes = list((context_override or {}).get("selected_codes") or merged_ctx.get("selected_codes") or ["CN", "US"]) visible_layers = dict((context_override or {}).get("visible_layers") or merged_ctx.get("visible_layers") or {}) @@ -401,6 +417,8 @@ async def stream_session_turn( "visible_layers": visible_layers, "time_basis": time_basis, "cutoff_at": cutoff_at, + "publish_id": publish_id, + "as_of": as_of, } if news_context: wf_earth_ctx["news_context"] = news_context @@ -679,6 +697,13 @@ async def stream_session_turn( current_max = int((getattr(ai_client, "llm_config", None) or {}).get("max_tokens") or 0) if type(ai_client) is AIProviderClient and ai_client.llm_config and current_max < 3200: effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=3200) + revision_context: dict[str, Any] | None = None + if domain == "compute" and is_revision_question(question): + revision_context = await build_revision_change_context( + db, + publish_id=(view_spec or {}).get("publish_id") or publish_id, + redact=(getattr(access, "tier", "public_zero_cost") != "admin"), + ) analysis_req = ( _build_news_analysis_request( question=question, @@ -710,6 +735,7 @@ async def stream_session_turn( conversation_summary=compacted_summary, memory_notes=clean_memory_notes, pinned_summaries=clean_pinned_summaries, + revision_context=revision_context, ) ) diff --git a/backend/app/services/ai/tool_registry.py b/backend/app/services/ai/tool_registry.py index c3b42945..1837f337 100644 --- a/backend/app/services/ai/tool_registry.py +++ b/backend/app/services/ai/tool_registry.py @@ -2,7 +2,7 @@ from __future__ import annotations -from datetime import UTC, datetime +from datetime import UTC, date, datetime import hashlib import ipaddress import socket @@ -18,7 +18,7 @@ from app.core.logging import get_logger from app.models.bgp_incident import BGPIncident from app.models.collected_data import CollectedData from app.models.earth_news import EarthNewsItem -from app.schemas.compute_configuration import ComputeConfiguration +from app.schemas.compute_configuration import ComputeConfiguration, ComputeObservation, source_for from app.services.ai_tools.schemas import FetchedEvidence from app.services.compute_configuration import read_configuration from app.services.compute_history import compute_history @@ -210,10 +210,42 @@ def filter_compute_config_by_cutoff( kept_sources.append(src) kept_source_ids = {s.id for s in kept_sources} - kept_obs = [ - obs for obs in config.observations - if obs.year <= cutoff_year and obs.source_id in kept_source_ids - ] + kept_obs: list[ComputeObservation] = [] + for obs in config.observations: + if obs.year > cutoff_year: + continue + surviving_values = { + code: val + for code, val in obs.values.items() + if source_for(obs, code) in kept_source_ids + } + if not surviving_values: + continue + per_code_sources = {code: source_for(obs, code) for code in surviving_values} + row_src = ( + obs.source_id + if obs.source_id in kept_source_ids + else next(iter(per_code_sources.values())) + ) + unique_sources = list(dict.fromkeys(per_code_sources.values())) + if len(unique_sources) == 1: + row_src = unique_sources[0] + cleaned_vs = None + else: + cleaned_vs = { + code: src_id + for code, src_id in per_code_sources.items() + if src_id != row_src + } or None + kept_obs.append( + obs.model_copy( + update={ + "source_id": row_src, + "values": surviving_values, + "value_sources": cleaned_vs, + } + ) + ) kept_innov = [ inn for inn in config.innovation if inn.year <= cutoff_year and inn.source_id in kept_source_ids @@ -259,9 +291,28 @@ async def query_compute_posture_tool( *, time_basis: TimeBasis = "retrospective", cutoff_at: str | None = None, + as_of: str | None = None, + publish_id: str | None = None, ) -> dict[str, Any]: """Read-only tool returning deterministic multi-metric compute series and provenance.""" - envelope = await read_configuration(db) + envelope = await read_configuration(db, as_of=as_of, publish_id=publish_id) + if envelope.get("snapshot_unavailable"): + empty_config = ComputeConfiguration( + reviewed_at=date.today(), sources=[], observations=[], innovation=[] + ) + result = compute_history(countries, mode, empty_config) + result["version"] = None + result["publish_id"] = None + result["published_at"] = None + result["as_of"] = envelope.get("as_of") + result["snapshot_unavailable"] = True + result["notice"] = envelope.get("notice") + result["is_default"] = False + result["time_basis"] = time_basis + result["cutoff_at"] = cutoff_at if time_basis == "as_known_then" else None + result["withheld_source_ids"] = [] + return result + raw_config = ComputeConfiguration.model_validate(envelope["config"]) effective_config, withheld_sources = filter_compute_config_by_cutoff( raw_config, time_basis=time_basis, cutoff_at=cutoff_at @@ -278,7 +329,12 @@ async def query_compute_posture_tool( result["innovation"] = [ r for r in (result.get("innovation") or []) if int(r.get("year") or 0) <= cutoff_year ] - result["version"] = envelope["revision"] + effective_pid = envelope.get("publish_id") or envelope["revision"] + result["version"] = effective_pid + result["publish_id"] = effective_pid + result["published_at"] = envelope.get("published_at") + result["as_of"] = envelope.get("as_of") + result["snapshot_unavailable"] = False result["is_default"] = envelope["is_default"] result["time_basis"] = time_basis result["cutoff_at"] = cutoff_at if time_basis == "as_known_then" else None @@ -890,6 +946,119 @@ async def query_vessel_posture_tool( } +async def query_cloud_posture_tool( + db: AsyncSession, + *, + time_basis: TimeBasis = "live", + cutoff_at: str | None = None, + correlate_domain: str | None = None, + latitude: float | None = None, + longitude: float | None = None, +) -> dict[str, Any]: + """Read-only meteorological cloud cover, convective cluster, and asset correlation summary.""" + from app.services.earth_clouds import ( + correlate_cloud_with_assets, + get_cloud_analysis_summary, + query_cloud_point, + ) + + summary = await get_cloud_analysis_summary(db) + point_info = None + if isinstance(latitude, (int, float)) and isinstance(longitude, (int, float)): + point_info = await query_cloud_point(float(latitude), float(longitude), db=db) + + correlation = None + if correlate_domain and hasattr(db, "execute"): + try: + correlation = await correlate_cloud_with_assets( + db, domain=correlate_domain, min_density=55.0, limit=12 + ) + except Exception: + correlation = None + + ev_id = "ev-cloud-1" + return { + "domain": "cloud", + "available": bool(summary.get("available")), + "mode": summary.get("mode"), + "degraded": summary.get("degraded"), + "version": summary.get("version"), + "captured_at": summary.get("captured_at"), + "source": summary.get("source"), + "satellites": summary.get("satellites") or [], + "global_summary": summary.get("global_summary") or {}, + "regions": summary.get("regions") or [], + "convective_clusters": (summary.get("convective_clusters") or [])[:12], + "point_query": point_info, + "asset_correlation": correlation, + "time_basis": time_basis, + "cutoff_at": cutoff_at if time_basis == "as_known_then" else None, + "evidence": { + ev_id: { + "id": ev_id, + "title": "Planet 全球静止气象卫星实时红外云图与强对流分析(global_cloud_map)", + "publisher": "NASA GIBS / EUMETSAT / Planet Earth Cloud Analytics", + "url": "/api/v1/data-products/clouds/summary", + "published_at": str(summary.get("captured_at") or datetime.now(UTC).date().isoformat()), + "locator": f"builtin:cloud:{summary.get('version') or 'static'}", + } + }, + "limitations": ( + [] + if summary.get("available") + else ["尚未采集实时卫星云图快照,当前无可分析的实时云量栅格。"] + ), + } + + +async def query_wind_posture_tool( + db: AsyncSession, + *, + time_basis: TimeBasis = "live", + cutoff_at: str | None = None, + latitude: float | None = None, + longitude: float | None = None, +) -> dict[str, Any]: + """Read-only NOAA GFS 10m global wind velocity, gale zones, and point vector summary.""" + from app.services.earth_wind import get_wind_analysis_summary, query_wind_point + + summary = await get_wind_analysis_summary(db) + point_info = None + if isinstance(latitude, (int, float)) and isinstance(longitude, (int, float)): + point_info = await query_wind_point(float(latitude), float(longitude), db=db) + + ev_id = "ev-wind-1" + return { + "domain": "wind", + "available": bool(summary.get("available")), + "is_active": bool(summary.get("is_active")), + "version": summary.get("version"), + "captured_at": summary.get("captured_at"), + "forecast_time": summary.get("forecast_time"), + "global_summary": summary.get("global_summary") or {}, + "regions": summary.get("regions") or [], + "storm_cores": (summary.get("storm_cores") or [])[:12], + "point_query": point_info, + "time_basis": time_basis, + "cutoff_at": cutoff_at if time_basis == "as_known_then" else None, + "evidence": { + ev_id: { + "id": ev_id, + "title": "NOAA GFS 全球 10m 海表风场与大风核分析(global_wind_gfs)", + "publisher": "NOAA NCEP / PacIOOS ERDDAP", + "url": "/api/v1/data-products/wind/summary", + "published_at": str(summary.get("forecast_time") or summary.get("captured_at") or datetime.now(UTC).date().isoformat()), + "locator": f"builtin:wind:{summary.get('version') or 'static'}", + } + }, + "limitations": ( + [] + if summary.get("available") + else ["尚未采集全球 10m 风场快照,当前无可分析的 GFS 风速网格。"] + ), + } + + async def query_global_situational_tool( db: AsyncSession, *, @@ -926,6 +1095,7 @@ async def query_global_situational_tool( cable_data = await query_cable_posture_tool(db, time_basis=time_basis, cutoff_at=cutoff_at) sat_data = await query_satellite_posture_tool(db, time_basis=time_basis, cutoff_at=cutoff_at) vessel_data = await query_vessel_posture_tool(db, time_basis=time_basis, cutoff_at=cutoff_at) + cloud_data = await query_cloud_posture_tool(db, time_basis=time_basis, cutoff_at=cutoff_at) vis = dict(visible_layers or {}) active_bgp = [it for it in bgp_items if str(it.get("status") or "").lower() == "active"] @@ -943,7 +1113,7 @@ async def query_global_situational_tool( "locator": f"builtin:global:codes={','.join(codes)}:basis={time_basis}", } } - for sub in (compute_data, cable_data, sat_data, vessel_data): + for sub in (compute_data, cable_data, sat_data, vessel_data, cloud_data): for k, v in (sub.get("evidence") or {}).items(): if k not in evidence and len(evidence) < 12: evidence[k] = v @@ -994,6 +1164,20 @@ async def query_global_situational_tool( "metric_text": f"{len(bgp_items)} 条(活跃 {len(active_bgp)})", "status": "incident_active" if active_bgp else ("telemetry_online" if bgp_items else "quiet"), }, + { + "domain": "cloud", + "label": "气象云图", + "layer_visible": bool(vis.get("clouds", True)), + "count": int((cloud_data.get("global_summary") or {}).get("convective_cluster_count") or 0), + "secondary_count": round(float((cloud_data.get("global_summary") or {}).get("global_cloud_cover_pct") or 0.0), 1), + "metric_text": ( + f"全球云量 {(cloud_data.get('global_summary') or {}).get('global_cloud_cover_pct', 0)}% · " + f"强对流 {(cloud_data.get('global_summary') or {}).get('convective_cluster_count', 0)} 个" + if cloud_data.get("available") + else "未采集实时云图" + ), + "status": "telemetry_online" if cloud_data.get("available") else "standby_or_empty", + }, ] limitations: list[str] = [] @@ -1031,6 +1215,13 @@ async def query_global_situational_tool( "underway": vessel_data.get("underway", 0), "by_type": vessel_data.get("by_type") or {}, }, + "cloud_summary": { + "available": cloud_data.get("available", False), + "captured_at": cloud_data.get("captured_at"), + "global_cloud_cover_pct": (cloud_data.get("global_summary") or {}).get("global_cloud_cover_pct"), + "convective_cluster_count": (cloud_data.get("global_summary") or {}).get("convective_cluster_count", 0), + "top_clusters": (cloud_data.get("convective_clusters") or [])[:3], + }, "time_basis": time_basis, "cutoff_at": cutoff_at if time_basis == "as_known_then" else None, "evidence": evidence, diff --git a/backend/app/services/ai/workflow_evolver.py b/backend/app/services/ai/workflow_evolver.py index 114d0a39..7cd414c5 100644 --- a/backend/app/services/ai/workflow_evolver.py +++ b/backend/app/services/ai/workflow_evolver.py @@ -1286,10 +1286,27 @@ def _deterministic_business_patches( bad_runs: list[dict[str, Any]], ) -> tuple[str, list[dict[str, Any]]]: nodes = [n for n in (base_graph.get("nodes") or []) if isinstance(n, dict)] - llm_node = next((n for n in nodes if n.get("node_type") in {"llm_agent", "tool_agent"}), None) - if llm_node is None: + llm_nodes = [n for n in nodes if n.get("node_type") in {"llm_agent", "tool_agent"}] + if not llm_nodes: return "当前工作流无可扩展推理节点。", [] + llm_node = llm_nodes[0] + if bad_runs: + failed_node_counts: dict[str, int] = {} + for br in bad_runs: + traces = (br.get("budget_used") or {}).get("node_traces") if isinstance(br.get("budget_used"), dict) else None + if not isinstance(traces, list): + continue + for item in traces: + if not isinstance(item, dict): + continue + nid = str(item.get("node_id") or "") + if item.get("status") in {"completed", "failed"} and any(n.get("id") == nid for n in llm_nodes): + failed_node_counts[nid] = failed_node_counts.get(nid, 0) + 1 + if failed_node_counts: + top_nid = max(failed_node_counts, key=lambda k: failed_node_counts[k]) + llm_node = next((n for n in llm_nodes if n.get("id") == top_nid), llm_node) + patches: list[dict[str, Any]] = [] if mode == "model_adapt": profile = health.get("active_model_profile") or {} @@ -1909,15 +1926,18 @@ async def _run_graph_single_sample( nodes_done: list[str] = [] verification: dict[str, Any] = {} evidence_count = 0 + targets = earth_context.get("targets") if isinstance(earth_context.get("targets"), list) else None + allow_external = bool(earth_context.get("allow_external_tools", False)) try: async for ev in run_workflow_dag_stream( db=db, workflow=test_wf, question=question, use_draft=True, + targets=targets, earth_context=earth_context, ai_client=ai_client, - allow_external_tools=False, + allow_external_tools=allow_external, ): ev_name = str(ev.get("event") or "") ev_data = ev.get("data") if isinstance(ev.get("data"), dict) else {} diff --git a/backend/app/services/ai/workflow_registry.py b/backend/app/services/ai/workflow_registry.py index a791bfc4..422f8dd2 100644 --- a/backend/app/services/ai/workflow_registry.py +++ b/backend/app/services/ai/workflow_registry.py @@ -19,6 +19,10 @@ from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevi from app.models.situational_assessment import WorkflowRun from app.schemas.ai import SituationalAnalysisRequest from app.services.ai.thinking_sanitizer import strip_thinking_text +from app.services.location.workflow_tools import ( + LOCATION_JUDGE_FINAL_SCHEMA, + LOCATION_JUDGE_R1_SCHEMA, +) logger = get_logger(__name__, service="ai_workflow_registry") @@ -65,6 +69,20 @@ TOOL_CATALOG: list[dict[str, Any]] = [ "category": "internal_read", "description": "查询航运密度、关键海峡通道船只态势。", }, + { + "id": "query_cloud_posture", + "name": "全球实时红外云图与强对流分析", + "name_en": "Live Satellite Cloud & Convection Analytics", + "category": "internal_read", + "description": "读取全球与重点航运/算力区域云量、强对流云团与云顶亮温数据。", + }, + { + "id": "query_wind_posture", + "name": "全球 10m 风场与大风区态势", + "name_en": "Global 10m Wind Field & Gale Analytics", + "category": "internal_read", + "description": "读取 NOAA GFS 全球 10m 风速、风向、大风核心区域与重点航道风场态势。", + }, { "id": "query_recent_earth_news", "name": "Earth 近期新闻动态", @@ -133,7 +151,42 @@ TOOL_CATALOG: list[dict[str, Any]] = [ "name": "位置结果强约束提交", "name_en": "Constrained Location Submit", "category": "location_guardrail", - "description": "通过 Schema 工具提交定位结论或 undisclosed/multi_site 终态。", + "description": "兼容旧版工具式位置提交定义。", + }, + { + "id": "location_normalize_context", + "name": "L0 位置上下文归一化与终态检查", + "name_en": "L0 Location Normalize & Terminal Check", + "category": "location_knowledge", + "description": "水合数据库与跨源线索、统一英文国名,并在已确认终态时短路。", + }, + { + "id": "location_knowledge_lookup", + "name": "L1 确定性设施知识库查询", + "name_en": "L1 Facility Knowledge Lookup", + "category": "location_knowledge", + "description": "串并行组合查询 builds_upon、ROR、Wikidata(P17) 与 PeeringDB(/api/fac)。", + }, + { + "id": "location_web_research", + "name": "L2 并行网页取证与证据编号", + "name_en": "L2 Parallel Web Research", + "category": "external_evidence", + "description": "按轮次并行抓取一手正文并执行结构化英文 WebSearch,为证据编号 E1..En。", + }, + { + "id": "location_geocode_verify", + "name": "L3 多粒度级联地理编码校验", + "name_en": "L3 Cascade Geocoder Verify", + "category": "location_guardrail", + "description": "按 街道地址 -> 设施名 -> 城市+省州 -> 城市 级联查 Nominatim 并校验国家与粒度。", + }, + { + "id": "location_persist_outcome", + "name": "L4 位置结果输出与终态持久化", + "name_en": "L4 Location Output & Persist", + "category": "location_guardrail", + "description": "输出标准候选坐标载荷与地球联动视角,或在有实证时落库不可定位终态。", }, ] @@ -145,10 +198,17 @@ VALID_NODE_TYPES: frozenset[str] = frozenset( {"trigger", "deterministic", "llm_agent", "guardrail", "output"} ) VALID_EDGE_CONDITIONS: frozenset[str] = frozenset( - {"always", "on_empty_or_low_confidence", "on_entity_type"} + { + "always", + "on_empty_or_low_confidence", + "on_entity_type", + "on_field_equals", + "on_guardrail_passed", + "on_guardrail_failed", + } ) PRESERVED_BUILTIN_EDGE_CONDITIONS: frozenset[str] = frozenset( - {"not_terminal", "high_confidence_hit", "fallback_to_agent", "ingest", "interactive"} + {"not_terminal", "on_terminal", "high_confidence_hit", "fallback_to_agent", "ingest", "interactive"} ) ALLOWED_EDGE_CONDITIONS: frozenset[str] = VALID_EDGE_CONDITIONS | PRESERVED_BUILTIN_EDGE_CONDITIONS @@ -428,8 +488,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "name": "算力/设施未知位置定位工作流", "name_en": "Compute & Facility Location Agent", "category": "location", - "description": "整合 builds_upon 继承、Wikidata、PeeringDB、可控 Tool-Calling 取证与地理编码硬校验的完整定位管线。", - "description_en": "Tiered facility geolocation combining builds_upon, Wikidata, PeeringDB, controlled tool-calling evidence, and geocoder verification.", + "description": "真正的条件路由 DAG 工作流:L0 归一化与终态短路 → L1 知识库 → 两轮并行联网取证与单轮结构化研判 → 级联地理编码与 3 条硬护栏。", + "description_en": "True conditional DAG workflow: L0 normalize -> L1 knowledge lookup -> 2-round parallel web research & JSON judgment -> cascade geocoder & 3 hard guardrails.", "is_default": False, "bindings": { "enabled": True, @@ -444,12 +504,13 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "nodes": [ _node( "l0_normalize", - "trigger", - "L0:实体归一化与终态短路", + "deterministic", + "L0:实体归一化与终态检查", "L0: Normalize & Terminal Check", 40, - 160, - description="切分 name_short、注入 Epoch Source 1..5/TOP500 一手链接与 builds_upon,若已标记 undisclosed/multi_site 则直接短路。", + 180, + description="水合数据库与跨源兄弟线索、转换英文国家名、过滤 .csv 原始表并在已确认终态时直接短路。", + tools=["location_normalize_context"], params={"short_circuit_terminal_statuses": True}, ), _node( @@ -457,55 +518,138 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "deterministic", "L1:确定性设施知识库查询", "L1: Knowledge Resolvers", - 420, - 160, - description="依次匹配 builds_upon 继承、Wikidata P625、PeeringDB /api/fac 及带商业云过滤的 ROR。", - tools=["builds_upon_inherit", "wikidata_lookup", "peeringdb_fac_lookup", "ror_lookup"], - params={"allow_low_confidence_short_circuit": False, "wikidata_enabled": True, "peeringdb_enabled": True}, + 380, + 80, + description="依次匹配 builds_upon、ROR,并行查询 Wikidata(P625+P17) 与 PeeringDB(/api/fac)。", + tools=["location_knowledge_lookup"], + params={ + "builds_upon_enabled": True, + "ror_enabled": True, + "wikidata_enabled": True, + "peeringdb_enabled": True, + }, ), _node( - "l2_agent_research", + "l2_research_r1", + "deterministic", + "L2-R1:并行一手抓取与英文搜索", + "L2-R1: Parallel Web Research", + 720, + 220, + description="并行抓取一手正文链接与 2 条精简英文搜索,为全部证据分配 E1..En 唯一编号。", + tools=["location_web_research"], + params={"round": 1, "max_search_queries": 2, "max_fetch_urls": 2}, + ), + _node( + "l2_judge_r1", "llm_agent", - "L2:多步 Tool-Calling 取证 Agent", - "L2: Tool-Calling Evidence Agent", - 800, - 300, - description="优先读取一手 source_url/Source 1..5,必要时多轮改写短查询搜索并调用 geocode_verify 落点。", + "L2-J1:首轮证据语义研判", + "L2-J1: Round-1 Judgment", + 1060, + 220, + description="基于 E1..En 证据输出单轮结构化 JSON:直接定位 / 发起定点补查 / 确认终态。", prompt_key="location.factcheck.resolve", - system_prompt="你是基础设施物理位置核查 Agent。严禁直接猜测或编造经纬度!必须先通过 fetch_source_url(优先使用元数据自带一手链接)或 web_search 找到物理设施/园区地址证据,再调用 geocode_verify 获取候选坐标 ID,最后调用 submit_location_result 提交结果。若确认为跨地域多站点或未披露地址,提交 multi_site 或 undisclosed。", - prompt="核查给定算力中心或 BGP 观测站的真实物理所在城市与设施位置。", - tools=["fetch_source_url", "web_search", "geocode_verify", "submit_location_result"], + system_prompt=( + "你是基础设施物理位置核查分析师。严格基于输入的 evidence_items(编号 E1..En)和 location_target 进行判断,严禁猜测或编造坐标/URL!\n" + "规则:\n" + "1) 只要证据已明确指出物理所在城市/园区(如数据中心运营商页面、政府规划/新闻稿、HPC 官网),直接设 decision='located' 并填写 city/country(英文国名)/facility_name/address 及引用的 evidence_ids;无需为追门牌号拖延。\n" + "2) 若发现重要线索但还缺关键城市名或正文细节,设 decision='need_followup',给出最多 2 条精准英文 followup_queries 或需全文抓取的 fetch_urls。\n" + "3) 若多条权威证据确认物理机房国与源登记国(总部国)不同,country 填实证物理部署国并在 country_override_reason 说明依据。\n" + "4) 仅当权威证据明确指出未披露、多地分布式、规划中、纯云端无实体时,才选对应终态(undisclosed/multi_site/planned/cloud_only)。\n" + "5) 输出语言规范:reasoning 和 country_override_reason 必须使用简洁的简体中文、不超过 120 字,且严禁出现 E1、E6、E1-E5 等内部证据编号(仅在 evidence_ids 数组填写编号供校验)。" + ), + prompt="核查给定设施的真实物理所在城市与园区位置,并按 JSON 契约返回初判结论。", thinking_enabled=True, - max_steps=4, - timeout_seconds=90, + max_steps=1, + timeout_seconds=60, native_web_search=False, + params={"output_schema": LOCATION_JUDGE_R1_SCHEMA, "allow_followup": True}, + ), + _node( + "l2_research_r2", + "deterministic", + "L2-R2:定向补搜与正文全文抓取", + "L2-R2: Targeted Follow-up Research", + 1400, + 340, + description="仅当 J1 判定需要补查时触发,执行 J1 给出的精准补搜词与候选页全文抓取。", + tools=["location_web_research"], + params={"round": 2, "max_search_queries": 2, "max_fetch_urls": 2}, + ), + _node( + "l2_judge_r2", + "llm_agent", + "L2-J2:综合全部证据终判", + "L2-J2: Final Evidence Judgment", + 1740, + 340, + description="结合两轮全部 E1..En 证据给出最终位置研判或明确无法定位原因。", + prompt_key="location.factcheck.resolve", + system_prompt=( + "你是基础设施物理位置终判分析师。严格依据两轮汇总的 evidence_items(E1..En)给出最终判定,禁止继续追问!\n" + "若证据支持某城市或园区,请设 decision='located' 并写明 city、country(英文)、facility_name、evidence_ids 与 confidence;" + "若跨国部署,填写 country_override_reason;若证据仍不足或明确未披露,输出 unresolved 或对应终态。\n" + "输出语言规范:reasoning 和 country_override_reason 必须使用简洁的简体中文、不超过 120 字,直接说明物理部署结论或具体信息缺口,严禁出现 E1、E6、E1-E5 等内部证据编号(evidence_ids 数组照常填写供校验)。" + ), + prompt="综合两轮证据完成最终物理位置裁决。", + thinking_enabled=True, + max_steps=1, + timeout_seconds=60, + native_web_search=False, + params={"output_schema": LOCATION_JUDGE_FINAL_SCHEMA, "allow_followup": False}, + ), + _node( + "l3_geocode", + "deterministic", + "L3:多粒度级联地理编码", + "L3: Cascade Geocoder", + 2080, + 180, + description="由代码按 街道地址 → 设施+城市 → 城市+省州 → 城市 级联查 Nominatim 落点并校验国家。", + tools=["location_geocode_verify"], ), _node( "l3_geo_guardrail", "guardrail", - "L3:国家边界硬校验与证据核验", - "L3: Geo Boundary Guardrail", - 1180, - 160, - description="强制校验经纬度范围、国家匹配一致性、引用 URL 真实性及城市级回退降级。", - guardrails={"min_confidence": 0.55, "enforce_country_match": True, "require_tool_cited_urls": True, "downgrade_geocoded_site_to_city": True}, + "L3:抗幻觉地理硬护栏", + "L3: Geo Anti-Hallucination Guardrail", + 2420, + 180, + description="校验证据真实引用(evidence_ids)、坐标>=城市级精度、置信度下限及受控跨国覆写。", + guardrails={ + "geo_verification": True, + "min_confidence": 0.55, + "enforce_country_match": True, + "require_tool_cited_urls": True, + "downgrade_geocoded_site_to_city": True, + }, ), _node( "l4_persist_outcome", "output", - "L4:候选输出或终态落库", - "L4: Candidate / Terminal State", - 1560, - 160, - description="返回高可信待确认候选坐标,或写入 undisclosed/multi_site/anonymous 防重复消耗。", + "L4:候选输出与终态落库", + "L4: Persist & Structured Output", + 2760, + 180, + description="输出标准化候选坐标载荷与地球聚焦视角,或在有实证时落库终态。", + tools=["location_persist_outcome"], + params={"persist_terminal_statuses": True, "fly_to_target": True}, ), ], "edges": [ _edge("loc-e1", "l0_normalize", "l1_knowledge", "未标记终态", "Not terminal", "not_terminal"), - _edge("loc-e2", "l1_knowledge", "l3_geo_guardrail", "高置信度命中", "Verified site hit", "high_confidence_hit"), - _edge("loc-e3", "l1_knowledge", "l2_agent_research", "未命中/需核查", "Miss or unverified", "fallback_to_agent"), - _edge("loc-e4", "l2_agent_research", "l3_geo_guardrail", "提交候选", "Submitted", "always"), - _edge("loc-e5", "l3_geo_guardrail", "l4_persist_outcome", "校验完成", "Validated", "always"), + _edge("loc-e2", "l0_normalize", "l4_persist_outcome", "已有终态缓存", "Cached terminal", "on_terminal"), + _edge("loc-e3", "l1_knowledge", "l4_persist_outcome", "知识库命中", "L1 hit", "high_confidence_hit"), + _edge("loc-e4", "l1_knowledge", "l2_research_r1", "未命中进联网取证", "Miss -> L2 research", "fallback_to_agent"), + _edge("loc-e5", "l2_research_r1", "l2_judge_r1", "首轮证据就绪", "R1 evidence ready", "always"), + _edge("loc-e6", "l2_judge_r1", "l2_research_r2", "需定向补查", "Need followup", "on_field_equals", "decision=need_followup"), + _edge("loc-e7", "l2_research_r2", "l2_judge_r2", "补查证据就绪", "R2 evidence ready", "always"), + _edge("loc-e8", "l2_judge_r1", "l3_geocode", "J1 定位成功", "J1 located", "on_field_equals", "decision=located"), + _edge("loc-e9", "l2_judge_r2", "l3_geocode", "J2 定位成功", "J2 located", "on_field_equals", "decision=located"), + _edge("loc-e10", "l3_geocode", "l3_geo_guardrail", "送入硬护栏", "Verify geo", "always"), + _edge("loc-e11", "l2_judge_r1", "l3_geo_guardrail", "J1 终态/未定论", "J1 non-located", "on_field_equals", "decision=undisclosed,multi_site,planned,cloud_only,anonymous,unresolved"), + _edge("loc-e12", "l2_judge_r2", "l3_geo_guardrail", "J2 终态/未定论", "J2 non-located", "on_field_equals", "decision=undisclosed,multi_site,planned,cloud_only,anonymous,unresolved"), + _edge("loc-e13", "l3_geo_guardrail", "l4_persist_outcome", "输出结论", "Emit outcome", "always"), ], }, }, @@ -983,6 +1127,100 @@ def _upgrade_untouched_legacy_positions(row: AIWorkflow, spec: dict[str, Any]) - return True +_LEGACY_LOC_NODE_IDS = frozenset( + {"l0_normalize", "l1_knowledge", "l2_agent_research", "l3_geo_guardrail", "l4_persist_outcome"} +) + + +def _upgrade_untouched_location_v1(row: AIWorkflow, spec: dict[str, Any]) -> bool: + """Upgrade retired 5-node `location.resolve_unknown` graphs (and legacy 5-node drafts) to the 9-node DAG.""" + if row.workflow_id != "location.resolve_unknown": + return False + changed = False + graph = row.published_graph if isinstance(row.published_graph, dict) else None + if graph: + node_ids = { + str(n.get("id") or "") + for n in (graph.get("nodes") or []) + if isinstance(n, dict) and n.get("id") + } + if node_ids == _LEGACY_LOC_NODE_IDS: + row.published_graph = copy.deepcopy(spec["graph"]) + changed = True + draft = row.draft_graph if isinstance(row.draft_graph, dict) else None + if draft: + draft_ids = { + str(n.get("id") or "") + for n in (draft.get("nodes") or []) + if isinstance(n, dict) and n.get("id") + } + if draft_ids == _LEGACY_LOC_NODE_IDS: + row.draft_graph = None + changed = True + return changed + + +_PREV_LOC_JUDGE_PROMPTS: dict[str, str] = { + "l2_judge_r1": ( + "你是基础设施物理位置核查分析师。严格基于输入的 evidence_items(编号 E1..En)和 location_target 进行判断,严禁猜测或编造坐标/URL!\n" + "规则:\n" + "1) 只要证据已明确指出物理所在城市/园区(如数据中心运营商页面、政府规划/新闻稿、HPC 官网),直接设 decision='located' 并填写 city/country(英文国名)/facility_name/address 及引用的 evidence_ids;无需为追门牌号拖延。\n" + "2) 若发现重要线索但还缺关键城市名或正文细节,设 decision='need_followup',给出最多 2 条精准英文 followup_queries 或需全文抓取的 fetch_urls。\n" + "3) 若多条权威证据确认物理机房国与源登记国(总部国)不同,country 填实证物理部署国并在 country_override_reason 说明依据。\n" + "4) 仅当权威证据明确指出未披露、多地分布式、规划中、纯云端无实体时,才选对应终态(undisclosed/multi_site/planned/cloud_only)。" + ), + "l2_judge_r2": ( + "你是基础设施物理位置终判分析师。严格依据两轮汇总的 evidence_items(E1..En)给出最终判定,禁止继续追问!\n" + "若证据支持某城市或园区,请设 decision='located' 并写明 city、country(英文)、facility_name、evidence_ids 与 confidence;" + "若跨国部署,填写 country_override_reason;若证据仍不足或明确未披露,输出 unresolved 或对应终态,并在 reasoning 说明具体缺口。" + ), +} + + +def _upgrade_untouched_location_judge_prompts(row: AIWorkflow, spec: dict[str, Any]) -> bool: + """Update untouched stock `l2_judge_r1` / `l2_judge_r2` prompts while preserving user edits.""" + if row.workflow_id != "location.resolve_unknown": + return False + target_prompts = { + str(n.get("id") or ""): str(n.get("system_prompt") or "") + for n in spec.get("graph", {}).get("nodes", []) + if isinstance(n, dict) and n.get("id") in _PREV_LOC_JUDGE_PROMPTS + } + if len(target_prompts) != len(_PREV_LOC_JUDGE_PROMPTS): + return False + + def _patch_graph(raw_graph: Any) -> tuple[dict[str, Any] | None, bool]: + if not isinstance(raw_graph, dict): + return None, False + nodes = raw_graph.get("nodes") + if not isinstance(nodes, list): + return None, False + cloned = copy.deepcopy(raw_graph) + graph_changed = False + for node in cloned.get("nodes", []): + if not isinstance(node, dict): + continue + nid = str(node.get("id") or "") + if nid not in _PREV_LOC_JUDGE_PROMPTS: + continue + current_prompt = str(node.get("system_prompt") or "") + if current_prompt == _PREV_LOC_JUDGE_PROMPTS[nid]: + node["system_prompt"] = target_prompts[nid] + graph_changed = True + return (cloned, True) if graph_changed else (None, False) + + changed = False + new_pub, pub_changed = _patch_graph(row.published_graph) + if pub_changed and new_pub is not None: + row.published_graph = new_pub + changed = True + new_draft, draft_changed = _patch_graph(row.draft_graph) + if draft_changed and new_draft is not None: + row.draft_graph = new_draft + changed = True + return changed + + async def ensure_builtin_workflows(db: AsyncSession) -> None: """Idempotently seed all 9 built-in workflows into `ai_workflows`.""" if not hasattr(db, "execute"): @@ -1000,6 +1238,10 @@ async def ensure_builtin_workflows(db: AsyncSession) -> None: existing_row = existing_by_id[wf_id] if _upgrade_untouched_legacy_positions(existing_row, spec): changed = True + if _upgrade_untouched_location_v1(existing_row, spec): + changed = True + if _upgrade_untouched_location_judge_prompts(existing_row, spec): + changed = True if not existing_row.bindings and spec.get("bindings"): existing_row.bindings = default_bindings changed = True diff --git a/backend/app/services/ai/workflow_runtime.py b/backend/app/services/ai/workflow_runtime.py index b84eb9a0..4e20c966 100644 --- a/backend/app/services/ai/workflow_runtime.py +++ b/backend/app/services/ai/workflow_runtime.py @@ -45,9 +45,13 @@ from app.services.ai.spatial_domain_agent import ( investigate_spatial_domain, ) from app.services.ai.thinking_sanitizer import merge_usage_dicts -from app.services.ai.tool_registry import TimeBasis, query_bgp_incidents_tool, query_compute_posture_tool +from app.services.ai.tool_registry import TimeBasis, query_compute_posture_tool from app.services.ai_client import AIProviderClient from app.services.compute_catalog import PARTICIPANTS +from app.services.compute_lineage import ( + build_revision_change_context, + is_revision_question, +) logger = get_logger(__name__, service="ai_workflow") @@ -648,6 +652,9 @@ class ViewSpec(BaseModel): is_drill: bool = False time_basis: TimeBasis = "retrospective" cutoff_at: str | None = None + publish_id: str | None = None + mode: str | None = None + focus_year: int | None = None replay_supported: bool = True replay_status: Literal["frozen", "incomplete_snapshot"] = "frozen" replay_notice: str | None = None @@ -881,6 +888,8 @@ def classify_turn_intent( "incident_focus": focus, "time_basis": time_basis, "cutoff_at": cutoff_at, + "publish_id": ctx.get("publish_id"), + "as_of": ctx.get("as_of"), "include_drill": include_drill, "visible_layers": visible_layers, } @@ -916,6 +925,8 @@ def classify_turn_intent( "incident_focus": "overview", "time_basis": time_basis, "cutoff_at": cutoff_at, + "publish_id": ctx.get("publish_id"), + "as_of": ctx.get("as_of"), "include_drill": include_drill, "visible_layers": visible_layers, } @@ -959,7 +970,7 @@ def classify_turn_intent( elif any(kw in q for kw in ("趋势", "走势", "历年", "演变", "走廊", "2020", "trend", "trajectory")): workflow_id = "compute.compare" view_preset = "trend" - elif any(kw in q for kw in ("为什么", "成因", "归因", "稀释", "回落", "剪刀差", "创新", "东数西算", "枢纽", "解释", "why", "explain")): + elif any(kw in q for kw in ("为什么", "成因", "归因", "稀释", "回落", "剪刀差", "创新", "东数西算", "枢纽", "解释", "修订", "改了", "变化", "重述", "why", "explain", "revised")): workflow_id = "compute.explain_gap" view_preset = "causal" elif metric_switched or any(kw in q for kw in ("只看", "切换", "改看", "switch")): @@ -982,6 +993,8 @@ def classify_turn_intent( "incident_focus": "overview", "time_basis": time_basis, "cutoff_at": cutoff_at, + "publish_id": ctx.get("publish_id"), + "as_of": ctx.get("as_of"), "include_drill": include_drill, "visible_layers": visible_layers, } @@ -1015,6 +1028,7 @@ def compile_compute_view_spec( series: dict[str, Any], posture: dict[str, Any], preset: ViewPreset = "default", + focus_year: int | None = None, enable_hubs: bool = False, auto_play: bool = False, replay_supported: bool = True, @@ -1025,6 +1039,10 @@ def compile_compute_view_spec( evidence_map = series.get("evidence") or {} time_basis: TimeBasis = series.get("time_basis") or "retrospective" cutoff_at = series.get("cutoff_at") + effective_publish_id = series.get("publish_id") or series.get("version") or posture.get("publish_id") + if series.get("snapshot_unavailable"): + replay_supported = False + replay_notice = replay_notice or series.get("notice") metric_zh, metric_en, default_unit = _METRIC_LABELS.get(mode, ("算力指标", "Compute Metric", "%")) unit = str(series.get("unit") or default_unit) effective_replay_notice = replay_notice or (_INCOMPLETE_COMPUTE_REPLAY_NOTICE if not replay_supported else None) @@ -1036,6 +1054,7 @@ def compile_compute_view_spec( if any(r.get("values", {}).get(c) is not None for c in codes) ] latest_year = int(observed_rows[-1]["year"]) if observed_rows else (years[-1] if years else None) + effective_focus_year = int(focus_year) if focus_year is not None else latest_year matrix_rows: list[dict[str, Any]] = [] max_numeric = 0.0 @@ -1325,6 +1344,9 @@ def compile_compute_view_spec( is_drill=False, time_basis=time_basis, cutoff_at=cutoff_at, + publish_id=effective_publish_id, + mode=mode, + focus_year=effective_focus_year, replay_supported=replay_supported, replay_status="frozen" if replay_supported else "incomplete_snapshot", replay_notice=effective_replay_notice, @@ -1335,7 +1357,7 @@ def compile_compute_view_spec( domain="compute", highlight_entities=highlight_ids, compute_mode=mode, - focus_year=latest_year, + focus_year=effective_focus_year, enable_national_hubs=enable_hubs, presentation_key="compute-posture-cn-us", auto_play_presentation=auto_play, @@ -1692,6 +1714,10 @@ async def execute_session_turn( for k, v in context_override.items(): if v is not None: merged_ctx[k] = v + if context_override.get("publish_id") and not context_override.get("as_of"): + merged_ctx["as_of"] = None + elif context_override.get("as_of") and not context_override.get("publish_id"): + merged_ctx["publish_id"] = None routed = classify_turn_intent(question, merged_ctx) workflow_id = routed["workflow_id"] @@ -1752,6 +1778,8 @@ async def execute_session_turn( domain = routed["domain"] time_basis: TimeBasis = routed["time_basis"] cutoff_at: str | None = routed["cutoff_at"] + publish_id: str | None = routed.get("publish_id") + as_of: str | None = routed.get("as_of") run_record = WorkflowRun( id=run_id, @@ -1813,11 +1841,14 @@ async def execute_session_turn( and domain == merged_ctx.get("domain") and time_basis == (merged_ctx.get("time_basis") or time_basis) and cutoff_at == merged_ctx.get("cutoff_at") + and publish_id == merged_ctx.get("publish_id") + and as_of == merged_ctx.get("as_of") and ( domain != "compute" or ( routed["selected_codes"] == (merged_ctx.get("selected_codes") or routed["selected_codes"]) and routed["mode"] == (merged_ctx.get("mode") or routed["mode"]) + and routed["focus_year"] == merged_ctx.get("focus_year") ) ) ) @@ -1967,8 +1998,17 @@ async def execute_session_turn( mode=mode, time_basis=time_basis, cutoff_at=cutoff_at, + as_of=as_of, + publish_id=publish_id, ) _check_cancelled() + revision_context: dict[str, Any] | None = None + if is_revision_question(question) and not series.get("snapshot_unavailable"): + revision_context = await build_revision_change_context( + db, + publish_id=series.get("publish_id") or publish_id, + redact=(access.tier != "admin"), + ) posture = await generate_or_get_compute_posture( db, countries=codes, @@ -1996,8 +2036,11 @@ async def execute_session_turn( question=question, time_basis=time_basis, cutoff_at=cutoff_at, + publish_id=publish_id, + as_of=as_of, series_override=series, posture_override=posture, + revision_context=revision_context, ai_client=ai_client if (use_paid_llm and access.can_use_paid_llm) else None, cancel_event=handle.cancel_event, ) @@ -2012,6 +2055,7 @@ async def execute_session_turn( series=series, posture=posture, preset=preset, + focus_year=routed["focus_year"], enable_hubs=enable_hubs, auto_play=routed["auto_play_presentation"], ) @@ -2112,6 +2156,8 @@ async def execute_session_turn( "visible_layers": routed.get("visible_layers") or {}, "time_basis": time_basis, "cutoff_at": cutoff_at, + "publish_id": publish_id, + "as_of": as_of, "include_drill": routed["include_drill"], "active_result_id": subject_key, "active_revision": revision, @@ -2157,6 +2203,8 @@ async def execute_session_turn( "generation_mode": generation_mode, "time_basis": time_basis, "cutoff_at": cutoff_at, + "publish_id": view_spec.publish_id, + "as_of": as_of, "context_state": next_context, "reply": { "answer_markdown": answer_md, diff --git a/backend/app/services/collectors/__init__.py b/backend/app/services/collectors/__init__.py index 536b66b2..f2ce6a52 100644 --- a/backend/app/services/collectors/__init__.py +++ b/backend/app/services/collectors/__init__.py @@ -38,7 +38,14 @@ from app.services.collectors.nro_delegated import NRODelegatedPrefixGeoCollector from app.services.collectors.news_live_streams import NewsLiveStreamsCollector from app.services.collectors.media_news_archive import MediaNewsArchiveCollector from app.services.collectors.aisstream import AISStreamCollector +from app.services.collectors.cloud_map import EarthCloudMapCollector +from app.services.collectors.earth_tiles import ( + CloudHDTilesCollector, + Sentinel2ImageryCollector, + VIIRSDailyImageryCollector, +) from app.services.collectors.vessel_ais import VesselAISCollector +from app.services.collectors.wind_gfs import EarthWindGFSCollector collector_registry.register(TOP500Collector()) collector_registry.register(EpochAIGPUCollector()) @@ -69,6 +76,11 @@ collector_registry.register(NewsLiveStreamsCollector()) collector_registry.register(MediaNewsArchiveCollector()) collector_registry.register(VesselAISCollector()) collector_registry.register(AISStreamCollector()) +collector_registry.register(EarthCloudMapCollector()) +collector_registry.register(CloudHDTilesCollector()) +collector_registry.register(Sentinel2ImageryCollector()) +collector_registry.register(VIIRSDailyImageryCollector()) +collector_registry.register(EarthWindGFSCollector()) __all__ = [ "BaseCollector", @@ -105,4 +117,9 @@ __all__ = [ "MediaNewsArchiveCollector", "VesselAISCollector", "AISStreamCollector", + "EarthCloudMapCollector", + "CloudHDTilesCollector", + "Sentinel2ImageryCollector", + "VIIRSDailyImageryCollector", + "EarthWindGFSCollector", ] diff --git a/backend/app/services/collectors/cloud_map.py b/backend/app/services/collectors/cloud_map.py new file mode 100644 index 00000000..bba4c45b --- /dev/null +++ b/backend/app/services/collectors/cloud_map.py @@ -0,0 +1,184 @@ +"""Built-in collector for global real-time satellite IR cloud imagery and spatial analytics.""" + +from __future__ import annotations + +from typing import Any + +from sqlalchemy import select + +from app.core.websocket.broadcaster import broadcaster +from app.models.datasource_config import DataSourceConfig +from app.services.collectors.base import BaseCollector +from app.services.earth_clouds import collect_latest_cloud_frame + + +class EarthCloudMapCollector(BaseCollector): + """Collect multi-satellite IR cloud map frames and structured atmospheric analytics.""" + + name = "global_cloud_map" + priority = "P1" + module = "L2" + frequency_hours = 1 + data_type = "cloud_map_record" + fail_on_empty = True + preserve_snapshot_on_failure = True + full_snapshot_reconcile = True + + async def _load_override_config(self) -> dict[str, Any]: + if not self._db_session or not callable(getattr(self._db_session, "execute", None)): + return {} + try: + result = await self._db_session.execute( + select(DataSourceConfig) + .where(DataSourceConfig.name == self.name) + .where(DataSourceConfig.is_active.is_(True)) + .limit(1) + ) + record = result.scalar_one_or_none() + if record and isinstance(record.config, dict): + return { + key: value + for key, value in record.config.items() + if key + in { + "enabled", + "primary_source", + "fallback_source", + "resolution", + "ir_threshold", + "contrast_gamma", + "convective_threshold", + "min_cluster_area_km2", + "polar_feather_enabled", + "max_history_frames", + "request_timeout_seconds", + "geocolor_enabled", + "relief_shading_strength", + "optical_flow_enabled", + } + and value is not None + } + except Exception: + return {} + return {} + + async def fetch(self) -> list[dict[str, Any]]: + override = await self._load_override_config() + result = await collect_latest_cloud_frame(self._db_session, override_config=override) + return [result] + + def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]: + if not raw_data: + return [] + bundle = raw_data[0] + frame = bundle.get("frame") or {} + summary = bundle.get("global_summary") or {} + regions = bundle.get("regions") or [] + clusters = bundle.get("convective_clusters") or [] + + version = str(frame.get("version") or "") + captured_at = frame.get("captured_at") + source_used = str(frame.get("source") or "multi_sat_ir") + satellites = list(frame.get("satellites") or []) + degraded = bool(frame.get("degraded", False)) + + records: list[dict[str, Any]] = [ + { + "source_id": "cloud_snapshot:latest", + "name": "全球实时红外云图快照", + "title": f"全球云图 {version}", + "description": ( + f"来源={source_used}, 全球平均云量={summary.get('global_cloud_cover_pct')}%, " + f"强对流云团={summary.get('convective_cluster_count', 0)} 个" + ), + "latitude": 0.0, + "longitude": 0.0, + "value": summary.get("global_cloud_cover_pct"), + "unit": "%", + "reference_date": captured_at, + "metadata": { + "record_kind": "cloud_map_snapshot", + "version": version, + "captured_at": captured_at, + "cloud_source": source_used, + "satellites": satellites, + "degraded": degraded, + "resolution": frame.get("resolution"), + "image_url": frame.get("image_url"), + "file_size_bytes": frame.get("file_size_bytes"), + "sha256": frame.get("sha256"), + **summary, + }, + } + ] + + for region in regions: + key = str(region.get("key") or "") + records.append( + { + "source_id": f"cloud_region:{key}", + "name": str(region.get("name") or key), + "title": f"区域云量 · {region.get('name') or key}", + "description": ( + f"云量 {region.get('cloud_cover_pct')}%, " + f"厚云 {region.get('overcast_coverage_pct')}%, " + f"最低亮温 {region.get('min_brightness_temp_c')}°C" + ), + "latitude": region.get("center_lat"), + "longitude": region.get("center_lon"), + "value": region.get("cloud_cover_pct"), + "unit": "%", + "reference_date": captured_at, + "metadata": { + "record_kind": "cloud_region_summary", + "version": version, + "captured_at": captured_at, + **region, + }, + } + ) + + for cluster in clusters: + cid = str(cluster.get("cluster_id") or "") + records.append( + { + "source_id": f"cloud_cluster:{cid}", + "name": f"强对流云团 {cid} ({cluster.get('region') or ''})", + "title": f"强对流核 {cid} · {cluster.get('min_brightness_temp_c')}°C", + "description": ( + f"估算面积 {cluster.get('area_km2')} km², " + f"峰值强度 {cluster.get('peak_intensity')}%, " + f"最低亮温 {cluster.get('min_brightness_temp_c')}°C" + ), + "latitude": cluster.get("latitude"), + "longitude": cluster.get("longitude"), + "value": cluster.get("area_km2"), + "unit": "km2", + "reference_date": captured_at, + "metadata": { + "record_kind": "cloud_convective_cluster", + "version": version, + "captured_at": captured_at, + **cluster, + }, + } + ) + + return records + + async def run(self, db) -> dict[str, Any]: + result = await super().run(db) + if result.get("status") == "success": + try: + await broadcaster.broadcast_earth_update( + { + "event": "earth.layer.changed", + "action": "cloud_map_updated", + "source": self.name, + "layers": ["clouds"], + "refresh_strategy": "reload", + } + ) + except Exception: + pass + return result diff --git a/backend/app/services/collectors/earth_tiles.py b/backend/app/services/collectors/earth_tiles.py new file mode 100644 index 00000000..5afa28f9 --- /dev/null +++ b/backend/app/services/collectors/earth_tiles.py @@ -0,0 +1,106 @@ +"""Collectors for NASA/EOX Earth tile pyramids (`cloud_hd_tiles`, Sentinel-2, VIIRS).""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any + +from app.core.logging import get_logger +from app.core.time import to_iso8601_utc +from app.core.websocket.broadcaster import broadcaster +from app.services.collectors.base import BaseCollector +from app.services.earth_tiles import TILE_SOURCES, warmup_tile_source + +logger = get_logger(__name__, service="collector.earth_tiles") + + +class _BaseEarthTileCollector(BaseCollector): + """Base BaseCollector implementation for managed Web-Mercator tile pyramids.""" + + priority = "P2" + module = "L1" + frequency_hours = 24 + data_type = "earth_tile_pyramid" + fail_on_empty = False + preserve_snapshot_on_failure = True + full_snapshot_reconcile = True + broadcast_layer = "basemap" + + async def fetch(self) -> list[dict[str, Any]]: + summary = await warmup_tile_source(self.name, db=self._db_session) + return [summary] + + def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]: + if not raw_data: + return [] + summary = raw_data[0] + cache_stats = summary.get("cache_stats") or {} + tile_count = int(cache_stats.get("tile_count") or 0) + total_mb = float(cache_stats.get("total_mb") or 0.0) + captured_at = to_iso8601_utc(datetime.now(UTC)) + return [ + { + "source_id": f"tile_pyramid:{self.name}", + "name": self.name, + "title": f"瓦片金字塔预热 · {self.name} (Z0–Z{summary.get('warmup_max_zoom', 3)})", + "description": ( + f"新抓取 {summary.get('fetched', 0)} 块,缓存命中 {summary.get('cached_hits', 0)} 块," + f"累计 {tile_count} 块 ({total_mb} MB)" + ), + "latitude": 0.0, + "longitude": 0.0, + "value": tile_count, + "unit": "tiles", + "reference_date": captured_at, + "metadata": { + "record_kind": "earth_tile_pyramid", + "captured_at": captured_at, + **summary, + }, + } + ] + + async def run(self, db) -> dict[str, Any]: + result = await super().run(db) + if result.get("status") == "success": + try: + await broadcaster.broadcast_earth_update( + { + "event": "earth.layer.changed", + "action": "tile_pyramid_warmed", + "source": self.name, + "layers": [self.broadcast_layer], + "refresh_strategy": "reload", + } + ) + except Exception: + pass + return result + + +class CloudHDTilesCollector(_BaseEarthTileCollector): + name = "cloud_hd_tiles" + priority = "P1" + module = "L2" + frequency_hours = 1 + broadcast_layer = "clouds" + + +class Sentinel2ImageryCollector(_BaseEarthTileCollector): + name = "earth_imagery_sentinel2" + frequency_hours = 24 + broadcast_layer = "basemap" + + +class VIIRSDailyImageryCollector(_BaseEarthTileCollector): + name = "earth_imagery_viirs_daily" + frequency_hours = 12 + broadcast_layer = "basemap" + + +__all__ = [ + "TILE_SOURCES", + "CloudHDTilesCollector", + "Sentinel2ImageryCollector", + "VIIRSDailyImageryCollector", +] diff --git a/backend/app/services/collectors/wind_gfs.py b/backend/app/services/collectors/wind_gfs.py new file mode 100644 index 00000000..8713d1ac --- /dev/null +++ b/backend/app/services/collectors/wind_gfs.py @@ -0,0 +1,144 @@ +"""Collector for NOAA NCEP GFS 10m global wind field (`global_wind_gfs`).""" + +from __future__ import annotations + +from typing import Any + +from app.core.logging import get_logger +from app.core.websocket.broadcaster import broadcaster +from app.services.collectors.base import BaseCollector +from app.services.earth_wind import WIND_REGIONS, collect_latest_wind_grid + +logger = get_logger(__name__, service="collector.wind_gfs") + +_REGION_COORDS = { + item["key"]: ( + (float(item["lat_min"]) + float(item["lat_max"])) / 2.0, + (float(item["lon_min"]) + float(item["lon_max"])) / 2.0, + ) + for item in WIND_REGIONS +} + + +class EarthWindGFSCollector(BaseCollector): + """Collect NOAA NCEP GFS global 10m wind field grids and regional gale analytics.""" + + name = "global_wind_gfs" + priority = "P1" + module = "L2" + frequency_hours = 3 + data_type = "wind_field_record" + fail_on_empty = True + preserve_snapshot_on_failure = True + full_snapshot_reconcile = True + + async def fetch(self) -> list[dict[str, Any]]: + result = await collect_latest_wind_grid(db=self._db_session) + return [result] + + def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]: + if not raw_data: + return [] + bundle = raw_data[0] + run = bundle.get("run") or {} + summary = bundle.get("global_summary") or {} + regions = bundle.get("regions") or [] + cores = bundle.get("storm_cores") or [] + + version = str(run.get("version") or "") + captured_at = run.get("captured_at") + forecast_time = run.get("forecast_time") + + records: list[dict[str, Any]] = [ + { + "source_id": "wind_snapshot:latest", + "name": "全球 10m 地面风场快照 (NOAA GFS)", + "title": f"全球风场 {version}", + "description": ( + f"全球均速={summary.get('mean_speed_ms')} m/s, 峰值={summary.get('max_speed_ms')} m/s, " + f"大风核心={summary.get('storm_core_count', 0)} 个" + ), + "latitude": 0.0, + "longitude": 0.0, + "value": summary.get("mean_speed_ms"), + "unit": "m/s", + "reference_date": captured_at, + "metadata": { + "record_kind": "wind_field_snapshot", + "version": version, + "captured_at": captured_at, + "forecast_time": forecast_time, + **summary, + }, + } + ] + + for reg in regions: + key = str(reg.get("key") or "") + center_lat, center_lon = _REGION_COORDS.get(key, (0.0, 0.0)) + records.append( + { + "source_id": f"wind_region:{key}", + "name": str(reg.get("name") or key), + "title": f"区域风场 · {reg.get('name') or key}", + "description": ( + f"均速 {reg.get('mean_speed_ms')} m/s, 峰值 {reg.get('max_speed_ms')} m/s, " + f"主导风向 {reg.get('dominant_cardinal')}" + ), + "latitude": center_lat, + "longitude": center_lon, + "value": reg.get("mean_speed_ms"), + "unit": "m/s", + "reference_date": captured_at, + "metadata": { + "record_kind": "wind_region_summary", + "version": version, + "captured_at": captured_at, + **reg, + }, + } + ) + + for core in cores: + cid = str(core.get("id") or "") + records.append( + { + "source_id": f"wind_core:{cid}", + "name": f"大风核心 {cid} ({core.get('region') or ''})", + "title": f"大风中心 {cid} · {core.get('max_speed_ms')} m/s", + "description": ( + f"估算面积 {core.get('area_km2')} km², " + f"蒲福 {core.get('beaufort')} 级" + ), + "latitude": core.get("lat"), + "longitude": core.get("lon"), + "value": core.get("max_speed_ms"), + "unit": "m/s", + "reference_date": captured_at, + "metadata": { + "record_kind": "wind_storm_core", + "version": version, + "captured_at": captured_at, + **core, + }, + } + ) + + return records + + async def run(self, db) -> dict[str, Any]: + result = await super().run(db) + if result.get("status") == "success": + try: + await broadcaster.broadcast_earth_update( + { + "event": "earth.layer.changed", + "action": "wind_grid_updated", + "source": self.name, + "layers": ["windField"], + "refresh_strategy": "reload", + } + ) + except Exception: + pass + return result diff --git a/backend/app/services/compute_center_locations.py b/backend/app/services/compute_center_locations.py index c359644a..19008858 100644 --- a/backend/app/services/compute_center_locations.py +++ b/backend/app/services/compute_center_locations.py @@ -648,6 +648,7 @@ def _context_to_query( "sources": list(context.get("sources") or []), "source_url": context.get("source_url") or "", "builds_upon": context.get("builds_upon") or "", + "cross_source_hints": list(context.get("cross_source_hints") or []), }, ) @@ -984,6 +985,50 @@ def resolve_compute_center_location_full( ) +def collect_high_precision_local_candidates( + *, + name: str | None = None, + source: str | None = None, + source_id: str | None = None, + operator: str | None = None, + site: str | None = None, + city: str | None = None, + country: str | None = None, + organization: str | None = None, + sources: list[str] | None = None, + source_url: str | None = None, + builds_upon: str | None = None, + source_raw_country: str | None = None, + include_builds_upon: bool = True, +) -> tuple[list[LocationCandidate], list[str]]: + """Run high-precision local resolvers (VerifiedSite, BuildsUpon) before external lookups.""" + query = build_compute_center_location_query( + name=name, + source=source, + source_id=source_id, + operator=operator, + site=site, + city=city, + country=country, + organization=organization, + sources=sources, + source_url=source_url, + builds_upon=builds_upon, + source_raw_country=source_raw_country, + ) + resolvers: list[Any] = [ + ComputeCenterSourceCoordinatesResolver(), + VerifiedComputeSiteResolver(), + ] + if include_builds_upon: + resolvers.append(BuildsUponComputeCenterResolver()) + pipeline = LocationPipeline( + resolvers, + sort_key=_compute_center_candidate_sort_key, + ) + return pipeline.collect_candidates(query) + + def collect_location_candidates( *, name: str | None = None, @@ -999,6 +1044,9 @@ def collect_location_candidates( source_url: str | None = None, builds_upon: str | None = None, source_raw_country: str | None = None, + include_builds_upon: bool = True, + include_ror: bool = True, + include_nominatim: bool = True, ) -> tuple[list[LocationCandidate], list[str]]: """Run the full resolution chain and return ranked candidates with attempted queries.""" query = build_compute_center_location_query( @@ -1015,7 +1063,30 @@ def collect_location_candidates( builds_upon=builds_upon, source_raw_country=source_raw_country, ) - return COMPUTE_CENTER_COLLECTION_PIPELINE.collect_candidates(query) + if include_builds_upon and include_ror and include_nominatim: + return COMPUTE_CENTER_COLLECTION_PIPELINE.collect_candidates(query) + + resolvers: list[Any] = [ + ComputeCenterSourceCoordinatesResolver(), + VerifiedComputeSiteResolver(), + ] + if include_builds_upon: + resolvers.append(BuildsUponComputeCenterResolver()) + if include_ror: + resolvers.append(ROROrganizationResolver()) + if include_nominatim: + resolvers.append( + NominatimResolver( + query_plan_builder=_compute_center_query_plan, + geocoder=lambda q: _geocode_online(q), + ) + ) + pipeline = LocationPipeline( + resolvers, + sort_key=_compute_center_candidate_sort_key, + failure_reason=COMPUTE_CENTER_COLLECTION_PIPELINE._failure_reason, + ) + return pipeline.collect_candidates(query) def build_compute_center_location_query( @@ -1032,6 +1103,7 @@ def build_compute_center_location_query( source_url: str | None = None, builds_upon: str | None = None, source_raw_country: str | None = None, + cross_source_hints: list[dict[str, Any]] | None = None, ) -> LocationQuery: name_value = coerce_str(name) context: dict[str, Any] = { @@ -1048,6 +1120,7 @@ def build_compute_center_location_query( "source_url": coerce_str(source_url), "builds_upon": coerce_str(builds_upon), "source_raw_country": coerce_str(source_raw_country), + "cross_source_hints": list(cross_source_hints or []), } return _context_to_query(context) @@ -1199,4 +1272,12 @@ async def upsert_compute_center_location( await session.commit() await session.refresh(record) await refresh_compute_center_location_cache(session) + try: + from app.core.cache import cache + from app.services.earth_layer_cache import invalidate_earth_layer_cache_for_source + + invalidate_earth_layer_cache_for_source("compute_center_locations") + cache.delete_pattern("data_ledger:*") + except Exception: + pass return record diff --git a/backend/app/services/compute_configuration.py b/backend/app/services/compute_configuration.py index d013ca81..21ac28f1 100644 --- a/backend/app/services/compute_configuration.py +++ b/backend/app/services/compute_configuration.py @@ -1,42 +1,272 @@ -"""Database overrides with bundled defaults and atomic, revision-checked publishing.""" +"""Database overrides with versioned revision ledger, as-of replay, and atomic publishing.""" +from __future__ import annotations + +from datetime import UTC, datetime, timedelta import hashlib +import json from pathlib import Path +from typing import Any from uuid import uuid4 +from fastapi import HTTPException +from sqlalchemy import desc, select +from sqlalchemy.dialects.postgresql import insert as pg_insert +from sqlalchemy.ext.asyncio import AsyncSession + from app.core.request_context import get_request_id +from app.core.time import to_iso8601_utc +from app.models.compute_configuration_revision import ComputeConfigurationRevision +from app.models.situational_assessment import ComputeEvidenceCandidate from app.models.system_log import AuditLog from app.models.system_setting import SystemSetting from app.models.user import User -from app.schemas.compute_configuration import ComputeConfiguration +from app.schemas.compute_configuration import ( + SHARE_METRICS, + ComputeConfiguration, + has_mixed_sources, +) from app.services.compute_catalog import COUNTRY_CATALOG -from fastapi import HTTPException -from sqlalchemy import select -from sqlalchemy.dialects.postgresql import insert -from sqlalchemy.ext.asyncio import AsyncSession +from app.services.compute_revision_diff import ( + diff_compute_configurations, + has_observation_value_delta, + summarize_diff, +) CATEGORY = "compute_comparison" DEFAULT_PATH = Path(__file__).with_name("compute_history_defaults.json") DEFAULT_CONFIGURATION = ComputeConfiguration.model_validate_json(DEFAULT_PATH.read_text()) DEFAULT_REVISION = hashlib.sha256(DEFAULT_PATH.read_bytes()).hexdigest() +INCOMPLETE_SNAPSHOT_NOTICE = ( + "历史快照不完整:所选系统发布时间早于版本库基线时间,无法还原当时的系统台账。" +) -def default_envelope() -> dict: + +def compute_content_fingerprint(config: ComputeConfiguration | dict[str, Any]) -> str: + """Return canonical SHA-256 hex digest of a compute configuration payload.""" + payload = ( + config.model_dump(mode="json") + if isinstance(config, ComputeConfiguration) + else ComputeConfiguration.model_validate(config).model_dump(mode="json") + ) + canonical = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + +DEFAULT_CONTENT_FINGERPRINT = compute_content_fingerprint(DEFAULT_CONFIGURATION) + + +def default_envelope() -> dict[str, Any]: return { "config": DEFAULT_CONFIGURATION.model_dump(mode="json"), "revision": DEFAULT_REVISION, + "publish_id": DEFAULT_REVISION, + "published_at": None, + "action": "baseline", "is_default": True, + "snapshot_unavailable": False, } -async def read_configuration(db: AsyncSession) -> dict: +def _dialect_name(db: AsyncSession) -> str: + bind = getattr(db, "bind", None) + name = getattr(getattr(bind, "dialect", None), "name", None) + if isinstance(name, str) and name: + return name + getter = getattr(db, "get_bind", None) + # Avoid invoking AsyncMock attributes as coroutines in unit tests. + if callable(getter) and not hasattr(getter, "assert_awaited"): + try: + resolved = getter() + name = getattr(getattr(resolved, "dialect", None), "name", None) + if isinstance(name, str) and name: + return name + except Exception: + pass + return "" + + +def _is_relational_session(db: AsyncSession) -> bool: + return _dialect_name(db) in {"postgresql", "sqlite"} + + +def _parse_as_of(as_of: datetime | str | None) -> datetime | None: + if as_of is None: + return None + if isinstance(as_of, datetime): + return as_of.astimezone(UTC) if as_of.tzinfo else as_of.replace(tzinfo=UTC) + raw = str(as_of).strip() + if not raw: + return None + try: + if len(raw) == 10 and raw[4] == "-" and raw[7] == "-": + return datetime.fromisoformat(f"{raw}T23:59:59.999999+00:00") + normalized = raw.replace("Z", "+00:00") + # Recover '+' decoded as space in unencoded URL query strings (e.g. '...52.97 00:00'). + if "T" in normalized and " " in normalized: + date_part, tz_part = normalized.rsplit(" ", 1) + if len(tz_part) == 5 and tz_part[2] == ":" and tz_part[:2].isdigit() and tz_part[3:].isdigit(): + normalized = f"{date_part}+{tz_part}" + parsed = datetime.fromisoformat(normalized) + return parsed.astimezone(UTC) if parsed.tzinfo else parsed.replace(tzinfo=UTC) + except ValueError as exc: + raise HTTPException(422, f"Invalid as_of timestamp: {as_of}") from exc + + +def _db_timestamp(dt: datetime, dialect: str) -> datetime: + utc_dt = dt.astimezone(UTC) if dt.tzinfo else dt.replace(tzinfo=UTC) + if dialect == "sqlite": + return utc_dt.replace(tzinfo=None) + return utc_dt + + +def _envelope_from_revision( + row: ComputeConfigurationRevision, + *, + as_of_dt: datetime | None = None, +) -> dict[str, Any]: + return { + "config": dict(row.config_payload or {}), + "revision": row.publish_id, + "publish_id": row.publish_id, + "published_at": to_iso8601_utc(row.published_at), + "action": row.action, + "is_default": bool(row.is_default_content), + "as_of": to_iso8601_utc(as_of_dt) if as_of_dt else None, + "snapshot_unavailable": False, + "presentation_status": row.presentation_status, + } + + +def _normalize_cached_envelope(payload: dict[str, Any]) -> dict[str, Any]: + out = dict(payload) + rev = out.get("revision") or out.get("publish_id") or DEFAULT_REVISION + out["revision"] = rev + out["publish_id"] = rev + out.setdefault("published_at", None) + out.setdefault("action", "baseline" if out.get("is_default") else "publish") + out.setdefault("is_default", False) + out.setdefault("snapshot_unavailable", False) + return out + + +async def ensure_compute_revision_baseline( + db: AsyncSession, + *, + commit: bool = True, + published_at: datetime | None = None, +) -> ComputeConfigurationRevision | None: + """Idempotently seal the initial compute configuration baseline into the revision ledger.""" + if not _is_relational_session(db): + return None + existing = ( + await db.execute( + select(ComputeConfigurationRevision) + .order_by(ComputeConfigurationRevision.id.asc()) + .limit(1) + ) + ).scalar_one_or_none() + if isinstance(existing, ComputeConfigurationRevision): + return existing + + setting_row = ( + await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY)) + ).scalar_one_or_none() + if setting_row is not None and isinstance(setting_row.payload, dict): + config_dict = dict(setting_row.payload.get("config") or default_envelope()["config"]) + publish_id = str(setting_row.payload.get("revision") or DEFAULT_REVISION) + else: + config_dict = default_envelope()["config"] + publish_id = DEFAULT_REVISION + + fp = compute_content_fingerprint(config_dict) + now = published_at or datetime.now(UTC) + dialect = _dialect_name(db) + baseline = ComputeConfigurationRevision( + publish_id=publish_id, + parent_publish_id=None, + action="baseline", + content_fingerprint=fp, + is_default_content=(fp == DEFAULT_CONTENT_FINGERPRINT), + config_payload=config_dict, + diff_summary=[], + source_candidate_ids=[], + publish_note="", + published_by_id=None, + published_by_name=None, + published_by_role=None, + published_at=_db_timestamp(now, dialect), + presentation_status="skipped", + presentation_attempts=0, + presentation_error="", + ) + db.add(baseline) + await db.flush() + if commit: + await db.commit() + return baseline + + +async def read_configuration( + db: AsyncSession, + *, + as_of: datetime | str | None = None, + publish_id: str | None = None, +) -> dict[str, Any]: + """Read current, pinned `publish_id`, or `as_of` historical compute configuration.""" + as_of_dt = _parse_as_of(as_of) + pid = (publish_id or "").strip() or None + dialect = _dialect_name(db) + + if pid is not None: + row = ( + await db.execute( + select(ComputeConfigurationRevision).where( + ComputeConfigurationRevision.publish_id == pid + ) + ) + ).scalar_one_or_none() + if not isinstance(row, ComputeConfigurationRevision): + raise HTTPException(404, f"Compute configuration revision not found: {pid}") + return _envelope_from_revision(row, as_of_dt=as_of_dt) + + if as_of_dt is not None: + bound_ts = _db_timestamp(as_of_dt, dialect) + row = ( + await db.execute( + select(ComputeConfigurationRevision) + .where(ComputeConfigurationRevision.published_at <= bound_ts) + .order_by( + desc(ComputeConfigurationRevision.published_at), + desc(ComputeConfigurationRevision.id), + ) + .limit(1) + ) + ).scalar_one_or_none() + if not isinstance(row, ComputeConfigurationRevision): + return { + "config": None, + "revision": None, + "publish_id": None, + "published_at": None, + "action": None, + "is_default": False, + "as_of": to_iso8601_utc(as_of_dt), + "snapshot_unavailable": True, + "notice": INCOMPLETE_SNAPSHOT_NOTICE, + } + return _envelope_from_revision(row, as_of_dt=as_of_dt) + record = ( await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY)) ).scalar_one_or_none() - return dict(record.payload) if record else default_envelope() + if record is not None and isinstance(record.payload, dict): + return _normalize_cached_envelope(record.payload) + return default_envelope() -def configuration_response(envelope: dict) -> dict: +def configuration_response(envelope: dict[str, Any]) -> dict[str, Any]: return { **envelope, "countries": [ @@ -46,6 +276,46 @@ def configuration_response(envelope: dict) -> dict: } +async def _load_locked_setting(db: AsyncSession, dialect: str) -> SystemSetting: + if dialect == "postgresql": + await db.execute( + pg_insert(SystemSetting) + .values(category=CATEGORY, payload=default_envelope()) + .on_conflict_do_nothing(index_elements=[SystemSetting.category]) + ) + return ( + await db.execute( + select(SystemSetting) + .where(SystemSetting.category == CATEGORY) + .with_for_update() + ) + ).scalar_one() + + if dialect == "sqlite": + existing = ( + await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY)) + ).scalar_one_or_none() + if existing is None: + existing = SystemSetting(category=CATEGORY, payload=default_envelope()) + db.add(existing) + await db.flush() + return existing + + # Fallback for mock DB sessions in isolated unit tests. + await db.execute( + pg_insert(SystemSetting) + .values(category=CATEGORY, payload=default_envelope()) + .on_conflict_do_nothing(index_elements=[SystemSetting.category]) + ) + return ( + await db.execute( + select(SystemSetting) + .where(SystemSetting.category == CATEGORY) + .with_for_update() + ) + ).scalar_one() + + async def publish_configuration( db: AsyncSession, *, @@ -53,47 +323,219 @@ async def publish_configuration( config: ComputeConfiguration, actor: User, reset: bool = False, -) -> dict: - # The unique category plus row lock also serializes concurrent first writes. - await db.execute( - insert(SystemSetting) - .values(category=CATEGORY, payload=default_envelope()) - .on_conflict_do_nothing(index_elements=[SystemSetting.category]) - ) - record = ( - await db.execute( - select(SystemSetting).where(SystemSetting.category == CATEGORY).with_for_update() - ) - ).scalar_one() - if record.payload["revision"] != revision: + publish_note: str = "", + source_candidate_ids: list[int] | None = None, +) -> dict[str, Any]: + """Atomically publish or reset compute configuration, writing revision history and cache together.""" + dialect = _dialect_name(db) + relational = dialect in {"postgresql", "sqlite"} + record = await _load_locked_setting(db, dialect) + + before = _normalize_cached_envelope(record.payload) + current_publish_id = str(before["revision"]) + if current_publish_id != revision: await db.rollback() raise HTTPException(409, "Configuration changed. Reload before saving your edits.") - envelope = ( - default_envelope() - if reset - else { - "config": config.model_dump(mode="json"), - "revision": uuid4().hex, - "is_default": reset, + + effective_config = DEFAULT_CONFIGURATION if reset else config + note = (publish_note or "").strip() + candidate_ids = list(dict.fromkeys(int(cid) for cid in (source_candidate_ids or []))) + + old_config = ComputeConfiguration.model_validate(before["config"]) + old_fp = compute_content_fingerprint(old_config) + new_config_dict = effective_config.model_dump(mode="json") + new_fp = compute_content_fingerprint(effective_config) + + if new_fp == old_fp and (not reset or bool(before.get("is_default"))): + return { + **before, + "publish_id": current_publish_id, + "no_changes": True, + "presentation_status": "skipped", } - ) - before = record.payload - if reset: - await db.delete(record) - else: - record.payload = envelope - # Audit and configuration commit together: a published edit must be attributable. + + # Share-metric mixed-source guard (M2): require explicit denominator note in publish_note. + if not reset and not note: + for obs in effective_config.observations: + if obs.metric in SHARE_METRICS and has_mixed_sources(obs): + await db.rollback() + raise HTTPException( + 422, + "跨报告局部修订份额数据时,必须在发布说明中写明同分母依据。", + ) + + referenced_candidates: list[ComputeEvidenceCandidate] = [] + if candidate_ids and relational: + found = ( + ( + await db.execute( + select(ComputeEvidenceCandidate).where( + ComputeEvidenceCandidate.id.in_(candidate_ids) + ) + ) + ) + .scalars() + .all() + ) + by_id = {c.id: c for c in found} + for cid in candidate_ids: + cand = by_id.get(cid) + if cand is None or cand.status != "approved" or cand.published_publish_id: + await db.rollback() + raise HTTPException( + 422, + f"候选证据 #{cid} 不存在、未审核通过或已随其他版本发布。", + ) + referenced_candidates.append(cand) + + now = datetime.now(UTC) + if relational: + latest_rev = ( + await db.execute( + select(ComputeConfigurationRevision) + .order_by(desc(ComputeConfigurationRevision.id)) + .limit(1) + ) + ).scalar_one_or_none() + if not isinstance(latest_rev, ComputeConfigurationRevision): + latest_rev = await ensure_compute_revision_baseline( + db, commit=False, published_at=now - timedelta(milliseconds=1) + ) + if latest_rev is not None and latest_rev.published_at is not None: + prev_ts = latest_rev.published_at + prev_utc = prev_ts.astimezone(UTC) if prev_ts.tzinfo else prev_ts.replace(tzinfo=UTC) + if now <= prev_utc: + now = prev_utc + timedelta(milliseconds=1) + + diff_summary = diff_compute_configurations(old_config, effective_config) + new_publish_id = uuid4().hex + is_default_content = new_fp == DEFAULT_CONTENT_FINGERPRINT + action = "reset" if reset else "publish" + presentation_status = "pending" if has_observation_value_delta(diff_summary) else "skipped" + + envelope: dict[str, Any] = { + "config": new_config_dict, + "revision": new_publish_id, + "publish_id": new_publish_id, + "published_at": to_iso8601_utc(now), + "action": action, + "is_default": is_default_content, + "no_changes": False, + "presentation_status": presentation_status, + "snapshot_unavailable": False, + } + + if relational: + revision_row = ComputeConfigurationRevision( + publish_id=new_publish_id, + parent_publish_id=current_publish_id, + action=action, + content_fingerprint=new_fp, + is_default_content=is_default_content, + config_payload=new_config_dict, + diff_summary=diff_summary, + source_candidate_ids=candidate_ids, + publish_note=note, + published_by_id=getattr(actor, "id", None), + published_by_name=getattr(actor, "username", None), + published_by_role=getattr(actor, "role", None), + published_at=_db_timestamp(now, dialect), + presentation_status=presentation_status, + presentation_attempts=0, + presentation_error="", + ) + db.add(revision_row) + for cand in referenced_candidates: + cand.published_publish_id = new_publish_id + + # Keep SystemSetting as synchronized current-version cache (never delete on reset). + record.payload = { + "config": new_config_dict, + "revision": new_publish_id, + "publish_id": new_publish_id, + "published_at": to_iso8601_utc(now), + "action": action, + "is_default": is_default_content, + } + db.add( AuditLog( - actor_id=actor.id, - actor_name=actor.username, + actor_id=getattr(actor, "id", None), + actor_name=getattr(actor, "username", None), action="compute_comparison.reset" if reset else "compute_comparison.update", target_type="system_setting", target_id=CATEGORY, result="success", request_id=get_request_id(), - details={"before": before, "after": envelope}, + details={ + "before": before, + "after": envelope, + "publish_id": new_publish_id, + "parent_publish_id": current_publish_id, + "publish_note": note, + "source_candidate_ids": candidate_ids, + "diff_summary": diff_summary[:25], + }, ) ) await db.commit() return envelope + + +async def list_configuration_revisions( + db: AsyncSession, + *, + limit: int = 20, + redact: bool = False, +) -> list[dict[str, Any]]: + """List recent compute configuration revisions newest first.""" + bounded = max(1, min(int(limit), 100)) + rows = ( + ( + await db.execute( + select(ComputeConfigurationRevision) + .order_by(desc(ComputeConfigurationRevision.id)) + .limit(bounded) + ) + ) + .scalars() + .all() + ) + items: list[dict[str, Any]] = [] + for row in rows: + change_count, summary_text = summarize_diff(row.diff_summary or [], action=row.action) + if redact: + items.append( + { + "id": row.id, + "publish_id": row.publish_id, + "action": row.action, + "published_at": to_iso8601_utc(row.published_at), + "is_default_content": bool(row.is_default_content), + "change_count": change_count, + "summary": summary_text, + } + ) + else: + items.append( + { + "id": row.id, + "publish_id": row.publish_id, + "parent_publish_id": row.parent_publish_id, + "action": row.action, + "published_at": to_iso8601_utc(row.published_at), + "is_default_content": bool(row.is_default_content), + "change_count": change_count, + "summary": summary_text, + "diff_summary": list(row.diff_summary or []), + "publish_note": row.publish_note or "", + "published_by_name": row.published_by_name, + "published_by_role": row.published_by_role, + "source_candidate_ids": list(row.source_candidate_ids or []), + "presentation_status": row.presentation_status, + "presentation_attempts": int(row.presentation_attempts or 0), + "presentation_error": row.presentation_error or "", + "presentation_delivered_at": to_iso8601_utc(row.presentation_delivered_at), + } + ) + return items diff --git a/backend/app/services/compute_history.py b/backend/app/services/compute_history.py index 47024339..52b87b4a 100644 --- a/backend/app/services/compute_history.py +++ b/backend/app/services/compute_history.py @@ -4,7 +4,12 @@ from copy import deepcopy from datetime import date from typing import Literal -from app.schemas.compute_configuration import ComputeConfiguration, ComputeObservation +from app.schemas.compute_configuration import ( + ComputeConfiguration, + ComputeObservation, + has_mixed_sources, + source_for, +) from app.services.compute_catalog import ( CATALOG, DEFAULT_PARTICIPANTS, @@ -130,6 +135,8 @@ def _latest_bilateral_pair( "rpi_percent": round(cn_val / us_val * 100, 1), "gap_pp": round(cn_val - us_val, 2), "evidence_id": latest.source_id, + "cn_evidence_id": source_for(latest, "CN"), + "us_evidence_id": source_for(latest, "US"), } if len(candidates) >= 2: prev = candidates[-2] @@ -161,6 +168,8 @@ def _build_bilateral_rpi(config: ComputeConfiguration, enabled: bool) -> dict | "rpi_percent": round(row.values["CN"] / row.values["US"] * 100, 1), "gap_pp": round(row.values["CN"] - row.values["US"], 2), "evidence_id": row.source_id, + "cn_evidence_id": source_for(row, "CN"), + "us_evidence_id": source_for(row, "US"), } for row in total_rows ] @@ -203,7 +212,7 @@ def _build_denominator_attribution( "latest_value": latest.values[country], "latest_global_total": latest.global_total, "unit": "EFlop/s (FP32)", - "evidence_ids": [latest.source_id], + "evidence_ids": [source_for(latest, country)], } denom_rows = [row for row in country_rows if row.global_total and row.global_total > 0] if len(denom_rows) >= 2: @@ -227,7 +236,9 @@ def _build_denominator_attribution( "global_to": curr_global, "global_growth_pct": round(global_growth, 1), "diluted_by_global_expansion": global_growth > country_growth, - "evidence_ids": list(dict.fromkeys([prev_row.source_id, curr_row.source_id])), + "evidence_ids": list( + dict.fromkeys([source_for(prev_row, country), source_for(curr_row, country)]) + ), } ) elif len(country_rows) >= 2: @@ -243,7 +254,9 @@ def _build_denominator_attribution( "country_from": prev_val, "country_to": curr_val, "country_growth_pct": round((curr_val - prev_val) / prev_val * 100, 1), - "evidence_ids": list(dict.fromkeys([prev_row.source_id, curr_row.source_id])), + "evidence_ids": list( + dict.fromkeys([source_for(prev_row, country), source_for(curr_row, country)]) + ), } ) result[code] = entry @@ -294,8 +307,19 @@ def compute_history( record = annual.get(year) observations = record.values if record else {} values, coverage = {}, {} + evidence_by_code: dict[str, list[str]] = {} for code, members in members_by_participant.items(): values[code], coverage[code] = _participant_value(members, observations, mode) + if record is not None: + evidence_by_code[code] = list( + dict.fromkeys( + source_for(record, member) + for member in members + if member in record.values + ) + ) + else: + evidence_by_code[code] = [] evidence_id = record.source_id if record else None rows.append( { @@ -305,6 +329,8 @@ def compute_history( "coverage": coverage, "global_total": record.global_total if record else None, "evidence_id": evidence_id, + "evidence_by_code": evidence_by_code, + "mixed_sources": has_mixed_sources(record) if record else False, } ) @@ -314,12 +340,28 @@ def compute_history( code: _participant_value(members, share_obs, "global_share")[0] for code, members in members_by_participant.items() } + share_evidence_by_code = { + code: ( + list( + dict.fromkeys( + source_for(share_record, member) + for member in members + if member in share_record.values + ) + ) + if share_record is not None + else [] + ) + for code, members in members_by_participant.items() + } divergence_rows.append( { "year": year, "period_label": (share_record.period_label or str(year)) if share_record else None, "values": share_values, "evidence_id": share_record.source_id if share_record else None, + "evidence_by_code": share_evidence_by_code, + "mixed_sources": has_mixed_sources(share_record) if share_record else False, } ) diff --git a/backend/app/services/compute_lineage.py b/backend/app/services/compute_lineage.py new file mode 100644 index 00000000..ebfd5805 --- /dev/null +++ b/backend/app/services/compute_lineage.py @@ -0,0 +1,430 @@ +"""Read-time lineage derivation and revision change context for compute observations.""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from fastapi import HTTPException +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.enums import UserRole +from app.models.compute_configuration_revision import ComputeConfigurationRevision +from app.models.situational_assessment import ComputeEvidenceCandidate, EvidenceRecord +from app.models.user import User +from app.schemas.compute_configuration import ( + ComputeConfiguration, + has_mixed_sources, + source_for, +) +from app.services.compute_catalog import PARTICIPANTS +from app.services.compute_configuration import read_configuration +from app.services.compute_revision_diff import ( + COUNTRY_ZH_LABELS, + METRIC_ZH_LABELS, + format_diff_entry, +) + +REVIEW_REASON_LABELS_ZH: dict[str, str] = { + "newer_authoritative_report": "更权威新版报告更新", + "corrects_prior_error": "更正历史录入误差", + "adds_missing_observation": "补充缺失年份观测", + "methodology_update": "同分母方法学修订", + "unverifiable_source": "来源无法核验", + "denominator_mismatch": "统计口径或分母不一致", + "extraction_error": "自动提取数值错误", + "superseded": "已被更新报告取代", + "duplicate": "重复候选", +} + +REDACTED_ACTOR_LABEL = "已人工复核" + +_REVISION_QUESTION_KEYWORDS = ( + "为什么变", + "为何变", + "怎么变", + "修订", + "改了", + "更正", + "重述", + "变动原因", + "变化原因", + "why did it change", + "what changed", + "why changed", + "revised", + "restated", + "revision", +) + + +def is_admin_user(user: User | None) -> bool: + return bool( + user is not None + and user.role in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value} + ) + + +def is_revision_question(question: str | None) -> bool: + q = (question or "").strip().lower() + if not q: + return False + return any(kw in q for kw in _REVISION_QUESTION_KEYWORDS) + + +def _iso(dt: Any) -> str | None: + if isinstance(dt, datetime): + return dt.isoformat() + if isinstance(dt, str): + return dt + return None + + +def _source_payload( + source_id: str | None, + sources_by_id: dict[str, Any], + ev_by_id: dict[str, EvidenceRecord], +) -> dict[str, Any] | None: + if not source_id: + return None + src = sources_by_id.get(source_id) + ev = ev_by_id.get(source_id) + if src is None and ev is None: + return {"id": source_id} + published_at: str | None = None + if src is not None and getattr(src, "published_at", None) is not None: + published_at = src.published_at.isoformat() + elif ev is not None and ev.published_at is not None: + published_at = _iso(ev.published_at) + return { + "id": source_id, + "title": (src.title if src is not None else None) or (ev.title if ev is not None else source_id), + "publisher": (src.publisher if src is not None else None) or (ev.publisher if ev is not None else ""), + "url": (src.url if src is not None else None) or (ev.url if ev is not None else ""), + "locator": (src.locator if src is not None else None) or (ev.locator if ev is not None else ""), + "report_year": src.report_year if src is not None else None, + "published_at": published_at, + "excerpt": ev.excerpt if ev is not None else None, + "content_sha256": ev.content_sha256 if ev is not None else None, + "retrieved_at": _iso(ev.retrieved_at) if ev is not None else None, + } + + +def _match_candidate_for_diff( + candidates: list[ComputeEvidenceCandidate], + *, + metric: str, + year: int, + code: str, +) -> ComputeEvidenceCandidate | None: + for cand in candidates: + proposed = cand.proposed_payload if isinstance(cand.proposed_payload, dict) else {} + if ( + str(proposed.get("metric") or "") == metric + and int(proposed.get("year") or 0) == year + and code in (proposed.get("values") or {}) + ): + return cand + for cand in candidates: + proposed = cand.proposed_payload if isinstance(cand.proposed_payload, dict) else {} + if str(proposed.get("metric") or "") == metric and int(proposed.get("year") or 0) == year: + return cand + return candidates[0] if len(candidates) == 1 else None + + +async def build_observation_lineage( + db: AsyncSession, + *, + code: str, + metric: str, + year: int, + publish_id: str | None = None, + as_of: str | None = None, + redact: bool = True, + max_revisions: int = 50, +) -> dict[str, Any]: + """Derive full observation provenance & revision timeline at read time without a mirror table.""" + norm_code = (code or "").strip().upper() + if norm_code not in PARTICIPANTS: + raise HTTPException(status_code=422, detail=f"Unknown compute participant code: {code}") + if metric not in METRIC_ZH_LABELS: + raise HTTPException(status_code=422, detail=f"Unknown compute metric: {metric}") + + envelope = await read_configuration(db, as_of=as_of, publish_id=publish_id) + if envelope.get("snapshot_unavailable"): + return { + "code": norm_code, + "country_name": COUNTRY_ZH_LABELS.get(norm_code) or PARTICIPANTS[norm_code].get("name") or norm_code, + "metric": metric, + "metric_label": METRIC_ZH_LABELS[metric], + "year": year, + "period_label": None, + "publish_id": None, + "published_at": None, + "as_of": envelope.get("as_of"), + "snapshot_unavailable": True, + "notice": envelope.get("notice"), + "redacted": redact, + "current": None, + "timestamps": { + "observation_period": str(year), + "report_published_at": None, + "ingested_at": None, + "effective_published_at": None, + }, + "timeline": [], + } + + cfg = ComputeConfiguration.model_validate(envelope["config"]) + effective_pid = str(envelope.get("publish_id") or envelope.get("revision") or "") + sources_by_id = {src.id: src for src in cfg.sources} + obs_row = next( + (obs for obs in cfg.observations if obs.metric == metric and obs.year == year), + None, + ) + current_value = float(obs_row.values[norm_code]) if (obs_row is not None and norm_code in obs_row.values) else None + current_source_id: str | None = None + if obs_row is not None: + current_source_id = source_for(obs_row, norm_code) if norm_code in obs_row.values else obs_row.source_id + + revisions: list[ComputeConfigurationRevision] = [] + if hasattr(db, "execute"): + target_rev: ComputeConfigurationRevision | None = None + if effective_pid: + target_rev = ( + await db.execute( + select(ComputeConfigurationRevision).where( + ComputeConfigurationRevision.publish_id == effective_pid + ) + ) + ).scalar_one_or_none() + stmt = select(ComputeConfigurationRevision) + if target_rev is not None: + stmt = stmt.where(ComputeConfigurationRevision.id <= target_rev.id) + stmt = stmt.order_by(ComputeConfigurationRevision.id.desc()).limit(max_revisions) + revisions = list((await db.execute(stmt)).scalars().all()) + + candidate_ids: set[int] = set() + referenced_source_ids: set[str] = set() + if current_source_id: + referenced_source_ids.add(current_source_id) + + matched_pairs: list[tuple[ComputeConfigurationRevision, dict[str, Any]]] = [] + for rev in revisions: + for entry in rev.diff_summary or []: + if not isinstance(entry, dict): + continue + if ( + entry.get("kind") == "observation_value" + and str(entry.get("metric") or "") == metric + and int(entry.get("year") or 0) == year + and str(entry.get("code") or "").upper() == norm_code + ): + matched_pairs.append((rev, entry)) + for cid in rev.source_candidate_ids or []: + if isinstance(cid, int): + candidate_ids.add(cid) + for sid_key in ("old_source_id", "new_source_id"): + sid_val = entry.get(sid_key) + if isinstance(sid_val, str) and sid_val: + referenced_source_ids.add(sid_val) + + candidates_by_id: dict[int, ComputeEvidenceCandidate] = {} + ev_by_id: dict[str, EvidenceRecord] = {} + if hasattr(db, "execute"): + if candidate_ids: + cand_rows = ( + await db.execute( + select(ComputeEvidenceCandidate).where( + ComputeEvidenceCandidate.id.in_(sorted(candidate_ids)) + ) + ) + ).scalars().all() + candidates_by_id = {c.id: c for c in cand_rows} + if referenced_source_ids: + ev_rows = ( + await db.execute( + select(EvidenceRecord).where( + EvidenceRecord.id.in_(sorted(referenced_source_ids)) + ) + ) + ).scalars().all() + ev_by_id = {ev.id: ev for ev in ev_rows} + + timeline: list[dict[str, Any]] = [] + latest_ingested_at: str | None = None + latest_effective_published_at: str | None = None + for rev, entry in matched_pairs: + rev_candidates = [ + candidates_by_id[cid] + for cid in (rev.source_candidate_ids or []) + if isinstance(cid, int) and cid in candidates_by_id + ] + cand = _match_candidate_for_diff( + rev_candidates, metric=metric, year=year, code=norm_code + ) + reason_code = cand.review_reason_code if cand is not None else None + reason_label = REVIEW_REASON_LABELS_ZH.get(reason_code) if reason_code else None + cand_created = _iso(cand.created_at) if cand is not None else None + rev_pub_at = _iso(rev.published_at) + if latest_effective_published_at is None and rev_pub_at: + latest_effective_published_at = rev_pub_at + if latest_ingested_at is None and cand_created: + latest_ingested_at = cand_created + + old_src_id = entry.get("old_source_id") + new_src_id = entry.get("new_source_id") + item: dict[str, Any] = { + "revision_id": rev.id, + "publish_id": rev.publish_id, + "published_at": rev_pub_at, + "action": rev.action, + "old_value": entry.get("old_value"), + "new_value": entry.get("new_value"), + "delta": entry.get("delta"), + "change_kind": entry.get("change_kind"), + "summary": format_diff_entry(entry), + "old_source_id": old_src_id, + "new_source_id": new_src_id, + "old_source": _source_payload(old_src_id, sources_by_id, ev_by_id) if old_src_id else None, + "new_source": _source_payload(new_src_id, sources_by_id, ev_by_id) if new_src_id else None, + "candidate_id": cand.id if cand is not None else None, + "candidate_created_at": cand_created, + "review_reason_code": reason_code, + "review_reason_label": reason_label, + "review_reason": None if redact else (cand.review_reason if cand is not None else None), + "reviewed_by": ( + (REDACTED_ACTOR_LABEL if (cand is not None and cand.reviewed_by) else None) + if redact + else (cand.reviewed_by if cand is not None else None) + ), + "reviewed_at": _iso(cand.reviewed_at) if cand is not None else None, + "publish_note": None if redact else (rev.publish_note or None), + "published_by_name": ( + (REDACTED_ACTOR_LABEL if rev.published_by_name else None) + if redact + else rev.published_by_name + ), + } + if not redact: + item["published_by_role"] = rev.published_by_role + timeline.append(item) + + current_source = _source_payload(current_source_id, sources_by_id, ev_by_id) + effective_published_at = latest_effective_published_at or envelope.get("published_at") + return { + "code": norm_code, + "country_name": COUNTRY_ZH_LABELS.get(norm_code) or PARTICIPANTS[norm_code].get("name") or norm_code, + "metric": metric, + "metric_label": METRIC_ZH_LABELS[metric], + "year": year, + "period_label": obs_row.period_label if obs_row is not None else None, + "publish_id": effective_pid, + "published_at": envelope.get("published_at"), + "as_of": envelope.get("as_of"), + "snapshot_unavailable": False, + "redacted": redact, + "current": { + "value": current_value, + "unit": "EFlops" if metric == "absolute" else "%", + "source_id": current_source_id, + "mixed_sources": has_mixed_sources(obs_row) if obs_row is not None else False, + "source": current_source, + }, + "timestamps": { + "observation_period": ( + obs_row.period_label + if (obs_row is not None and obs_row.period_label) + else str(year) + ), + "report_published_at": (current_source or {}).get("published_at"), + "ingested_at": latest_ingested_at, + "effective_published_at": effective_published_at, + }, + "timeline": timeline, + } + + +async def build_revision_change_context( + db: AsyncSession, + *, + publish_id: str | None = None, + redact: bool = True, +) -> dict[str, Any] | None: + """Return current/pinned revision diff & linked candidate review rationale for Copilot context.""" + if not hasattr(db, "execute"): + return None + rev_row: ComputeConfigurationRevision | None = None + if publish_id: + rev_row = ( + await db.execute( + select(ComputeConfigurationRevision).where( + ComputeConfigurationRevision.publish_id == publish_id + ) + ) + ).scalar_one_or_none() + if rev_row is None: + rev_row = ( + await db.execute( + select(ComputeConfigurationRevision) + .order_by(ComputeConfigurationRevision.id.desc()) + .limit(1) + ) + ).scalar_one_or_none() + if rev_row is None: + return None + + cand_ids = [cid for cid in (rev_row.source_candidate_ids or []) if isinstance(cid, int)] + candidates: list[ComputeEvidenceCandidate] = [] + if cand_ids: + candidates = list( + ( + await db.execute( + select(ComputeEvidenceCandidate).where( + ComputeEvidenceCandidate.id.in_(cand_ids) + ) + ) + ).scalars().all() + ) + + diff_items: list[dict[str, Any]] = [] + for entry in rev_row.diff_summary or []: + if not isinstance(entry, dict): + continue + item = { + **entry, + "summary": format_diff_entry(entry), + } + diff_items.append(item) + + candidate_reasons: list[dict[str, Any]] = [] + for cand in candidates: + code = cand.review_reason_code + reason_label = REVIEW_REASON_LABELS_ZH.get(code) if code else None + src_payload = cand.source_payload if isinstance(cand.source_payload, dict) else {} + prop_payload = cand.proposed_payload if isinstance(cand.proposed_payload, dict) else {} + candidate_reasons.append( + { + "candidate_id": cand.id, + "source_id": src_payload.get("id") or prop_payload.get("source_id"), + "source_title": src_payload.get("title") or "", + "review_reason_code": code, + "review_reason_label": reason_label, + "review_reason": None if redact else (cand.review_reason or None), + "reviewed_by": (REDACTED_ACTOR_LABEL if cand.reviewed_by else None) if redact else cand.reviewed_by, + "reviewed_at": _iso(cand.reviewed_at), + } + ) + + return { + "revision_id": rev_row.id, + "publish_id": rev_row.publish_id, + "parent_publish_id": rev_row.parent_publish_id, + "published_at": _iso(rev_row.published_at), + "action": rev_row.action, + "publish_note": None if redact else (rev_row.publish_note or None), + "diff_summary": diff_items, + "candidate_reasons": candidate_reasons, + "redacted": redact, + } diff --git a/backend/app/services/compute_revision_diff.py b/backend/app/services/compute_revision_diff.py new file mode 100644 index 00000000..98ae1489 --- /dev/null +++ b/backend/app/services/compute_revision_diff.py @@ -0,0 +1,311 @@ +"""Pure diff utilities for versioned compute comparison configurations.""" + +from __future__ import annotations + +from typing import Any + +from app.schemas.compute_configuration import ( + ComputeConfiguration, + ComputeObservation, + source_for, +) + +METRIC_ZH_LABELS: dict[str, str] = { + "global_share": "全球总算力份额", + "intelligent_share": "全球智能算力份额", + "absolute": "计算设备总规模", + "frontier_cluster_share": "前沿智算集群份额", + "chip_inflow_share": "高端算力芯片流向份额", +} + +COUNTRY_ZH_LABELS: dict[str, str] = { + "CN": "中国", + "US": "美国", + "JP": "日本", + "DE": "德国", + "GB": "英国", + "FR": "法国", + "KR": "韩国", + "IN": "印度", +} + + +def _observation_key(row: ComputeObservation) -> tuple[str, int]: + return (row.metric, row.year) + + +def _diff_keyed_section( + section: str, + old_items: dict[Any, dict[str, Any]], + new_items: dict[Any, dict[str, Any]], +) -> dict[str, Any] | None: + old_keys = set(old_items) + new_keys = set(new_items) + added = len(new_keys - old_keys) + removed = len(old_keys - new_keys) + modified = sum(1 for key in (old_keys & new_keys) if old_items[key] != new_items[key]) + if not (added or removed or modified): + return None + return { + "kind": "section_changed", + "section": section, + "added": added, + "removed": removed, + "modified": modified, + } + + +def diff_compute_configurations( + old: ComputeConfiguration, + new: ComputeConfiguration, +) -> list[dict[str, Any]]: + """Compute structured observation-level diffs and section-level counts between two configs.""" + diffs: list[dict[str, Any]] = [] + + old_obs = {_observation_key(row): row for row in old.observations} + new_obs = {_observation_key(row): row for row in new.observations} + + all_keys = sorted(set(old_obs) | set(new_obs), key=lambda k: (k[0], k[1])) + for metric, year in all_keys: + old_row = old_obs.get((metric, year)) + new_row = new_obs.get((metric, year)) + + if old_row is None and new_row is not None: + diffs.append( + { + "kind": "observation_row_added", + "metric": metric, + "year": year, + "period_label": new_row.period_label, + } + ) + for code in sorted(new_row.values): + new_val = float(new_row.values[code]) + diffs.append( + { + "kind": "observation_value", + "metric": metric, + "year": year, + "period_label": new_row.period_label, + "code": code, + "old_value": None, + "new_value": new_val, + "delta": round(new_val, 4), + "change_kind": "new_observation", + "old_source_id": None, + "new_source_id": source_for(new_row, code), + } + ) + continue + + if old_row is not None and new_row is None: + diffs.append( + { + "kind": "observation_row_removed", + "metric": metric, + "year": year, + "period_label": old_row.period_label, + } + ) + for code in sorted(old_row.values): + old_val = float(old_row.values[code]) + diffs.append( + { + "kind": "observation_value", + "metric": metric, + "year": year, + "period_label": old_row.period_label, + "code": code, + "old_value": old_val, + "new_value": None, + "delta": round(-old_val, 4), + "change_kind": "observation_removed", + "old_source_id": source_for(old_row, code), + "new_source_id": None, + } + ) + continue + + assert old_row is not None and new_row is not None + if (old_row.period_label or None) != (new_row.period_label or None): + diffs.append( + { + "kind": "period_label_changed", + "metric": metric, + "year": year, + "old": old_row.period_label, + "new": new_row.period_label, + } + ) + + for code in sorted(set(old_row.values) | set(new_row.values)): + has_old = code in old_row.values + has_new = code in new_row.values + old_val = float(old_row.values[code]) if has_old else None + new_val = float(new_row.values[code]) if has_new else None + old_src = source_for(old_row, code) if has_old else None + new_src = source_for(new_row, code) if has_new else None + + if old_val is None and new_val is not None: + diffs.append( + { + "kind": "observation_value", + "metric": metric, + "year": year, + "period_label": new_row.period_label, + "code": code, + "old_value": None, + "new_value": new_val, + "delta": round(new_val, 4), + "change_kind": "new_observation", + "old_source_id": None, + "new_source_id": new_src, + } + ) + elif old_val is not None and new_val is None: + diffs.append( + { + "kind": "observation_value", + "metric": metric, + "year": year, + "period_label": new_row.period_label, + "code": code, + "old_value": old_val, + "new_value": None, + "delta": round(-old_val, 4), + "change_kind": "observation_removed", + "old_source_id": old_src, + "new_source_id": None, + } + ) + elif old_val is not None and new_val is not None: + delta = round(new_val - old_val, 4) + if delta != 0: + diffs.append( + { + "kind": "observation_value", + "metric": metric, + "year": year, + "period_label": new_row.period_label, + "code": code, + "old_value": old_val, + "new_value": new_val, + "delta": delta, + "change_kind": "historical_revision", + "old_source_id": old_src, + "new_source_id": new_src, + } + ) + elif old_src != new_src: + diffs.append( + { + "kind": "observation_value", + "metric": metric, + "year": year, + "period_label": new_row.period_label, + "code": code, + "old_value": old_val, + "new_value": new_val, + "delta": 0.0, + "change_kind": "source_reattributed", + "old_source_id": old_src, + "new_source_id": new_src, + } + ) + + section_specs = [ + ( + "sources", + {s.id: s.model_dump(mode="json") for s in old.sources}, + {s.id: s.model_dump(mode="json") for s in new.sources}, + ), + ( + "innovation", + {row.year: row.model_dump(mode="json") for row in old.innovation}, + {row.year: row.model_dump(mode="json") for row in new.innovation}, + ), + ( + "structures", + {(row.scope, row.year): row.model_dump(mode="json") for row in old.structures}, + {(row.scope, row.year): row.model_dump(mode="json") for row in new.structures}, + ), + ( + "milestones", + {row.id: row.model_dump(mode="json") for row in old.milestones}, + {row.id: row.model_dump(mode="json") for row in new.milestones}, + ), + ( + "national_hubs", + {row.id: row.model_dump(mode="json") for row in old.national_hubs}, + {row.id: row.model_dump(mode="json") for row in new.national_hubs}, + ), + ] + for section_name, old_map, new_map in section_specs: + entry = _diff_keyed_section(section_name, old_map, new_map) + if entry is not None: + diffs.append(entry) + + return diffs + + +def has_observation_value_delta(diff_summary: list[dict[str, Any]]) -> bool: + """Return True when diff_summary contains at least one non-zero observation value delta.""" + return any( + item.get("kind") == "observation_value" + and item.get("delta") is not None + and float(item["delta"]) != 0.0 + for item in (diff_summary or []) + ) + + +def format_diff_entry(entry: dict[str, Any]) -> str: + """Render a concise Chinese summary string for one diff_summary entry.""" + kind = entry.get("kind") + if kind == "observation_value": + metric = METRIC_ZH_LABELS.get(str(entry.get("metric") or ""), str(entry.get("metric") or "")) + year = entry.get("year") + code = str(entry.get("code") or "") + country = COUNTRY_ZH_LABELS.get(code, code) + unit = " EFlops" if entry.get("metric") == "absolute" else "%" + change_kind = entry.get("change_kind") + if change_kind == "historical_revision": + delta = float(entry.get("delta") or 0.0) + delta_unit = " EFlops" if entry.get("metric") == "absolute" else "pp" + return ( + f"{year} 年 {metric} {country} " + f"{entry.get('old_value')}{unit} → {entry.get('new_value')}{unit}({delta:+.2g}{delta_unit})" + ) + if change_kind == "new_observation": + return f"新增 {year} 年 {metric} {country} {entry.get('new_value')}{unit}" + if change_kind == "observation_removed": + return f"移除 {year} 年 {metric} {country}(原 {entry.get('old_value')}{unit})" + if change_kind == "source_reattributed": + return f"{year} 年 {metric} {country} 来源变更:{entry.get('old_source_id')} → {entry.get('new_source_id')}" + if kind == "period_label_changed": + return f"{entry.get('year')} 年统计周期标签变更:{entry.get('old') or '全年'} → {entry.get('new') or '全年'}" + if kind == "observation_row_added": + return f"新增 {entry.get('year')} 年 {METRIC_ZH_LABELS.get(str(entry.get('metric') or ''), entry.get('metric'))} 观测行" + if kind == "observation_row_removed": + return f"移除 {entry.get('year')} 年 {METRIC_ZH_LABELS.get(str(entry.get('metric') or ''), entry.get('metric'))} 观测行" + if kind == "section_changed": + return ( + f"{entry.get('section')} 变更(+{entry.get('added', 0)} / " + f"-{entry.get('removed', 0)} / ~{entry.get('modified', 0)})" + ) + return "配置已更新" + + +def summarize_diff(diff_summary: list[dict[str, Any]], action: str = "publish") -> tuple[int, str]: + """Return (change_count, first_summary) suitable for revision lists.""" + entries = list(diff_summary or []) + if not entries: + if action == "baseline": + return 0, "初始基线封存" + if action == "reset": + return 0, "恢复内置权威报告数据" + return 0, "无观测数值变更" + primary = next( + (item for item in entries if item.get("kind") == "observation_value"), + entries[0], + ) + return len(entries), format_diff_entry(primary) diff --git a/backend/app/services/data_jobs.py b/backend/app/services/data_jobs.py index a10ab057..ff5f5483 100644 --- a/backend/app/services/data_jobs.py +++ b/backend/app/services/data_jobs.py @@ -628,6 +628,18 @@ async def _clear_derived_datasource_data_in_batches( progress_offset=progress_offset + sum(deleted_counts.values()), ) return deleted_counts + if source == "global_cloud_map": + from app.services.earth_clouds import clear_all_cloud_map_artifacts + + return {"cloud_map_artifacts": clear_all_cloud_map_artifacts()} + if source in {"cloud_hd_tiles", "earth_imagery_sentinel2", "earth_imagery_viirs_daily"}: + from app.services.earth_tiles import clear_tile_source_cache + + return {"tile_cache_files": clear_tile_source_cache(source)} + if source == "global_wind_gfs": + from app.services.earth_wind import clear_all_wind_artifacts + + return {"wind_artifacts": clear_all_wind_artifacts()} return await clear_derived_datasource_data(db, source) @@ -638,6 +650,8 @@ async def _run_clear_cache_job(db: AsyncSession, task: CollectionTask) -> None: earth_deleted_count = invalidate_earth_layer_cache_for_source(source) dashboard_deleted_count = int(cache.delete("dashboard:stats")) + int(cache.delete("dashboard:summary")) + cache.delete_pattern("collected:*") + cache.delete_pattern("data_ledger:*") deleted_count = earth_deleted_count + dashboard_deleted_count task.records_processed = deleted_count diff --git a/backend/app/services/datasource_connectivity.py b/backend/app/services/datasource_connectivity.py index aba0069f..6ade43aa 100644 --- a/backend/app/services/datasource_connectivity.py +++ b/backend/app/services/datasource_connectivity.py @@ -277,6 +277,36 @@ def _prepare_builtin_http_probe( json.dumps({"host": "rrc00", "type": "UPDATE", "require": "announcements"}), ) probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)") + elif source == "global_cloud_map": + if "SERVICE=" not in probe_url.upper(): + probe_params = { + "SERVICE": "WMS", + "REQUEST": "GetMap", + "VERSION": "1.1.1", + "LAYERS": "Himawari_AHI_Band13_Clean_Infrared", + "STYLES": "", + "FORMAT": "image/png", + "TRANSPARENT": "true", + "SRS": "EPSG:4326", + "BBOX": "-180,-90,180,90", + "WIDTH": "64", + "HEIGHT": "32", + } + probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)") + elif source in {"cloud_hd_tiles", "earth_imagery_sentinel2", "earth_imagery_viirs_daily"}: + probe_url = ( + probe_url.replace("{z}", "0") + .replace("{y}", "0") + .replace("{x}", "0") + ) + probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)") + elif source == "global_wind_gfs": + if "?" not in probe_url: + probe_url = ( + f"{probe_url}?ugrd10m[(last)][(-10):10:(10)][(0):10:(10)]," + "vgrd10m[(last)][(-10):10:(10)][(0):10:(10)]" + ) + probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)") return probe_url, probe_params, probe_headers @@ -308,6 +338,36 @@ async def _validate_builtin_probe_response(source: str, response: httpx.Response return "RIS Live 返回非 JSON 响应。" return None if isinstance(payload, dict) else "RIS Live 响应结构异常。" + if source in { + "global_cloud_map", + "cloud_hd_tiles", + "earth_imagery_sentinel2", + "earth_imagery_viirs_daily", + }: + content_type = str(response.headers.get("content-type") or "").lower() + if not content_type.startswith("image/"): + return f"遥感影像上游未返回图像内容(content-type={content_type or 'unknown'})。" + return None + + if source == "global_wind_gfs": + raw = await _read_bounded_probe_bytes(response, limit=8192) + text = raw.decode(response.encoding or "utf-8", errors="replace").strip() + if not text: + return "GFS 风场 ERDDAP 响应为空。" + if "ugrd10m" in text and "vgrd10m" in text: + return None + first_row = next(csv.reader(io.StringIO(text)), []) + if len(first_row) >= 5: + try: + float(first_row[1]) + float(first_row[2]) + float(first_row[3]) + float(first_row[4]) + return None + except ValueError: + pass + return "GFS 风场 ERDDAP 响应格式异常(缺少有效风矢量列)。" + if source not in _ARCGIS_SOURCES | {"bgpstream_bgp", "celestrak_tle", "epoch_ai_gpu"}: return None diff --git a/backend/app/services/earth_boundaries.py b/backend/app/services/earth_boundaries.py index 7a2a3fe3..647f420f 100644 --- a/backend/app/services/earth_boundaries.py +++ b/backend/app/services/earth_boundaries.py @@ -1,13 +1,22 @@ -"""Earth boundary static asset service.""" +"""Earth boundary PMTiles artifact service. + +Sources are downloaded once per build into the persistent boundary data +directory, the China POV builder (``scripts/build_earth_boundary_pmtiles.py``) +produces a versioned PMTiles archive plus small hover assets, and the API +serves them with HTTP Range support. Web and desktop clients share the same +``/api/v1/earth/boundaries/...`` URLs. +""" from __future__ import annotations import asyncio import hashlib import json +import os import shutil -import subprocess import sys +import tempfile +import zipfile from datetime import UTC, datetime from functools import lru_cache from pathlib import Path @@ -16,17 +25,21 @@ from uuid import uuid4 import httpx +from app.core.logging import get_logger + + +logger = get_logger(__name__) REPO_ROOT = Path(__file__).resolve().parents[3] -SOURCE_OUTPUT_DIR = REPO_ROOT / "data/earth-boundary-sources" -SOURCE_MANIFEST_PATH = SOURCE_OUTPUT_DIR / "manifest.json" -BUILD_RESULT_PATH = SOURCE_OUTPUT_DIR / "build-result.json" -BUILD_JOB_PATH = SOURCE_OUTPUT_DIR / "build-job.json" -BOUNDARY_OUTPUT_DIR = REPO_ROOT / "frontend/public/earth/data/boundaries/v1" -BOUNDARY_MANIFEST_PATH = BOUNDARY_OUTPUT_DIR / "manifest.json" -PMTILES_ARTIFACT_PATH = ( - REPO_ROOT / "frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles" +BOUNDARY_DATA_DIR = Path( + os.environ.get("PLANET_EARTH_BOUNDARY_DIR") or REPO_ROOT / "backend/data/earth-boundaries" ) +SOURCE_OUTPUT_DIR = BOUNDARY_DATA_DIR / "sources" +SOURCE_MANIFEST_PATH = SOURCE_OUTPUT_DIR / "manifest.json" +BUILD_RESULT_PATH = BOUNDARY_DATA_DIR / "build-result.json" +BUILD_JOB_PATH = BOUNDARY_DATA_DIR / "build-job.json" +BOUNDARY_OUTPUT_DIR = BOUNDARY_DATA_DIR / "artifacts" +BOUNDARY_MANIFEST_PATH = BOUNDARY_OUTPUT_DIR / "manifest.json" POLICY_FALLBACK_PATH = ( REPO_ROOT / "frontend/public/earth/data/countries-admin0.china-pov-v1.geojson" ) @@ -34,36 +47,78 @@ POV_POLICY_PATH = REPO_ROOT / "config/earth-boundary-pov-policy.china-v1.json" POV_GEOMETRY_PATH = REPO_ROOT / "resources/earth/boundary-pov-geometry.china-v1.json" LOCAL_CONFIG_PATH = REPO_ROOT / "config/earth-boundary-sources.local.json" EXAMPLE_CONFIG_PATH = REPO_ROOT / "config/earth-boundary-sources.example.json" +BUILDER_PATH = REPO_ROOT / "scripts/build_earth_boundary_pmtiles.py" +BUILDER_MODULE_PATHS = ( + BUILDER_PATH, + REPO_ROOT / "scripts/earth_boundary_geometry.py", + REPO_ROOT / "scripts/earth_boundary_policy.py", +) +MANIFEST_SCHEMA = "planet-earth-boundaries/v2" +REQUIRED_TOOLS = ("tippecanoe",) +REQUIRED_POLICY_RULES = {"china-taiwan-penghu", "china-hong-kong", "china-macao", "kosovo"} +DOWNLOAD_CHUNK_BYTES = 1024 * 1024 BOUNDARY_SOURCE_KINDS = { "earth_admin0_boundaries": "admin0-boundaries", "earth_coastline": "coastline", + "earth_disputed_lines": "disputed-lines", "earth_claim_lines": "claim-lines", + "earth_admin1_lines": "admin1-lines", + "earth_populated_places": "populated-places", } +_NE_GEOJSON = "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson" DEFAULT_PUBLIC_BOUNDARY_SOURCES = { "earth_admin0_boundaries": { "displayName": "Natural Earth Admin-0 Countries", "sourceKind": "admin0-boundaries", - "endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_admin_0_countries.geojson", + "endpoint": f"{_NE_GEOJSON}/ne_10m_admin_0_countries.geojson", "method": "GET", "headers": {}, "auth_type": "none", "license": "Natural Earth public domain", }, "earth_coastline": { - "displayName": "Natural Earth Coastline", + "displayName": "OpenStreetMap Coastlines (osmdata.openstreetmap.de)", "sourceKind": "coastline", - "endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_coastline.geojson", + "endpoint": "https://osmdata.openstreetmap.de/download/coastlines-split-4326.zip", + "method": "GET", + "headers": {}, + "auth_type": "none", + "timeout": 1800, + "license": "ODbL 1.0 © OpenStreetMap contributors", + }, + "earth_disputed_lines": { + "displayName": "Natural Earth Disputed Boundaries", + "sourceKind": "disputed-lines", + "endpoint": f"{_NE_GEOJSON}/ne_10m_admin_0_boundary_lines_disputed_areas.geojson", "method": "GET", "headers": {}, "auth_type": "none", "license": "Natural Earth public domain", }, "earth_claim_lines": { - "displayName": "Natural Earth Disputed Boundaries", + "displayName": "Natural Earth China POV Maritime Indicator", "sourceKind": "claim-lines", - "endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_admin_0_boundary_lines_disputed_areas.geojson", + "endpoint": f"{_NE_GEOJSON}/ne_10m_admin_0_boundary_lines_maritime_indicator_chn.geojson", + "method": "GET", + "headers": {}, + "auth_type": "none", + "license": "Natural Earth public domain", + }, + "earth_admin1_lines": { + "displayName": "Natural Earth Admin-1 Lines", + "sourceKind": "admin1-lines", + "endpoint": f"{_NE_GEOJSON}/ne_10m_admin_1_states_provinces_lines.geojson", + "method": "GET", + "headers": {}, + "auth_type": "none", + "license": "Natural Earth public domain", + }, + "earth_populated_places": { + "displayName": "Natural Earth Populated Places", + "sourceKind": "populated-places", + "endpoint": f"{_NE_GEOJSON}/ne_10m_populated_places.geojson", "method": "GET", "headers": {}, "auth_type": "none", @@ -73,11 +128,18 @@ DEFAULT_PUBLIC_BOUNDARY_SOURCES = { BUILD_CONFIG = { "builder": "scripts/build_earth_boundary_pmtiles.py", + "schema": MANIFEST_SCHEMA, "format": "pmtiles+mvt", - "production_target": "pmtiles-mvt", + "minZoom": 0, + "maxZoom": 10, + "coastlineMaxZoom": 10, } +class _NotModified(Exception): + """Upstream answered 304 for a conditional source download.""" + + class EarthBoundaryBuildError(RuntimeError): def __init__(self, message: str, *, code: str = "build_failed", details: Any = None) -> None: super().__init__(message) @@ -141,13 +203,11 @@ def _read_json(path: Path) -> dict[str, Any]: def _write_json(path: Path, payload: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) - with path.open("w", encoding="utf-8") as f: + tmp = path.with_suffix(path.suffix + ".tmp") + with tmp.open("w", encoding="utf-8") as f: json.dump(payload, f, ensure_ascii=False, indent=2) f.write("\n") - - -def _sha256_bytes(payload: bytes) -> str: - return hashlib.sha256(payload).hexdigest() + tmp.replace(path) def _stable_json_hash(payload: Any) -> str: @@ -170,69 +230,15 @@ def _versioned_asset(path: Path) -> tuple[dict[str, Any], str]: return _read_versioned_asset_cached(path, stat.st_mtime_ns, stat.st_size) -def _artifact_extension(endpoint: str, content_type: str, payload: bytes) -> str: - suffix = Path(endpoint.split("?", 1)[0]).suffix.lower() - if suffix in {".json", ".geojson", ".zip", ".pbf"}: - return suffix - if "geo+json" in content_type or b'"FeatureCollection"' in payload[:4096]: - return ".geojson" - if "json" in content_type: - return ".json" - return ".dat" +def _display_path(path: Path) -> str: + try: + return str(path.relative_to(REPO_ROOT)) + except ValueError: + return str(path) -def _json_feature_count(payload: Any) -> int: - if isinstance(payload, dict) and isinstance(payload.get("features"), list): - return len(payload["features"]) - if isinstance(payload, list): - return len(payload) - return 1 if payload else 0 - - -def _directory_stats(path: Path) -> dict[str, int]: - if not path.exists(): - return {"file_count": 0, "size_bytes": 0} - files = [item for item in path.rglob("*") if item.is_file()] - return {"file_count": len(files), "size_bytes": sum(item.stat().st_size for item in files)} - - -def _write_high_precision_geojson_manifest( - sources: list[dict[str, Any]], - build_input_hash: str, - missing_tools: list[str], -) -> dict[str, Any]: - admin0 = next(source for source in sources if source["kind"] == "admin0-boundaries") - coastline = next(source for source in sources if source["kind"] == "coastline") - claim_lines = next(source for source in sources if source["kind"] == "claim-lines") - result = subprocess.run( - [ - sys.executable, - str(Path(__file__).resolve().parents[3] / "scripts/build_earth_boundary_china_pov_geojson.py"), - "--admin0-source", admin0["path"], - "--coastline-source", coastline["path"], - "--claims-source", claim_lines["path"], - "--output-dir", _relative(BOUNDARY_OUTPUT_DIR), - "--build-input-hash", build_input_hash, - "--pov-policy", _relative(POV_POLICY_PATH), - "--pov-geometry", str(POV_GEOMETRY_PATH), - ], - cwd=REPO_ROOT, - capture_output=True, - text=True, - ) - if result.returncode: - raise EarthBoundaryBuildError( - result.stderr.strip() or "Earth boundary policy build failed", - code="policy_build_failed", - ) - manifest = _read_json(BOUNDARY_MANIFEST_PATH) - manifest["missingTools"] = missing_tools - _write_json(BOUNDARY_MANIFEST_PATH, manifest) - return manifest - - -def _relative(path: Path) -> str: - return str(path.relative_to(REPO_ROOT)) +def missing_build_tools() -> list[str]: + return [tool for tool in REQUIRED_TOOLS if shutil.which(tool) is None] def load_boundary_config() -> tuple[dict[str, Any], str]: @@ -288,19 +294,19 @@ def _build_input_hash(source_manifest: dict[str, Any]) -> str: "pov_policy": source_manifest.get("povPolicy"), "pov_geometry_sha256": _versioned_asset(POV_GEOMETRY_PATH)[1], "build_config": BUILD_CONFIG, + "builder_sha256": { + path.name: _file_sha256(path) for path in BUILDER_MODULE_PATHS if path.exists() + }, } ) -def _has_current_artifacts(boundary_manifest: dict[str, Any], build_input_hash: str) -> bool: - return ( - bool(boundary_manifest) - and boundary_manifest.get("buildInputHash") == build_input_hash - and boundary_manifest.get("tileProvider") == "pmtiles-mvt" - and _policy_verified(boundary_manifest) - and PMTILES_ARTIFACT_PATH.exists() - and _pmtiles_hover_exists(boundary_manifest) - ) +def _file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as f: + for chunk in iter(lambda: f.read(DOWNLOAD_CHUNK_BYTES), b""): + digest.update(chunk) + return digest.hexdigest() def _policy_verified(manifest: dict[str, Any]) -> bool: @@ -311,65 +317,86 @@ def _policy_verified(manifest: dict[str, Any]) -> bool: policy.get("profile") == "china-pov-v1" and coverage.get("profile") == policy["profile"] and coverage.get("sha256") == policy_hash - and coverage.get("reviewedGeometrySourceCommit") - == geometry.get("sourceCommit") + and coverage.get("reviewedGeometrySourceCommit") == geometry.get("sourceCommit") and coverage.get("geometrySha256") == geometry_hash and coverage.get("applied") is True - and {"china-taiwan-penghu", "china-hong-kong", "china-macao", "kosovo"} - <= set(coverage.get("appliedRuleIds") or []) + and REQUIRED_POLICY_RULES <= set(coverage.get("appliedRuleIds") or []) ) -def _geojson_artifacts_exist(manifest: dict[str, Any]) -> bool: - paths = [manifest.get("base"), manifest.get("hoverIndex")] - if manifest.get("chinaClaims", {}).get("available"): - paths.append(manifest.get("claimLine")) - for asset in paths: - if not isinstance(asset, str) or Path(asset).name != asset: - return False - if not (BOUNDARY_OUTPUT_DIR / asset).is_file(): - return False - return True +def _manifest_artifact_names(manifest: dict[str, Any]) -> list[str]: + names = [ + (manifest.get("pmtiles") or {}).get("path"), + manifest.get("hoverIndex"), + manifest.get("hoverBorders"), + manifest.get("geoLabels"), + ] + return [name for name in names if isinstance(name, str) and name] -def _pmtiles_hover_exists(manifest: dict[str, Any]) -> bool: - hover = manifest.get("hoverIndex") +def _artifacts_exist(manifest: dict[str, Any]) -> bool: + names = _manifest_artifact_names(manifest) + required = [ + (manifest.get("pmtiles") or {}).get("path"), + manifest.get("hoverIndex"), + manifest.get("hoverBorders"), + ] + if not all(isinstance(name, str) and name for name in required): + return False + return all(Path(name).name == name and (BOUNDARY_OUTPUT_DIR / name).is_file() for name in names) + + +def _high_precision_ready(manifest: dict[str, Any]) -> bool: return ( - isinstance(hover, str) - and Path(hover).name == hover - and (BOUNDARY_OUTPUT_DIR / hover).is_file() + manifest.get("schema") == MANIFEST_SCHEMA + and manifest.get("tileProvider") == "pmtiles-mvt" + and _policy_verified(manifest) + and _artifacts_exist(manifest) ) +def _has_current_artifacts(boundary_manifest: dict[str, Any], build_input_hash: str) -> bool: + return ( + boundary_manifest.get("buildInputHash") == build_input_hash + and _high_precision_ready(boundary_manifest) + ) + + +def get_public_boundary_manifest() -> dict[str, Any] | None: + """Manifest for Earth clients, or ``None`` when no verified artifact exists.""" + manifest = _read_json(BOUNDARY_MANIFEST_PATH) + if not _high_precision_ready(manifest): + return None + return manifest + + +def resolve_boundary_artifact(name: str) -> Path | None: + """Only files listed by the current verified manifest are served.""" + if not name or Path(name).name != name: + return None + manifest = get_public_boundary_manifest() + if manifest is None or name not in _manifest_artifact_names(manifest): + return None + path = BOUNDARY_OUTPUT_DIR / name + return path if path.is_file() else None + + def get_boundary_status() -> dict[str, Any]: config_payload, config_source = load_boundary_config() effective_source_configs = _source_configs_with_defaults(config_payload) boundary_manifest = _read_json(BOUNDARY_MANIFEST_PATH) - pmtiles_exists = PMTILES_ARTIFACT_PATH.exists() manifest_exists = BOUNDARY_MANIFEST_PATH.exists() - high_precision_ready = ( - manifest_exists - and _policy_verified(boundary_manifest) - and ( - ( - boundary_manifest.get("tileProvider") == "pmtiles-mvt" - and pmtiles_exists - and _pmtiles_hover_exists(boundary_manifest) - ) - or ( - boundary_manifest.get("tileProvider") == "geojson-high-precision" - and _geojson_artifacts_exist(boundary_manifest) - ) - ) - ) + high_precision_ready = manifest_exists and _high_precision_ready(boundary_manifest) legacy_exists = POLICY_FALLBACK_PATH.exists() and _policy_verified( _versioned_asset(POLICY_FALLBACK_PATH)[0] ) provider = ( - boundary_manifest.get("tileProvider") + "pmtiles-mvt" if high_precision_ready else "policy-geojson-fallback" if legacy_exists else "missing" ) + pmtiles_info = boundary_manifest.get("pmtiles") or {} + missing_tools = missing_build_tools() return { "provider": provider, "high_precision_ready": high_precision_ready, @@ -377,8 +404,10 @@ def get_boundary_status() -> dict[str, Any]: "policy_publishable": bool( high_precision_ready and boundary_manifest.get("povPolicy", {}).get("publicationReady") ), + "build_tools_ready": not missing_tools, + "missing_tools": missing_tools, "config_source": config_source, - "config_path": _relative(LOCAL_CONFIG_PATH), + "config_path": _display_path(LOCAL_CONFIG_PATH), "config_exists": LOCAL_CONFIG_PATH.exists(), "config": config_payload, "effective_default_sources": [ @@ -388,8 +417,9 @@ def get_boundary_status() -> dict[str, Any]: and source_config.get("endpoint") == DEFAULT_PUBLIC_BOUNDARY_SOURCES[source_key]["endpoint"] ], "manifest": { - "path": _relative(BOUNDARY_MANIFEST_PATH), + "path": _display_path(BOUNDARY_MANIFEST_PATH), "exists": manifest_exists, + "schema": boundary_manifest.get("schema"), "tileProvider": boundary_manifest.get("tileProvider"), "buildInputHash": boundary_manifest.get("buildInputHash"), "builtAt": boundary_manifest.get("builtAt"), @@ -397,17 +427,17 @@ def get_boundary_status() -> dict[str, Any]: "publicationReady": boundary_manifest.get("povPolicy", {}).get("publicationReady", False), }, "pmtiles": { - "path": _relative(PMTILES_ARTIFACT_PATH), - "exists": pmtiles_exists, - "size_bytes": PMTILES_ARTIFACT_PATH.stat().st_size if pmtiles_exists else 0, + "path": pmtiles_info.get("path"), + "exists": high_precision_ready, + "size_bytes": pmtiles_info.get("sizeBytes", 0) if high_precision_ready else 0, }, "legacy": { - "path": _relative(POLICY_FALLBACK_PATH), + "path": _display_path(POLICY_FALLBACK_PATH), "exists": legacy_exists, "size_bytes": POLICY_FALLBACK_PATH.stat().st_size if legacy_exists else 0, }, "source_manifest": { - "path": _relative(SOURCE_MANIFEST_PATH), + "path": _display_path(SOURCE_MANIFEST_PATH), "exists": SOURCE_MANIFEST_PATH.exists(), }, "last_build": _read_json(BUILD_RESULT_PATH), @@ -415,6 +445,69 @@ def get_boundary_status() -> dict[str, Any]: } +def _artifact_extension(endpoint: str, content_type: str, head: bytes) -> str: + suffix = Path(endpoint.split("?", 1)[0]).suffix.lower() + if suffix in {".json", ".geojson", ".zip"}: + return suffix + if head.startswith(b"PK\x03\x04"): + return ".zip" + if "geo+json" in content_type or b'"FeatureCollection"' in head: + return ".geojson" + if "json" in content_type: + return ".json" + return ".dat" + + +def _zip_shapefile_feature_count(path: Path) -> int: + """Count shapefile records from the .shx index (100-byte header, 8 bytes per record).""" + try: + with zipfile.ZipFile(path) as archive: + for info in archive.infolist(): + if info.filename.endswith("lines.shx"): + return max(0, (info.file_size - 100) // 8) + except zipfile.BadZipFile as exc: + raise EarthBoundaryBuildError( + f"{path.name} is not a valid zip archive", code="invalid_source" + ) from exc + return 0 + + +def _source_feature_count(path: Path, extension: str) -> int: + if extension == ".zip": + return _zip_shapefile_feature_count(path) + if extension in {".json", ".geojson"}: + with path.open("r", encoding="utf-8") as f: + payload = json.load(f) + if isinstance(payload, dict) and isinstance(payload.get("features"), list): + return len(payload["features"]) + if isinstance(payload, list): + return len(payload) + return 1 if payload else 0 + return 0 + + +def _previous_source(source_key: str, endpoint: str) -> dict[str, Any] | None: + """Last downloaded artifact for this endpoint, if it is still on disk.""" + for source in _read_json(SOURCE_MANIFEST_PATH).get("sources") or []: + if source.get("id") != source_key or source.get("endpoint") != endpoint: + continue + path = Path(str(source.get("path") or "")) + if path.is_file() and source.get("sha256") and path.name.startswith(str(source["sha256"])): + return source + return None + + +def _conditional_headers(previous: dict[str, Any] | None) -> dict[str, str]: + if not previous: + return {} + headers = {} + if previous.get("etag"): + headers["If-None-Match"] = str(previous["etag"]) + if previous.get("lastModified"): + headers["If-Modified-Since"] = str(previous["lastModified"]) + return headers + + async def _download_source( source_key: str, source_config: dict[str, Any], @@ -435,65 +528,108 @@ async def _download_source( details={"source": source_key, "method": method}, ) - if endpoint.startswith("file://") or Path(endpoint).expanduser().exists(): - payload = Path(endpoint.removeprefix("file://")).expanduser().read_bytes() - content_type = "application/octet-stream" - if progress_callback: - progress_callback(1, len(payload), len(payload)) - else: - timeout = float(source_config.get("timeout") or 120) - headers = source_config.get("headers") if isinstance(source_config.get("headers"), dict) else {} - async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client: - async with client.stream(method, endpoint, headers=headers) as response: - response.raise_for_status() - content_type = response.headers.get("content-type", "") - total = int(response.headers.get("content-length") or 0) - chunks = [] - downloaded = 0 - async for chunk in response.aiter_bytes(): - if not chunk: - continue - chunks.append(chunk) - downloaded += len(chunk) - if progress_callback: - progress_callback( - (downloaded / total) if total else None, - downloaded, - total, - ) - payload = b"".join(chunks) + source_dir = SOURCE_OUTPUT_DIR / source_key + source_dir.mkdir(parents=True, exist_ok=True) + previous = _previous_source(source_key, endpoint) + digest = hashlib.sha256() + content_type = "" + head = b"" + validators: dict[str, str] = {} + not_modified = False + with tempfile.NamedTemporaryFile(dir=source_dir, prefix=".download-", delete=False) as tmp: + tmp_path = Path(tmp.name) + try: + local_path = Path(endpoint.removeprefix("file://")).expanduser() + if endpoint.startswith("file://") or local_path.exists(): + total = local_path.stat().st_size + with local_path.open("rb") as src: + while chunk := src.read(DOWNLOAD_CHUNK_BYTES): + head = head or chunk[:4096] + digest.update(chunk) + tmp.write(chunk) + if progress_callback: + progress_callback(1, total, total) + else: + timeout = float(source_config.get("timeout") or 120) + headers = source_config.get("headers") if isinstance(source_config.get("headers"), dict) else {} + # Re-use the stored artifact when the upstream file is unchanged + # (the OSM coastline archive alone is ~900 MB). + headers = {**headers, **_conditional_headers(previous)} + async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client: + async with client.stream(method, endpoint, headers=headers) as response: + if response.status_code == 304 and previous: + not_modified = True + raise _NotModified + response.raise_for_status() + validators = { + key: value + for key, value in ( + ("etag", response.headers.get("etag")), + ("lastModified", response.headers.get("last-modified")), + ) + if value + } + content_type = response.headers.get("content-type", "") + # Content-Length counts encoded bytes; aiter_bytes yields decoded ones. + encoded = bool(response.headers.get("content-encoding")) + total = 0 if encoded else int(response.headers.get("content-length") or 0) + downloaded = 0 + async for chunk in response.aiter_bytes(DOWNLOAD_CHUNK_BYTES): + if not chunk: + continue + head = head or chunk[:4096] + digest.update(chunk) + tmp.write(chunk) + downloaded += len(chunk) + if progress_callback: + progress_callback((downloaded / total) if total else None, downloaded, total) + except _NotModified: + pass + except BaseException: + tmp_path.unlink(missing_ok=True) + raise - extension = _artifact_extension(endpoint, content_type, payload) - parsed: Any = None - if extension in {".json", ".geojson"}: - parsed = json.loads(payload.decode("utf-8")) - feature_count = _json_feature_count(parsed) + if not_modified and previous: + tmp_path.unlink(missing_ok=True) + if progress_callback: + progress_callback(1, 0, 0) + logger.info("earth_boundary_source_not_modified", extra={"source": source_key}) + return {**previous, "notModified": True} + + sha256 = digest.hexdigest() + extension = _artifact_extension(endpoint, content_type, head) + artifact_path = source_dir / f"{sha256}{extension}" + tmp_path.replace(artifact_path) + for stale in source_dir.iterdir(): + if stale.is_file() and stale != artifact_path: + stale.unlink() + feature_count = _source_feature_count(artifact_path, extension) if feature_count <= 0: raise EarthBoundaryBuildError( f"{source_key} downloaded payload contains no features", code="empty_source", details={"source": source_key}, ) - - sha256 = _sha256_bytes(payload) - source_dir = SOURCE_OUTPUT_DIR / source_key - source_dir.mkdir(parents=True, exist_ok=True) - artifact_path = source_dir / f"{sha256}{extension}" - artifact_path.write_bytes(payload) return { "id": source_key, "kind": source_config.get("sourceKind") or BOUNDARY_SOURCE_KINDS[source_key], - "path": _relative(artifact_path), + "endpoint": endpoint, + "path": str(artifact_path), "sha256": sha256, "featureCount": feature_count, "license": source_config.get("license"), + **validators, } -async def _run_step(args: list[str]) -> dict[str, Any]: +async def _run_builder(args: list[str]) -> dict[str, Any]: + command = [sys.executable, str(BUILDER_PATH), *args] + nice = shutil.which("nice") + if nice: + # Keep API latency stable while a production rebuild runs in the backend container. + command = [nice, "-n", "10", *command] process = await asyncio.create_subprocess_exec( - sys.executable, - *args, + *command, cwd=REPO_ROOT, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, @@ -501,7 +637,7 @@ async def _run_step(args: list[str]) -> dict[str, Any]: stdout_bytes, stderr_bytes = await process.communicate() stdout = stdout_bytes.decode("utf-8", errors="replace").strip() stderr = stderr_bytes.decode("utf-8", errors="replace").strip() - payload: dict[str, Any] = {"stdout": stdout, "stderr": stderr, "returncode": process.returncode} + payload: dict[str, Any] = {"returncode": process.returncode, "stderr_tail": stderr[-4000:]} last_line = stdout.splitlines()[-1:] or [] if last_line: try: @@ -510,7 +646,7 @@ async def _run_step(args: list[str]) -> dict[str, Any]: payload["result"] = last_line[0] if process.returncode != 0: raise EarthBoundaryBuildError( - stderr or stdout or f"command failed: {' '.join(args)}", + (stderr.splitlines()[-1] if stderr else "") or "Earth boundary PMTiles build failed", code="build_command_failed", details=payload, ) @@ -518,8 +654,15 @@ async def _run_step(args: list[str]) -> dict[str, Any]: async def build_boundary_assets(progress_callback: Any = None) -> dict[str, Any]: - config_payload, config_source = load_boundary_config() + missing_tools = missing_build_tools() + if missing_tools: + raise EarthBoundaryBuildError( + f"PMTiles build tools missing: {', '.join(missing_tools)}", + code="missing_tools", + details={"missing_tools": missing_tools}, + ) + config_payload, _config_source = load_boundary_config() source_configs = _source_configs_with_defaults(config_payload) missing = [source for source in BOUNDARY_SOURCE_KINDS if source not in source_configs] if missing: @@ -531,6 +674,7 @@ async def build_boundary_assets(progress_callback: Any = None) -> dict[str, Any] sources = [] source_keys = list(BOUNDARY_SOURCE_KINDS) + span = 52 / len(source_keys) for index, source_key in enumerate(source_keys): source_config = source_configs[source_key] if not isinstance(source_config, dict): @@ -539,21 +683,28 @@ async def build_boundary_assets(progress_callback: Any = None) -> dict[str, Any] code="invalid_config", details={"source": source_key}, ) - source_start = 8 + index * 18 - source_end = source_start + 18 + source_start = 8 + index * span + source_end = source_start + span if progress_callback: progress_callback(source_start, "download", f"正在下载 {source_key}") - def report_download_progress(ratio: float | None, downloaded: int, total: int) -> None: + def report_download_progress( + ratio: float | None, + downloaded: int, + total: int, + _start: float = source_start, + _end: float = source_end, + _key: str = source_key, + ) -> None: if not progress_callback: return if ratio is None: - progress_callback(source_start + 8, "download", f"{source_key} 已下载 {downloaded} bytes") + progress_callback(_start + span / 2, "download", f"{_key} 已下载 {downloaded} bytes") return progress_callback( - source_start + (source_end - source_start) * ratio, + _start + (_end - _start) * ratio, "download", - f"{source_key} 下载 {int(ratio * 100)}%", + f"{_key} 下载 {int(ratio * 100)}%", downloaded_bytes=downloaded, total_bytes=total, ) @@ -561,91 +712,71 @@ async def build_boundary_assets(progress_callback: Any = None) -> dict[str, Any] sources.append(await _download_source(source_key, source_config, report_download_progress)) source_manifest = { - "schema": "planet-earth-boundary-sources/v2", + "schema": "planet-earth-boundary-sources/v3", "sources": sources, "povPolicy": _read_json(POV_POLICY_PATH), } if progress_callback: - progress_callback(65, "manifest", "正在写入边界源 manifest") + progress_callback(62, "manifest", "正在写入边界源 manifest") _write_json(SOURCE_MANIFEST_PATH, source_manifest) build_input_hash = _build_input_hash(source_manifest) boundary_manifest = _read_json(BOUNDARY_MANIFEST_PATH) build_skipped = _has_current_artifacts(boundary_manifest, build_input_hash) - missing_tools = [tool for tool in ("tippecanoe", "pmtiles") if shutil.which(tool) is None] - if missing_tools and not build_skipped: - if progress_callback: - progress_callback(82, "build", "缺少 PMTiles 工具,正在生成 GeoJSON 高清包") - boundary_manifest = _write_high_precision_geojson_manifest( - sources, - build_input_hash, - missing_tools, - ) - result = { - "status": "built_geojson_fallback", - "code": "missing_tools", - "missing_tools": missing_tools, - "sources": sources, - "boundary_manifest": _relative(BOUNDARY_MANIFEST_PATH), - "manifest": boundary_manifest, - } - _write_json(BUILD_RESULT_PATH, result) - if progress_callback: - progress_callback(96, "finalize", "GeoJSON 高清国界包已生成") - return {**get_boundary_status(), "build": result} - if build_skipped: if progress_callback: progress_callback(96, "unchanged", "高精国界已是最新") - build_result = { + build_result: dict[str, Any] = { "status": "unchanged", "reason": "source manifest and build config hash unchanged", "buildInputHash": build_input_hash, } else: if progress_callback: - progress_callback(72, "build", "正在构建 PMTiles/MVT") - admin0 = next(source for source in sources if source["kind"] == "admin0-boundaries") - coastline = next(source for source in sources if source["kind"] == "coastline") - claim_lines = next(source for source in sources if source["kind"] == "claim-lines") - build_result = await _run_step( - [ - "scripts/build_earth_boundary_pmtiles.py", - "--admin0-source", - admin0["path"], - "--coastline-source", - coastline["path"], - "--claims-source", - claim_lines["path"], - "--output", - _relative(PMTILES_ARTIFACT_PATH), - "--manifest", - _relative(BOUNDARY_MANIFEST_PATH), - "--build-input-hash", - build_input_hash, - "--pov-policy", - _relative(POV_POLICY_PATH), - "--pov-geometry", - str(POV_GEOMETRY_PATH), - ] - ) + progress_callback(66, "build", "正在构建 PMTiles/MVT(海岸线 z0–z10)") + by_kind = {source["kind"]: source["path"] for source in sources} + builder_args = [ + "--admin0-source", by_kind["admin0-boundaries"], + "--coastline-source", by_kind["coastline"], + "--disputed-source", by_kind["disputed-lines"], + "--claims-source", by_kind["claim-lines"], + "--admin1-source", by_kind["admin1-lines"], + "--output-dir", str(BOUNDARY_OUTPUT_DIR), + "--build-input-hash", build_input_hash, + "--pov-policy", str(POV_POLICY_PATH), + "--pov-geometry", str(POV_GEOMETRY_PATH), + "--min-zoom", str(BUILD_CONFIG["minZoom"]), + "--max-zoom", str(BUILD_CONFIG["maxZoom"]), + "--coastline-max-zoom", str(BUILD_CONFIG["coastlineMaxZoom"]), + "--temp-dir", str(BOUNDARY_DATA_DIR / "tmp"), + ] + if "populated-places" in by_kind: + builder_args.extend(["--places-source", by_kind["populated-places"]]) + build_result = await _run_builder(builder_args) if progress_callback: progress_callback(95, "finalize", "正在校验构建产物") boundary_manifest = _read_json(BOUNDARY_MANIFEST_PATH) - boundary_stats = _directory_stats(BOUNDARY_OUTPUT_DIR) + if not _high_precision_ready(boundary_manifest): + raise EarthBoundaryBuildError( + "Earth boundary build finished without a verified China POV manifest", + code="unverified_artifact", + details={"manifest": _display_path(BOUNDARY_MANIFEST_PATH)}, + ) result = { "status": "unchanged" if build_skipped else "built", "sources": sources, - "source_manifest": _relative(SOURCE_MANIFEST_PATH), - "boundary_manifest": _relative(BOUNDARY_MANIFEST_PATH), - "pmtiles_artifact": _relative(PMTILES_ARTIFACT_PATH), - "pmtiles_exists": PMTILES_ARTIFACT_PATH.exists(), - "boundary_stats": boundary_stats, + "source_manifest": _display_path(SOURCE_MANIFEST_PATH), + "boundary_manifest": _display_path(BOUNDARY_MANIFEST_PATH), + "pmtiles": boundary_manifest.get("pmtiles"), "manifest": boundary_manifest, "build_result": build_result, } _write_json(BUILD_RESULT_PATH, result) + logger.info( + "earth_boundary_build_finished", + extra={"status": result["status"], "pmtiles_bytes": (boundary_manifest.get("pmtiles") or {}).get("sizeBytes")}, + ) return {**get_boundary_status(), "build": result} @@ -674,6 +805,7 @@ async def _run_boundary_build_job(job_id: str) -> None: ) _append_job_log("高精国界构建完成") except EarthBoundaryBuildError as exc: + logger.warning("earth_boundary_build_failed", extra={"code": exc.code, "error": str(exc)}) _set_job_state( id=job_id, status="failed", @@ -686,6 +818,7 @@ async def _run_boundary_build_job(job_id: str) -> None: ) _append_job_log(str(exc)) except Exception as exc: # pragma: no cover - defensive guard for background task + logger.exception("earth_boundary_build_crashed") _set_job_state( id=job_id, status="failed", @@ -703,6 +836,13 @@ async def start_boundary_build_job() -> dict[str, Any]: async with _build_job_lock: if _build_task and not _build_task.done(): return {"accepted": False, "job": _public_job_state()} + missing_tools = missing_build_tools() + if missing_tools: + raise EarthBoundaryBuildError( + f"PMTiles build tools missing: {', '.join(missing_tools)}", + code="missing_tools", + details={"missing_tools": missing_tools}, + ) job_id = uuid4().hex _set_job_state( id=job_id, diff --git a/backend/app/services/earth_clouds.py b/backend/app/services/earth_clouds.py new file mode 100644 index 00000000..c03ba759 --- /dev/null +++ b/backend/app/services/earth_clouds.py @@ -0,0 +1,1826 @@ +"""Real-time global satellite IR cloud map engine, storage, and spatial analytics.""" + +from __future__ import annotations + +import asyncio +from datetime import UTC, datetime +import hashlib +import io +import json +import math +import os +from pathlib import Path +import re +from time import perf_counter +from typing import Any +from urllib.parse import urlparse +from uuid import uuid4 + +import cv2 +import httpx +import numpy as np +from PIL import Image +from pydantic import BaseModel, Field, field_validator +from sqlalchemy import select +from sqlalchemy.dialects.postgresql import insert as pg_insert +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.logging import get_logger +from app.core.request_context import get_request_id +from app.core.time import to_iso8601_utc +from app.models.collected_data import CollectedData +from app.models.datasource import DataSource +from app.models.system_log import AuditLog +from app.models.system_setting import SystemSetting +from app.models.user import User +from app.models.vessel import VesselPosition + +logger = get_logger(__name__, service="earth_clouds") + +REPO_ROOT = Path(__file__).resolve().parents[3] +CLOUD_DATA_DIR = REPO_ROOT / "data" / "earth-clouds" +CLOUD_CONFIG_CATEGORY = "earth_cloud_map" +DEFAULT_STATIC_CLOUD_URL = "./assets/earth_clouds_2048.png" +ANALYSIS_GRID_WIDTH = 720 +ANALYSIS_GRID_HEIGHT = 360 +VERSION_PATTERN = re.compile(r"^[A-Za-z0-9._-]{4,64}$") + +NASA_GIBS_WMS_URL = "https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi" +EUMETVIEW_WMS_URL = "https://view.eumetsat.int/geoserver/wms" +MATTEASON_BASE_URL = "https://clouds.matteason.co.uk/images" + +SATELLITE_SOURCES: tuple[dict[str, Any], ...] = ( + { + "id": "himawari", + "label": "Himawari-9 (JMA)", + "provider": "gibs", + "url": NASA_GIBS_WMS_URL, + "layer": "Himawari_AHI_Band13_Clean_Infrared", + "visual_layer": "Himawari_AHI_Band3_Red_Visible_1km", + "sub_lon": 140.7, + }, + { + "id": "goes_east", + "label": "GOES-East (NOAA)", + "provider": "gibs", + "url": NASA_GIBS_WMS_URL, + "layer": "GOES-East_ABI_Band13_Clean_Infrared", + "visual_layer": "GOES-East_ABI_GeoColor", + "sub_lon": -75.2, + }, + { + "id": "goes_west", + "label": "GOES-West (NOAA)", + "provider": "gibs", + "url": NASA_GIBS_WMS_URL, + "layer": "GOES-West_ABI_Band13_Clean_Infrared", + "visual_layer": "GOES-West_ABI_GeoColor", + "sub_lon": -137.2, + }, + { + "id": "msg_fes", + "label": "Meteosat 0° (EUMETSAT)", + "provider": "eumetview", + "url": EUMETVIEW_WMS_URL, + "layer": "msg_fes:ir108", + "visual_layer": "msg_fes:rgb_naturalenhncd", + "sub_lon": 0.0, + }, + { + "id": "msg_iodc", + "label": "Meteosat IODC (EUMETSAT)", + "provider": "eumetview", + "url": EUMETVIEW_WMS_URL, + "layer": "msg_iodc:ir108", + "visual_layer": "msg_iodc:rgb_naturalenhncd", + "sub_lon": 45.5, + }, +) + +# Official GIBS Clean_Longwave_Infrared_Window_Band.xml non-grayscale palette entries: +# (R, G, B, midpoint Brightness Temperature in Celsius). +GIBS_BAND13_COLOR_LUT: tuple[tuple[int, int, int, float], ...] = ( + (127, 0, 127, -90.6), + (140, 13, 135, -89.6), + (153, 25, 142, -88.6), + (165, 38, 150, -87.6), + (178, 51, 157, -86.6), + (191, 64, 165, -85.6), + (204, 76, 173, -84.6), + (217, 89, 180, -83.6), + (229, 102, 188, -82.6), + (242, 114, 195, -81.6), + (255, 127, 203, -80.6), + (26, 0, 0, -69.6), + (51, 0, 0, -68.6), + (77, 0, 0, -67.6), + (102, 0, 0, -66.6), + (128, 0, 0, -65.6), + (153, 0, 0, -64.6), + (179, 0, 0, -63.6), + (204, 0, 0, -62.6), + (230, 0, 0, -61.6), + (255, 0, 0, -60.6), + (255, 26, 0, -59.6), + (255, 51, 0, -58.6), + (255, 77, 0, -57.6), + (255, 102, 0, -56.6), + (255, 128, 0, -55.6), + (255, 153, 0, -54.6), + (255, 179, 0, -53.6), + (255, 204, 0, -52.6), + (255, 230, 0, -51.6), + (255, 255, 0, -50.6), + (230, 255, 0, -49.6), + (204, 255, 0, -48.6), + (179, 255, 0, -47.6), + (153, 255, 0, -46.6), + (128, 255, 0, -45.6), + (102, 255, 0, -44.6), + (77, 255, 0, -43.6), + (51, 255, 0, -42.6), + (26, 255, 0, -41.6), + (0, 255, 0, -40.6), + (0, 234, 10, -39.6), + (0, 212, 19, -38.6), + (0, 191, 29, -37.6), + (0, 170, 38, -36.6), + (0, 149, 48, -35.6), + (0, 128, 58, -34.6), + (0, 106, 67, -33.6), + (0, 85, 77, -32.6), + (0, 64, 86, -31.6), + (0, 42, 96, -30.85), + (0, 21, 105, -30.35), + (0, 0, 115, -29.85), + (0, 0, 125, -29.35), + (0, 13, 122, -28.85), + (0, 26, 129, -28.35), + (0, 38, 136, -27.85), + (0, 51, 143, -27.35), + (0, 64, 150, -26.85), + (0, 76, 157, -26.35), + (0, 89, 164, -25.85), + (0, 102, 171, -25.35), + (0, 115, 178, -24.85), + (0, 128, 185, -24.35), + (0, 140, 192, -23.85), + (0, 153, 199, -23.35), + (0, 166, 206, -22.85), + (0, 178, 213, -22.35), + (0, 191, 220, -21.85), + (0, 204, 227, -21.35), + (0, 217, 234, -20.85), + (0, 230, 241, -20.35), + (0, 242, 248, -19.85), + (0, 255, 255, -19.35), +) + +FOCUS_REGIONS: tuple[dict[str, Any], ...] = ( + { + "key": "east_asia_scs", + "name": "东亚与南海", + "name_en": "East Asia & South China Sea", + "lat_min": 10.0, + "lat_max": 42.0, + "lon_min": 100.0, + "lon_max": 135.0, + }, + { + "key": "malacca_maritime", + "name": "马六甲与印尼航道", + "name_en": "Malacca & Maritime SE Asia", + "lat_min": -8.0, + "lat_max": 12.0, + "lon_min": 92.0, + "lon_max": 122.0, + }, + { + "key": "west_pacific_typhoon", + "name": "西北太平洋台风带", + "name_en": "Western Pacific Typhoon Belt", + "lat_min": 5.0, + "lat_max": 35.0, + "lon_min": 120.0, + "lon_max": 165.0, + }, + { + "key": "red_sea_suez", + "name": "红海与苏伊士走廊", + "name_en": "Red Sea & Suez Corridor", + "lat_min": 10.0, + "lat_max": 33.0, + "lon_min": 30.0, + "lon_max": 50.0, + }, + { + "key": "western_europe", + "name": "欧洲西部", + "name_en": "Western Europe", + "lat_min": 36.0, + "lat_max": 60.0, + "lon_min": -12.0, + "lon_max": 22.0, + }, + { + "key": "north_america_east", + "name": "北美东海岸", + "name_en": "North America East Coast", + "lat_min": 24.0, + "lat_max": 50.0, + "lon_min": -85.0, + "lon_max": -60.0, + }, + { + "key": "north_america_west", + "name": "北美西海岸", + "name_en": "North America West Coast", + "lat_min": 24.0, + "lat_max": 52.0, + "lon_min": -135.0, + "lon_max": -112.0, + }, + { + "key": "north_atlantic", + "name": "北大西洋航道", + "name_en": "North Atlantic Corridor", + "lat_min": 35.0, + "lat_max": 62.0, + "lon_min": -60.0, + "lon_max": -10.0, + }, +) + +_GIBS_3D_LUT: np.ndarray | None = None +_CLOUD_WRITE_LOCK = asyncio.Lock() + + +class CloudMapRevisionConflictError(RuntimeError): + """Raised when saving cloud map configuration with a stale revision.""" + + +class CloudMapConfig(BaseModel): + enabled: bool = True + primary_source: str = Field(default="multi_sat_ir") + fallback_source: str = Field(default="matteason_live") + resolution: str = Field(default="4096x2048") + ir_threshold: int = Field(default=22, ge=0, le=80) + contrast_gamma: float = Field(default=0.88, ge=0.5, le=2.0) + convective_threshold: int = Field(default=82, ge=45, le=96) + min_cluster_area_km2: int = Field(default=35000, ge=5000, le=500000) + polar_feather_enabled: bool = True + max_history_frames: int = Field(default=24, ge=4, le=48) + timelapse_enabled: bool = True + show_convective_markers: bool = False + default_opacity: float = Field(default=0.38, ge=0.1, le=0.8) + request_timeout_seconds: int = Field(default=45, ge=5, le=60) + geocolor_enabled: bool = True + relief_shading_strength: float = Field(default=0.45, ge=0.0, le=1.0) + optical_flow_enabled: bool = True + + @field_validator("primary_source") + @classmethod + def validate_primary_source(cls, value: str) -> str: + normalized = str(value or "multi_sat_ir").strip().lower() + if normalized not in {"multi_sat_ir", "matteason_live"}: + raise ValueError("primary_source must be 'multi_sat_ir' or 'matteason_live'") + return normalized + + @field_validator("fallback_source") + @classmethod + def validate_fallback_source(cls, value: str) -> str: + normalized = str(value or "matteason_live").strip().lower() + if normalized not in {"matteason_live", "static"}: + raise ValueError("fallback_source must be 'matteason_live' or 'static'") + return normalized + + @field_validator("resolution") + @classmethod + def validate_resolution(cls, value: str) -> str: + normalized = str(value or "4096x2048").strip().lower() + if normalized not in {"2048x1024", "4096x2048"}: + raise ValueError("resolution must be '2048x1024' or '4096x2048'") + return normalized + + +DEFAULT_CLOUD_CONFIG = CloudMapConfig() +DEFAULT_CLOUD_REVISION = hashlib.sha256( + DEFAULT_CLOUD_CONFIG.model_dump_json().encode("utf-8") +).hexdigest()[:16] + + +def _default_envelope() -> dict[str, Any]: + return { + "config": DEFAULT_CLOUD_CONFIG.model_dump(mode="json"), + "revision": DEFAULT_CLOUD_REVISION, + "is_default": True, + } + + +def _get_data_dir() -> Path: + return CLOUD_DATA_DIR + + +def _manifest_path() -> Path: + return _get_data_dir() / "manifest.json" + + +def _frames_dir() -> Path: + return _get_data_dir() / "frames" + + +def _grids_dir() -> Path: + return _get_data_dir() / "grids" + + +def _temps_dir() -> Path: + return _get_data_dir() / "temps" + + +def _ensure_dirs() -> None: + _frames_dir().mkdir(parents=True, exist_ok=True) + _grids_dir().mkdir(parents=True, exist_ok=True) + _temps_dir().mkdir(parents=True, exist_ok=True) + + +def _atomic_write_bytes(path: Path, content: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = path.with_name(f".{path.name}.{uuid4().hex[:8]}.tmp") + tmp_path.write_bytes(content) + os.replace(tmp_path, path) + + +def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None: + raw = json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8") + _atomic_write_bytes(path, raw) + + +def _read_manifest() -> dict[str, Any]: + path = _manifest_path() + if not path.exists(): + return {"latest_version": None, "updated_at": None, "frames": []} + try: + data = json.loads(path.read_text(encoding="utf-8")) + except Exception: + return {"latest_version": None, "updated_at": None, "frames": []} + if not isinstance(data, dict): + return {"latest_version": None, "updated_at": None, "frames": []} + frames = data.get("frames") + return { + "latest_version": data.get("latest_version"), + "updated_at": data.get("updated_at"), + "frames": [item for item in frames if isinstance(item, dict)] if isinstance(frames, list) else [], + } + + +def parse_resolution(resolution: str) -> tuple[int, int]: + return (4096, 2048) if resolution == "4096x2048" else (2048, 1024) + + +def _get_gibs_3d_lut() -> np.ndarray: + """Build a quantized 5-bit/channel RGB -> Brightness Temperature (°C) lookup table.""" + global _GIBS_3D_LUT + if _GIBS_3D_LUT is not None: + return _GIBS_3D_LUT + + palette_rgb = np.array([[r, g, b] for r, g, b, _ in GIBS_BAND13_COLOR_LUT], dtype=np.int32) + palette_temp = np.array([temp for _, _, _, temp in GIBS_BAND13_COLOR_LUT], dtype=np.float32) + + levels = np.arange(32, dtype=np.int32) * 8 + 4 + rr, gg, bb = np.meshgrid(levels, levels, levels, indexing="ij") + grid_rgb = np.stack([rr, gg, bb], axis=-1).reshape(-1, 3) + diff = grid_rgb[:, None, :] - palette_rgb[None, :, :] + dist_sq = np.sum(diff * diff, axis=-1) + nearest_idx = np.argmin(dist_sq, axis=1) + _GIBS_3D_LUT = palette_temp[nearest_idx].reshape(32, 32, 32) + return _GIBS_3D_LUT + + +def _disambiguate_dvorak_cold_gray( + valid: np.ndarray, + gray: np.ndarray, + chroma: np.ndarray, + temp_c: np.ndarray, +) -> tuple[np.ndarray, np.ndarray]: + """Recover Dvorak cold gray/white cloud cores enclosed by <= -52°C convective rings. + + Also masks pure-white GOES/GIBS missing scan-band stripes outside convective rings + so they never become bogus -91.5°C storm clusters. Runs purely vectorized in C/NumPy + to avoid tens of thousands of Python per-component calls holding the GIL. + """ + updated_valid = valid.copy() + result = temp_c.copy() + cold_ring = updated_valid & (chroma >= 12) & (result <= -52.0) + + if np.any(cold_ring): + near_cold_ring = ( + cv2.dilate(cold_ring.astype(np.uint8), np.ones((7, 7), dtype=np.uint8), iterations=1) > 0 + ) + else: + near_cold_ring = np.zeros_like(updated_valid, dtype=bool) + + white_stripe = updated_valid & (chroma < 8) & (gray >= 245) & ~near_cold_ring + if np.any(white_stripe): + updated_valid[white_stripe] = False + + if not np.any(cold_ring): + return result, updated_valid + + height, width = updated_valid.shape + max_hole_pixels = max(512, int(height * width * 0.015)) + not_ring = (~cold_ring).astype(np.uint8) + num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(not_ring, connectivity=8) + if num_labels <= 1: + return result, updated_valid + + areas = stats[:, cv2.CC_STAT_AREA] + lefts = stats[:, cv2.CC_STAT_LEFT] + tops = stats[:, cv2.CC_STAT_TOP] + widths = stats[:, cv2.CC_STAT_WIDTH] + heights = stats[:, cv2.CC_STAT_HEIGHT] + touches_edge = ( + (lefts == 0) + | (tops == 0) + | (lefts + widths >= width) + | (tops + heights >= height) + ) + touches_invalid = np.zeros(num_labels, dtype=bool) + if np.any(~updated_valid): + touches_invalid[np.unique(labels[~updated_valid])] = True + + is_hole = (areas > 0) & (areas <= max_hole_pixels) & ~touches_edge & ~touches_invalid + is_hole[0] = False + + if np.any(is_hole): + dvorak_core = is_hole[labels] & updated_valid & (chroma < 12) + if np.any(dvorak_core): + sub_gray = gray[dvorak_core] + result[dvorak_core] = -70.1 - (np.clip(sub_gray, 0.0, 230.0) / 230.0) * 10.0 + ultra_wrap = dvorak_core & (gray >= 248) + if np.any(ultra_wrap): + result[ultra_wrap] = -91.5 + + return result, updated_valid + + +def decode_gibs_band13_to_temp_and_valid(rgba_arr: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Invert GIBS Band13 Clean IR RGBA pixels into Brightness Temperature (°C) and valid mask.""" + rgb = rgba_arr[:, :, :3].astype(np.int32) + alpha = rgba_arr[:, :, 3] + valid = alpha > 12 + + r_ch = rgb[:, :, 0] + g_ch = rgb[:, :, 1] + b_ch = rgb[:, :, 2] + chroma = np.maximum(np.maximum(r_ch, g_ch), b_ch) - np.minimum(np.minimum(r_ch, g_ch), b_ch) + gray = ((r_ch + g_ch + b_ch) // 3).astype(np.float32) + + temp_c = 57.3 - (np.clip(gray, 0.0, 197.0) / 197.0) * 76.4 + color_mask = valid & (chroma >= 12) + if np.any(color_mask): + lut = _get_gibs_3d_lut() + temp_c[color_mask] = lut[ + r_ch[color_mask] >> 3, + g_ch[color_mask] >> 3, + b_ch[color_mask] >> 3, + ] + + temp_c, valid = _disambiguate_dvorak_cold_gray(valid, gray, chroma, temp_c) + temp_c[~valid] = np.nan + return temp_c.astype(np.float32), valid + + +def decode_eumetview_ir_to_temp_and_valid(rgba_arr: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Convert EUMETView grayscale IR10.8 image into approximate Brightness Temperature (°C).""" + alpha = rgba_arr[:, :, 3] + valid = alpha > 12 + gray = np.mean(rgba_arr[:, :, :3].astype(np.float32), axis=2) + # EUMETView IR108 is 8-bit inverted brightness (warm dark ~1 -> +42°C, cold bright 255 -> -76°C). + temp_c = 42.0 - (gray / 255.0) * 118.0 + temp_c[~valid] = np.nan + return temp_c.astype(np.float32), valid + + +def temperature_to_density( + temp_c: np.ndarray, + *, + ir_threshold: int, + contrast_gamma: float, +) -> np.ndarray: + """Map physical Brightness Temperature (°C) monotonically to 0..255 cloud density.""" + # ir_threshold 0..80 maps clear-sky cutoff from +26°C down to -18°C (22 -> +13.9°C). + clear_cutoff_c = 26.0 - (float(ir_threshold) / 100.0) * 55.0 + dense_cloud_c = -55.0 + span = max(18.0, clear_cutoff_c - dense_cloud_c) + normalized = np.clip((clear_cutoff_c - temp_c) / span, 0.0, 1.0) + normalized = np.where(np.isnan(temp_c), 0.0, normalized) + if abs(contrast_gamma - 1.0) > 1e-3: + normalized = np.power(normalized, float(contrast_gamma)) + return np.clip(np.round(normalized * 255.0), 0, 255).astype(np.uint8) + + +def _compute_satellite_longitude_weights(width: int, sub_lon: float) -> np.ndarray: + lons = np.linspace(-180.0, 180.0, width, endpoint=False, dtype=np.float32) + (180.0 / width) + delta_rad = np.deg2rad(((lons - sub_lon + 180.0) % 360.0) - 180.0) + cos_val = np.cos(delta_rad) + # Favor near-nadir pixels cleanly while preserving thin feathering near disk edges. + return np.power(np.maximum(0.0, cos_val - 0.12), 1.5) + 0.005 + + +def _apply_polar_and_seam_smoothing( + density_u8: np.ndarray, + *, + polar_feather_enabled: bool, +) -> np.ndarray: + height, width = density_u8.shape + out = density_u8.astype(np.float32) + + if polar_feather_enabled: + lats = np.linspace(90.0, -90.0, height, endpoint=False, dtype=np.float32) - (90.0 / height) + abs_lat = np.abs(lats) + # Smooth taper from 62° to 80° to soften geostationary limb cutoff near poles. + t = np.clip((abs_lat - 62.0) / 18.0, 0.0, 1.0) + polar_weight = 1.0 - (t * t * (3.0 - 2.0 * t)) * 0.92 + out *= polar_weight[:, None] + + # Subtle seam blend across ±180° dateline (first & last 4 columns). + seam_w = 4 + if width > seam_w * 2: + left = out[:, :seam_w].copy() + right = out[:, -seam_w:].copy() + avg = 0.5 * (left + np.flip(right, axis=1)) + alpha = np.linspace(0.5, 0.0, seam_w, dtype=np.float32)[None, :] + out[:, :seam_w] = left * (1.0 - alpha) + avg * alpha + out[:, -seam_w:] = right * (1.0 - np.flip(alpha, axis=1)) + np.flip(avg, axis=1) * np.flip(alpha, axis=1) + + return np.clip(np.round(out), 0, 255).astype(np.uint8) + + +def _decode_image_bytes(raw: bytes, width: int, height: int) -> np.ndarray: + with Image.open(io.BytesIO(raw)) as img: + rgba = img.convert("RGBA") + if rgba.size != (width, height): + rgba = rgba.resize((width, height), Image.Resampling.BILINEAR) + return np.array(rgba, dtype=np.uint8) + + +def _bound_cv_threads() -> None: + try: + cv2.setNumThreads(min(2, os.cpu_count() or 1)) + except Exception: + pass + + +def synthesize_multi_sat_ir( + satellite_payloads: list[tuple[dict[str, Any], bytes]], + *, + config: CloudMapConfig, +) -> tuple[np.ndarray, np.ndarray, list[str]]: + """Composite multiple geostationary satellite IR PNGs into global density & temp grids.""" + _bound_cv_threads() + width, height = parse_resolution(config.resolution) + temp_accum = np.zeros((height, width), dtype=np.float32) + weight_accum = np.zeros((height, width), dtype=np.float32) + active_satellites: list[str] = [] + + for sat, payload_bytes in satellite_payloads: + rgba_arr = _decode_image_bytes(payload_bytes, width, height) + if sat["provider"] == "gibs": + sat_temp, valid = decode_gibs_band13_to_temp_and_valid(rgba_arr) + else: + sat_temp, valid = decode_eumetview_ir_to_temp_and_valid(rgba_arr) + + if not np.any(valid): + continue + + lon_weights = _compute_satellite_longitude_weights(width, float(sat["sub_lon"])) + pixel_weight = np.where(valid, lon_weights[None, :], 0.0) + safe_temp = np.where(valid, sat_temp, 0.0) + temp_accum += safe_temp * pixel_weight + weight_accum += pixel_weight + active_satellites.append(str(sat["id"])) + + if not active_satellites or not np.any(weight_accum > 0.0): + raise RuntimeError("No valid geostationary IR satellite frames could be decoded") + + covered = weight_accum > 0.0 + composite_temp = np.full((height, width), np.nan, dtype=np.float32) + composite_temp[covered] = temp_accum[covered] / weight_accum[covered] + + density = temperature_to_density( + composite_temp, + ir_threshold=config.ir_threshold, + contrast_gamma=config.contrast_gamma, + ) + # Light edge-preserving denoise to soften WMS resampling quantization. + density = cv2.GaussianBlur(density, (3, 3), 0.6) + density = _apply_polar_and_seam_smoothing( + density, + polar_feather_enabled=config.polar_feather_enabled, + ) + return density, composite_temp, active_satellites + + +def decode_matteason_cloud_bytes( + payload_bytes: bytes, + *, + config: CloudMapConfig, +) -> tuple[np.ndarray, np.ndarray]: + """Normalize Matt Eason equirectangular cloud texture into global density & approx temp.""" + width, height = parse_resolution(config.resolution) + rgba_arr = _decode_image_bytes(payload_bytes, width, height) + rgb_mean = np.mean(rgba_arr[:, :, :3].astype(np.float32), axis=2) + alpha = rgba_arr[:, :, 3].astype(np.float32) + raw_density = np.minimum(rgb_mean, alpha) / 255.0 + cutoff = max(0.0, min(0.6, config.ir_threshold / 180.0)) + scaled = np.clip((raw_density - cutoff) / max(0.25, 1.0 - cutoff), 0.0, 1.0) + if abs(config.contrast_gamma - 1.0) > 1e-3: + scaled = np.power(scaled, float(config.contrast_gamma)) + density = np.clip(np.round(scaled * 255.0), 0, 255).astype(np.uint8) + approx_temp = (20.0 - (density.astype(np.float32) / 255.0) * 90.0).astype(np.float32) + return density, approx_temp + + +def _encode_cloud_webp(density_u8: np.ndarray) -> bytes: + """Encode density field as RGBA WebP compatible with Three.js cloud shader & HTML preview.""" + rgba = np.empty((density_u8.shape[0], density_u8.shape[1], 4), dtype=np.uint8) + rgba[:, :, 0] = density_u8 + rgba[:, :, 1] = density_u8 + rgba[:, :, 2] = density_u8 + rgba[:, :, 3] = density_u8 + img = Image.fromarray(rgba, mode="RGBA") + buf = io.BytesIO() + img.save(buf, format="WEBP", quality=88, method=1) + return buf.getvalue() + + +def _lat_lon_to_grid_indices(lat: float, lon: float) -> tuple[int, int]: + clamped_lat = max(-89.999, min(89.999, float(lat))) + wrapped_lon = ((float(lon) + 180.0) % 360.0) - 180.0 + row = int(max(0, min(ANALYSIS_GRID_HEIGHT - 1, math.floor((90.0 - clamped_lat) / 0.5)))) + col = int(max(0, min(ANALYSIS_GRID_WIDTH - 1, math.floor((wrapped_lon + 180.0) / 0.5)))) + return row, col + + +def _classify_cloud_density(density_pct: float, convective_threshold: int) -> str: + if density_pct >= float(convective_threshold): + return "convective" + if density_pct >= 55.0: + return "overcast" + if density_pct >= 20.0: + return "partly_cloudy" + return "clear" + + +def _match_region_name(lat: float, lon: float) -> tuple[str, str]: + for region in FOCUS_REGIONS: + if ( + region["lat_min"] <= lat <= region["lat_max"] + and region["lon_min"] <= lon <= region["lon_max"] + ): + return str(region["name"]), str(region["name_en"]) + if -23.5 <= lat <= 23.5: + return "热带海域/陆区", "Tropics" + if lat > 23.5: + return "北半球中高纬", "Northern Mid-High Latitudes" + return "南半球中高纬", "Southern Mid-High Latitudes" + + +def analyze_cloud_density_grid( + density_u8: np.ndarray, + temp_c: np.ndarray, + *, + config: CloudMapConfig, + previous_snapshot: dict[str, Any] | None = None, + previous_regions: dict[str, float] | None = None, +) -> dict[str, Any]: + """Downsample density/temperature fields and compute regional & convective analytics.""" + _bound_cv_threads() + grid_density = cv2.resize( + density_u8, + (ANALYSIS_GRID_WIDTH, ANALYSIS_GRID_HEIGHT), + interpolation=cv2.INTER_AREA, + ) + temp_filled = np.where(np.isnan(temp_c), 25.0, temp_c).astype(np.float32) + grid_temp = cv2.resize( + temp_filled, + (ANALYSIS_GRID_WIDTH, ANALYSIS_GRID_HEIGHT), + interpolation=cv2.INTER_AREA, + ) + + density_pct = (grid_density.astype(np.float32) / 255.0) * 100.0 + lat_centers = 90.0 - (np.arange(ANALYSIS_GRID_HEIGHT, dtype=np.float32) + 0.5) * 0.5 + lon_centers = -180.0 + (np.arange(ANALYSIS_GRID_WIDTH, dtype=np.float32) + 0.5) * 0.5 + lat_weights = np.cos(np.deg2rad(lat_centers)).clip(min=0.01)[:, None] + + def _weighted_stats(mask_rows: np.ndarray | None = None) -> tuple[float, float, float]: + sub_d = density_pct if mask_rows is None else density_pct[mask_rows] + sub_w = np.broadcast_to(lat_weights, density_pct.shape) + if mask_rows is not None: + sub_w = sub_w[mask_rows] + w_sum = float(np.sum(sub_w)) or 1.0 + mean_cover = float(np.sum(sub_d * sub_w) / w_sum) + overcast_ratio = float(np.sum((sub_d >= 55.0) * sub_w) / w_sum) * 100.0 + conv_ratio = float(np.sum((sub_d >= float(config.convective_threshold)) * sub_w) / w_sum) * 100.0 + return round(mean_cover, 2), round(overcast_ratio, 2), round(conv_ratio, 2) + + global_mean, global_overcast, global_conv = _weighted_stats() + north_mean, _, _ = _weighted_stats(lat_centers >= 0.0) + south_mean, _, _ = _weighted_stats(lat_centers < 0.0) + tropics_mean, _, _ = _weighted_stats((lat_centers >= -23.5) & (lat_centers <= 23.5)) + + prev_global = None + if isinstance(previous_snapshot, dict): + try: + prev_global = float(previous_snapshot.get("global_cloud_cover_pct")) + except (TypeError, ValueError): + prev_global = None + + region_summaries: list[dict[str, Any]] = [] + for region in FOCUS_REGIONS: + row_mask = (lat_centers >= region["lat_min"]) & (lat_centers <= region["lat_max"]) + col_mask = (lon_centers >= region["lon_min"]) & (lon_centers <= region["lon_max"]) + sub_d = density_pct[np.ix_(row_mask, col_mask)] + sub_t = grid_temp[np.ix_(row_mask, col_mask)] + sub_w = np.broadcast_to(lat_weights[row_mask], sub_d.shape) + w_sum = float(np.sum(sub_w)) or 1.0 + mean_cover = round(float(np.sum(sub_d * sub_w) / w_sum), 2) + overcast_pct = round(float(np.sum((sub_d >= 55.0) * sub_w) / w_sum) * 100.0, 2) + conv_pct = round( + float(np.sum((sub_d >= float(config.convective_threshold)) * sub_w) / w_sum) * 100.0, 2 + ) + min_temp = round(float(np.min(sub_t)), 1) if sub_t.size else None + prev_val = (previous_regions or {}).get(region["key"]) + delta_pct = round(mean_cover - prev_val, 2) if prev_val is not None else None + region_summaries.append( + { + "key": region["key"], + "name": region["name"], + "name_en": region["name_en"], + "center_lat": round((region["lat_min"] + region["lat_max"]) * 0.5, 2), + "center_lon": round((region["lon_min"] + region["lon_max"]) * 0.5, 2), + "cloud_cover_pct": mean_cover, + "overcast_coverage_pct": overcast_pct, + "convective_coverage_pct": conv_pct, + "min_brightness_temp_c": min_temp, + "delta_pct": delta_pct, + } + ) + + # Extract convective / cyclone candidate clusters via connected components. + conv_mask = (density_pct >= float(config.convective_threshold)).astype(np.uint8) + num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(conv_mask, connectivity=8) + # 0.5° x 0.5° cell area at equator ≈ (111.32 * 0.5)^2 ≈ 3098 km² + cell_area_eq_km2 = (111.32 * 0.5) ** 2 + clusters: list[dict[str, Any]] = [] + if num_labels > 1: + label_areas = stats[1:, cv2.CC_STAT_AREA] + candidate_indices = np.flatnonzero(label_areas >= 3) + 1 + if candidate_indices.size > 200: + order = np.argsort(stats[candidate_indices, cv2.CC_STAT_AREA])[::-1][:200] + candidate_indices = candidate_indices[order] + else: + candidate_indices = np.empty((0,), dtype=np.int32) + + for label_id in candidate_indices.tolist(): + x = int(stats[label_id, cv2.CC_STAT_LEFT]) + y = int(stats[label_id, cv2.CC_STAT_TOP]) + w = int(stats[label_id, cv2.CC_STAT_WIDTH]) + h = int(stats[label_id, cv2.CC_STAT_HEIGHT]) + sub_mask = labels[y : y + h, x : x + w] == label_id + sub_lat_weights = lat_weights[y : y + h] + area_km2 = round(float(np.sum(sub_mask * sub_lat_weights)) * cell_area_eq_km2, 0) + if area_km2 < float(config.min_cluster_area_km2): + continue + + cx, cy = centroids[label_id] + center_lon = round(-180.0 + (float(cx) + 0.5) * 0.5, 2) + center_lat = round(90.0 - (float(cy) + 0.5) * 0.5, 2) + peak_intensity = round(float(np.max(density_pct[y : y + h, x : x + w][sub_mask])), 1) + min_temp_c = round(float(np.min(grid_temp[y : y + h, x : x + w][sub_mask])), 1) + region_zh, region_en = _match_region_name(center_lat, center_lon) + clusters.append( + { + "cluster_id": f"conv-{len(clusters) + 1}", + "latitude": center_lat, + "longitude": center_lon, + "area_km2": int(area_km2), + "peak_intensity": peak_intensity, + "min_brightness_temp_c": min_temp_c, + "region": region_zh, + "region_en": region_en, + "bbox": { + "lon_min": round(-180.0 + x * 0.5, 2), + "lon_max": round(-180.0 + (x + w) * 0.5, 2), + "lat_max": round(90.0 - y * 0.5, 2), + "lat_min": round(90.0 - (y + h) * 0.5, 2), + }, + } + ) + + clusters.sort(key=lambda item: (item["area_km2"], item["peak_intensity"]), reverse=True) + clusters = clusters[:25] + for idx, item in enumerate(clusters, start=1): + item["cluster_id"] = f"conv-{idx}" + + global_min_temp = round(float(np.min(grid_temp)), 1) if grid_temp.size else None + + return { + "grid_density": grid_density, + "grid_temp_i8": np.clip(np.round(grid_temp), -120, 80).astype(np.int8), + "global_summary": { + "global_cloud_cover_pct": global_mean, + "global_overcast_pct": global_overcast, + "global_convective_pct": global_conv, + "northern_hemisphere_pct": north_mean, + "southern_hemisphere_pct": south_mean, + "tropics_pct": tropics_mean, + "delta_pct": round(global_mean - prev_global, 2) if prev_global is not None else None, + "convective_cluster_count": len(clusters), + "min_brightness_temp_c": global_min_temp, + }, + "regions": region_summaries, + "convective_clusters": clusters, + } + + +def _wms_getmap_params(layer: str, width: int, height: int) -> dict[str, str]: + return { + "SERVICE": "WMS", + "REQUEST": "GetMap", + "VERSION": "1.1.1", + "LAYERS": layer, + "STYLES": "", + "FORMAT": "image/png", + "TRANSPARENT": "true", + "SRS": "EPSG:4326", + "BBOX": "-180,-90,180,90", + "WIDTH": str(width), + "HEIGHT": str(height), + } + + +async def _fetch_multi_sat_payloads( + config: CloudMapConfig, + *, + layer_field: str = "layer", +) -> list[tuple[dict[str, Any], bytes]]: + width, height = parse_resolution(config.resolution) + timeout = httpx.Timeout(float(config.request_timeout_seconds)) + headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthCloudCollector)"} + + async def _get_one(client: httpx.AsyncClient, sat: dict[str, Any]) -> tuple[dict[str, Any], bytes] | None: + layer_name = str(sat.get(layer_field) or "").strip() + if not layer_name: + return None + params = _wms_getmap_params(layer_name, width, height) + try: + response = await client.get(str(sat["url"]), params=params) + response.raise_for_status() + content_type = str(response.headers.get("content-type") or "").lower() + if not content_type.startswith("image/"): + logger.warning_event( + "Cloud satellite WMS returned non-image content", + event="earth.cloud_map.wms_invalid_content_type", + context={"satellite": sat["id"], "layer": layer_name, "content_type": content_type}, + ) + return None + return sat, response.content + except Exception as exc: + logger.warning_event( + "Cloud satellite WMS request failed", + event="earth.cloud_map.wms_fetch_failed", + context={"satellite": sat["id"], "layer": layer_name, "error": str(exc)}, + ) + return None + + async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client: + semaphore = asyncio.Semaphore(5) + + async def _limited_get(sat: dict[str, Any]) -> tuple[dict[str, Any], bytes] | None: + async with semaphore: + return await _get_one(client, sat) + + results = await asyncio.gather(*(_limited_get(sat) for sat in SATELLITE_SOURCES)) + return [item for item in results if item is not None] + + +async def _fetch_matteason_bytes(config: CloudMapConfig) -> bytes: + size_path = "4096x2048" if config.resolution == "4096x2048" else "2048x1024" + url = f"{MATTEASON_BASE_URL}/{size_path}/clouds-alpha.png" + timeout = httpx.Timeout(float(config.request_timeout_seconds)) + headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthCloudCollector)"} + async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client: + response = await client.get(url) + response.raise_for_status() + content_type = str(response.headers.get("content-type") or "").lower() + if not content_type.startswith("image/"): + raise RuntimeError(f"Unexpected Matt Eason content-type: {content_type}") + return response.content + + +def _flows_dir() -> Path: + return _get_data_dir() / "flows" + + +def _save_frame_artifacts_sync( + *, + version: str, + captured_at: str, + source_used: str, + satellites: list[str], + degraded: bool, + config: CloudMapConfig, + webp_bytes: bytes, + visual_webp_bytes: bytes | None = None, + flow_webp_bytes: bytes | None = None, + flow_prev_version: str | None = None, + flow_max_uv: float = 0.0, + grid_density: np.ndarray, + grid_temp_i8: np.ndarray, + global_summary: dict[str, Any], + regions: list[dict[str, Any]], + clusters: list[dict[str, Any]], +) -> dict[str, Any]: + _ensure_dirs() + _flows_dir().mkdir(parents=True, exist_ok=True) + frame_path = _frames_dir() / f"{version}.webp" + visual_path = _frames_dir() / f"{version}_vis.webp" + flow_path = _flows_dir() / f"{version}.webp" + grid_path = _grids_dir() / f"{version}.bin" + temp_path = _temps_dir() / f"{version}.bin" + + _atomic_write_bytes(frame_path, webp_bytes) + if visual_webp_bytes: + _atomic_write_bytes(visual_path, visual_webp_bytes) + if flow_webp_bytes: + _atomic_write_bytes(flow_path, flow_webp_bytes) + _atomic_write_bytes(grid_path, grid_density.tobytes()) + _atomic_write_bytes(temp_path, grid_temp_i8.tobytes()) + + sha256 = hashlib.sha256(webp_bytes).hexdigest() + frame_entry = { + "version": version, + "captured_at": captured_at, + "source": source_used, + "satellites": satellites, + "degraded": degraded, + "resolution": config.resolution, + "file_size_bytes": len(webp_bytes), + "sha256": sha256, + "image_url": f"/api/v1/earth/clouds/frames/{version}", + "visual_url": f"/api/v1/earth/clouds/frames/{version}/visual" if visual_webp_bytes else None, + "flow_url": f"/api/v1/earth/clouds/flows/{version}" if flow_webp_bytes else None, + "flow_prev_version": flow_prev_version if flow_webp_bytes else None, + "flow_max_uv": float(flow_max_uv) if flow_webp_bytes else 0.0, + "global_summary": global_summary, + "regions": regions, + "convective_clusters": clusters, + } + + manifest = _read_manifest() + frames = [item for item in manifest.get("frames", []) if item.get("version") != version] + frames.insert(0, frame_entry) + kept_frames = frames[: config.max_history_frames] + dropped_versions = { + str(item.get("version")) + for item in frames[config.max_history_frames :] + if item.get("version") + } + + _atomic_write_json( + _manifest_path(), + { + "latest_version": version, + "updated_at": captured_at, + "frames": kept_frames, + }, + ) + + for old_version in dropped_versions: + _remove_version_files(old_version) + + return frame_entry + + +def _remove_version_files(version: str) -> int: + if not VERSION_PATTERN.match(version): + return 0 + removed = 0 + for target in ( + _frames_dir() / f"{version}.webp", + _frames_dir() / f"{version}_vis.webp", + _flows_dir() / f"{version}.webp", + _grids_dir() / f"{version}.bin", + _temps_dir() / f"{version}.bin", + ): + if target.exists(): + try: + target.unlink() + removed += 1 + except OSError: + pass + return removed + + +def prune_cloud_map_artifacts(max_frames: int = 24) -> int: + """Prune stale cloud frame/grid/flow artifacts beyond retention limit and orphaned temp files.""" + if not _get_data_dir().exists(): + return 0 + manifest = _read_manifest() + frames = manifest.get("frames", []) + kept = frames[: max(1, int(max_frames))] + kept_versions = {str(item.get("version")) for item in kept if item.get("version")} + removed = 0 + + for item in frames[max(1, int(max_frames)) :]: + ver = str(item.get("version") or "") + if ver: + removed += _remove_version_files(ver) + + for directory in (_frames_dir(), _flows_dir(), _grids_dir(), _temps_dir()): + if not directory.exists(): + continue + for file_path in directory.iterdir(): + base_stem = file_path.stem.removesuffix("_vis") + if file_path.name.startswith(".") or base_stem not in kept_versions: + try: + file_path.unlink() + removed += 1 + except OSError: + pass + + if len(kept) != len(frames): + _atomic_write_json( + _manifest_path(), + { + "latest_version": kept[0].get("version") if kept else None, + "updated_at": manifest.get("updated_at"), + "frames": kept, + }, + ) + return removed + + +def clear_all_cloud_map_artifacts() -> int: + """Remove all persisted cloud frame images, visual/flow maps, grids, and manifest.""" + removed = 0 + for directory in (_frames_dir(), _flows_dir(), _grids_dir(), _temps_dir()): + if not directory.exists(): + continue + for file_path in directory.iterdir(): + if file_path.is_file(): + try: + file_path.unlink() + removed += 1 + except OSError: + pass + manifest_file = _manifest_path() + if manifest_file.exists(): + try: + manifest_file.unlink() + removed += 1 + except OSError: + pass + return removed + + +async def read_cloud_map_configuration(db: AsyncSession | None) -> dict[str, Any]: + if db is None or not callable(getattr(db, "execute", None)): + return _default_envelope() + result = await db.execute( + select(SystemSetting).where(SystemSetting.category == CLOUD_CONFIG_CATEGORY) + ) + record = result.scalar_one_or_none() + if not record or not isinstance(record.payload, dict): + return _default_envelope() + payload = dict(record.payload) + try: + validated = CloudMapConfig.model_validate(payload.get("config") or {}) + except Exception: + validated = DEFAULT_CLOUD_CONFIG + return { + "config": validated.model_dump(mode="json"), + "revision": str(payload.get("revision") or DEFAULT_CLOUD_REVISION), + "is_default": bool(payload.get("is_default", False)), + } + + +async def save_cloud_map_configuration( + db: AsyncSession, + *, + revision: str, + config: CloudMapConfig, + actor: User, + reset: bool = False, +) -> dict[str, Any]: + dialect_name = "" + try: + bind = db.get_bind() + dialect_name = str(getattr(getattr(bind, "dialect", None), "name", "") or "").lower() + except Exception: + dialect_name = "" + + if dialect_name == "postgresql": + await db.execute( + pg_insert(SystemSetting) + .values(category=CLOUD_CONFIG_CATEGORY, payload=_default_envelope()) + .on_conflict_do_nothing(index_elements=[SystemSetting.category]) + ) + record = ( + await db.execute( + select(SystemSetting) + .where(SystemSetting.category == CLOUD_CONFIG_CATEGORY) + .with_for_update() + ) + ).scalar_one() + else: + record = ( + await db.execute( + select(SystemSetting).where(SystemSetting.category == CLOUD_CONFIG_CATEGORY) + ) + ).scalar_one_or_none() + if record is None: + record = SystemSetting(category=CLOUD_CONFIG_CATEGORY, payload=_default_envelope()) + db.add(record) + + current_revision = str((record.payload or {}).get("revision") or DEFAULT_CLOUD_REVISION) + if current_revision != revision: + await db.rollback() + raise CloudMapRevisionConflictError("Configuration changed by another editor. Reload and retry.") + + envelope = ( + _default_envelope() + if reset + else { + "config": config.model_dump(mode="json"), + "revision": uuid4().hex[:16], + "is_default": False, + } + ) + before = dict(record.payload or {}) + if reset: + if getattr(record, "id", None) is not None: + await db.delete(record) + else: + record.payload = envelope + + db.add( + AuditLog( + actor_id=actor.id, + actor_name=actor.username, + action="earth_cloud_map.reset" if reset else "earth_cloud_map.update", + target_type="system_setting", + target_id=CLOUD_CONFIG_CATEGORY, + result="success", + request_id=get_request_id(), + details={"before": before, "after": envelope}, + ) + ) + await db.commit() + return envelope + + +async def collect_latest_cloud_frame( + db: AsyncSession | None = None, + *, + override_config: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Fetch, composite, analyze, and persist one live satellite cloud frame.""" + envelope = await read_cloud_map_configuration(db) + merged_cfg = {**envelope["config"], **(override_config or {})} + config = CloudMapConfig.model_validate(merged_cfg) + + manifest = _read_manifest() + prev_frames = manifest.get("frames", []) + prev_entry = prev_frames[0] if prev_frames else None + prev_snapshot = prev_entry.get("global_summary") if isinstance(prev_entry, dict) else None + prev_regions: dict[str, float] = {} + if isinstance(prev_entry, dict) and isinstance(prev_entry.get("regions"), list): + for item in prev_entry["regions"]: + if isinstance(item, dict) and item.get("key") is not None: + try: + prev_regions[str(item["key"])] = float(item["cloud_cover_pct"]) + except (TypeError, ValueError): + pass + + density: np.ndarray | None = None + temp_c: np.ndarray | None = None + visual_payloads: list[tuple[dict[str, Any], bytes]] = [] + source_used = config.primary_source + satellites: list[str] = [] + degraded = False + + if config.primary_source == "multi_sat_ir": + if config.geocolor_enabled: + payloads, visual_payloads = await asyncio.gather( + _fetch_multi_sat_payloads(config, layer_field="layer"), + _fetch_multi_sat_payloads(config, layer_field="visual_layer"), + ) + else: + payloads = await _fetch_multi_sat_payloads(config, layer_field="layer") + if payloads: + density, temp_c, satellites = await asyncio.to_thread( + synthesize_multi_sat_ir, + payloads, + config=config, + ) + if len(satellites) < len(SATELLITE_SOURCES): + degraded = True + elif config.fallback_source == "matteason_live": + raw = await _fetch_matteason_bytes(config) + density, temp_c = await asyncio.to_thread( + decode_matteason_cloud_bytes, + raw, + config=config, + ) + source_used = "matteason_live" + satellites = ["eumetsat_nasa_mosaic"] + degraded = True + else: + raw = await _fetch_matteason_bytes(config) + density, temp_c = await asyncio.to_thread( + decode_matteason_cloud_bytes, + raw, + config=config, + ) + source_used = "matteason_live" + satellites = ["eumetsat_nasa_mosaic"] + + if density is None or temp_c is None: + raise RuntimeError("Failed to fetch cloud imagery from all configured upstream sources") + + now_utc = datetime.now(UTC) + version = now_utc.strftime("%Y%m%dT%H%M%SZ") + captured_at = to_iso8601_utc(now_utc) or now_utc.isoformat() + + def _finalize() -> tuple[dict[str, Any], dict[str, Any]]: + from app.services.earth_clouds_fx import ( + compute_dis_optical_flow_webp, + decode_visual_payloads, + fuse_daytime_visible_into_density, + synthesize_geocolor_visual_webp, + ) + + width, height = parse_resolution(config.resolution) + decoded_visuals = ( + decode_visual_payloads(visual_payloads, width, height) + if (config.geocolor_enabled and visual_payloads) + else [] + ) + fused_density = ( + fuse_daytime_visible_into_density( + density, + temp_c, + decoded_visuals, + width=width, + height=height, + now_utc=now_utc, + ) + if decoded_visuals + else density + ) + + analysis = analyze_cloud_density_grid( + fused_density, + temp_c, + config=config, + previous_snapshot=prev_snapshot, + previous_regions=prev_regions, + ) + webp_bytes = _encode_cloud_webp(fused_density) + visual_webp_bytes = ( + synthesize_geocolor_visual_webp( + decoded_visuals, + fused_density, + width=width, + height=height, + ) + if decoded_visuals + else None + ) + flow_webp_bytes: bytes | None = None + flow_prev_version: str | None = None + flow_max_uv = 0.0 + if config.optical_flow_enabled and isinstance(prev_entry, dict) and prev_entry.get("version"): + prev_ver = str(prev_entry["version"]) + prev_frame_file = _frames_dir() / f"{prev_ver}.webp" + if prev_ver != version and prev_frame_file.exists(): + try: + prev_rgba = _decode_image_bytes(prev_frame_file.read_bytes(), width, height) + prev_density = prev_rgba[:, :, 3] + flow_res = compute_dis_optical_flow_webp(prev_density, fused_density) + if flow_res is not None: + flow_webp_bytes, flow_max_uv = flow_res + flow_prev_version = prev_ver + except Exception as exc: + logger.warning_event( + "Cloud optical flow calculation failed", + event="earth.cloud_map.optical_flow_failed", + context={"prev_version": prev_ver, "error": str(exc)}, + ) + + entry = _save_frame_artifacts_sync( + version=version, + captured_at=captured_at, + source_used=source_used, + satellites=satellites, + degraded=degraded, + config=config, + webp_bytes=webp_bytes, + visual_webp_bytes=visual_webp_bytes, + flow_webp_bytes=flow_webp_bytes, + flow_prev_version=flow_prev_version, + flow_max_uv=flow_max_uv, + grid_density=analysis["grid_density"], + grid_temp_i8=analysis["grid_temp_i8"], + global_summary=analysis["global_summary"], + regions=analysis["regions"], + clusters=analysis["convective_clusters"], + ) + return entry, analysis + + async with _CLOUD_WRITE_LOCK: + frame_entry, analysis = await asyncio.to_thread(_finalize) + + return { + "frame": frame_entry, + "global_summary": analysis["global_summary"], + "regions": analysis["regions"], + "convective_clusters": analysis["convective_clusters"], + "config": config.model_dump(mode="json"), + } + + +def _summarize_storage() -> dict[str, Any]: + total_bytes = 0 + file_count = 0 + for directory in (_frames_dir(), _flows_dir(), _grids_dir(), _temps_dir()): + if not directory.exists(): + continue + for file_path in directory.iterdir(): + if file_path.is_file(): + file_count += 1 + try: + total_bytes += file_path.stat().st_size + except OSError: + pass + return { + "file_count": file_count, + "total_bytes": total_bytes, + "total_mb": round(total_bytes / (1024 * 1024), 2), + } + + +async def get_cloud_map_runtime_meta(db: AsyncSession | None = None) -> dict[str, Any]: + envelope = await read_cloud_map_configuration(db) + config = CloudMapConfig.model_validate(envelope["config"]) + manifest = _read_manifest() + frames = manifest.get("frames", []) + latest = frames[0] if frames else None + latest_version = str(latest.get("version")) if isinstance(latest, dict) and latest.get("version") else None + frame_exists = bool( + latest_version + and VERSION_PATTERN.match(latest_version) + and (_frames_dir() / f"{latest_version}.webp").exists() + ) + + if not config.enabled: + mode = "static" + image_url = DEFAULT_STATIC_CLOUD_URL + elif frame_exists and latest is not None: + mode = "realtime" + image_url = f"/api/v1/earth/clouds/frames/{latest_version}" + else: + mode = "fallback_static" + image_url = DEFAULT_STATIC_CLOUD_URL + + visual_exists = bool( + frame_exists + and config.geocolor_enabled + and (_frames_dir() / f"{latest_version}_vis.webp").exists() + ) + flow_exists = bool( + frame_exists + and config.optical_flow_enabled + and (_flows_dir() / f"{latest_version}.webp").exists() + ) + + hd_tiles_available = False + if db is not None and hasattr(db, "execute"): + try: + hd_row = ( + await db.execute(select(DataSource.is_active).where(DataSource.source == "cloud_hd_tiles")) + ).scalar_one_or_none() + hd_tiles_available = bool(hd_row) + except Exception: + hd_tiles_available = False + + history_frames = [ + { + "version": item.get("version"), + "captured_at": item.get("captured_at"), + "source": item.get("source"), + "satellites": item.get("satellites") or [], + "degraded": bool(item.get("degraded", False)), + "resolution": item.get("resolution"), + "file_size_bytes": item.get("file_size_bytes"), + "image_url": item.get("image_url"), + "visual_url": ( + f"/api/v1/earth/clouds/frames/{item.get('version')}/visual" + if (_frames_dir() / f"{item.get('version')}_vis.webp").exists() + else None + ), + "flow_url": ( + f"/api/v1/earth/clouds/flows/{item.get('version')}" + if (_flows_dir() / f"{item.get('version')}.webp").exists() + else None + ), + "flow_prev_version": item.get("flow_prev_version"), + "flow_max_uv": float(item.get("flow_max_uv") or 0.0), + "global_summary": item.get("global_summary") or {}, + } + for item in frames + if isinstance(item, dict) + and item.get("version") + and (_frames_dir() / f"{item.get('version')}.webp").exists() + ] + + return { + "enabled": config.enabled, + "mode": mode, + "degraded": bool(latest.get("degraded", False)) if (frame_exists and latest) else (config.enabled), + "source": latest.get("source") if (frame_exists and latest) else "static", + "satellites": (latest.get("satellites") or []) if (frame_exists and latest) else [], + "captured_at": latest.get("captured_at") if (frame_exists and latest) else None, + "version": latest_version if frame_exists else None, + "image_url": image_url, + "visual_url": f"/api/v1/earth/clouds/frames/{latest_version}/visual" if visual_exists else None, + "flow_url": f"/api/v1/earth/clouds/flows/{latest_version}" if flow_exists else None, + "flow_prev_version": latest.get("flow_prev_version") if (flow_exists and latest) else None, + "flow_max_uv": float(latest.get("flow_max_uv") or 0.0) if (flow_exists and latest) else 0.0, + "geocolor_enabled": config.geocolor_enabled, + "relief_shading_strength": config.relief_shading_strength, + "optical_flow_enabled": config.optical_flow_enabled, + "hd_tiles_available": hd_tiles_available, + "default_opacity": config.default_opacity, + "timelapse_enabled": config.timelapse_enabled, + "show_convective_markers": config.show_convective_markers, + "convective_threshold": config.convective_threshold, + "frames": history_frames, + "summary": (latest.get("global_summary") or {}) if (frame_exists and latest) else {}, + "regions": (latest.get("regions") or []) if (frame_exists and latest) else [], + "convective_clusters": (latest.get("convective_clusters") or []) if (frame_exists and latest) else [], + "storage_stats": _summarize_storage(), + } + + +def read_cloud_frame_bytes(version: str) -> bytes | None: + if not VERSION_PATTERN.match(version): + return None + target = (_frames_dir() / f"{version}.webp").resolve() + frames_root = _frames_dir().resolve() + if target.parent != frames_root or not target.exists(): + return None + return target.read_bytes() + + +def read_cloud_visual_frame_bytes(version: str) -> bytes | None: + if not VERSION_PATTERN.match(version): + return None + target = (_frames_dir() / f"{version}_vis.webp").resolve() + frames_root = _frames_dir().resolve() + if target.parent != frames_root or not target.exists(): + return None + return target.read_bytes() + + +def read_cloud_flow_bytes(version: str) -> bytes | None: + if not VERSION_PATTERN.match(version): + return None + target = (_flows_dir() / f"{version}.webp").resolve() + flows_root = _flows_dir().resolve() + if target.parent != flows_root or not target.exists(): + return None + return target.read_bytes() + + +def _load_latest_analysis_grids() -> tuple[dict[str, Any] | None, np.ndarray | None, np.ndarray | None]: + manifest = _read_manifest() + frames = manifest.get("frames", []) + if not frames: + return None, None, None + latest = frames[0] + version = str(latest.get("version") or "") + if not VERSION_PATTERN.match(version): + return None, None, None + grid_file = _grids_dir() / f"{version}.bin" + if not grid_file.exists(): + return None, None, None + raw = grid_file.read_bytes() + expected = ANALYSIS_GRID_WIDTH * ANALYSIS_GRID_HEIGHT + if len(raw) != expected: + return None, None, None + density = np.frombuffer(raw, dtype=np.uint8).reshape((ANALYSIS_GRID_HEIGHT, ANALYSIS_GRID_WIDTH)) + + temp_file = _temps_dir() / f"{version}.bin" + temp_i8 = None + if temp_file.exists(): + t_raw = temp_file.read_bytes() + if len(t_raw) == expected: + temp_i8 = np.frombuffer(t_raw, dtype=np.int8).reshape( + (ANALYSIS_GRID_HEIGHT, ANALYSIS_GRID_WIDTH) + ) + return latest, density, temp_i8 + + +async def query_cloud_point( + lat: float, + lon: float, + db: AsyncSession | None = None, +) -> dict[str, Any]: + envelope = await read_cloud_map_configuration(db) + config = CloudMapConfig.model_validate(envelope["config"]) + latest, density_grid, temp_grid = _load_latest_analysis_grids() + if latest is None or density_grid is None: + return { + "available": False, + "latitude": round(float(lat), 4), + "longitude": round(float(lon), 4), + "cloud_cover_pct": None, + "classification": "unavailable", + "brightness_temp_c": None, + "captured_at": None, + } + + row, col = _lat_lon_to_grid_indices(lat, lon) + pct = round(float(density_grid[row, col]) / 255.0 * 100.0, 1) + temp_val = int(temp_grid[row, col]) if temp_grid is not None else None + region_zh, region_en = _match_region_name(lat, lon) + return { + "available": True, + "latitude": round(float(lat), 4), + "longitude": round(float(lon), 4), + "cloud_cover_pct": pct, + "classification": _classify_cloud_density(pct, config.convective_threshold), + "brightness_temp_c": temp_val, + "region": region_zh, + "region_en": region_en, + "version": latest.get("version"), + "captured_at": latest.get("captured_at"), + "source": latest.get("source"), + } + + +async def get_cloud_analysis_summary(db: AsyncSession | None = None) -> dict[str, Any]: + meta = await get_cloud_map_runtime_meta(db) + return { + "available": meta["mode"] == "realtime", + "mode": meta["mode"], + "degraded": meta["degraded"], + "version": meta["version"], + "captured_at": meta["captured_at"], + "source": meta["source"], + "satellites": meta["satellites"], + "global_summary": meta["summary"], + "regions": meta["regions"], + "convective_clusters": meta["convective_clusters"], + } + + +async def _load_asset_candidates(db: AsyncSession, domain: str) -> list[dict[str, Any]]: + from app.api.v1.visualization import ( + _build_compute_centers_geojson, + _build_landing_points_geojson, + _build_satellites_geojson, + ) + from app.core.collected_data_fields import get_record_field + + candidates: list[dict[str, Any]] = [] + if domain == "vessels": + rows = ( + await db.execute( + select(VesselPosition) + .where( + VesselPosition.latitude.is_not(None), + VesselPosition.longitude.is_not(None), + ) + .order_by(VesselPosition.received_at.desc()) + .limit(2000) + ) + ).scalars().all() + for row in rows: + candidates.append( + { + "id": str(row.mmsi), + "name": row.name or f"MMSI {row.mmsi}", + "entity_type": "vessel", + "latitude": float(row.latitude), + "longitude": float(row.longitude), + "extra": {"sog": row.sog, "vessel_type": row.vessel_type_name}, + } + ) + return candidates + + fc: dict[str, Any] = {} + if domain == "cables": + fc = await _build_landing_points_geojson(db) + elif domain == "compute_centers": + fc = await _build_compute_centers_geojson(limit=1500, db=db) + else: + fc = await _build_satellites_geojson(limit=1000, db=db) + + for feat in fc.get("features") or []: + geom = feat.get("geometry") or {} + coords = geom.get("coordinates") + if not isinstance(coords, (list, tuple)) or len(coords) < 2: + continue + try: + lon_val = float(coords[0]) + lat_val = float(coords[1]) + except (TypeError, ValueError): + continue + props = feat.get("properties") or {} + candidates.append( + { + "id": str(props.get("id") or props.get("source_id") or props.get("norad_id") or props.get("name") or ""), + "name": str(props.get("name") or props.get("title") or "Asset"), + "entity_type": str(props.get("type") or props.get("category") or domain), + "latitude": lat_val, + "longitude": lon_val, + "extra": { + k: props[k] + for k in ("country", "city", "constellation", "cable_count") + if props.get(k) is not None + }, + } + ) + + if not candidates and domain in {"cables", "compute_centers"}: + # Lightweight fallback when visualization geojson helpers have empty sources + rows = ( + await db.execute( + select(CollectedData) + .where( + CollectedData.is_current.is_(True), + CollectedData.deleted_at.is_(None), + ) + .limit(1500) + ) + ).scalars().all() + for row in rows: + lat_val = get_record_field(row, "latitude") + lon_val = get_record_field(row, "longitude") + if not isinstance(lat_val, (int, float)) or not isinstance(lon_val, (int, float)): + continue + candidates.append( + { + "id": str(row.source_id or row.id), + "name": row.name or row.title or f"Record #{row.id}", + "entity_type": str(row.data_type or domain), + "latitude": float(lat_val), + "longitude": float(lon_val), + "extra": {"country": get_record_field(row, "country")}, + } + ) + return candidates + + +async def correlate_cloud_with_assets( + db: AsyncSession, + *, + domain: str, + min_density: float = 55.0, + limit: int = 25, +) -> dict[str, Any]: + """Cross-reference current cloud density grid against spatial assets in DB.""" + normalized_domain = str(domain or "").strip().lower() + if normalized_domain not in {"vessels", "cables", "compute_centers", "satellites"}: + raise ValueError("domain must be one of: vessels, cables, compute_centers, satellites") + + latest, density_grid, temp_grid = _load_latest_analysis_grids() + if latest is None or density_grid is None: + return { + "available": False, + "domain": normalized_domain, + "min_density": min_density, + "captured_at": None, + "total_checked": 0, + "affected_count": 0, + "items": [], + } + + candidates = await _load_asset_candidates(db, normalized_domain) + + affected: list[dict[str, Any]] = [] + for item in candidates: + row_idx, col_idx = _lat_lon_to_grid_indices(item["latitude"], item["longitude"]) + pct = round(float(density_grid[row_idx, col_idx]) / 255.0 * 100.0, 1) + if pct < min_density: + continue + temp_val = int(temp_grid[row_idx, col_idx]) if temp_grid is not None else None + region_zh, _ = _match_region_name(item["latitude"], item["longitude"]) + affected.append( + { + **item, + "cloud_cover_pct": pct, + "brightness_temp_c": temp_val, + "region": region_zh, + } + ) + + affected.sort(key=lambda entry: entry["cloud_cover_pct"], reverse=True) + bounded_limit = max(1, min(int(limit), 100)) + return { + "available": True, + "domain": normalized_domain, + "min_density": min_density, + "version": latest.get("version"), + "captured_at": latest.get("captured_at"), + "total_checked": len(candidates), + "affected_count": len(affected), + "items": affected[:bounded_limit], + } + + +async def test_cloud_map_source(source_id: str, timeout_seconds: int = 15) -> dict[str, Any]: + """Probe upstream cloud source using GET with tiny image size (GIBS rejects HEAD).""" + normalized = str(source_id or "multi_sat_ir").strip().lower() + if normalized not in {"multi_sat_ir", "matteason_live"}: + raise ValueError("source_id must be 'multi_sat_ir' or 'matteason_live'") + + timeout = httpx.Timeout(float(max(5, min(timeout_seconds, 45)))) + headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthCloudProbe)"} + started = perf_counter() + + if normalized == "matteason_live": + probe_url = f"{MATTEASON_BASE_URL}/2048x1024/clouds-alpha.png" + async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client: + async with client.stream("GET", probe_url) as resp: + resp.raise_for_status() + content_type = str(resp.headers.get("content-type") or "").lower() + if not content_type.startswith("image/"): + raise RuntimeError(f"Unexpected content-type: {content_type}") + return { + "source_id": normalized, + "ok": True, + "latency_ms": round((perf_counter() - started) * 1000, 1), + "satellites": [{"id": "matteason_live", "ok": True}], + } + + async def _probe_sat(client: httpx.AsyncClient, sat: dict[str, Any]) -> dict[str, Any]: + t0 = perf_counter() + params = _wms_getmap_params(str(sat["layer"]), 64, 32) + try: + resp = await client.get(str(sat["url"]), params=params) + resp.raise_for_status() + ct = str(resp.headers.get("content-type") or "").lower() + if not ct.startswith("image/"): + return {"id": sat["id"], "label": sat["label"], "ok": False, "error": f"content-type={ct}"} + return { + "id": sat["id"], + "label": sat["label"], + "ok": True, + "latency_ms": round((perf_counter() - t0) * 1000, 1), + } + except Exception as exc: + return {"id": sat["id"], "label": sat["label"], "ok": False, "error": str(exc)} + + async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client: + sat_results = await asyncio.gather(*(_probe_sat(client, sat) for sat in SATELLITE_SOURCES)) + + ok_count = sum(1 for item in sat_results if item["ok"]) + return { + "source_id": normalized, + "ok": ok_count > 0, + "reachable_count": ok_count, + "total_count": len(SATELLITE_SOURCES), + "latency_ms": round((perf_counter() - started) * 1000, 1), + "satellites": sat_results, + } + + +async def get_cloud_datasource_summary(db: AsyncSession) -> dict[str, Any] | None: + ds = ( + await db.execute(select(DataSource).where(DataSource.source == "global_cloud_map")) + ).scalar_one_or_none() + if ds is None: + return None + return { + "id": ds.id, + "source": ds.source, + "name": ds.name, + "is_active": ds.is_active, + "frequency_minutes": ds.frequency_minutes, + "last_run_at": to_iso8601_utc(ds.last_run_at), + "next_run_at": to_iso8601_utc(ds.next_run_at), + "last_status": ds.last_status, + } + + +def validate_whitelisted_cloud_url(url: str) -> str: + parsed = urlparse(str(url or "").strip()) + allowed_hosts = {"gibs.earthdata.nasa.gov", "view.eumetsat.int", "clouds.matteason.co.uk"} + if parsed.scheme != "https" or (parsed.hostname or "").lower() not in allowed_hosts: + raise ValueError("Cloud URL must target a whitelisted meteorological HTTPS host") + return url diff --git a/backend/app/services/earth_clouds_fx.py b/backend/app/services/earth_clouds_fx.py new file mode 100644 index 00000000..13074cf2 --- /dev/null +++ b/backend/app/services/earth_clouds_fx.py @@ -0,0 +1,276 @@ +"""GeoColor daytime visible compositing and DIS optical flow synthesis for cloud maps.""" + +from __future__ import annotations + +from datetime import UTC, datetime +import io +import math +from typing import Any, Sequence + +import cv2 +import numpy as np +from PIL import Image + + +def _longitude_weight_vector(width: int, sub_lon_deg: float) -> np.ndarray: + lons = ((np.arange(width, dtype=np.float32) + 0.5) / float(width)) * 360.0 - 180.0 + delta = np.abs(((lons - float(sub_lon_deg) + 180.0) % 360.0) - 180.0) + sigma = 46.0 + weights = np.exp(-0.5 * (delta / sigma) ** 2).astype(np.float32) + weights[delta > 74.0] = 0.0 + return weights + + +def _decode_rgba_resized(payload_bytes: bytes, width: int, height: int) -> np.ndarray: + with Image.open(io.BytesIO(payload_bytes)) as img: + converted = img.convert("RGBA") + if converted.size != (width, height): + converted = converted.resize((width, height), Image.Resampling.BILINEAR) + return np.asarray(converted, dtype=np.uint8) + + +def decode_visual_payloads( + visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]], + width: int, + height: int, +) -> list[tuple[dict[str, Any], np.ndarray]]: + """Decode and resize visible satellite payloads once so density & GeoColor share buffers.""" + decoded: list[tuple[dict[str, Any], np.ndarray]] = [] + for sat, payload in visual_payloads: + if isinstance(payload, np.ndarray): + if payload.shape[:2] == (height, width) and payload.shape[2] == 4: + decoded.append((sat, payload)) + continue + try: + rgba = _decode_rgba_resized(payload, width, height) + decoded.append((sat, rgba)) + except Exception: + continue + return decoded + + +def _solar_cosine_grid(width: int, height: int, now_utc: datetime) -> tuple[np.ndarray, np.ndarray]: + """Return `(cos_sza_2d, lats_deg_1d)` on the equirectangular cloud grid.""" + utc = now_utc.astimezone(UTC) if now_utc.tzinfo else now_utc.replace(tzinfo=UTC) + doy = utc.timetuple().tm_yday + decl = math.radians(-23.44 * math.cos(2.0 * math.pi * (doy + 10) / 365.0)) + utc_hour = utc.hour + utc.minute / 60.0 + utc.second / 3600.0 + subsolar_lon = (12.0 - utc_hour) * 15.0 + + lats_deg = (90.0 - ((np.arange(height, dtype=np.float32) + 0.5) / float(height)) * 180.0) + lons_deg = (((np.arange(width, dtype=np.float32) + 0.5) / float(width)) * 360.0 - 180.0) + lat_rad = np.deg2rad(lats_deg)[:, None] + ha_rad = np.deg2rad(lons_deg - subsolar_lon)[None, :] + cos_sza = ( + np.sin(lat_rad) * math.sin(decl) + + np.cos(lat_rad) * math.cos(decl) * np.cos(ha_rad) + ).astype(np.float32) + return cos_sza, lats_deg + + +def fuse_daytime_visible_into_density( + density_u8: np.ndarray, + temp_c: np.ndarray, + visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]], + *, + width: int, + height: int, + now_utc: datetime | None = None, +) -> np.ndarray: + """Recover warm daytime low clouds (stratocumulus) from sunlit visible channels.""" + if not visual_payloads or density_u8.shape != (height, width) or temp_c.shape != (height, width): + return density_u8 + + cos_sza, lats_deg = _solar_cosine_grid(width, height, now_utc or datetime.now(UTC)) + polar_w = np.clip((76.0 - np.abs(lats_deg)) / 12.0, 0.0, 1.0).astype(np.float32)[:, None] + day_weight = (np.clip((cos_sza - 0.12) / 0.24, 0.0, 1.0) * polar_w).astype(np.float32) + if not np.any(day_weight > 0.01): + return density_u8 + + decoded_visuals = decode_visual_payloads(visual_payloads, width, height) + if not decoded_visuals: + return density_u8 + + cos_safe = np.clip(cos_sza, 0.30, 1.0) + safe_temp = np.where(np.isfinite(temp_c), temp_c, 15.0).astype(np.float32) + # Band-pass gate: peaks on -2C..+16C warm low clouds while suppressing hot deserts (>+24C) and sub-zero snow (<-8C). + warm_low_cloud_gate = ( + np.clip((24.0 - safe_temp) / 12.0, 0.0, 1.0) + * np.clip((safe_temp + 8.0) / 10.0, 0.0, 1.0) + ).astype(np.float32) + + vis_accum = np.zeros((height, width), dtype=np.float32) + weight_accum = np.zeros((height, width), dtype=np.float32) + + for sat, rgba in decoded_visuals: + rgb = rgba[:, :, :3].astype(np.float32) + alpha = rgba[:, :, 3].astype(np.float32) + luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2] + not_clipped = ~( + (rgb[:, :, 0] >= 254.0) + & (rgb[:, :, 1] >= 254.0) + & (rgb[:, :, 2] >= 254.0) + & (safe_temp > -10.0) + ) + valid = (alpha > 12.0) & (luma > 8.0) & not_clipped + if not np.any(valid): + continue + + chroma = (np.max(rgb, axis=2) - np.min(rgb, axis=2)) / 255.0 + is_color = float(np.nanpercentile(chroma[valid], 95)) > 0.08 + if is_color: + min_rgb = np.min(rgb, axis=2) + albedo = min_rgb / cos_safe + whiteness = np.clip(1.0 - chroma / 0.36, 0.0, 1.0) + sat_cloud = np.clip((albedo - 85.0) / 135.0, 0.0, 1.0) * whiteness * warm_low_cloud_gate + else: + albedo = luma / cos_safe + sat_cloud = np.clip((albedo - 88.0) / 132.0, 0.0, 1.0) * warm_low_cloud_gate + + lon_w = _longitude_weight_vector(width, float(sat.get("sub_lon", 0.0))) + pix_w = np.where(valid, lon_w[None, :], 0.0) + vis_accum += sat_cloud * pix_w + weight_accum += pix_w + + covered = weight_accum > 0.0 + if not np.any(covered): + return density_u8 + + vis_cloud = np.zeros((height, width), dtype=np.float32) + vis_cloud[covered] = vis_accum[covered] / weight_accum[covered] + vis_cloud *= day_weight + + vis_u8 = np.clip(np.round(vis_cloud * 255.0), 0, 255).astype(np.uint8) + vis_u8 = cv2.GaussianBlur(vis_u8, (3, 3), 0.6) + return np.maximum(density_u8, vis_u8) + + +def synthesize_geocolor_visual_webp( + visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]], + density_u8: np.ndarray, + *, + width: int, + height: int, +) -> bytes | None: + """Composite daytime GeoColor/Visible satellite WMS tiles into an RGBA WebP overlay.""" + if not visual_payloads or density_u8.shape != (height, width): + return None + + decoded_visuals = decode_visual_payloads(visual_payloads, width, height) + if not decoded_visuals: + return None + + rgb_accum = np.zeros((height, width, 3), dtype=np.float32) + weight_accum = np.zeros((height, width), dtype=np.float32) + valid_sources = 0 + + for sat, rgba in decoded_visuals: + rgb = rgba[:, :, :3].astype(np.float32) + alpha = rgba[:, :, 3].astype(np.float32) + luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2] + + # EUMETView/GIBS return opaque black over night hemispheres or pure-white clipped wedges. + # Mask out dark night pixels and non-dense pure-white [255,255,255] fill artifacts. + not_clipped = ~( + (rgb[:, :, 0] >= 254.0) + & (rgb[:, :, 1] >= 254.0) + & (rgb[:, :, 2] >= 254.0) + & (density_u8 < 180) + ) + valid = (alpha > 12.0) & (luma > 22.0) & not_clipped + if not np.any(valid): + continue + + lon_w = _longitude_weight_vector(width, float(sat.get("sub_lon", 0.0))) + # Emphasize cloud-rich pixels from daytime channels so dark ocean reflectance doesn't darken clouds. + pix_w = np.where(valid, lon_w[None, :], 0.0) + rgb_accum += rgb * pix_w[:, :, None] + weight_accum += pix_w + valid_sources += 1 + + if valid_sources == 0 or not np.any(weight_accum > 0.0): + return None + + covered = weight_accum > 0.0 + comp_rgb = np.full((height, width, 3), 238.0, dtype=np.float32) + comp_rgb[covered] = rgb_accum[covered] / weight_accum[covered, None] + + # Purify cloud colors toward clean sunlight white so underlying dark land/ocean never tints thin clouds green/brown + density_f = density_u8.astype(np.float32) / 255.0 + comp_luma = ( + 0.299 * comp_rgb[:, :, 0] + 0.587 * comp_rgb[:, :, 1] + 0.114 * comp_rgb[:, :, 2] + ) + daylight_factor = np.where( + covered, + np.clip((comp_luma - 28.0) / 140.0, 0.0, 1.0), + 0.0, + ).astype(np.float32) + fallback_tone = np.clip(212.0 + density_f * 43.0, 0.0, 255.0) + for ch in range(3): + blended = comp_rgb[:, :, ch] * daylight_factor + fallback_tone * (1.0 - daylight_factor) + comp_rgb[:, :, ch] = blended * 0.65 + fallback_tone * 0.35 + + out_rgba = np.empty((height, width, 4), dtype=np.uint8) + out_rgba[:, :, :3] = np.clip(np.round(comp_rgb), 0, 255).astype(np.uint8) + # Alpha encodes visible daylight availability multiplied by cloud density. + vis_alpha = np.clip(np.round(density_f * (0.35 + 0.65 * daylight_factor) * 255.0), 0, 255).astype(np.uint8) + out_rgba[:, :, 3] = vis_alpha + + img = Image.fromarray(out_rgba, mode="RGBA") + buf = io.BytesIO() + img.save(buf, format="WEBP", quality=86, method=1) + return buf.getvalue() + + +def compute_dis_optical_flow_webp( + prev_density_u8: np.ndarray, + curr_density_u8: np.ndarray, + *, + flow_width: int = 512, + flow_height: int = 256, +) -> tuple[bytes, float] | None: + """Compute dense DIS optical flow between consecutive cloud density frames. + + Returns `(webp_bytes, max_uv)` where pixels encode normalized UV displacement: + - `R = round((du / max_uv * 0.5 + 0.5) * 255)` + - `G = round((dv / max_uv * 0.5 + 0.5) * 255)` + Using OpenCV's inverted-V orientation converted directly to WebGL UV delta (`v` positive up). + """ + if prev_density_u8 is None or curr_density_u8 is None: + return None + if prev_density_u8.size == 0 or curr_density_u8.size == 0: + return None + + prev_small = cv2.resize(prev_density_u8, (flow_width, flow_height), interpolation=cv2.INTER_AREA) + curr_small = cv2.resize(curr_density_u8, (flow_width, flow_height), interpolation=cv2.INTER_AREA) + + dis = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM) + flow_px = dis.calc(prev_small, curr_small, None) + if flow_px is None or flow_px.shape[:2] != (flow_height, flow_width): + return None + + # Smooth vector field slightly so advection warps stay coherent without blockiness + flow_px = cv2.GaussianBlur(flow_px, (7, 7), 1.6) + + # Convert pixel displacement to normalized equirectangular UV displacement. + # Flip Y sign because image rows increase downward while equirectangular V increases upward in Three.js Canvas/Image unless flipY=true. + # Three.js default Texture.flipY=true puts row 0 (North) at v=1 and row H-1 (South) at v=0, so positive image dy (southward) corresponds to negative dv. + du = flow_px[:, :, 0].astype(np.float32) / float(flow_width) + dv = -flow_px[:, :, 1].astype(np.float32) / float(flow_height) + + # Suppress tiny noisy vectors in clear sky regions + max_uv = float(max(np.percentile(np.maximum(np.abs(du), np.abs(dv)), 99.5), 1e-4)) + max_uv = min(max_uv, 0.08) + + u_norm = np.clip(du / max_uv, -1.0, 1.0) * 0.5 + 0.5 + v_norm = np.clip(dv / max_uv, -1.0, 1.0) * 0.5 + 0.5 + + rgb = np.empty((flow_height, flow_width, 3), dtype=np.uint8) + rgb[:, :, 0] = np.clip(np.round(u_norm * 255.0), 0, 255).astype(np.uint8) + rgb[:, :, 1] = np.clip(np.round(v_norm * 255.0), 0, 255).astype(np.uint8) + rgb[:, :, 2] = 128 + + img = Image.fromarray(rgb, mode="RGB") + buf = io.BytesIO() + img.save(buf, format="WEBP", quality=92, method=1) + return buf.getvalue(), round(float(max_uv), 6) diff --git a/backend/app/services/earth_layer_adapters.py b/backend/app/services/earth_layer_adapters.py index 0ef075e1..f2ec15b7 100644 --- a/backend/app/services/earth_layer_adapters.py +++ b/backend/app/services/earth_layer_adapters.py @@ -116,6 +116,27 @@ EARTH_LAYER_ADAPTERS: tuple[EarthLayerAdapter, ...] = ( cache_patterns=(), refresh_strategy="delta", ), + EarthLayerAdapter( + sources=frozenset({"global_cloud_map", "cloud_hd_tiles"}), + tables=frozenset({"collected_data"}), + layers=("clouds",), + cache_patterns=(), + refresh_strategy="reload", + ), + EarthLayerAdapter( + sources=frozenset({"global_wind_gfs"}), + tables=frozenset({"collected_data"}), + layers=("windField",), + cache_patterns=(), + refresh_strategy="reload", + ), + EarthLayerAdapter( + sources=frozenset({"earth_imagery_sentinel2", "earth_imagery_viirs_daily"}), + tables=frozenset({"collected_data"}), + layers=("basemap",), + cache_patterns=(), + refresh_strategy="reload", + ), ) _ADAPTERS_BY_SOURCE = { diff --git a/backend/app/services/earth_tiles.py b/backend/app/services/earth_tiles.py new file mode 100644 index 00000000..f43561e8 --- /dev/null +++ b/backend/app/services/earth_tiles.py @@ -0,0 +1,932 @@ +"""Managed Web-Mercator tile pyramid proxy, warmup collection, LRU cache, and basemap settings.""" + +from __future__ import annotations + +import asyncio +from datetime import UTC, datetime +import hashlib +import io +import math +import os +from pathlib import Path +import time +from typing import Any +from uuid import uuid4 + +import cv2 +import httpx +import numpy as np +from PIL import Image +from pydantic import BaseModel, Field, field_validator +from sqlalchemy import select +from sqlalchemy.dialects.postgresql import insert as pg_insert +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.data_sources import get_data_sources_config +from app.core.datasource_defaults import DEFAULT_DATASOURCES +from app.core.logging import get_logger +from app.core.request_context import get_request_id +from app.models.datasource import DataSource +from app.models.datasource_config import DataSourceConfig +from app.models.system_log import AuditLog +from app.models.system_setting import SystemSetting +from app.models.user import User +from app.services.earth_clouds import ( + EUMETVIEW_WMS_URL, + decode_eumetview_ir_to_temp_and_valid, + decode_gibs_band13_to_temp_and_valid, + temperature_to_density, +) + +ORIGIN_SHIFT_3857 = 20037508.342789244 + +logger = get_logger(__name__, service="earth_tiles") + +REPO_ROOT = Path(__file__).resolve().parents[3] +TILES_DATA_DIR = REPO_ROOT / "data" / "earth-tiles" +BASEMAP_CONFIG_CATEGORY = "earth_basemap" +CLOUD_HD_TILE_TTL_SECONDS = 1800 + +TILE_SOURCES: tuple[str, ...] = ( + "cloud_hd_tiles", + "earth_imagery_sentinel2", + "earth_imagery_viirs_daily", +) +BASEMAP_TILE_SOURCES: tuple[str, ...] = ( + "earth_imagery_sentinel2", + "earth_imagery_viirs_daily", +) + +DEFAULT_TILE_TEMPLATES: dict[str, str] = { + "cloud_hd_tiles": ( + "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/" + "GOES-East_ABI_GeoColor/default/default/" + "GoogleMapsCompatible_Level7/{z}/{y}/{x}.png" + ), + "earth_imagery_sentinel2": ( + "https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2024_3857/default/" + "GoogleMapsCompatible/{z}/{y}/{x}.jpg" + ), + "earth_imagery_viirs_daily": ( + "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/" + "VIIRS_SNPP_CorrectedReflectance_TrueColor/default/default/" + "GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg" + ), +} + + +class BasemapRevisionConflictError(RuntimeError): + """Raised when saving basemap configuration with a stale revision.""" + + +class BasemapConfig(BaseModel): + active_source: str = Field(default="earth_imagery_sentinel2") + hd_tiles_enabled: bool = True + cloud_hd_tiles_enabled: bool = False + lod_switch_altitude: float = Field(default=1.85, ge=1.2, le=5.0) + max_zoom: int = Field(default=7, ge=2, le=10) + warmup_max_zoom: int = Field(default=3, ge=1, le=4) + max_cache_mb: int = Field(default=1024, ge=128, le=8192) + request_timeout_seconds: int = Field(default=15, ge=5, le=45) + + @field_validator("active_source") + @classmethod + def validate_active_source(cls, value: str) -> str: + normalized = str(value or "earth_imagery_sentinel2").strip() + if normalized not in {"static", *BASEMAP_TILE_SOURCES}: + raise ValueError( + "active_source must be 'static', 'earth_imagery_sentinel2', or 'earth_imagery_viirs_daily'" + ) + return normalized + + +DEFAULT_BASEMAP_CONFIG = BasemapConfig() +DEFAULT_BASEMAP_REVISION = hashlib.sha256( + DEFAULT_BASEMAP_CONFIG.model_dump_json().encode("utf-8") +).hexdigest()[:16] + + +def _default_basemap_envelope() -> dict[str, Any]: + return { + "config": DEFAULT_BASEMAP_CONFIG.model_dump(mode="json"), + "revision": DEFAULT_BASEMAP_REVISION, + "is_default": True, + } + + +def _tiles_root() -> Path: + return TILES_DATA_DIR + + +def _source_dir(source_key: str) -> Path: + if source_key not in TILE_SOURCES: + raise ValueError(f"Unsupported tile source: {source_key}") + return _tiles_root() / source_key + + +def _tile_path(source_key: str, z: int, x: int, y: int) -> Path: + return _source_dir(source_key) / str(int(z)) / str(int(x)) / f"{int(y)}.webp" + + +def _atomic_write_bytes(path: Path, content: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = path.with_name(f".{path.name}.{uuid4().hex[:8]}.tmp") + try: + tmp_path.write_bytes(content) + os.replace(tmp_path, path) + finally: + if tmp_path.exists(): + try: + tmp_path.unlink() + except OSError: + pass + + +def validate_tile_coords(source_key: str, z: int, x: int, y: int, max_zoom: int = 10) -> None: + if source_key not in TILE_SOURCES: + raise ValueError("Unsupported tile source") + if z < 0 or z > max_zoom: + raise ValueError("Zoom level out of range") + limit = 1 << z + if x < 0 or x >= limit or y < 0 or y >= limit: + raise ValueError("Tile coordinates out of range") + + +def _tile_center_lon(z: int, x: int) -> float: + n = float(1 << max(0, z)) + return ((float(x) + 0.5) / n) * 360.0 - 180.0 + + +def _tile_center_lat(z: int, y: int) -> float: + n = float(1 << max(0, z)) + merc_y = math.pi * (1.0 - 2.0 * ((float(y) + 0.5) / n)) + return math.degrees(math.atan(math.sinh(merc_y))) + + +def _tile_solar_cosine(z: int, x: int, y: int, now_utc: datetime | None = None) -> float: + utc = now_utc or datetime.now(UTC) + utc = utc.astimezone(UTC) if utc.tzinfo else utc.replace(tzinfo=UTC) + doy = utc.timetuple().tm_yday + decl = math.radians(-23.44 * math.cos(2.0 * math.pi * (doy + 10) / 365.0)) + utc_hour = utc.hour + utc.minute / 60.0 + utc.second / 3600.0 + subsolar_lon = (12.0 - utc_hour) * 15.0 + lat_rad = math.radians(_tile_center_lat(z, y)) + ha_rad = math.radians(_tile_center_lon(z, x) - subsolar_lon) + return ( + math.sin(lat_rad) * math.sin(decl) + + math.cos(lat_rad) * math.cos(decl) * math.cos(ha_rad) + ) + + +def _tile_to_3857_bbox(z: int, x: int, y: int) -> str: + n = 1 << max(0, int(z)) + tile_span = (2.0 * ORIGIN_SHIFT_3857) / float(n) + minx = -ORIGIN_SHIFT_3857 + float(x) * tile_span + maxx = minx + tile_span + maxy = ORIGIN_SHIFT_3857 - float(y) * tile_span + miny = maxy - tile_span + return f"{minx:.3f},{miny:.3f},{maxx:.3f},{maxy:.3f}" + + +def _resolve_cloud_hd_ir_fallback( + z: int, + x: int, + y: int, +) -> tuple[str, dict[str, str] | None, str, int]: + """Return `(url, query_params, provider, src_zoom)` for 5-satellite Band13/IR10.8 cloud tiles.""" + lon = _tile_center_lon(z, x) + if 23.0 <= lon < 93.0 or -37.5 <= lon < 23.0: + wms_layer = "msg_fes:ir108" if lon < 23.0 else "msg_iodc:ir108" + params = { + "SERVICE": "WMS", + "REQUEST": "GetMap", + "VERSION": "1.1.1", + "LAYERS": wms_layer, + "STYLES": "", + "FORMAT": "image/png", + "TRANSPARENT": "true", + "SRS": "EPSG:3857", + "BBOX": _tile_to_3857_bbox(z, x, y), + "WIDTH": "256", + "HEIGHT": "256", + } + return EUMETVIEW_WMS_URL, params, "eumetview", int(z) + + if lon < -106.0: + layer = "GOES-West_ABI_Band13_Clean_Infrared" + elif lon < -37.5: + layer = "GOES-East_ABI_Band13_Clean_Infrared" + else: + layer = "Himawari_AHI_Band13_Clean_Infrared" + + ir_z = min(int(z), 6) + shift = max(0, int(z) - ir_z) + ir_x = int(x) >> shift + ir_y = int(y) >> shift + wmts_url = ( + f"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/" + f"{layer}/default/default/GoogleMapsCompatible_Level6/{ir_z}/{ir_y}/{ir_x}.png" + ) + return wmts_url, None, "gibs", ir_z + + +def _resolve_cloud_hd_request( + default_template: str, + z: int, + x: int, + y: int, + *, + now_utc: datetime | None = None, + daytime: bool | None = None, +) -> tuple[str, dict[str, str] | None, str]: + """Route HD cloud tiles across 5 geostationary satellites using daytime 1km/2km visible or nighttime IR.""" + if "GOES-East_ABI_GeoColor" not in default_template and "GOES-East_ABI_Band13" not in default_template: + url = ( + default_template.replace("{z}", str(int(z))) + .replace("{y}", str(int(y))) + .replace("{x}", str(int(x))) + ) + return url, None, "gibs" + + is_daytime = ( + daytime + if daytime is not None + else (_tile_solar_cosine(z, x, y, now_utc) > 0.14) + ) + if not is_daytime: + ir_url, ir_params, ir_provider, _ = _resolve_cloud_hd_ir_fallback(z, x, y) + return ir_url, ir_params, ir_provider + + lon = _tile_center_lon(z, x) + if lon < -106.0: + layer = "GOES-West_ABI_GeoColor" + provider = "gibs_geocolor" + elif lon < -37.5: + layer = "GOES-East_ABI_GeoColor" + provider = "gibs_geocolor" + elif lon < 93.0: + wms_layer = "msg_fes:rgb_naturalenhncd" if lon < 23.0 else "msg_iodc:rgb_naturalenhncd" + params = { + "SERVICE": "WMS", + "REQUEST": "GetMap", + "VERSION": "1.1.1", + "LAYERS": wms_layer, + "STYLES": "", + "FORMAT": "image/png", + "TRANSPARENT": "true", + "SRS": "EPSG:3857", + "BBOX": _tile_to_3857_bbox(z, x, y), + "WIDTH": "256", + "HEIGHT": "256", + } + return EUMETVIEW_WMS_URL, params, "eumetview_visible" + else: + layer = "Himawari_AHI_Band3_Red_Visible_1km" + provider = "gibs_visible" + + wmts_z = min(int(z), 7) + shift = max(0, int(z) - wmts_z) + wmts_x = int(x) >> shift + wmts_y = int(y) >> shift + wmts_url = ( + f"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/" + f"{layer}/default/default/GoogleMapsCompatible_Level7/{wmts_z}/{wmts_y}/{wmts_x}.png" + ) + return wmts_url, None, provider + + +def _crop_subtile_rgba( + raw_bytes: bytes, + z_target: int, + x_target: int, + y_target: int, + z_src: int, +) -> np.ndarray: + with Image.open(io.BytesIO(raw_bytes)) as img: + rgba = np.asarray(img.convert("RGBA"), dtype=np.uint8) + shift = int(z_target) - int(z_src) + if shift <= 0 or rgba.shape[0] < (1 << shift) or rgba.shape[1] < (1 << shift): + if rgba.shape[:2] != (256, 256): + return cv2.resize(rgba, (256, 256), interpolation=cv2.INTER_LINEAR) + return rgba + mask = (1 << shift) - 1 + sub_x = int(x_target) & mask + sub_y = int(y_target) & mask + cell_h = max(1, rgba.shape[0] >> shift) + cell_w = max(1, rgba.shape[1] >> shift) + crop = rgba[sub_y * cell_h:(sub_y + 1) * cell_h, sub_x * cell_w:(sub_x + 1) * cell_w] + return cv2.resize(crop, (256, 256), interpolation=cv2.INTER_LINEAR) + + +def _decode_ir_density_and_temp( + ir_rgba: np.ndarray, + ir_provider: str, +) -> tuple[np.ndarray, np.ndarray]: + if ir_provider == "eumetview": + temp, valid = decode_eumetview_ir_to_temp_and_valid(ir_rgba) + else: + temp, valid = decode_gibs_band13_to_temp_and_valid(ir_rgba) + density = temperature_to_density(temp, ir_threshold=22, contrast_gamma=0.88) + density_u8 = np.where(valid, density, 0).astype(np.uint8) + return density_u8, temp + + +def _encode_tile_webp( + source_key: str, + raw_bytes: bytes, + *, + provider: str = "gibs", + ir_bytes: bytes | None = None, + ir_provider: str = "gibs", + cos_sza: float = 1.0, + z: int = 0, + x: int = 0, + y: int = 0, + ir_z_src: int | None = None, +) -> bytes: + if source_key == "cloud_hd_tiles": + src_z = min(int(z), 6) if provider == "gibs" else int(z) + rgba = _crop_subtile_rgba(raw_bytes, z, x, y, src_z) + if provider in ("gibs_geocolor", "gibs_visible", "eumetview_visible"): + rgb = rgba[:, :, :3].astype(np.float32) + alpha = rgba[:, :, 3].astype(np.float32) + luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2] + + ir_density = np.zeros(rgba.shape[:2], dtype=np.uint8) + safe_temp = np.full(rgba.shape[:2], 15.0, dtype=np.float32) + cool_gate = np.ones(rgba.shape[:2], dtype=np.float32) + if ir_bytes: + try: + ir_rgba = _crop_subtile_rgba( + ir_bytes, z, x, y, ir_z_src if ir_z_src is not None else min(int(z), 6) + ) + ir_density, temp = _decode_ir_density_and_temp(ir_rgba, ir_provider) + safe_temp = np.where(np.isfinite(temp), temp, 15.0).astype(np.float32) + # Band-pass warm low-cloud gate: peaks on -2C..+16C stratocumulus and suppresses freezing snow (<-8C) and hot deserts (>+24C). + cool_gate = ( + np.clip((24.0 - safe_temp) / 12.0, 0.0, 1.0) + * np.clip((safe_temp + 8.0) / 10.0, 0.0, 1.0) + ).astype(np.float32) + except Exception: + pass + + not_clipped = ~( + (rgb[:, :, 0] >= 254.0) + & (rgb[:, :, 1] >= 254.0) + & (rgb[:, :, 2] >= 254.0) + & (safe_temp > -10.0) + ) + valid = (alpha > 12.0) & (luma > 8.0) & not_clipped + + cos_safe = max(0.30, float(cos_sza)) + if provider == "gibs_visible": + albedo = luma / cos_safe + vis = np.clip((albedo - 88.0) / 132.0, 0.0, 1.0) * cool_gate + else: + chroma = (np.max(rgb, axis=2) - np.min(rgb, axis=2)) / 255.0 + whiteness = np.clip(1.0 - chroma / 0.36, 0.0, 1.0) + min_rgb = np.min(rgb, axis=2) + albedo = min_rgb / cos_safe + vis = np.clip((albedo - 85.0) / 135.0, 0.0, 1.0) * whiteness * cool_gate + + vis_u8 = np.where(valid, np.clip(np.round(vis * 255.0), 0, 255), 0).astype(np.uint8) + density = np.maximum(ir_density, vis_u8) + else: + density, _ = _decode_ir_density_and_temp(rgba, provider) + density = cv2.GaussianBlur(density, (3, 3), 0.5) + + out = np.empty_like(rgba) + out[:, :, 0] = density + out[:, :, 1] = density + out[:, :, 2] = density + out[:, :, 3] = density + out_img = Image.fromarray(out, mode="RGBA") + else: + with Image.open(io.BytesIO(raw_bytes)) as img: + out_img = img.convert("RGB") + + buf = io.BytesIO() + out_img.save(buf, format="WEBP", quality=84, method=1) + return buf.getvalue() + + +def summarize_tile_source_cache(source_key: str) -> dict[str, Any]: + root = _source_dir(source_key) + if not root.exists(): + return {"tile_count": 0, "total_bytes": 0, "total_mb": 0.0, "zoom_levels": []} + tile_count = 0 + total_bytes = 0 + zooms: set[int] = set() + for path in root.rglob("*.webp"): + if path.name.startswith(".") or not path.is_file(): + continue + tile_count += 1 + try: + total_bytes += path.stat().st_size + zoom_dir = path.relative_to(root).parts[0] + if zoom_dir.isdigit(): + zooms.add(int(zoom_dir)) + except (OSError, IndexError, ValueError): + pass + return { + "tile_count": tile_count, + "total_bytes": total_bytes, + "total_mb": round(total_bytes / (1024 * 1024), 2), + "zoom_levels": sorted(zooms), + } + + +def prune_tile_source_cache(source_key: str, max_cache_mb: int) -> int: + root = _source_dir(source_key) + if not root.exists(): + return 0 + limit_bytes = max(16, int(max_cache_mb)) * 1024 * 1024 + files: list[tuple[float, int, Path]] = [] + total_bytes = 0 + for path in root.rglob("*.webp"): + if path.name.startswith(".") or not path.is_file(): + continue + try: + st = path.stat() + except OSError: + continue + total_bytes += st.st_size + files.append((st.st_mtime, st.st_size, path)) + + if total_bytes <= limit_bytes: + return 0 + + files.sort(key=lambda item: item[0]) + removed = 0 + for _mtime, size, path in files: + if total_bytes <= limit_bytes: + break + try: + path.unlink() + total_bytes -= size + removed += 1 + except OSError: + pass + return removed + + +def clear_tile_source_cache(source_key: str) -> int: + root = _source_dir(source_key) + if not root.exists(): + return 0 + removed = 0 + for path in root.rglob("*"): + if path.is_file(): + try: + path.unlink() + removed += 1 + except OSError: + pass + for directory in sorted((p for p in root.rglob("*") if p.is_dir()), reverse=True): + try: + directory.rmdir() + except OSError: + pass + return removed + + +async def _get_source_runtime_settings( + db: AsyncSession | None, + source_key: str, +) -> tuple[bool, str, dict[str, Any]]: + default_template = DEFAULT_TILE_TEMPLATES[source_key] + ds_active = True + endpoint = default_template + cfg: dict[str, Any] = { + "warmup_max_zoom": 2 if source_key == "cloud_hd_tiles" else 3, + "max_zoom": 7 if source_key == "cloud_hd_tiles" else (10 if source_key == "earth_imagery_sentinel2" else 9), + "max_cache_mb": 512 if source_key == "cloud_hd_tiles" else 1024, + "request_timeout_seconds": 15, + } + + if db is None or not hasattr(db, "execute"): + return ds_active, endpoint, cfg + + try: + ds_row = ( + await db.execute(select(DataSource).where(DataSource.source == source_key)) + ).scalar_one_or_none() + if ds_row is not None: + ds_active = bool(ds_row.is_active) + except Exception: + pass + + try: + cfg_row = ( + await db.execute(select(DataSourceConfig).where(DataSourceConfig.name == source_key)) + ).scalar_one_or_none() + if cfg_row is not None: + if cfg_row.endpoint: + endpoint = str(cfg_row.endpoint).strip() + if isinstance(cfg_row.config, dict): + for key, val in cfg_row.config.items(): + if val is not None: + cfg[key] = val + except Exception: + pass + + try: + yaml_url = await get_data_sources_config().get_url(source_key, db) + if yaml_url: + endpoint = yaml_url + except Exception: + pass + + return ds_active, endpoint, cfg + + +def _is_cloud_tile_fresh(target: Path) -> bool: + try: + return (time.time() - target.stat().st_mtime) < CLOUD_HD_TILE_TTL_SECONDS + except OSError: + return False + + +def _is_valid_image_response(resp: Any) -> bool: + if not isinstance(resp, httpx.Response) or resp.status_code != 200: + return False + ctype = str(resp.headers.get("content-type") or "").lower() + return ctype.startswith("image/") + + +async def _safe_get( + client: httpx.AsyncClient, + url: str, + params: dict[str, str] | None = None, +) -> httpx.Response | Exception: + try: + return await client.get(url, params=params) + except Exception as exc: + return exc + + +async def _fetch_and_encode_tile( + client: httpx.AsyncClient, + source_key: str, + template: str, + z: int, + x: int, + y: int, + *, + raise_on_error: bool = True, +) -> bytes | None: + if source_key == "cloud_hd_tiles": + cos_sza = _tile_solar_cosine(z, x, y) + is_daytime = cos_sza > 0.14 + url, query_params, provider = _resolve_cloud_hd_request( + template, z, x, y, daytime=is_daytime + ) + if provider in ("gibs_geocolor", "gibs_visible", "eumetview_visible"): + ir_url, ir_params, ir_provider, ir_z_src = _resolve_cloud_hd_ir_fallback(z, x, y) + primary_res, ir_res = await asyncio.gather( + _safe_get(client, url, query_params), + _safe_get(client, ir_url, ir_params), + ) + ir_bytes = ir_res.content if _is_valid_image_response(ir_res) else None + if _is_valid_image_response(primary_res): + return await asyncio.to_thread( + _encode_tile_webp, + source_key, + primary_res.content, + provider=provider, + ir_bytes=ir_bytes, + ir_provider=ir_provider, + cos_sza=cos_sza, + z=z, + x=x, + y=y, + ir_z_src=ir_z_src, + ) + if ir_bytes is not None: + return await asyncio.to_thread( + _encode_tile_webp, + source_key, + ir_bytes, + provider=ir_provider, + z=z, + x=x, + y=y, + ) + if isinstance(primary_res, Exception) and raise_on_error: + raise primary_res + if isinstance(primary_res, httpx.Response) and primary_res.status_code not in (200, 404) and raise_on_error: + primary_res.raise_for_status() + return None + else: + url = ( + template.replace("{z}", str(int(z))) + .replace("{y}", str(int(y))) + .replace("{x}", str(int(x))) + ) + query_params = None + provider = "gibs" + + response = await client.get(url, params=query_params) + if response.status_code == 404: + return None + response.raise_for_status() + if not _is_valid_image_response(response): + return None + return await asyncio.to_thread( + _encode_tile_webp, + source_key, + response.content, + provider=provider, + z=z, + x=x, + y=y, + ) + + +async def get_or_fetch_tile( + source_key: str, + z: int, + x: int, + y: int, + *, + db: AsyncSession | None = None, +) -> tuple[bytes | None, bool]: + """Return `(webp_bytes, is_allowed)` enforcing `DataSource.is_active` and caching as WebP.""" + ds_active, template, cfg = await _get_source_runtime_settings(db, source_key) + max_zoom = int(cfg.get("max_zoom") or 8) + validate_tile_coords(source_key, z, x, y, max_zoom=max_zoom) + + if not ds_active: + return None, False + + target = _tile_path(source_key, z, x, y) + if target.exists() and (source_key != "cloud_hd_tiles" or _is_cloud_tile_fresh(target)): + try: + os.utime(target, None) + except OSError: + pass + return target.read_bytes(), True + + timeout = httpx.Timeout(float(cfg.get("request_timeout_seconds") or 15)) + headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthTileProxy)"} + async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client: + webp_bytes = await _fetch_and_encode_tile(client, source_key, template, z, x, y) + + if webp_bytes is None: + return None, True + + await asyncio.to_thread(_atomic_write_bytes, target, webp_bytes) + return webp_bytes, True + + +async def warmup_tile_source( + source_key: str, + *, + db: AsyncSession | None = None, + max_zoom_override: int | None = None, +) -> dict[str, Any]: + """Pre-warm z=0..warmup_max_zoom tile pyramid into managed local WebP storage.""" + if source_key not in TILE_SOURCES: + raise ValueError(f"Unsupported tile source: {source_key}") + + _ds_active, template, cfg = await _get_source_runtime_settings(db, source_key) + warmup_max = int( + max_zoom_override + if max_zoom_override is not None + else cfg.get("warmup_max_zoom") or (2 if source_key == "cloud_hd_tiles" else 3) + ) + warmup_max = max(0, min(4, warmup_max)) + max_cache_mb = int(cfg.get("max_cache_mb") or 1024) + timeout = httpx.Timeout(float(cfg.get("request_timeout_seconds") or 15)) + headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthTileWarmup)"} + + coords: list[tuple[int, int, int]] = [] + for z in range(0, warmup_max + 1): + dim = 1 << z + for x in range(dim): + for y in range(dim): + coords.append((z, x, y)) + + fetched = 0 + cached_hits = 0 + failed = 0 + total_bytes = 0 + semaphore = asyncio.Semaphore(8) + + async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client: + async def _worker(z: int, x: int, y: int) -> None: + nonlocal fetched, cached_hits, failed, total_bytes + target = _tile_path(source_key, z, x, y) + if target.exists() and (source_key != "cloud_hd_tiles" or _is_cloud_tile_fresh(target)): + cached_hits += 1 + try: + total_bytes += target.stat().st_size + except OSError: + pass + return + + async with semaphore: + try: + webp_bytes = await _fetch_and_encode_tile( + client, source_key, template, z, x, y, raise_on_error=True + ) + if webp_bytes is None: + failed += 1 + return + await asyncio.to_thread(_atomic_write_bytes, target, webp_bytes) + fetched += 1 + total_bytes += len(webp_bytes) + except Exception as exc: + failed += 1 + logger.warning_event( + "Tile warmup request failed", + event="earth.tiles.warmup_failed", + context={"source": source_key, "z": z, "x": x, "y": y, "error": str(exc)}, + ) + + await asyncio.gather(*(_worker(z, x, y) for z, x, y in coords)) + + pruned = await asyncio.to_thread(prune_tile_source_cache, source_key, max_cache_mb) + cache_stats = await asyncio.to_thread(summarize_tile_source_cache, source_key) + return { + "source": source_key, + "warmup_max_zoom": warmup_max, + "total_targets": len(coords), + "fetched": fetched, + "cached_hits": cached_hits, + "failed": failed, + "pruned": pruned, + "written_bytes": total_bytes, + "cache_stats": cache_stats, + } + + +async def prune_all_tile_caches(db: AsyncSession | None = None) -> int: + removed = 0 + for source_key in TILE_SOURCES: + _, _, cfg = await _get_source_runtime_settings(db, source_key) + max_mb = int(cfg.get("max_cache_mb") or 1024) + removed += await asyncio.to_thread(prune_tile_source_cache, source_key, max_mb) + return removed + + +async def read_basemap_configuration(db: AsyncSession | None) -> dict[str, Any]: + if db is None or not callable(getattr(db, "execute", None)): + return _default_basemap_envelope() + result = await db.execute( + select(SystemSetting).where(SystemSetting.category == BASEMAP_CONFIG_CATEGORY) + ) + record = result.scalar_one_or_none() + if not record or not isinstance(record.payload, dict): + return _default_basemap_envelope() + payload = dict(record.payload) + try: + validated = BasemapConfig.model_validate(payload.get("config") or {}) + except Exception: + validated = DEFAULT_BASEMAP_CONFIG + return { + "config": validated.model_dump(mode="json"), + "revision": str(payload.get("revision") or DEFAULT_BASEMAP_REVISION), + "is_default": bool(payload.get("is_default", False)), + } + + +async def save_basemap_configuration( + db: AsyncSession, + *, + revision: str, + config: BasemapConfig, + actor: User, + reset: bool = False, +) -> dict[str, Any]: + dialect_name = "" + try: + bind = db.get_bind() + dialect_name = str(getattr(getattr(bind, "dialect", None), "name", "") or "").lower() + except Exception: + dialect_name = "" + + if dialect_name == "postgresql": + await db.execute( + pg_insert(SystemSetting) + .values(category=BASEMAP_CONFIG_CATEGORY, payload=_default_basemap_envelope()) + .on_conflict_do_nothing(index_elements=[SystemSetting.category]) + ) + record = ( + await db.execute( + select(SystemSetting) + .where(SystemSetting.category == BASEMAP_CONFIG_CATEGORY) + .with_for_update() + ) + ).scalar_one() + else: + record = ( + await db.execute( + select(SystemSetting).where(SystemSetting.category == BASEMAP_CONFIG_CATEGORY) + ) + ).scalar_one_or_none() + if record is None: + record = SystemSetting( + category=BASEMAP_CONFIG_CATEGORY, + payload=_default_basemap_envelope(), + ) + db.add(record) + + current_revision = str((record.payload or {}).get("revision") or DEFAULT_BASEMAP_REVISION) + if current_revision != revision: + await db.rollback() + raise BasemapRevisionConflictError( + "Configuration changed by another editor. Reload and retry." + ) + + envelope = ( + _default_basemap_envelope() + if reset + else { + "config": config.model_dump(mode="json"), + "revision": uuid4().hex[:16], + "is_default": False, + } + ) + before = dict(record.payload or {}) + if reset: + if getattr(record, "id", None) is not None: + await db.delete(record) + else: + record.payload = envelope + + db.add( + AuditLog( + actor_id=actor.id, + actor_name=actor.username, + action="earth_basemap.reset" if reset else "earth_basemap.update", + target_type="system_setting", + target_id=BASEMAP_CONFIG_CATEGORY, + result="success", + request_id=get_request_id(), + details={"before": before, "after": envelope}, + ) + ) + await db.commit() + return envelope + + +async def get_basemap_runtime_meta(db: AsyncSession | None = None) -> dict[str, Any]: + envelope = await read_basemap_configuration(db) + config = BasemapConfig.model_validate(envelope["config"]) + + source_items: list[dict[str, Any]] = [] + active_map: dict[str, bool] = {} + for source_key in TILE_SOURCES: + is_active, template, cfg = await _get_source_runtime_settings(db, source_key) + cache_stats = await asyncio.to_thread(summarize_tile_source_cache, source_key) + meta_defaults = DEFAULT_DATASOURCES.get(source_key, {}) + active_map[source_key] = is_active + source_items.append( + { + "source": source_key, + "display_name": meta_defaults.get("display_name") or source_key, + "is_active": is_active, + "has_data": cache_stats["tile_count"] > 0, + "cached_tiles": cache_stats["tile_count"], + "cache_mb": cache_stats["total_mb"], + "zoom_levels": cache_stats["zoom_levels"], + "max_zoom": int(cfg.get("max_zoom") or config.max_zoom), + "warmup_max_zoom": int(cfg.get("warmup_max_zoom") or config.warmup_max_zoom), + "max_cache_mb": int(cfg.get("max_cache_mb") or config.max_cache_mb), + "tile_url_template": f"/api/v1/earth/tiles/{source_key}/{{z}}/{{x}}/{{y}}.webp", + "upstream_template": template, + } + ) + + active_source = config.active_source + hd_ready = bool( + config.hd_tiles_enabled + and active_source in BASEMAP_TILE_SOURCES + and active_map.get(active_source, False) + ) + cloud_hd_ready = bool( + config.cloud_hd_tiles_enabled and active_map.get("cloud_hd_tiles", False) + ) + return { + "active_source": active_source, + "hd_tiles_enabled": config.hd_tiles_enabled, + "cloud_hd_tiles_enabled": config.cloud_hd_tiles_enabled, + "hd_tiles_ready": hd_ready, + "cloud_hd_tiles_ready": cloud_hd_ready, + "lod_switch_altitude": config.lod_switch_altitude, + "max_zoom": config.max_zoom, + "warmup_max_zoom": config.warmup_max_zoom, + "max_cache_mb": config.max_cache_mb, + "tile_url_template": ( + f"/api/v1/earth/tiles/{active_source}/{{z}}/{{x}}/{{y}}.webp" + if hd_ready + else None + ), + "cloud_tile_url_template": ( + "/api/v1/earth/tiles/cloud_hd_tiles/{z}/{x}/{y}.webp" + if cloud_hd_ready + else None + ), + "sources": source_items, + } diff --git a/backend/app/services/earth_wind.py b/backend/app/services/earth_wind.py new file mode 100644 index 00000000..a8b53403 --- /dev/null +++ b/backend/app/services/earth_wind.py @@ -0,0 +1,735 @@ +"""NOAA NCEP GFS 10m global wind field collector, storage, analytics, and point query engine.""" + +from __future__ import annotations + +import asyncio +import csv +from datetime import UTC, datetime +import io +import json +import math +import os +from pathlib import Path +import re +from typing import Any +from uuid import uuid4 + +import cv2 +import httpx +import numpy as np +from pydantic import BaseModel, Field +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.data_sources import get_data_sources_config +from app.core.logging import get_logger +from app.core.time import to_iso8601_utc +from app.models.datasource import DataSource +from app.models.datasource_config import DataSourceConfig + +logger = get_logger(__name__, service="earth_wind") + +REPO_ROOT = Path(__file__).resolve().parents[3] +WIND_DATA_DIR = REPO_ROOT / "data" / "earth-wind" +DEFAULT_GFS_ERDDAP_URL = "https://pae-paha.pacioos.hawaii.edu/erddap/griddap/ncep_global.csv0" +VERSION_PATTERN = re.compile(r"^[A-Za-z0-9._-]{4,64}$") +_WIND_WRITE_LOCK = asyncio.Lock() + +EARTH_CIRCUMFERENCE_KM = 40075.017 + +# Reuse consistent maritime / aviation meteorological zones for global posture rollups +WIND_REGIONS: tuple[dict[str, Any], ...] = ( + { + "key": "west_pacific", + "name": "西北太平洋", + "name_en": "Western North Pacific", + "lat_min": 5.0, + "lat_max": 35.0, + "lon_min": 120.0, + "lon_max": 165.0, + }, + { + "key": "east_asia_coast", + "name": "东亚沿海", + "name_en": "East Asia Coastal Corridor", + "lat_min": 18.0, + "lat_max": 42.0, + "lon_min": 105.0, + "lon_max": 135.0, + }, + { + "key": "south_china_sea", + "name": "南海海域", + "name_en": "South China Sea", + "lat_min": 3.0, + "lat_max": 23.0, + "lon_min": 105.0, + "lon_max": 122.0, + }, + { + "key": "indian_ocean", + "name": "印度洋航道", + "name_en": "Indian Ocean Corridor", + "lat_min": -20.0, + "lat_max": 20.0, + "lon_min": 50.0, + "lon_max": 98.0, + }, + { + "key": "arabian_red_sea", + "name": "阿拉伯海与红海", + "name_en": "Arabian & Red Sea", + "lat_min": 10.0, + "lat_max": 30.0, + "lon_min": 32.0, + "lon_max": 68.0, + }, + { + "key": "north_pacific", + "name": "北太平洋航线", + "name_en": "North Pacific Corridor", + "lat_min": 30.0, + "lat_max": 58.0, + "lon_min": 140.0, + "lon_max": -125.0, + }, + { + "key": "gulf_caribbean", + "name": "墨西哥湾与加勒比", + "name_en": "Gulf & Caribbean", + "lat_min": 10.0, + "lat_max": 32.0, + "lon_min": -98.0, + "lon_max": -60.0, + }, + { + "key": "north_atlantic", + "name": "北大西洋航道", + "name_en": "North Atlantic Corridor", + "lat_min": 35.0, + "lat_max": 62.0, + "lon_min": -60.0, + "lon_max": -10.0, + }, +) + + +class WindFieldConfig(BaseModel): + grid_step_deg: float = Field(default=2.0, ge=1.0, le=5.0) + gale_threshold_ms: float = Field(default=17.2, ge=10.0, le=35.0) + request_timeout_seconds: int = Field(default=25, ge=5, le=60) + max_history_runs: int = Field(default=12, ge=2, le=48) + + +DEFAULT_WIND_CONFIG = WindFieldConfig() + + +def _wind_dir() -> Path: + return WIND_DATA_DIR + + +def _manifest_path() -> Path: + return _wind_dir() / "manifest.json" + + +def _grids_dir() -> Path: + return _wind_dir() / "grids" + + +def _ensure_wind_dirs() -> None: + _grids_dir().mkdir(parents=True, exist_ok=True) + + +def _atomic_write_bytes(path: Path, content: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = path.with_name(f".{path.name}.{uuid4().hex[:8]}.tmp") + try: + tmp_path.write_bytes(content) + os.replace(tmp_path, path) + finally: + if tmp_path.exists(): + try: + tmp_path.unlink() + except OSError: + pass + + +def _atomic_write_json(path: Path, payload: Any) -> None: + encoded = json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8") + _atomic_write_bytes(path, encoded) + + +def _read_manifest() -> dict[str, Any]: + path = _manifest_path() + if not path.exists(): + return {"latest_version": None, "updated_at": None, "runs": []} + try: + parsed = json.loads(path.read_text(encoding="utf-8")) + if isinstance(parsed, dict) and isinstance(parsed.get("runs"), list): + return parsed + except Exception: + pass + return {"latest_version": None, "updated_at": None, "runs": []} + + +def _wind_vector_to_bearing_deg(u_ms: float, v_ms: float) -> float: + """Meteorological heading TO which wind blows (0=N, 90=E, 180=S, 270=W).""" + return (math.degrees(math.atan2(u_ms, v_ms)) + 360.0) % 360.0 + + +def _bearing_to_cardinal(deg: float) -> str: + dirs = ("N", "NE", "E", "SE", "S", "SW", "W", "NW") + idx = int(round((deg % 360.0) / 45.0)) % 8 + return dirs[idx] + + +def _speed_to_beaufort(speed_ms: float) -> int: + thresholds = (0.3, 1.6, 3.4, 5.5, 8.0, 10.8, 13.9, 17.2, 20.8, 24.5, 28.5, 32.7) + for force, limit in enumerate(thresholds): + if speed_ms < limit: + return force + return 12 + + +def _match_region_name(lat: float, lon: float) -> tuple[str, str]: + wrapped = ((float(lon) + 180.0) % 360.0) - 180.0 + for reg in WIND_REGIONS: + if not (reg["lat_min"] <= lat <= reg["lat_max"]): + continue + lon_min, lon_max = reg["lon_min"], reg["lon_max"] + if lon_min <= lon_max: + in_lon = lon_min <= wrapped <= lon_max + else: + in_lon = wrapped >= lon_min or wrapped <= lon_max + if in_lon: + return reg["name"], reg["name_en"] + return "公海全球风场", "Global High Seas" + + +async def read_wind_configuration(db: AsyncSession | None = None) -> dict[str, Any]: + endpoint = DEFAULT_GFS_ERDDAP_URL + raw_cfg: dict[str, Any] = {} + if db is not None and hasattr(db, "execute"): + try: + row = ( + await db.execute( + select(DataSourceConfig).where(DataSourceConfig.name == "global_wind_gfs") + ) + ).scalar_one_or_none() + if row is not None: + if row.endpoint: + endpoint = str(row.endpoint).strip() + if isinstance(row.config, dict): + raw_cfg = dict(row.config) + except Exception: + pass + try: + yaml_url = await get_data_sources_config().get_url("global_wind_gfs", db) + if yaml_url: + endpoint = yaml_url + except Exception: + pass + + try: + validated = WindFieldConfig.model_validate(raw_cfg) + except Exception: + validated = DEFAULT_WIND_CONFIG + return { + "endpoint": endpoint, + "config": validated.model_dump(mode="json"), + } + + +def parse_erddap_csv0_wind(csv_text: str) -> dict[str, Any]: + """Parse PacIOOS ERDDAP `ncep_global.csv0` `ugrd10m,vgrd10m` into `[-180..180]` grids.""" + rows: list[tuple[float, float, float, float]] = [] + forecast_time: str | None = None + + reader = csv.reader(io.StringIO(csv_text)) + for line in reader: + if len(line) < 5: + continue + t_raw, lat_s, lon_s, u_s, v_s = line[0].strip(), line[1].strip(), line[2].strip(), line[3].strip(), line[4].strip() + if t_raw.lower() == "time" or lat_s.lower() == "latitude": + continue + try: + lat = float(lat_s) + lon_raw = float(lon_s) + u_val = float(u_s) + v_val = float(v_s) + except ValueError: + continue + if not (math.isfinite(lat) and math.isfinite(lon_raw) and math.isfinite(u_val) and math.isfinite(v_val)): + continue + if forecast_time is None and t_raw: + forecast_time = t_raw + # Shift 0..360 longitude to [-180, 180) + lon_norm = ((lon_raw + 180.0) % 360.0) - 180.0 + rows.append((round(lat, 3), round(lon_norm, 3), u_val, v_val)) + + if not rows: + raise RuntimeError("GFS wind ERDDAP payload contained zero valid grid samples") + + lats = sorted({item[0] for item in rows}) + lons = sorted({item[1] for item in rows}) + lat_idx = {val: i for i, val in enumerate(lats)} + lon_idx = {val: i for i, val in enumerate(lons)} + + height = len(lats) + width = len(lons) + u_grid = np.zeros((height, width), dtype=np.float32) + v_grid = np.zeros((height, width), dtype=np.float32) + + for lat, lon, u_val, v_val in rows: + u_grid[lat_idx[lat], lon_idx[lon]] = u_val + v_grid[lat_idx[lat], lon_idx[lon]] = v_val + + return { + "forecast_time": forecast_time, + "lats": np.asarray(lats, dtype=np.float32), + "lons": np.asarray(lons, dtype=np.float32), + "u": u_grid, + "v": v_grid, + } + + +def analyze_wind_grid( + parsed: dict[str, Any], + *, + config: WindFieldConfig, +) -> dict[str, Any]: + lats = parsed["lats"] + lons = parsed["lons"] + u_grid = parsed["u"] + v_grid = parsed["v"] + speed = np.sqrt(u_grid * u_grid + v_grid * v_grid).astype(np.float32) + + lat_weights = np.maximum(np.cos(np.deg2rad(lats)), 0.05).astype(np.float32)[:, None] + weight_sum = float(np.sum(lat_weights) * speed.shape[1]) + + mean_speed = float(np.sum(speed * lat_weights) / max(weight_sum, 1e-6)) + max_speed = float(np.max(speed)) + gale_mask = speed >= float(config.gale_threshold_ms) + gale_cov_pct = float(np.sum(gale_mask.astype(np.float32) * lat_weights) / max(weight_sum, 1e-6) * 100.0) + + # Identify coherent gale/storm cores via connected components + gale_u8 = (gale_mask.astype(np.uint8) * 255) + num_labels, labels, stats, _centroids = cv2.connectedComponentsWithStats(gale_u8, connectivity=8) + dlat = abs(float(lats[1] - lats[0])) if len(lats) > 1 else config.grid_step_deg + dlon = abs(float(lons[1] - lons[0])) if len(lons) > 1 else config.grid_step_deg + + storm_cores: list[dict[str, Any]] = [] + for label_id in range(1, num_labels): + pixel_count = int(stats[label_id, cv2.CC_STAT_AREA]) + if pixel_count < 3: + continue + comp_mask = labels == label_id + comp_lats = lats[np.where(comp_mask)[0]] + comp_lons = lons[np.where(comp_mask)[1]] + center_lat = float(np.mean(comp_lats)) + center_lon = float(np.mean(comp_lons)) + comp_speeds = speed[comp_mask] + peak_ms = float(np.max(comp_speeds)) + avg_ms = float(np.mean(comp_speeds)) + cell_area = ( + (dlat / 360.0) * EARTH_CIRCUMFERENCE_KM + * ((dlon / 360.0) * EARTH_CIRCUMFERENCE_KM * max(math.cos(math.radians(center_lat)), 0.1)) + ) + area_km2 = round(pixel_count * cell_area) + region_zh, region_en = _match_region_name(center_lat, center_lon) + storm_cores.append( + { + "id": f"gale-{label_id}", + "lat": round(center_lat, 2), + "lon": round(center_lon, 2), + "max_speed_ms": round(peak_ms, 1), + "mean_speed_ms": round(avg_ms, 1), + "beaufort": _speed_to_beaufort(peak_ms), + "area_km2": area_km2, + "region": region_zh, + "region_en": region_en, + "severity": "storm" if peak_ms >= 24.5 else "gale", + } + ) + storm_cores.sort(key=lambda item: item["max_speed_ms"], reverse=True) + storm_cores = storm_cores[:24] + + region_summaries: list[dict[str, Any]] = [] + for reg in WIND_REGIONS: + lat_mask = (lats >= reg["lat_min"]) & (lats <= reg["lat_max"]) + if reg["lon_min"] <= reg["lon_max"]: + lon_mask = (lons >= reg["lon_min"]) & (lons <= reg["lon_max"]) + else: + lon_mask = (lons >= reg["lon_min"]) | (lons <= reg["lon_max"]) + sub_mask = np.outer(lat_mask, lon_mask) + if not np.any(sub_mask): + continue + sub_speed = speed[sub_mask] + sub_u = u_grid[sub_mask] + sub_v = v_grid[sub_mask] + mean_reg = float(np.mean(sub_speed)) + max_reg = float(np.max(sub_speed)) + gale_reg = float(np.mean(sub_speed >= float(config.gale_threshold_ms)) * 100.0) + dom_u = float(np.mean(sub_u)) + dom_v = float(np.mean(sub_v)) + dom_deg = _wind_vector_to_bearing_deg(dom_u, dom_v) + posture = "gale_warning" if gale_reg >= 12.0 or max_reg >= 20.8 else ("breezy" if mean_reg >= 10.8 else "moderate") + region_summaries.append( + { + "key": reg["key"], + "name": reg["name"], + "name_en": reg["name_en"], + "mean_speed_ms": round(mean_reg, 1), + "max_speed_ms": round(max_reg, 1), + "gale_coverage_pct": round(gale_reg, 1), + "dominant_direction_deg": round(dom_deg, 1), + "dominant_cardinal": _bearing_to_cardinal(dom_deg), + "posture": posture, + } + ) + + return { + "global_summary": { + "mean_speed_ms": round(mean_speed, 2), + "max_speed_ms": round(max_speed, 2), + "gale_coverage_pct": round(gale_cov_pct, 2), + "storm_core_count": len(storm_cores), + "grid_width": int(u_grid.shape[1]), + "grid_height": int(u_grid.shape[0]), + "step_deg": round(float(config.grid_step_deg), 2), + "forecast_time": parsed.get("forecast_time"), + }, + "regions": region_summaries, + "storm_cores": storm_cores, + } + + +def _remove_wind_run_files(version: str) -> int: + if not VERSION_PATTERN.match(version): + return 0 + target = _grids_dir() / f"{version}.npz" + if target.exists(): + try: + target.unlink() + return 1 + except OSError: + pass + return 0 + + +def prune_wind_artifacts(max_runs: int = 12) -> int: + if not _wind_dir().exists(): + return 0 + manifest = _read_manifest() + runs = manifest.get("runs", []) + kept = runs[: max(1, int(max_runs))] + kept_versions = {str(item.get("version")) for item in kept if item.get("version")} + removed = 0 + for item in runs[max(1, int(max_runs)) :]: + ver = str(item.get("version") or "") + if ver: + removed += _remove_wind_run_files(ver) + if _grids_dir().exists(): + for file_path in _grids_dir().iterdir(): + if file_path.name.startswith(".") or file_path.stem not in kept_versions: + try: + file_path.unlink() + removed += 1 + except OSError: + pass + if len(kept) != len(runs): + _atomic_write_json( + _manifest_path(), + { + "latest_version": kept[0].get("version") if kept else None, + "updated_at": manifest.get("updated_at"), + "runs": kept, + }, + ) + return removed + + +def clear_all_wind_artifacts() -> int: + removed = 0 + if _grids_dir().exists(): + for file_path in _grids_dir().iterdir(): + if file_path.is_file(): + try: + file_path.unlink() + removed += 1 + except OSError: + pass + manifest_file = _manifest_path() + if manifest_file.exists(): + try: + manifest_file.unlink() + removed += 1 + except OSError: + pass + return removed + + +def _save_wind_run_sync( + *, + version: str, + captured_at: str, + parsed: dict[str, Any], + analysis: dict[str, Any], + max_history_runs: int, +) -> dict[str, Any]: + _ensure_wind_dirs() + grid_path = _grids_dir() / f"{version}.npz" + tmp_path = grid_path.with_name(f".{version}.{uuid4().hex[:8]}.npz") + try: + np.savez_compressed( + tmp_path, + lats=parsed["lats"], + lons=parsed["lons"], + u=parsed["u"], + v=parsed["v"], + ) + os.replace(tmp_path, grid_path) + finally: + if tmp_path.exists(): + try: + tmp_path.unlink() + except OSError: + pass + + entry = { + "version": version, + "captured_at": captured_at, + "forecast_time": parsed.get("forecast_time"), + "source": "global_wind_gfs", + "grid_url": f"/api/v1/earth/wind/grid/{version}", + "file_size_bytes": grid_path.stat().st_size if grid_path.exists() else 0, + "global_summary": analysis["global_summary"], + "regions": analysis["regions"], + "storm_cores": analysis["storm_cores"], + } + + manifest = _read_manifest() + runs = [item for item in manifest.get("runs", []) if item.get("version") != version] + runs.insert(0, entry) + kept_runs = runs[: max(1, int(max_history_runs))] + dropped = [str(item.get("version") or "") for item in runs[max(1, int(max_history_runs)) :]] + _atomic_write_json( + _manifest_path(), + { + "latest_version": version, + "updated_at": captured_at, + "runs": kept_runs, + }, + ) + for old_ver in dropped: + _remove_wind_run_files(old_ver) + return entry + + +async def collect_latest_wind_grid(db: AsyncSession | None = None) -> dict[str, Any]: + env = await read_wind_configuration(db) + config = WindFieldConfig.model_validate(env["config"]) + endpoint = str(env["endpoint"] or DEFAULT_GFS_ERDDAP_URL).rstrip("/") + stride = max(1, int(round(float(config.grid_step_deg) * 2.0))) + query_url = ( + f"{endpoint}?ugrd10m[(last)][(-90):{stride}:(90)][(0):{stride}:(359.5)]," + f"vgrd10m[(last)][(-90):{stride}:(90)][(0):{stride}:(359.5)]" + ) + timeout = httpx.Timeout(float(config.request_timeout_seconds)) + headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthWindCollector)"} + + async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client: + response = await client.get(query_url) + response.raise_for_status() + csv_text = response.text + + parsed = await asyncio.to_thread(parse_erddap_csv0_wind, csv_text) + analysis = await asyncio.to_thread(analyze_wind_grid, parsed, config=config) + + now_utc = datetime.now(UTC) + version = now_utc.strftime("%Y%m%dT%H%M%SZ") + captured_at = to_iso8601_utc(now_utc) or now_utc.isoformat() + + async with _WIND_WRITE_LOCK: + entry = await asyncio.to_thread( + _save_wind_run_sync, + version=version, + captured_at=captured_at, + parsed=parsed, + analysis=analysis, + max_history_runs=config.max_history_runs, + ) + + return { + "run": entry, + "global_summary": analysis["global_summary"], + "regions": analysis["regions"], + "storm_cores": analysis["storm_cores"], + "config": config.model_dump(mode="json"), + } + + +def _load_wind_npz(version: str) -> dict[str, np.ndarray] | None: + if not VERSION_PATTERN.match(version): + return None + path = (_grids_dir() / f"{version}.npz").resolve() + root = _grids_dir().resolve() + if path.parent != root or not path.exists(): + return None + with np.load(path, allow_pickle=False) as archive: + return { + "lats": archive["lats"].copy(), + "lons": archive["lons"].copy(), + "u": archive["u"].copy(), + "v": archive["v"].copy(), + } + + +async def get_wind_runtime_meta(db: AsyncSession | None = None) -> dict[str, Any]: + ds_active = True + if db is not None and hasattr(db, "execute"): + try: + row = ( + await db.execute(select(DataSource).where(DataSource.source == "global_wind_gfs")) + ).scalar_one_or_none() + if row is not None: + ds_active = bool(row.is_active) + except Exception: + pass + + manifest = _read_manifest() + runs = manifest.get("runs", []) + latest = runs[0] if runs else None + latest_version = str(latest.get("version")) if isinstance(latest, dict) and latest.get("version") else None + exists = bool(latest_version and (_grids_dir() / f"{latest_version}.npz").exists()) + + available = bool(ds_active and exists) + return { + "available": available, + "is_active": ds_active, + "version": latest_version if exists else None, + "captured_at": latest.get("captured_at") if exists and latest else None, + "forecast_time": latest.get("forecast_time") if exists and latest else None, + "grid_url": f"/api/v1/earth/wind/grid/{latest_version}" if available else None, + "global_summary": (latest.get("global_summary") or {}) if exists and latest else {}, + "regions": (latest.get("regions") or []) if exists and latest else [], + "storm_cores": (latest.get("storm_cores") or []) if exists and latest else [], + "has_data": exists, + } + + +def read_wind_grid_payload(version: str) -> dict[str, Any] | None: + manifest = _read_manifest() + entry = next( + (item for item in manifest.get("runs", []) if item.get("version") == version), + None, + ) + arrays = _load_wind_npz(version) + if arrays is None: + return None + lats = arrays["lats"] + lons = arrays["lons"] + u = arrays["u"] + v = arrays["v"] + speed = np.sqrt(u * u + v * v) + return { + "version": version, + "captured_at": entry.get("captured_at") if entry else None, + "forecast_time": entry.get("forecast_time") if entry else None, + "width": int(u.shape[1]), + "height": int(u.shape[0]), + "lat_min": float(lats[0]), + "lat_max": float(lats[-1]), + "lon_min": float(lons[0]), + "lon_max": float(lons[-1]), + "max_speed_ms": round(float(np.max(speed)), 2), + "u": [round(float(val), 2) for val in u.ravel().tolist()], + "v": [round(float(val), 2) for val in v.ravel().tolist()], + } + + +async def query_wind_point( + lat: float, + lon: float, + db: AsyncSession | None = None, +) -> dict[str, Any]: + env = await read_wind_configuration(db) + config = WindFieldConfig.model_validate(env["config"]) + manifest = _read_manifest() + runs = manifest.get("runs", []) + latest = runs[0] if runs else None + version = str(latest.get("version") or "") if isinstance(latest, dict) else "" + arrays = _load_wind_npz(version) if version else None + if arrays is None: + return { + "available": False, + "latitude": round(float(lat), 4), + "longitude": round(float(lon), 4), + "u_ms": None, + "v_ms": None, + "speed_ms": None, + "direction_deg": None, + "direction_cardinal": None, + "beaufort": None, + } + + lats = arrays["lats"] + lons = arrays["lons"] + u_arr = arrays["u"] + v_arr = arrays["v"] + + clamped_lat = max(float(lats[0]), min(float(lats[-1]), float(lat))) + wrapped_lon = ((float(lon) + 180.0) % 360.0) - 180.0 + + # Bilinear interpolation across grid + lat_pos = float(np.interp(clamped_lat, lats, np.arange(len(lats), dtype=np.float32))) + lon_pos = float(np.interp(wrapped_lon, lons, np.arange(len(lons), dtype=np.float32))) + r0 = min(int(math.floor(lat_pos)), len(lats) - 1) + r1 = min(r0 + 1, len(lats) - 1) + c0 = min(int(math.floor(lon_pos)), len(lons) - 1) + c1 = min(c0 + 1, len(lons) - 1) + dr = lat_pos - r0 + dc = lon_pos - c0 + + def _bilerp(grid: np.ndarray) -> float: + top = float(grid[r0, c0]) * (1.0 - dc) + float(grid[r0, c1]) * dc + bot = float(grid[r1, c0]) * (1.0 - dc) + float(grid[r1, c1]) * dc + return top * (1.0 - dr) + bot * dr + + u_val = _bilerp(u_arr) + v_val = _bilerp(v_arr) + speed = math.hypot(u_val, v_val) + bearing = _wind_vector_to_bearing_deg(u_val, v_val) + region_zh, region_en = _match_region_name(lat, lon) + + return { + "available": True, + "latitude": round(float(lat), 4), + "longitude": round(float(lon), 4), + "u_ms": round(u_val, 2), + "v_ms": round(v_val, 2), + "speed_ms": round(speed, 2), + "direction_deg": round(bearing, 1), + "direction_cardinal": _bearing_to_cardinal(bearing), + "beaufort": _speed_to_beaufort(speed), + "is_gale": speed >= float(config.gale_threshold_ms), + "region": region_zh, + "region_en": region_en, + "version": version, + "captured_at": latest.get("captured_at") if latest else None, + "forecast_time": latest.get("forecast_time") if latest else None, + } + + +async def get_wind_analysis_summary(db: AsyncSession | None = None) -> dict[str, Any]: + meta = await get_wind_runtime_meta(db) + return { + "available": meta["available"], + "is_active": meta["is_active"], + "version": meta["version"], + "captured_at": meta["captured_at"], + "forecast_time": meta["forecast_time"], + "global_summary": meta["global_summary"], + "regions": meta["regions"], + "storm_cores": meta["storm_cores"], + } diff --git a/backend/app/services/location/agent_resolver.py b/backend/app/services/location/agent_resolver.py deleted file mode 100644 index 20a267ae..00000000 --- a/backend/app/services/location/agent_resolver.py +++ /dev/null @@ -1,664 +0,0 @@ -"""Controlled multi-step Tool-Calling agent & L1 resolvers for unknown facility locations.""" - -from __future__ import annotations - -import asyncio -from datetime import UTC, datetime -import json -from typing import Any -from uuid import uuid4 - -from sqlalchemy import select -from sqlalchemy.ext.asyncio import AsyncSession - -from app.core.logging import get_logger -from app.models.compute_center_location import ComputeCenterLocationRecord -from app.models.situational_assessment import WorkflowRun -from app.schemas.ai import SituationalAnalysisRequest -from app.services.ai.tool_registry import isolate_untrusted_external_text, safe_web_fetch -from app.services.ai.workflow_registry import resolve_runtime_workflow_node -from app.services.location.llm_fallback import ( - DEFAULT_MIN_CONFIDENCE, - LocationLLMFallbackResult, - collect_llm_location_fallback_candidate, -) -from app.services.location.models import LocationCandidate, LocationQuery -from app.services.location.resolvers.nominatim import build_default_nominatim_geocoder -from app.services.location.resolvers.peeringdb_facility import lookup_peeringdb_facility -from app.services.location.resolvers.wikidata import lookup_wikidata_facility -from app.services.location.text import coerce_str, normalize_country_text, normalize_text, parse_float - -logger = get_logger(__name__, service="location_agent") - -TERMINAL_UNLOCATABLE_STATUSES: frozenset[str] = frozenset({"undisclosed", "multi_site", "anonymous"}) -_agent_geocoder = build_default_nominatim_geocoder() - -LOCATION_AGENT_TOOLS: list[dict[str, Any]] = [ - { - "name": "fetch_source_url", - "description": "Fetch and read a primary source webpage (especially Epoch Source 1..5 or TOP500 detail URL) cleanly with prompt-injection isolation.", - "parameters": { - "type": "object", - "properties": {"url": {"type": "string", "description": "Public http/https URL"}}, - "required": ["url"], - }, - }, - { - "name": "web_search", - "description": "Search the web using concise English or local-language queries (do not chain long hardware suffixes).", - "parameters": { - "type": "object", - "properties": {"query": {"type": "string", "description": "Concise search query"}}, - "required": ["query"], - }, - }, - { - "name": "geocode_verify", - "description": "Verify a physical facility address or city via geocoder and receive a verified geocode_candidate_id with coordinates and country.", - "parameters": { - "type": "object", - "properties": { - "place_query": {"type": "string", "description": "Address, campus, or city + country"}, - "country": {"type": "string", "description": "Expected country name"}, - }, - "required": ["place_query"], - }, - }, - { - "name": "submit_location_result", - "description": "Finalize location verification using a geocode_candidate_id from geocode_verify, or report a terminal status (undisclosed/multi_site/anonymous/unresolved).", - "parameters": { - "type": "object", - "properties": { - "status": { - "type": "string", - "enum": ["located", "undisclosed", "multi_site", "anonymous", "unresolved"], - }, - "facility_name": {"type": "string"}, - "address": {"type": "string"}, - "city": {"type": "string"}, - "region": {"type": "string"}, - "country": {"type": "string"}, - "precision": {"type": "string", "enum": ["precise", "site", "city"]}, - "geocode_candidate_id": {"type": "string"}, - "citations": { - "type": "array", - "items": {"type": "string"}, - "description": "URLs directly observed in fetch_source_url or web_search outputs", - }, - "confidence": {"type": "number"}, - "reasoning": {"type": "string"}, - }, - "required": ["status", "reasoning"], - }, - }, -] - - -async def run_l1_structured_facility_resolvers( - query: LocationQuery, - *, - db: AsyncSession | None = None, -) -> tuple[list[LocationCandidate], list[str], bool]: - """Run async L1 Wikidata & PeeringDB lookups respecting `location.resolve_unknown` config.""" - l1_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l1_knowledge") - params = (l1_node or {}).get("params") or {} - enabled_tools = set((l1_node or {}).get("tools") or []) - allow_low_short_circuit = bool(params.get("allow_low_confidence_short_circuit", False)) - - tasks = [] - if params.get("wikidata_enabled", True) and (not enabled_tools or "wikidata_lookup" in enabled_tools): - tasks.append(lookup_wikidata_facility(query)) - if params.get("peeringdb_enabled", True) and (not enabled_tools or "peeringdb_fac_lookup" in enabled_tools): - tasks.append(lookup_peeringdb_facility(query)) - - candidates: list[LocationCandidate] = [] - attempted: list[str] = [] - if tasks: - results = await asyncio.gather(*tasks, return_exceptions=True) - for out in results: - if isinstance(out, Exception): - continue - attempted.extend(out.attempted_queries) - candidates.extend(out.candidates) - return candidates, attempted, allow_low_short_circuit - - -async def _persist_terminal_location_status( - db: AsyncSession | None, - *, - query: LocationQuery, - terminal_status: str, - reasoning: str, -) -> None: - if db is None or not hasattr(db, "execute"): - return - extra = query.extra or {} - source = coerce_str(extra.get("source")) - source_id = coerce_str(extra.get("source_id")) - if not source or not source_id: - return - try: - from app.services.compute_center_locations import refresh_compute_center_location_cache - - existing = await db.scalar( - select(ComputeCenterLocationRecord) - .where(ComputeCenterLocationRecord.source == source) - .where(ComputeCenterLocationRecord.source_id == source_id) - ) - if existing is None: - existing = ComputeCenterLocationRecord( - source=source, - source_id=source_id, - name=query.name, - operator=coerce_str(extra.get("operator")) or None, - site=coerce_str(extra.get("site")) or None, - city=query.city, - country=query.country, - latitude=None, - longitude=None, - precision="unknown", - confidence=0.0, - location_source=f"agent_terminal_{terminal_status}", - source_note=reasoning[:500] or f"Marked {terminal_status} by location agent", - needs_confirmation=False, - verification_status=terminal_status, - verified_at=datetime.now(UTC), - ) - db.add(existing) - else: - existing.precision = "unknown" - existing.latitude = None - existing.longitude = None - existing.verification_status = terminal_status - existing.location_source = f"agent_terminal_{terminal_status}" - existing.source_note = reasoning[:500] or existing.source_note - existing.verified_at = datetime.now(UTC) - await db.commit() - await refresh_compute_center_location_cache(db) - except Exception as exc: - logger.warning_event( - "Failed to persist terminal unlocatable status", - event="location.agent.persist_terminal_failed", - context={"source_id": source_id, "status": terminal_status, "error": str(exc)}, - ) - - -async def _record_location_workflow_run( - db: AsyncSession | None, - *, - question: str, - status_value: str, - tool_trace: list[str], - steps_used: int, - error_message: str = "", -) -> None: - if db is None or not hasattr(db, "add"): - return - try: - db.add( - WorkflowRun( - id=f"run_{uuid4().hex[:16]}", - workflow_id="location.resolve_unknown", - status=status_value, - access_tier="admin", - actor_key="admin:collect-location", - question=question[:500], - tool_trace=tool_trace, - budget_used={"steps": steps_used}, - error_message=error_message[:500], - completed_at=datetime.now(UTC), - ) - ) - await db.commit() - except Exception: - try: - await db.rollback() - except Exception: - pass - - -async def run_controlled_location_agent( - *, - provider_client: Any, - web_search_client: Any | None, - query: LocationQuery, - entity_type: str = "compute_center", - db: AsyncSession | None = None, - attempted_queries: list[str] | None = None, -) -> tuple[LocationLLMFallbackResult, str | None]: - """Run the 3-4 step Tool-Calling location agent and return `(result, terminal_status)`.""" - extra = query.extra or {} - l2_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l2_agent_research") - l3_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l3_geo_guardrail") - if l2_node and not l2_node.get("enabled", True): - return ( - LocationLLMFallbackResult( - candidates=[], - attempted_queries=list(attempted_queries or []), - failure_reason="Location agent node is disabled by workflow configuration.", - ), - None, - ) - - max_steps = max(1, min(int((l2_node or {}).get("max_steps") or 4), 6)) - allowed_tool_names = set((l2_node or {}).get("tools") or [t["name"] for t in LOCATION_AGENT_TOOLS]) - min_confidence = float(((l3_node or {}).get("guardrails") or {}).get("min_confidence") or DEFAULT_MIN_CONFIDENCE) - require_tool_urls = bool(((l3_node or {}).get("guardrails") or {}).get("require_tool_cited_urls", True)) - - active_tools = [t for t in LOCATION_AGENT_TOOLS if t["name"] in allowed_tool_names] - if not any(t["name"] == "submit_location_result" for t in active_tools): - active_tools.append(LOCATION_AGENT_TOOLS[-1]) - - observed_urls: set[str] = set() - geocode_candidates: dict[str, dict[str, Any]] = {} - tool_trace: list[str] = ["l0_normalize", "l1_knowledge"] - agent_attempts: list[str] = [] - source_urls = [ - str(u).strip() - for u in [*([extra.get("source_url")] if extra.get("source_url") else []), *(extra.get("sources") or [])] - if str(u or "").strip().startswith(("http://", "https://")) - ] - - system_prompt = (l2_node or {}).get("system_prompt") or ( - "你是算力与网络基础设施物理位置查证 Agent。严禁编造经纬度!" - "1) 若存在 primary_source_urls,优先调用 fetch_source_url;" - "2) 否则调用 web_search 查询物理地址;" - "3) 将查到的物理地址/城市传入 geocode_verify 获取 candidate_id;" - "4) 最后调用 submit_location_result 提交结果。" - ) - user_objective = (l2_node or {}).get("prompt") or ( - f"请查证目标设施 {query.name or extra.get('source_id')} 的物理所在城市或园区。" - ) - context_payload = { - "name": query.name, - "name_short": query.aliases[0] if query.aliases else query.name, - "operator": extra.get("operator") or None, - "site": extra.get("site") or None, - "city": query.city, - "country": query.country, - "raw_country": extra.get("source_raw_country"), - "primary_source_urls": source_urls[:5], - } - - messages: list[dict[str, Any]] = [ - { - "role": "user", - "content": ( - f"{user_objective}\n\n目标上下文 JSON:\n" - f"{json.dumps(context_payload, ensure_ascii=False)}" - ), - } - ] - submitted_payload: dict[str, Any] | None = None - last_text_response = "" - steps_taken = 0 - - for step in range(1, max_steps + 1): - steps_taken = step - req = SituationalAnalysisRequest( - title=f"Location agent step {step}", - objective=user_objective, - system_prompt=system_prompt, - context=context_payload, - preferred_model=(l2_node or {}).get("model_override"), - messages=messages, - tools=active_tools, - tool_choice="auto" if step < max_steps else {"type": "function", "name": "submit_location_result"}, - native_web_search=bool((l2_node or {}).get("native_web_search", False)), - ) - try: - resp = await provider_client.analyze(req) - except Exception as exc: - await _record_location_workflow_run( - db, - question=str(query.name or ""), - status_value="failed", - tool_trace=tool_trace, - steps_used=steps_taken, - error_message=str(exc), - ) - return ( - LocationLLMFallbackResult( - candidates=[], - attempted_queries=[*(attempted_queries or []), *agent_attempts], - failure_reason=f"Location agent failed: {exc}", - ), - None, - ) - - last_text_response = str(getattr(resp, "content", "") or "") - tool_calls = list(getattr(resp, "tool_calls", None) or []) - if not tool_calls: - # Provider returned plain text (no tool calling support); break cleanly into deterministic fallback. - break - - messages.append( - { - "role": "assistant", - "content": last_text_response, - "tool_calls": [ - {"id": tc.id, "name": tc.name, "arguments": tc.arguments} - for tc in tool_calls - ], - } - ) - - for tc in tool_calls: - raw_args = tc.arguments - if isinstance(raw_args, str): - try: - raw_args = json.loads(raw_args) - except json.JSONDecodeError: - raw_args = {} - args = raw_args if isinstance(raw_args, dict) else {} - tool_trace.append(f"l2_agent_research:{tc.name}") - if tc.name == "fetch_source_url": - target_url = coerce_str(args.get("url")) - agent_attempts.append(f"fetch_url:{target_url}") - try: - fetched = await asyncio.wait_for(safe_web_fetch(target_url, timeout_seconds=8), timeout=10.0) - final_url = ( - coerce_str(fetched.get("final_url") or fetched.get("url")) - if isinstance(fetched, dict) - else coerce_str(getattr(fetched, "final_url", None) or getattr(fetched, "url", None)) - ) or target_url - title = fetched.get("title", "") if isinstance(fetched, dict) else getattr(fetched, "title", "") - text = fetched.get("content", "") if isinstance(fetched, dict) else getattr(fetched, "text", "") - observed_urls.add(target_url) - observed_urls.add(final_url) - tool_output = isolate_untrusted_external_text(final_url, title, text, max_chars=2400) - except Exception as exc: - tool_output = {"error": f"fetch failed: {exc}", "url": target_url} - messages.append( - { - "role": "tool", - "tool_call_id": tc.id, - "name": tc.name, - "content": json.dumps(tool_output, ensure_ascii=False), - } - ) - elif tc.name == "web_search": - q_str = coerce_str(args.get("query")) - agent_attempts.append(f"web_search:{q_str}") - if web_search_client is None: - tool_output = {"error": "WebSearch is not enabled or missing API key"} - else: - try: - evidences = await web_search_client.search(q_str, max_results=5) - items = [] - for ev in evidences: - u = coerce_str(getattr(ev, "url", "")) - if u: - observed_urls.add(u) - items.append( - { - "title": getattr(ev, "title", ""), - "url": u, - "snippet": getattr(ev, "snippet", "")[:400], - } - ) - tool_output = {"results": items} - except Exception as exc: - tool_output = {"error": str(exc)} - messages.append( - { - "role": "tool", - "tool_call_id": tc.id, - "name": tc.name, - "content": json.dumps(tool_output, ensure_ascii=False), - } - ) - elif tc.name == "geocode_verify": - place_q = coerce_str(args.get("place_query")) - expected_c = normalize_country_text(args.get("country") or query.country) - agent_attempts.append(f"geocode_verify:{place_q}") - try: - geo_res = await asyncio.to_thread(_agent_geocoder, place_q) - except Exception as exc: - logger.warning_event( - "Location agent geocode_verify failed", - event="location_agent.geocode_verify.failed", - context={"place_query": place_q, "error": str(exc)}, - ) - geo_res = None - geocode_error = f"geocoder request failed: {exc}" - else: - geocode_error = "" - if geocode_error: - tool_output = {"found": False, "error": geocode_error, "retryable": True} - elif not isinstance(geo_res, dict): - tool_output = {"found": False, "reason": "No geocoder match"} - else: - lat = parse_float(geo_res.get("lat") if geo_res.get("lat") is not None else geo_res.get("latitude")) - lon = parse_float(geo_res.get("lon") if geo_res.get("lon") is not None else geo_res.get("longitude")) - addr = geo_res.get("address") if isinstance(geo_res.get("address"), dict) else {} - res_country = normalize_country_text(addr.get("country") or geo_res.get("country")) - if ( - lat in (None, 0.0) - or lon in (None, 0.0) - or not (-90.0 <= lat <= 90.0) - or not (-180.0 <= lon <= 180.0) - ): - tool_output = {"found": False, "reason": "Invalid geocoder coordinates"} - elif expected_c and res_country and normalize_text(res_country) != normalize_text(expected_c): - tool_output = { - "found": False, - "reason": f"Country mismatch: got {res_country}, expected {expected_c}", - } - else: - cid = f"geo_{len(geocode_candidates) + 1}" - geocode_candidates[cid] = { - "latitude": lat, - "longitude": lon, - "display_name": coerce_str(geo_res.get("display_name")) or place_q, - "city": coerce_str( - addr.get("city") - or addr.get("town") - or addr.get("village") - or addr.get("municipality") - or geo_res.get("city") - ), - "region": coerce_str(addr.get("state") or addr.get("region") or geo_res.get("region")), - "country": res_country or expected_c or query.country, - } - tool_output = {"found": True, "geocode_candidate_id": cid, **geocode_candidates[cid]} - messages.append( - { - "role": "tool", - "tool_call_id": tc.id, - "name": tc.name, - "content": json.dumps(tool_output, ensure_ascii=False), - } - ) - elif tc.name == "submit_location_result": - submitted_payload = dict(args) - tool_trace.append("l3_geo_guardrail") - messages.append( - { - "role": "tool", - "tool_call_id": tc.id, - "name": tc.name, - "content": json.dumps({"accepted": True}), - } - ) - if submitted_payload is not None: - break - - if submitted_payload is None: - # Fallback for providers/mocks without tool_calls support - evidence_list = [] - if web_search_client is not None: - from app.services.location.llm_fallback import collect_location_search_evidence - - search_res = await collect_location_search_evidence( - web_search_client=web_search_client, - query=query, - entity_type=entity_type, - ) - agent_attempts.extend(search_res.attempted_queries) - evidence_list = search_res.evidence - if evidence_list or last_text_response: - fallback_res = await collect_llm_location_fallback_candidate( - provider_client=provider_client, - query=query, - entity_type=entity_type, - db=db, - attempted_queries=[*(attempted_queries or []), *agent_attempts], - search_evidence=evidence_list, - min_confidence=min_confidence, - ) - await _record_location_workflow_run( - db, - question=str(query.name or ""), - status_value="completed" if fallback_res.candidates else "failed", - tool_trace=[*tool_trace, "llm_fallback"], - steps_used=steps_taken, - error_message=fallback_res.failure_reason or "", - ) - return fallback_res, None - await _record_location_workflow_run( - db, - question=str(query.name or ""), - status_value="failed", - tool_trace=tool_trace, - steps_used=steps_taken, - error_message="Agent did not submit location result", - ) - return ( - LocationLLMFallbackResult( - candidates=[], - attempted_queries=[*(attempted_queries or []), *agent_attempts], - failure_reason="Location agent reached step budget without submitting a verified location.", - ), - None, - ) - - sub_status = str(submitted_payload.get("status") or "unresolved").strip().lower() - reasoning = coerce_str(submitted_payload.get("reasoning")) - if sub_status in TERMINAL_UNLOCATABLE_STATUSES: - await _persist_terminal_location_status( - db, - query=query, - terminal_status=sub_status, - reasoning=reasoning, - ) - await _record_location_workflow_run( - db, - question=str(query.name or ""), - status_value="completed", - tool_trace=[*tool_trace, f"l4_persist_outcome:{sub_status}"], - steps_used=steps_taken, - ) - return ( - LocationLLMFallbackResult( - candidates=[], - attempted_queries=[*(attempted_queries or []), *agent_attempts], - failure_reason=reasoning or f"Facility confirmed as {sub_status}.", - ), - sub_status, - ) - - geo_cid = coerce_str(submitted_payload.get("geocode_candidate_id")) - geo_entry = geocode_candidates.get(geo_cid) - if sub_status != "located" or geo_entry is None: - reason = reasoning or "Submitted result missing verified geocode_candidate_id" - await _record_location_workflow_run( - db, - question=str(query.name or ""), - status_value="failed", - tool_trace=tool_trace, - steps_used=steps_taken, - error_message=reason, - ) - return ( - LocationLLMFallbackResult( - candidates=[], - attempted_queries=[*(attempted_queries or []), *agent_attempts], - failure_reason=reason, - ), - None, - ) - - citations = [ - str(c).strip() - for c in (submitted_payload.get("citations") or []) - if str(c or "").strip() - ] - verified_citations = [c for c in citations if c in observed_urls] - if require_tool_urls and not verified_citations: - reason = "No verified citation URLs observed in tool outputs" - await _record_location_workflow_run( - db, - question=str(query.name or ""), - status_value="failed", - tool_trace=tool_trace, - steps_used=steps_taken, - error_message=reason, - ) - return ( - LocationLLMFallbackResult( - candidates=[], - attempted_queries=[*(attempted_queries or []), *agent_attempts], - failure_reason=reason, - ), - None, - ) - - expected_country = normalize_country_text(query.country) - resolved_country = normalize_country_text(submitted_payload.get("country") or geo_entry.get("country")) - if expected_country and resolved_country and normalize_text(resolved_country) != normalize_text(expected_country): - reason = f"Country mismatch ({resolved_country} != {expected_country})" - await _record_location_workflow_run( - db, - question=str(query.name or ""), - status_value="failed", - tool_trace=tool_trace, - steps_used=steps_taken, - error_message=reason, - ) - return ( - LocationLLMFallbackResult( - candidates=[], - attempted_queries=[*(attempted_queries or []), *agent_attempts], - failure_reason=reason, - ), - None, - ) - - confidence = min(max(parse_float(submitted_payload.get("confidence")) or 0.78, 0.0), 1.0) - raw_precision = coerce_str(submitted_payload.get("precision")).lower() - precision = raw_precision if raw_precision in {"precise", "site", "city"} else "city" - facility_label = coerce_str(submitted_payload.get("facility_name")) or coerce_str(geo_entry.get("display_name")) or coerce_str(query.name) - candidate = LocationCandidate( - latitude=float(geo_entry["latitude"]), - longitude=float(geo_entry["longitude"]), - display_name=facility_label, - precision=precision, - confidence=max(confidence, min_confidence), - query=f"location_agent:{entity_type}:{query.name or extra.get('source_id') or 'unknown'}", - source="llm_location_factcheck", - source_note=reasoning or f"Verified via tool-calling agent ({len(verified_citations)} citations)", - matched_fields=("name", "tool_calling_agent"), - needs_confirmation=True, - city=coerce_str(submitted_payload.get("city")) or geo_entry.get("city") or query.city or None, - region=coerce_str(submitted_payload.get("region")) or geo_entry.get("region") or query.region or None, - country=resolved_country or expected_country or query.country, - matched_location_name=facility_label, - raw_payload={"citations": verified_citations or citations, "geocode_candidate_id": geo_cid}, - ) - await _record_location_workflow_run( - db, - question=str(query.name or ""), - status_value="completed", - tool_trace=[*tool_trace, "l4_persist_outcome:located"], - steps_used=steps_taken, - ) - return ( - LocationLLMFallbackResult( - candidates=[candidate], - attempted_queries=[*(attempted_queries or []), *agent_attempts], - failure_reason=None, - ), - None, - ) diff --git a/backend/app/services/location/llm_fallback.py b/backend/app/services/location/llm_fallback.py deleted file mode 100644 index c127333b..00000000 --- a/backend/app/services/location/llm_fallback.py +++ /dev/null @@ -1,1346 +0,0 @@ -"""LLM-backed fallback candidate generation for hard-to-resolve locations.""" - -from __future__ import annotations - -import json -import re -from dataclasses import dataclass -from typing import Any, Iterable - -from sqlalchemy.ext.asyncio import AsyncSession - -from app.core.logging import get_logger -from app.core.countries import COUNTRY_ENTRIES, normalize_country -from app.schemas.ai import SituationalAnalysisRequest -from app.ai_tasks.prompts import get_effective_prompt -from app.services.ai_client import AIProviderClient -from app.services.ai_tools.evidence_store import normalize_search_evidence -from app.services.ai_tools.web_search import WebSearchClient, WebSearchError -from app.services.location.models import LocationCandidate, LocationQuery -from app.services.location.resolvers.nominatim import build_default_nominatim_geocoder -from app.services.location.text import ( - coerce_str, - normalize_country_text, - normalize_text, - parse_float, -) - -VALID_LLM_PRECISIONS = {"precise", "site", "city"} -DEFAULT_MIN_CONFIDENCE = 0.55 -LOCATION_NORMALIZE_PROMPT_KEY = "location.factcheck.normalize" -LOCATION_RESOLVE_PROMPT_KEY = "location.factcheck.resolve" -MODEL_CONFIDENCE_WEIGHT = 0.25 -LOG_TEXT_LIMIT = 1200 -LOG_EVIDENCE_LIMIT = 5 -logger = get_logger(__name__, service="location") -_geocode_llm_city = build_default_nominatim_geocoder() -_LLM_LOCATION_NAME_KEYS = ( - "matched_location_name", - "display_name", - "location_name", - "location", - "place", - "city", -) -_NAME_HINT_STOPWORDS = { - "ai", - "cloud", - "cluster", - "compute", - "computer", - "gpu", - "hpc", - "mercury", - "phase", - "super", - "supercomputer", -} -LLM_PRECISION_ALIASES = { - "precise": "precise", - "exact": "precise", - "coordinate": "precise", - "coordinates": "precise", - "site": "site", - "site level": "site", - "site-level": "site", - "site_level": "site", - "facility": "site", - "facility level": "site", - "city": "city", - "city level": "city", - "city-level": "city", - "city_level": "city", -} - - -@dataclass(frozen=True) -class LocationLLMFallbackResult: - candidates: list[LocationCandidate] - attempted_queries: list[str] - failure_reason: str | None = None - - -@dataclass(frozen=True) -class LocationSearchEvidenceResult: - evidence: list[dict[str, Any]] - attempted_queries: list[str] - failure_reason: str | None = None - - -@dataclass(frozen=True) -class LocationEvidenceScore: - score: float - model_confidence: float - source_quality: float - entity_match: float - geography_match: float - precision_quality: float - conflict_penalty: float - weak_evidence_penalty: float - name_location_hint: float - summary: str - - -def _truncate_log_text(value: Any, limit: int = LOG_TEXT_LIMIT) -> str: - text = coerce_str(value) - if len(text) <= limit: - return text - return f"{text[:limit]}…" - - -def _summarize_search_evidence(evidence: list[dict[str, Any]] | None) -> list[dict[str, Any]]: - items: list[dict[str, Any]] = [] - for item in (evidence or [])[:LOG_EVIDENCE_LIMIT]: - if not isinstance(item, dict): - continue - items.append( - { - "title": _truncate_log_text(item.get("title"), 180), - "source": _truncate_log_text(item.get("source") or item.get("name"), 120), - "url": _truncate_log_text(item.get("url"), 240), - "snippet": _truncate_log_text( - item.get("snippet") - or item.get("content") - or item.get("text") - or item.get("summary"), - 360, - ), - } - ) - return items - - -def _first_json_object(text: str) -> dict[str, Any] | None: - stripped = text.strip() - if not stripped: - return None - if stripped.startswith("```"): - stripped = re.sub(r"^```(?:json)?\s*", "", stripped, flags=re.IGNORECASE) - stripped = re.sub(r"\s*```$", "", stripped) - try: - data = json.loads(stripped) - return data if isinstance(data, dict) else None - except json.JSONDecodeError: - pass - - start = stripped.find("{") - end = stripped.rfind("}") - if start < 0 or end <= start: - return None - try: - data = json.loads(stripped[start : end + 1]) - except json.JSONDecodeError: - return None - return data if isinstance(data, dict) else None - - -def _compact_evidence(value: Any) -> str: - if isinstance(value, list): - parts = [_evidence_label(item) for item in value if _evidence_label(item)] - return "; ".join(parts[:3]) - return coerce_str(value) - - -def _evidence_items(value: Any) -> list[dict[str, Any]]: - if isinstance(value, list): - raw_items = value - elif value in (None, ""): - raw_items = [] - else: - raw_items = [value] - - items: list[dict[str, Any]] = [] - for item in raw_items: - if isinstance(item, dict): - items.append(dict(item)) - else: - text = coerce_str(item) - if text: - items.append({"text": text}) - return items - - -def _evidence_label(item: Any) -> str: - if isinstance(item, dict): - source = coerce_str(item.get("source") or item.get("title") or item.get("name")) - url = coerce_str(item.get("url")) - text = coerce_str(item.get("text") or item.get("quote") or item.get("summary")) - if source and url: - return f"{source} ({url})" - if source: - return source - if url: - return url - return text - return coerce_str(item) - - -def _evidence_text(item: dict[str, Any]) -> str: - return " ".join( - coerce_str(item.get(key)) - for key in ("title", "source", "name", "url", "snippet", "content", "text", "quote", "summary") - if coerce_str(item.get(key)) - ) - - -def _search_evidence_entity_match(item: dict[str, Any], query: LocationQuery) -> bool: - haystack = normalize_text(_evidence_text(item)) - if not haystack: - return False - needles = [ - coerce_str(query.name), - *[coerce_str(alias) for alias in query.aliases], - ] - return any(normalize_text(needle) and normalize_text(needle) in haystack for needle in needles) - - -def _evidence_has_location_assertion(item: dict[str, Any], city: str) -> bool: - normalized_city = normalize_text(city) - text = normalize_text(_evidence_text(item)) - if not normalized_city or normalized_city not in text: - return False - assertion_terms = ( - "located", - "situated", - "built", - "hosted", - "deployed", - "installed", - "facility", - "campus", - "site", - "data center", - "datacenter", - "supercomputer center", - "位于", - "位於", - "坐落", - "建置", - "設置", - "设置", - ) - return any(term in text for term in assertion_terms) - - -def _city_is_unsupported_name_hint(payload: dict[str, Any], query: LocationQuery, evidence_items: list[dict[str, Any]]) -> bool: - city = coerce_str(payload.get("city") or query.city) - if not city: - return False - normalized_city = normalize_text(city) - normalized_name = normalize_text(query.name) - if not normalized_city or not normalized_name or normalized_city not in normalized_name: - return False - return not any(_evidence_has_location_assertion(item, city) for item in evidence_items) - - -def _normalize_llm_precision(value: Any) -> str: - text = coerce_str(value).lower() - return LLM_PRECISION_ALIASES.get(text, text) - - -def _detect_country_in_text(text: str) -> str: - normalized_text = normalize_text(text) - if not normalized_text: - return "" - for canonical, aliases in COUNTRY_ENTRIES: - variants = [canonical, *aliases] - for variant in variants: - normalized_variant = normalize_text(variant) - if not normalized_variant: - continue - if normalized_variant.isascii(): - if len(normalized_variant) < 4: - continue - if re.search(rf"\b{re.escape(normalized_variant)}\b", normalized_text): - return canonical - elif normalized_variant in normalized_text: - return canonical - return "" - - -def _extract_city_from_text(text: str, *, country: str | None = None) -> str: - patterns = [ - r"\(([^()]{2,80})\)", - r"\blocated\s+(?:in|at)\s+([^,.;()\n]{2,80})(?:,\s*([^.;()\n]{2,80}))?", - r"\bbased\s+in\s+([^,.;()\n]{2,80})(?:,\s*([^.;()\n]{2,80}))?", - r"\b位[于於]\s*(?:[^,。;;\n]{0,40}?的\s*)?([^,。;;()\n]{2,40})", - ] - normalized_country = normalize_text(country) - for pattern in patterns: - match = re.search(pattern, text, flags=re.IGNORECASE) - if not match: - continue - for group in match.groups(): - candidate = coerce_str(group) - if not candidate: - continue - candidate = re.sub(r"^(?:the\s+city\s+of|city\s+of)\s+", "", candidate, flags=re.I) - candidate = candidate.strip(" -–—::,,。.;;") - if not candidate: - continue - if normalized_country and normalize_text(candidate) == normalized_country: - continue - if normalize_country(candidate): - continue - return candidate - return "" - - -def _payload_from_free_text(text: str, *, query: LocationQuery) -> dict[str, Any] | None: - """Build a conservative payload when the model answered in prose. - - This is deliberately small: it only extracts a country and a city/place-like - phrase. The normal scoring and geocoding gates still decide whether the - result can become a candidate. - """ - if not coerce_str(text): - return None - country = _detect_country_in_text(text) or normalize_country_text(query.country) - city = _extract_city_from_text(text, country=country) - if not city or not country: - return None - evidence_text = " ".join(coerce_str(text).split())[:500] - return { - "precision": "city", - "confidence": 0.55, - "city": city, - "country": country, - "matched_location_name": f"{city}, {country}", - "evidence": [ - { - "source": "LLM prose location factcheck", - "source_type": "generic", - "entity_match": bool( - normalize_text(query.name) - and normalize_text(query.name) in normalize_text(text) - ), - "text": evidence_text, - } - ], - "reasoning_summary": "Location extracted from a non-JSON LLM answer.", - "parse_strategy": "free_text_location_extraction", - } - - -def _query_name_city_terms(query: LocationQuery) -> list[str]: - values = [ - query.name, - *query.aliases, - (query.extra or {}).get("site"), - ] - terms: list[str] = [] - seen: set[str] = set() - for value in values: - text = coerce_str(value) - if not text: - continue - for raw_token in re.findall(r"[A-Za-z][A-Za-z.'-]{2,}|[\u4e00-\u9fff]{2,}", text): - token = raw_token.strip(" .'-") - key = normalize_text(token) - if not key or key in seen or key in _NAME_HINT_STOPWORDS: - continue - seen.add(key) - terms.append(token.title() if token.isupper() else token) - return terms[:5] - - -def _payload_from_query_name_geocode(query: LocationQuery) -> dict[str, Any] | None: - """Use entity-name city hints only after LLM parsing fails. - - The hint is accepted only when the derived term geocodes to a city-like - result in the query country. This keeps names such as "MUSICA Phase 1" - from becoming arbitrary coordinates while allowing "TAIPEI-1" -> Taipei. - """ - country = normalize_country_text(query.country) - if not country: - return None - for term in _query_name_city_terms(query): - geocode_query = f"{term}, {country}" - try: - result = _geocode_llm_city(geocode_query) - except Exception: - continue - if not isinstance(result, dict): - continue - latitude = parse_float(result.get("lat")) - longitude = parse_float(result.get("lon")) - if latitude in (None, 0.0) or longitude in (None, 0.0): - continue - address = result.get("address") if isinstance(result.get("address"), dict) else {} - city = ( - address.get("city") - or address.get("town") - or address.get("village") - or address.get("municipality") - or address.get("suburb") - ) - result_country = normalize_country_text(address.get("country") or country) - if not city or normalize_text(result_country) != normalize_text(country): - continue - if normalize_text(term) not in normalize_text(city) and normalize_text(term) not in normalize_text(result.get("display_name")): - continue - return { - "latitude": latitude, - "longitude": longitude, - "precision": "city", - "confidence": 0.50, - "city": city, - "region": address.get("state") or address.get("region"), - "country": result_country, - "matched_location_name": result.get("display_name") or geocode_query, - "evidence": [ - { - "source": "Entity name city hint", - "source_type": "generic", - "entity_match": True, - "text": ( - f"Derived city term '{term}' from entity name " - f"'{coerce_str(query.name)}' and verified it by geocoding." - ), - } - ], - "reasoning_summary": "City derived from entity name after LLM parsing failed.", - "parse_strategy": "query_name_city_hint", - "coordinate_source": "nominatim_city_fallback", - } - return None - - -def _extract_llm_coordinates(payload: dict[str, Any]) -> tuple[float | None, float | None]: - latitude = parse_float( - payload.get("latitude") - if payload.get("latitude") not in (None, "") - else payload.get("lat") - ) - longitude = parse_float( - payload.get("longitude") - if payload.get("longitude") not in (None, "") - else ( - payload.get("lon") - if payload.get("lon") not in (None, "") - else payload.get("lng") - ) - ) - if latitude not in (None, 0.0) and longitude not in (None, 0.0): - return latitude, longitude - - coordinates = payload.get("coordinates") or payload.get("coordinate") - if isinstance(coordinates, dict): - latitude = parse_float( - coordinates.get("latitude") - if coordinates.get("latitude") not in (None, "") - else coordinates.get("lat") - ) - longitude = parse_float( - coordinates.get("longitude") - if coordinates.get("longitude") not in (None, "") - else ( - coordinates.get("lon") - if coordinates.get("lon") not in (None, "") - else coordinates.get("lng") - ) - ) - elif isinstance(coordinates, (list, tuple)) and len(coordinates) >= 2: - first = parse_float(coordinates[0]) - second = parse_float(coordinates[1]) - if first is not None and second is not None: - # GeoJSON-style [lon, lat] is the common interchange format. - longitude, latitude = first, second - return latitude, longitude - - -def _fill_city_coordinates_from_geocoder( - payload: dict[str, Any], - *, - query: LocationQuery, -) -> tuple[dict[str, Any], str | None]: - city = coerce_str(payload.get("city") or query.city) - country = coerce_str(payload.get("country") or query.country) - geocode_queries: list[str] = [] - - def add_geocode_query(value: str) -> None: - cleaned = coerce_str(value) - if cleaned and cleaned not in geocode_queries: - geocode_queries.append(cleaned) - - if city and country: - add_geocode_query(f"{city}, {country}") - for key in _LLM_LOCATION_NAME_KEYS: - value = payload.get(key) - if not isinstance(value, str): - continue - if country and country.lower() not in value.lower(): - add_geocode_query(f"{value}, {country}") - add_geocode_query(value) - - if not geocode_queries: - return payload, None - expected_country = normalize_text(normalize_country_text(country or query.country)) - failures: list[str] = [] - geocode_query = "" - result: dict[str, Any] | None = None - for candidate_query in geocode_queries: - geocode_query = candidate_query - try: - maybe_result = _geocode_llm_city(geocode_query) - except Exception as exc: - failures.append(f"{geocode_query}: {exc}") - continue - if not isinstance(maybe_result, dict): - failures.append(f"{geocode_query}: no result") - continue - latitude = parse_float(maybe_result.get("lat")) - longitude = parse_float(maybe_result.get("lon")) - if ( - latitude in (None, 0.0) - or longitude in (None, 0.0) - or not (-90.0 <= latitude <= 90.0) - or not (-180.0 <= longitude <= 180.0) - ): - failures.append(f"{geocode_query}: invalid coordinates") - continue - cand_addr = maybe_result.get("address") if isinstance(maybe_result.get("address"), dict) else {} - cand_country = normalize_text(normalize_country_text(cand_addr.get("country"))) - if expected_country and cand_country and cand_country != expected_country: - failures.append(f"{geocode_query}: country mismatch ({cand_country} != {expected_country})") - continue - result = maybe_result - break - if result is None: - detail = "; ".join(failures[:3]) or "no usable geocode query" - return payload, f"city geocode fallback found no usable result ({detail})" - - latitude = parse_float(result.get("lat")) - longitude = parse_float(result.get("lon")) - if ( - latitude in (None, 0.0) - or longitude in (None, 0.0) - or not (-90.0 <= latitude <= 90.0) - or not (-180.0 <= longitude <= 180.0) - ): - return payload, f"city geocode fallback returned invalid coordinates for '{geocode_query}'" - address = result.get("address") if isinstance(result.get("address"), dict) else {} - city = ( - city - or address.get("city") - or address.get("town") - or address.get("village") - or address.get("municipality") - or address.get("suburb") - ) - country = country or address.get("country") - try: - raw_precision = _normalize_llm_precision(payload.get("precision")) or "city" - except Exception: - raw_precision = "city" - # City-level geocoder fallback must never keep inflated site/precise claims. - precision = "city" if raw_precision in {"precise", "site", "city"} else raw_precision - filled = { - **payload, - "latitude": latitude, - "longitude": longitude, - "precision": precision, - "city": payload.get("city") or city, - "region": payload.get("region") or address.get("state") or address.get("region"), - "country": payload.get("country") or address.get("country") or country, - "matched_location_name": ( - payload.get("matched_location_name") - or result.get("display_name") - or geocode_query - ), - "coordinate_source": "nominatim_city_fallback", - } - return filled, None - - -def _truthy_evidence_field(item: dict[str, Any], *keys: str) -> bool: - for key in keys: - value = item.get(key) - if isinstance(value, bool): - if value: - return True - elif coerce_str(value).lower() in {"true", "yes", "exact", "strong"}: - return True - return False - - -def _source_quality_score(evidence_items: list[dict[str, Any]]) -> float: - best = 0.0 - for item in evidence_items: - source_type = normalize_text( - item.get("source_type") - or item.get("type") - or item.get("source_kind") - or "" - ) - source_text = normalize_text( - " ".join( - [ - coerce_str(item.get("source")), - coerce_str(item.get("url")), - coerce_str(item.get("text")), - coerce_str(item.get("summary")), - ] - ) - ) - combined = f"{source_type} {source_text}" - if any(token in combined for token in ("official", "government", "gov", "edu", "university")): - best = max(best, 0.35) - elif any(token in combined for token in ("database", "registry", "wikipedia", "news", "press")): - best = max(best, 0.25) - elif combined.strip(): - best = max(best, 0.15) - return best - - -def _entity_match_score(payload: dict[str, Any], query: LocationQuery, evidence_items: list[dict[str, Any]]) -> float: - if any( - _truthy_evidence_field(item, "entity_match", "matches_entity", "name_match") - for item in evidence_items - ): - return 0.25 - - names = [ - query.name, - *query.aliases, - (query.extra or {}).get("site"), - (query.extra or {}).get("operator"), - (query.extra or {}).get("organization"), - ] - needles = [normalize_text(name) for name in names if normalize_text(name)] - haystack = normalize_text( - " ".join( - [ - coerce_str(payload.get("matched_location_name")), - coerce_str(payload.get("reasoning_summary")), - *[_evidence_label(item) for item in evidence_items], - ] - ) - ) - if needles and any(needle in haystack for needle in needles): - return 0.25 - return 0.0 - - -def _geography_match_score(payload: dict[str, Any], query: LocationQuery) -> float: - city = normalize_text(payload.get("city") or query.city) - country = normalize_text(normalize_country_text(payload.get("country") or query.country)) - context_country = normalize_text(normalize_country_text(query.country)) - if city and country and (not context_country or country == context_country): - return 0.20 - if country and (not context_country or country == context_country): - return 0.05 - return 0.0 - - -def _precision_quality_score(precision: str) -> float: - return { - "precise": 0.15, - "site": 0.12, - "city": 0.08, - }.get(precision, 0.0) - - -def _name_location_hint_score(payload: dict[str, Any], query: LocationQuery) -> float: - query_name = normalize_text(query.name) - city = normalize_text(payload.get("city") or query.city) - matched_name = normalize_text(payload.get("matched_location_name")) - if not query_name or not city: - return 0.0 - if city in query_name or query_name in city: - return 0.07 - if matched_name and (city in matched_name) and any(part in query_name for part in city.split()): - return 0.04 - return 0.0 - - -def _ambiguity_text(payload: dict[str, Any], evidence_items: list[dict[str, Any]]) -> str: - return normalize_text( - " ".join( - [ - coerce_str(payload.get("ambiguity")), - coerce_str(payload.get("conflicts")), - coerce_str(payload.get("reasoning_summary")), - *[_evidence_label(item) for item in evidence_items], - ] - ) - ) - - -def _conflict_penalty(payload: dict[str, Any], evidence_items: list[dict[str, Any]]) -> float: - penalty = 0.0 - ambiguity_text = _ambiguity_text(payload, evidence_items) - cleaned_text = re.sub( - r"\b(?:no|without|not|zero)\s+(?:conflict|contradiction|ambiguity)s?\b|无冲突|未见矛盾", - " ", - ambiguity_text, - ) - if any( - token in cleaned_text - for token in ("conflict", "contradict", "inconsistent", "冲突", "矛盾", "不一致") - ): - penalty += 0.35 - if any( - _truthy_evidence_field(item, "has_conflict", "conflicting") - for item in evidence_items - ): - penalty += 0.35 - return min(penalty, 0.45) - - -def _weak_evidence_penalty( - payload: dict[str, Any], - evidence_items: list[dict[str, Any]], - *, - query: LocationQuery, - entity_match: float, - geography_match: float, - conflict_penalty: float, -) -> float: - ambiguity_text = _ambiguity_text(payload, evidence_items) - cleaned_text = re.sub(r"\b(?:no|without|not)\s+ambiguity\b|无歧义", " ", ambiguity_text) - penalty = 0.0 - if any( - token in cleaned_text - for token in ("ambiguous", "unclear", "weak", "guess", "存疑", "不确定", "猜测", "无法确认") - ): - penalty += 0.20 - if any(_truthy_evidence_field(item, "ambiguous") for item in evidence_items): - penalty += 0.15 - if _city_is_unsupported_name_hint(payload, query, evidence_items): - penalty += 0.10 - if conflict_penalty == 0.0 and entity_match > 0 and geography_match >= 0.20: - return min(penalty, 0.15) - return min(penalty, 0.30) - - -def _score_llm_location_payload( - payload: dict[str, Any], - *, - query: LocationQuery, - precision: str, -) -> LocationEvidenceScore: - model_confidence = parse_float(payload.get("confidence")) - model_confidence = min(max(model_confidence if model_confidence is not None else 0.0, 0.0), 1.0) - evidence_items = _evidence_items(payload.get("evidence")) - source_quality = _source_quality_score(evidence_items) - entity_match = _entity_match_score(payload, query, evidence_items) - geography_match = _geography_match_score(payload, query) - precision_quality = _precision_quality_score(precision) - conflict_penalty = _conflict_penalty(payload, evidence_items) - weak_evidence_penalty = _weak_evidence_penalty( - payload, - evidence_items, - query=query, - entity_match=entity_match, - geography_match=geography_match, - conflict_penalty=conflict_penalty, - ) - name_location_hint = _name_location_hint_score(payload, query) - score = ( - model_confidence * MODEL_CONFIDENCE_WEIGHT - + source_quality - + entity_match - + geography_match - + precision_quality - + name_location_hint - - conflict_penalty - - weak_evidence_penalty - ) - score = min(max(score, 0.0), 1.0) - if _city_is_unsupported_name_hint(payload, query, evidence_items): - score = min(score, 0.54) - summary = ( - f"combined={score:.2f}; model={model_confidence:.2f}; " - f"source={source_quality:.2f}; entity={entity_match:.2f}; " - f"geo={geography_match:.2f}; precision={precision_quality:.2f}; " - f"conflict={conflict_penalty:.2f}; weak={weak_evidence_penalty:.2f}; " - f"name_hint={name_location_hint:.2f}" - ) - return LocationEvidenceScore( - score=score, - model_confidence=model_confidence, - source_quality=source_quality, - entity_match=entity_match, - geography_match=geography_match, - precision_quality=precision_quality, - conflict_penalty=conflict_penalty, - weak_evidence_penalty=weak_evidence_penalty, - name_location_hint=name_location_hint, - summary=summary, - ) - - -def _candidate_from_payload( - payload: dict[str, Any], - *, - query: LocationQuery, - entity_type: str, - min_confidence: float, -) -> tuple[LocationCandidate | None, str | None]: - latitude, longitude = _extract_llm_coordinates(payload) - if ( - latitude in (None, 0.0) - or longitude in (None, 0.0) - or not (-90.0 <= latitude <= 90.0) - or not (-180.0 <= longitude <= 180.0) - ): - return None, "missing, invalid, or zero latitude/longitude" - - precision = _normalize_llm_precision(payload.get("precision")) - if precision not in VALID_LLM_PRECISIONS: - return None, f"precision '{payload.get('precision')}' is not precise/site/city" - - city = coerce_str(payload.get("city")) or query.city or None - payload_country = normalize_country_text(payload.get("country")) - expected_country = normalize_country_text(query.country) - if payload_country and expected_country and normalize_text(payload_country) != normalize_text(expected_country): - return None, f"country '{payload_country}' contradicts expected '{expected_country}'" - country = payload_country or expected_country or query.country - evidence_score = _score_llm_location_payload(payload, query=query, precision=precision) - if evidence_score.score < min_confidence: - return None, ( - f"combined evidence score {evidence_score.score:.2f} is below minimum " - f"{min_confidence}; {evidence_score.summary}" - ) - confidence = evidence_score.score - - matched_location_name = ( - coerce_str(payload.get("matched_location_name")) - or coerce_str(payload.get("display_name")) - or coerce_str(query.name) - or "LLM factcheck location" - ) - evidence = _compact_evidence(payload.get("evidence")) - reasoning_summary = coerce_str(payload.get("reasoning_summary")) - source_note_parts = ["LLM location factcheck fallback"] - if payload.get("coordinate_source") == "nominatim_city_fallback": - source_note_parts.append("coordinates: Nominatim city fallback") - if evidence: - source_note_parts.append(f"evidence: {evidence}") - if reasoning_summary: - source_note_parts.append(f"summary: {reasoning_summary}") - source_note_parts.append(f"score: {evidence_score.summary}") - - extra = query.extra or {} - matched_fields = tuple( - field - for field in ("name", "site", "operator", "organization", "city", "country") - if ( - (field in {"name", "city", "country"} and getattr(query, field, None)) - or coerce_str(extra.get(field)) - ) - ) or ("llm_factcheck",) - - return LocationCandidate( - latitude=float(latitude), - longitude=float(longitude), - display_name=matched_location_name, - precision=precision, - confidence=confidence, - query=f"llm_factcheck:{entity_type}:{coerce_str(query.name) or 'unknown'}", - source="llm_location_factcheck", - source_note="; ".join(source_note_parts), - matched_fields=matched_fields, - needs_confirmation=True, - city=city, - region=coerce_str(payload.get("region")) or query.region or None, - country=country or None, - matched_location_name=matched_location_name, - location_verified_at=None, - suggested_registry_entry={ - "canonical_name": matched_location_name, - "aliases": list( - { - value - for value in [ - coerce_str(query.name), - *[coerce_str(alias) for alias in query.aliases], - coerce_str(extra.get("operator")), - coerce_str(extra.get("site")), - ] - if value - } - ), - "operator": coerce_str(extra.get("operator")) or None, - "site": coerce_str(extra.get("site")) or None, - "country": country or None, - "city": city, - "region": coerce_str(payload.get("region")) or query.region or None, - "latitude": float(latitude), - "longitude": float(longitude), - "precision": precision, - "confidence": confidence, - "source_note": "; ".join(source_note_parts), - "llm_model_confidence": evidence_score.model_confidence, - "llm_combined_confidence": evidence_score.score, - "llm_score_breakdown": { - "source_quality": evidence_score.source_quality, - "entity_match": evidence_score.entity_match, - "geography_match": evidence_score.geography_match, - "precision_quality": evidence_score.precision_quality, - "conflict_penalty": evidence_score.conflict_penalty, - "weak_evidence_penalty": evidence_score.weak_evidence_penalty, - "name_location_hint": evidence_score.name_location_hint, - }, - }, - raw_payload={ - "llm_payload": payload, - "search_evidence": payload.get("search_evidence") or [], - }, - ), None - - -def _normalize_llm_payload(payload: dict[str, Any]) -> dict[str, Any]: - for key in ("candidate", "location", "result"): - nested = payload.get(key) - if isinstance(nested, dict): - return nested - return payload - - -def _query_context(query: LocationQuery) -> dict[str, Any]: - extra = dict(query.extra or {}) - return { - "name": query.name, - "aliases": list(query.aliases), - "city": query.city, - "region": query.region, - "country": query.country, - "source_latitude": query.source_latitude, - "source_longitude": query.source_longitude, - "extra": extra, - } - - -def _observations(query: LocationQuery, attempted_queries: Iterable[str]) -> list[str]: - extra = query.extra or {} - fields = [ - ("name", query.name), - ("aliases", ", ".join(query.aliases)), - ("site", extra.get("site")), - ("operator", extra.get("operator")), - ("organization", extra.get("organization")), - ("city", query.city), - ("region", query.region), - ("country", query.country), - ("source", extra.get("source")), - ("source_id", extra.get("source_id")), - ("collector", extra.get("collector")), - ] - observations = [ - f"{label}: {value}" - for label, value in fields - if coerce_str(value) - ] - attempts = [coerce_str(item) for item in attempted_queries if coerce_str(item)] - if attempts: - observations.append("previous resolver attempts: " + " | ".join(attempts[:12])) - return observations - - -def _location_search_query(query: LocationQuery, entity_type: str) -> str: - extra = query.extra or {} - parts = [ - coerce_str(query.name), - coerce_str(extra.get("site")), - coerce_str(extra.get("operator")), - coerce_str(extra.get("organization")), - coerce_str(query.city), - coerce_str(query.country), - "physical location", - ] - if entity_type == "bgp_collector": - parts.append("route collector city") - elif entity_type == "compute_center": - parts.append("datacenter supercomputer facility city") - return " ".join(part for part in parts if part) - - -async def collect_location_search_evidence( - *, - web_search_client: WebSearchClient, - query: LocationQuery, - entity_type: str, - max_results: int = 5, -) -> LocationSearchEvidenceResult: - search_query = _location_search_query(query, entity_type) - attempt = f"web_search:{entity_type}:{search_query}" - logger.info_event( - "Collecting location search evidence", - event="location.factcheck.web_search.start", - context={ - "entity_type": entity_type, - "search_query": search_query, - "location_query": _query_context(query), - "max_results": max_results, - }, - ) - try: - evidence = await web_search_client.search(search_query, max_results=max_results) - except WebSearchError as exc: - logger.warning_event( - "Location search evidence failed", - event="location.factcheck.web_search.failed", - context={ - "entity_type": entity_type, - "search_query": search_query, - "error": str(exc), - }, - ) - return LocationSearchEvidenceResult( - evidence=[], - attempted_queries=[attempt], - failure_reason=f"WebSearch location evidence failed: {exc}", - ) - except Exception as exc: - logger.warning_event( - "Location search evidence unavailable", - event="location.factcheck.web_search.unavailable", - context={ - "entity_type": entity_type, - "search_query": search_query, - "error": str(exc), - }, - ) - return LocationSearchEvidenceResult( - evidence=[], - attempted_queries=[attempt], - failure_reason=f"WebSearch location evidence unavailable: {exc}", - ) - normalized = normalize_search_evidence(evidence, limit=max_results) - if not normalized: - logger.warning_event( - "Location search returned no usable evidence", - event="location.factcheck.web_search.empty", - context={ - "entity_type": entity_type, - "search_query": search_query, - }, - ) - return LocationSearchEvidenceResult( - evidence=[], - attempted_queries=[attempt], - failure_reason="WebSearch returned no usable location evidence.", - ) - logger.info_event( - "Collected location search evidence", - event="location.factcheck.web_search.result", - context={ - "entity_type": entity_type, - "search_query": search_query, - "evidence_count": len(normalized), - "evidence": _summarize_search_evidence(normalized), - }, - ) - return LocationSearchEvidenceResult( - evidence=normalized, - attempted_queries=[attempt], - failure_reason=None, - ) - - -async def _repair_location_payload_from_text( - *, - provider_client: AIProviderClient, - raw_text: str, - query: LocationQuery, - entity_type: str, - db: AsyncSession | None = None, -) -> dict[str, Any] | None: - """Second-pass structure repair for models that answer in prose. - - The first LLM call owns the factcheck. This call is intentionally framed as - extraction/normalization only; it should not introduce new facts. - """ - if not coerce_str(raw_text): - return None - prompt = await get_effective_prompt(db, LOCATION_NORMALIZE_PROMPT_KEY) - request = SituationalAnalysisRequest( - title=f"Normalize location factcheck for {entity_type}", - objective=prompt.prompt, - system_prompt=prompt.system_prompt or None, - context={ - "entity_type": entity_type, - "location_query": _query_context(query), - "raw_location_factcheck_text": raw_text[:4000], - "required_json_schema": { - "latitude": "number|null", - "longitude": "number|null", - "precision": "precise|site|city", - "confidence": "number from 0 to 1", - "city": "string|null", - "region": "string|null", - "country": "string|null", - "matched_location_name": "string", - "evidence": "array of objects with source/source_type/entity_match/text/url when present", - "ambiguity": "string|null", - "reasoning_summary": "short string", - }, - }, - observations=[], - constraints=[ - "Return only strict JSON. Do not wrap it in markdown.", - "Do not add new evidence or locations that are not present in the supplied text.", - "If exact coordinates are absent but a city and country are present, set latitude and longitude to null and precision to city.", - "Use confidence 0.55-0.70 for credible city-level text; use lower confidence for weak or ambiguous text.", - ], - ) - try: - response = await provider_client.analyze(request) - except Exception: - return None - payload = _first_json_object(response.content) - return _normalize_llm_payload(payload) if isinstance(payload, dict) else None - - -async def collect_llm_location_fallback_candidate( - *, - provider_client: AIProviderClient, - query: LocationQuery, - entity_type: str, - db: AsyncSession | None = None, - attempted_queries: Iterable[str] = (), - search_evidence: list[dict[str, Any]] | None = None, - min_confidence: float = DEFAULT_MIN_CONFIDENCE, -) -> LocationLLMFallbackResult: - """Ask the configured LLM for one fact-checked location candidate. - - The result is intentionally conservative: invalid, low-confidence, or - non-city-level responses are treated as no candidate. Callers should only - use this in user-triggered collection flows. - """ - attempt = f"llm_factcheck:{entity_type}:{coerce_str(query.name) or 'unknown'}" - if search_evidence is not None and not search_evidence: - logger.warning_event( - "Skipping LLM location factcheck because search evidence is empty", - event="location.factcheck.llm.skipped_no_evidence", - context={ - "entity_type": entity_type, - "attempt": attempt, - "location_query": _query_context(query), - }, - ) - return LocationLLMFallbackResult( - candidates=[], - attempted_queries=[attempt], - failure_reason="LLM location factcheck skipped: no WebSearch evidence.", - ) - prompt = await get_effective_prompt(db, LOCATION_RESOLVE_PROMPT_KEY) - request = SituationalAnalysisRequest( - title=f"Location factcheck fallback for {entity_type}", - objective=prompt.prompt, - system_prompt=prompt.system_prompt or None, - context={ - "entity_type": entity_type, - "location_query": _query_context(query), - "search_evidence": search_evidence or [], - "required_json_schema": { - "latitude": "number", - "longitude": "number", - "precision": "precise|site|city", - "confidence": "number from 0 to 1", - "city": "string|null", - "region": "string|null", - "country": "string|null", - "matched_location_name": "string", - "evidence": "array of short source/evidence phrases", - "evidence[].source_type": "official|government|academic|database|news|generic", - "evidence[].entity_match": "boolean when the evidence names the queried entity", - "ambiguity": "string|null describing same-name conflicts or contradictory sources", - "reasoning_summary": "short string", - }, - }, - observations=_observations(query, attempted_queries), - constraints=[ - "Return only strict JSON. Do not wrap it in markdown.", - "Do not return country-level, regional-only, or unknown precision.", - "Do not invent coordinates. Use lower confidence when evidence is incomplete.", - "Calibrate model confidence using this rubric: 0.85-1.0 for exact facility coordinates backed by an authoritative source; 0.70-0.84 for a confirmed facility/campus with strong public evidence; 0.55-0.69 for a confirmed city-level location backed by credible sources but without exact facility coordinates; 0.35-0.54 for weak or ambiguous city evidence; below 0.35 when the location is mostly a guess.", - "Return evidence as objects when possible, including source, url, source_type, and entity_match.", - "Include source names or URLs in evidence when known. The backend will recompute the final confidence from model confidence plus evidence quality.", - "If search_evidence is provided, use only that evidence as factual support.", - "Do not treat a website footer, office address, publisher address, or contact address as the entity's physical location.", - "If the entity name contains a city name, do not choose that city unless evidence explicitly says the entity/facility/supercomputer is located, hosted, built, deployed, or installed there.", - "Prefer the facility/site if known; otherwise use the best supported city.", - ], - ) - logger.info_event( - "Sending location factcheck request to LLM", - event="location.factcheck.llm.request", - context={ - "entity_type": entity_type, - "attempt": attempt, - "title": request.title, - "objective": request.objective, - "location_query": request.context.get("location_query"), - "observations": request.observations, - "constraints": request.constraints, - "search_evidence_count": len(search_evidence or []), - "search_evidence": _summarize_search_evidence(search_evidence), - }, - ) - try: - response = await provider_client.analyze(request) - except Exception as exc: - logger.warning_event( - "LLM location factcheck failed", - event="location.factcheck.llm.failed", - context={ - "entity_type": entity_type, - "attempt": attempt, - "error": str(exc), - }, - ) - return LocationLLMFallbackResult( - candidates=[], - attempted_queries=[attempt], - failure_reason=f"LLM location factcheck failed: {exc}", - ) - - logger.info_event( - "Received location factcheck response from LLM", - event="location.factcheck.llm.response", - context={ - "entity_type": entity_type, - "attempt": attempt, - "provider": response.provider, - "model": response.model, - "content": _truncate_log_text(response.content, 2000), - }, - ) - payload = _first_json_object(response.content) - if payload is None: - logger.warning_event( - "LLM location factcheck response was not strict JSON; attempting repair", - event="location.factcheck.llm.non_json", - context={ - "entity_type": entity_type, - "attempt": attempt, - "content": _truncate_log_text(response.content, 1200), - }, - ) - payload = await _repair_location_payload_from_text( - provider_client=provider_client, - raw_text=response.content, - query=query, - entity_type=entity_type, - db=db, - ) - if payload is None: - payload = _payload_from_free_text(response.content, query=query) - if payload is None and entity_type != "compute_center": - payload = _payload_from_query_name_geocode(query) - if payload is None: - logger.warning_event( - "LLM location factcheck produced no parseable payload", - event="location.factcheck.llm.unparseable", - context={ - "entity_type": entity_type, - "attempt": attempt, - }, - ) - return LocationLLMFallbackResult( - candidates=[], - attempted_queries=[attempt], - failure_reason=( - "LLM location factcheck did not return a parseable city-level " - "location fact." - ), - ) - payload = _normalize_llm_payload(payload) - if search_evidence: - payload["search_evidence"] = search_evidence - existing_evidence = _evidence_items(payload.get("evidence")) - search_by_url = { - str(item.get("url")).strip(): item - for item in search_evidence - if isinstance(item, dict) and item.get("url") - } - enriched_evidence = [] - for item in existing_evidence: - url = coerce_str(item.get("url")) - matched_search = search_by_url.get(url) - if matched_search is not None: - enriched_evidence.append( - { - **item, - "entity_match": item.get("entity_match") or _search_evidence_entity_match(matched_search, query), - } - ) - else: - enriched_evidence.append(item) - payload["evidence"] = enriched_evidence - latitude, longitude = _extract_llm_coordinates(payload) - city_geocode_failure = None - if latitude in (None, 0.0) or longitude in (None, 0.0): - payload, city_geocode_failure = _fill_city_coordinates_from_geocoder( - payload, - query=query, - ) - candidate, rejection_reason = _candidate_from_payload( - payload, - query=query, - entity_type=entity_type, - min_confidence=min_confidence, - ) - if candidate is None: - if city_geocode_failure and rejection_reason == "missing, invalid, or zero latitude/longitude": - rejection_reason = f"{rejection_reason}; {city_geocode_failure}" - logger.warning_event( - "Rejected LLM location factcheck candidate", - event="location.factcheck.llm.rejected", - context={ - "entity_type": entity_type, - "attempt": attempt, - "reason": rejection_reason, - "payload": payload, - "search_evidence_count": len(search_evidence or []), - "search_evidence": _summarize_search_evidence(search_evidence), - }, - ) - return LocationLLMFallbackResult( - candidates=[], - attempted_queries=[attempt], - failure_reason=( - "LLM location factcheck returned no acceptable city-level candidate" - + (f": {rejection_reason}." if rejection_reason else ".") - ), - ) - logger.info_event( - "Accepted LLM location factcheck candidate", - event="location.factcheck.llm.accepted", - context={ - "entity_type": entity_type, - "attempt": attempt, - "candidate": candidate.to_dict(), - "payload": payload, - "search_evidence_count": len(search_evidence or []), - "search_evidence": _summarize_search_evidence(search_evidence), - }, - ) - return LocationLLMFallbackResult( - candidates=[candidate], - attempted_queries=[attempt], - failure_reason=None, - ) diff --git a/backend/app/services/location/resolvers/nominatim.py b/backend/app/services/location/resolvers/nominatim.py index 3f5f04a2..5f476c44 100644 --- a/backend/app/services/location/resolvers/nominatim.py +++ b/backend/app/services/location/resolvers/nominatim.py @@ -21,6 +21,7 @@ from typing import Any, Callable import httpx +from app.core.countries import normalize_country from app.core.logging import get_logger from ..models import LocationCandidate, LocationQuery, ResolverOutput @@ -71,8 +72,12 @@ def build_default_nominatim_geocoder( "format": "jsonv2", "limit": 1, "addressdetails": 1, + "accept-language": "en", + }, + headers={ + "User-Agent": user_agent, + "Accept-Language": "en", }, - headers={"User-Agent": user_agent}, timeout=timeout_seconds, ) response.raise_for_status() @@ -125,6 +130,42 @@ _DEFAULT_SITE_CATEGORIES = frozenset( ) +def resolve_geocoder_country( + address: dict[str, Any] | None, + raw_result: dict[str, Any] | None = None, +) -> str: + """Resolve canonical country from explicit name/multilingual parts first, then ISO country_code.""" + addr = address if isinstance(address, dict) else {} + raw = raw_result if isinstance(raw_result, dict) else {} + + for candidate in (addr.get("country"), raw.get("country")): + text = coerce_str(candidate) + if not text: + continue + direct = normalize_country(text) + if direct: + return direct + if "/" in text: + for part in text.split("/"): + part_canonical = normalize_country(part.strip()) + if part_canonical: + return part_canonical + + for code in (addr.get("country_code"), raw.get("country_code")): + code_text = coerce_str(code) + if code_text: + code_canonical = normalize_country(code_text) + if code_canonical: + return code_canonical + + return normalize_country_text( + addr.get("country") + or raw.get("country") + or addr.get("country_code") + or raw.get("country_code") + ) + + def interpret_geocode_result( result: dict[str, Any], *, @@ -161,9 +202,7 @@ def interpret_geocode_result( if context_country: normalized_context = normalize_text(normalize_country_text(context_country)) - normalized_result = normalize_text( - normalize_country_text(address.get("country")) - ) + normalized_result = normalize_text(resolve_geocoder_country(address, result)) if ( normalized_context and normalized_result @@ -211,7 +250,7 @@ def _candidate_from_geocode( or None ) region = address.get("state") or address.get("region") - country = address.get("country") or query.country or None + country = resolve_geocoder_country(address, raw_result) or query.country or None display_name = raw_result.get("display_name") or geocode_query confidence = city_confidence if classification == "city" else site_confidence diff --git a/backend/app/services/location/resolvers/peeringdb_facility.py b/backend/app/services/location/resolvers/peeringdb_facility.py index bfa11904..95998c28 100644 --- a/backend/app/services/location/resolvers/peeringdb_facility.py +++ b/backend/app/services/location/resolvers/peeringdb_facility.py @@ -15,22 +15,51 @@ PEERINGDB_USER_AGENT = "Planet-Intelligence-System/1.0" PEERINGDB_TIMEOUT_SECONDS = 6.0 +_GENERIC_OPERATOR_NAMES = frozenset( + { + "google", + "ibm", + "microsoft", + "amazon", + "aws", + "meta", + "facebook", + "nebius", + "nebius ai", + "oracle", + "alibaba", + "tencent", + "bytedance", + "nvidia", + "apple", + "openai", + "xai", + "equinix", + "digital realty", + "coreweave", + "lambda", + } +) + + async def lookup_peeringdb_facility( query: LocationQuery, *, timeout_seconds: float = PEERINGDB_TIMEOUT_SECONDS, ) -> ResolverOutput: - """Query PeeringDB facilities matching the target site/operator/name.""" + """Query PeeringDB facilities matching the target site/name (never generic operator alone).""" extra = query.extra or {} search_terms: list[str] = [] for raw in [ extra.get("site"), - extra.get("operator"), *(query.aliases or ()), query.name, ]: cleaned = coerce_str(raw) - if cleaned and len(cleaned) >= 3 and cleaned not in search_terms: + norm = normalize_text(cleaned) + if not cleaned or len(cleaned) < 3 or norm in _GENERIC_OPERATOR_NAMES: + continue + if cleaned not in search_terms: search_terms.append(cleaned) if not search_terms: return ResolverOutput() diff --git a/backend/app/services/location/resolvers/wikidata.py b/backend/app/services/location/resolvers/wikidata.py index 753ffd9a..4300feca 100644 --- a/backend/app/services/location/resolvers/wikidata.py +++ b/backend/app/services/location/resolvers/wikidata.py @@ -80,6 +80,44 @@ async def lookup_wikidata_facility( continue term_tokens = set(normalize_text(term).split()) + expected_country = normalize_text(normalize_country_text(query.country)) + country_qids: set[str] = set() + if expected_country: + for entity in entities.values(): + if not isinstance(entity, dict): + continue + for p17 in (entity.get("claims") or {}).get("P17") or []: + dataval = (((p17.get("mainsnak") or {}).get("datavalue") or {}).get("value") if isinstance(p17, dict) else None) + if isinstance(dataval, dict) and dataval.get("id"): + country_qids.add(str(dataval["id"])) + country_labels: dict[str, list[str]] = {} + if country_qids: + try: + c_resp = await client.get( + WIKIDATA_API_URL, + params={ + "action": "wbgetentities", + "ids": "|".join(sorted(country_qids)[:12]), + "props": "labels", + "languages": "en|zh", + "format": "json", + }, + ) + c_resp.raise_for_status() + for c_qid, c_ent in ((c_resp.json() or {}).get("entities") or {}).items(): + if not isinstance(c_ent, dict): + continue + c_labels = c_ent.get("labels") or {} + vals = [ + coerce_str((c_labels.get(lang) or {}).get("value")) + for lang in ("en", "zh") + if coerce_str((c_labels.get(lang) or {}).get("value")) + ] + if vals: + country_labels[c_qid] = vals + except Exception: + country_labels = {} + for qid, entity in entities.items(): if not isinstance(entity, dict): continue @@ -97,6 +135,18 @@ async def lookup_wikidata_facility( continue claims = entity.get("claims") or {} + resolved_p17_countries: list[str] = [] + for p17 in claims.get("P17") or []: + dataval = (((p17.get("mainsnak") or {}).get("datavalue") or {}).get("value") if isinstance(p17, dict) else None) + c_qid = str(dataval.get("id") or "") if isinstance(dataval, dict) else "" + for raw_label in country_labels.get(c_qid, []): + norm_c = normalize_country_text(raw_label) or raw_label + if norm_c and norm_c not in resolved_p17_countries: + resolved_p17_countries.append(norm_c) + if expected_country and resolved_p17_countries: + if not any(normalize_text(c) == expected_country for c in resolved_p17_countries): + continue + coord_claims = claims.get("P625") or [] for claim in coord_claims: mainsnak = claim.get("mainsnak") if isinstance(claim, dict) else None @@ -113,7 +163,11 @@ async def lookup_wikidata_facility( or not (-180.0 <= lon <= 180.0) ): continue - country = normalize_country_text(query.country) + country = ( + resolved_p17_countries[0] + if resolved_p17_countries + else normalize_country_text(query.country) + ) candidates.append( LocationCandidate( latitude=lat, @@ -129,7 +183,11 @@ async def lookup_wikidata_facility( city=query.city or None, country=country or query.country, matched_location_name=label or term, - raw_payload={"wikidata_qid": qid, "description": desc}, + raw_payload={ + "wikidata_qid": qid, + "description": desc, + **({"wikidata_country": resolved_p17_countries[0]} if resolved_p17_countries else {}), + }, ) ) break diff --git a/backend/app/services/location/workflow_tools.py b/backend/app/services/location/workflow_tools.py new file mode 100644 index 00000000..e16ae0cd --- /dev/null +++ b/backend/app/services/location/workflow_tools.py @@ -0,0 +1,1438 @@ +"""Atomic workflow tools, cascade geocoder, and L3 geo guardrails for `location.resolve_unknown`.""" + +from __future__ import annotations + +import asyncio +import copy +from dataclasses import dataclass +from datetime import UTC, datetime +import re +from typing import Any +from uuid import uuid4 + +from sqlalchemy import select + +from app.core.cache import cache +from app.core.collected_data_fields import get_record_field +from app.core.compute_types import compute_record_filter +from app.core.countries import get_country_search_variants +from app.core.logging import get_logger +from app.services.earth_layer_cache import invalidate_earth_layer_cache_for_source +from app.models.ai_workflow import AIWorkflow +from app.models.collected_data import CollectedData +from app.models.compute_center_location import ComputeCenterLocationRecord +from app.models.situational_assessment import WorkflowRun +from app.services.ai.dag_evidence import ( + EvidenceLedger, + is_tabular_dataset_url, + normalize_evidence_url, +) +from app.services.ai.tool_registry import isolate_untrusted_external_text, safe_web_fetch +from app.services.ai_tools.web_search import normalize_web_search_provider +from app.services.bgp_collector_locations import ( + build_bgp_collector_location_query, + collect_bgp_collector_location_candidates, + get_bgp_collector_location_dict, +) +from app.services.compute_center_locations import ( + COMPUTE_CENTER_LOCATION_CACHE, + _short_system_name, + build_compute_center_location_query, + collect_location_candidates, + get_compute_center_location_dict, + refresh_compute_center_location_cache, +) +from app.services.location.models import LocationCandidate, LocationQuery +from app.services.location.resolvers.nominatim import ( + _DEFAULT_SITE_CATEGORIES, + build_default_nominatim_geocoder, + resolve_geocoder_country, +) +from app.services.location.resolvers.peeringdb_facility import lookup_peeringdb_facility +from app.services.location.resolvers.wikidata import lookup_wikidata_facility +from app.services.location.text import ( + coerce_str, + normalize_country_text, + normalize_text, + parse_float, +) + +logger = get_logger(__name__, service="location_workflow") + +DEFAULT_MIN_CONFIDENCE = 0.55 +TERMINAL_UNLOCATABLE_STATUSES: frozenset[str] = frozenset( + {"undisclosed", "multi_site", "planned", "cloud_only", "anonymous"} +) +_PAREN_EVIDENCE_ID_RE = re.compile( + r"[\(\(\[]\s*E\d{1,3}(?:[\s,、/&\-–—]+E?\d{1,3})*\s*[\)\)\]]" +) +_BARE_EVIDENCE_ID_RE = re.compile( + r"(? str: + """Remove internal evidence IDs (e.g., E6, E1-E5, (E3)) and tidy orphaned punctuation.""" + cleaned = coerce_str(text) + if not cleaned: + return "" + cleaned = _PAREN_EVIDENCE_ID_RE.sub("", cleaned) + cleaned = _BARE_EVIDENCE_ID_RE.sub("", cleaned) + cleaned = _EMPTY_PARENS_RE.sub("", cleaned) + cleaned = _ORPHAN_LIST_SEP_RE.sub(r"\1 ", cleaned) + cleaned = _SPACE_BEFORE_PUNCT_RE.sub(r"\1", cleaned) + cleaned = re.sub(r"\s{2,}", " ", cleaned) + cleaned = re.sub(r"^[,,、;;:\s]+", "", cleaned) + cleaned = re.sub(r"(\s+[,,、])+", "", cleaned) + return cleaned.strip() + + +_agent_geocoder = build_default_nominatim_geocoder() + + +@dataclass(frozen=True) +class LocationAgentResult: + candidates: list[LocationCandidate] + attempted_queries: list[str] + failure_reason: str | None = None + workflow_run_id: str | None = None + terminal_status: str | None = None + + +_BASE_JUDGE_PROPERTIES: dict[str, Any] = { + "facility_name": {"type": "string", "description": "Physical data center / campus / lab name"}, + "address": {"type": "string", "description": "Street address if explicitly attested in evidence"}, + "city": {"type": "string", "description": "Physical city/town/locality name (required for located)"}, + "region": {"type": "string", "description": "State / province / region if known"}, + "country": {"type": "string", "description": "Actual physical country in English (e.g. United States, Iceland)"}, + "country_override_reason": { + "type": "string", + "description": "当物理部署国与源登记国不同时必填;使用简洁简体中文(不超过 120 字),禁止出现 E1 等证据编号", + }, + "precision": {"type": "string", "enum": ["precise", "site", "city"]}, + "confidence": {"type": "number", "description": "0.0-1.0 evidence confidence"}, + "evidence_ids": { + "type": "array", + "items": {"type": "string"}, + "description": "Evidence IDs observed in input evidence list (e.g. ['E1', 'E3'])", + }, + "reasoning": { + "type": "string", + "description": "使用简洁简体中文(不超过 120 字)说明核验结论与依据,禁止出现 E1、E1-E5 等内部证据编号", + }, +} + +LOCATION_JUDGE_R1_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "decision": { + "type": "string", + "enum": [ + "located", + "need_followup", + "undisclosed", + "multi_site", + "planned", + "cloud_only", + "anonymous", + "unresolved", + ], + }, + **_BASE_JUDGE_PROPERTIES, + "followup_queries": { + "type": "array", + "items": {"type": "string"}, + "description": "Up to 2 short English search queries when decision='need_followup'", + }, + "fetch_urls": { + "type": "array", + "items": {"type": "string"}, + "description": "Up to 2 promising evidence URLs from R1 requiring full-page fetch", + }, + }, + "required": ["decision", "reasoning"], +} + +LOCATION_JUDGE_FINAL_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "decision": { + "type": "string", + "enum": [ + "located", + "undisclosed", + "multi_site", + "planned", + "cloud_only", + "anonymous", + "unresolved", + ], + }, + **_BASE_JUDGE_PROPERTIES, + }, + "required": ["decision", "reasoning"], +} + + +def english_country_name(value: Any) -> str: + """Return the English country name via the shared registry for search and Nominatim.""" + canonical = normalize_country_text(value) + if not canonical: + return "" + for variant in get_country_search_variants(canonical): + if variant != canonical and variant.isascii() and len(variant) > 2: + return variant + return canonical + + +def get_evidence_ledger(workflow_state: dict[str, Any]) -> EvidenceLedger: + ledger = workflow_state.get("evidence_ledger") + if isinstance(ledger, EvidenceLedger): + return ledger + ledger = EvidenceLedger() + workflow_state["evidence_ledger"] = ledger + return ledger + + +async def load_cross_source_compute_hints( + db: Any, + *, + name: str | None, + source: str | None, + source_id: str, +) -> tuple[list[str], str | None, str | None, list[dict[str, Any]]]: + """Gather sibling compute records from other sources (e.g. Epoch AI <-> TOP500).""" + short_name = _short_system_name(name) + norm_short = normalize_text(short_name) + if db is None or not hasattr(db, "execute") or len(norm_short) < 4: + return [], None, None, [] + try: + stmt = ( + select(CollectedData) + .where(compute_record_filter(CollectedData)) + .where(CollectedData.is_current.is_(True)) + .where(CollectedData.deleted_at.is_(None)) + .where(CollectedData.name.ilike(f"%{short_name}%")) + .limit(8) + ) + rows = (await db.execute(stmt)).scalars().all() + except Exception: + return [], None, None, [] + + extra_sources: list[str] = [] + extra_source_url: str | None = None + extra_builds_upon: str | None = None + hints: list[dict[str, Any]] = [] + for row in rows: + row_source = getattr(row, "source", None) + row_sid = getattr(row, "source_id", None) + if not row_source or not row_sid: + continue + if row_sid == source_id or (source and row_source == source): + continue + row_short = normalize_text(_short_system_name(getattr(row, "name", None))) + if norm_short not in row_short and row_short not in norm_short: + continue + meta = getattr(row, "extra_data", None) or {} + if not isinstance(meta, dict): + meta = {} + row_sources = [str(u).strip() for u in (meta.get("sources") or []) if str(u or "").strip()] + for u in row_sources: + if u not in extra_sources: + extra_sources.append(u) + if not extra_source_url and (meta.get("source_url") or meta.get("detail_url")): + cand_url = str(meta.get("source_url") or meta.get("detail_url")).strip() + if cand_url and not is_tabular_dataset_url(cand_url): + extra_source_url = cand_url + if not extra_builds_upon and meta.get("builds_upon"): + extra_builds_upon = str(meta["builds_upon"]).strip() + hints.append( + { + "source": row_source, + "source_id": row_sid, + "name": getattr(row, "name", None), + "country": get_record_field(row, "country"), + "raw_country": meta.get("raw_country"), + "location": meta.get("location"), + "sources": row_sources[:3], + } + ) + return extra_sources, extra_source_url, extra_builds_upon, hints + + +async def _load_compute_record_by_source_id(db: Any, source_id: str) -> CollectedData | None: + if not source_id or source_id == "unresolved" or db is None or not hasattr(db, "execute"): + return None + try: + stmt = ( + select(CollectedData) + .where(compute_record_filter(CollectedData)) + .where(CollectedData.is_current.is_(True)) + .where(CollectedData.source_id == source_id) + .order_by(CollectedData.id.desc()) + .limit(1) + ) + return (await db.execute(stmt)).scalars().first() + except Exception: + return None + + +async def tool_location_normalize_context( + db: Any, + *, + question: str, + targets: list[dict[str, Any]], + earth_context: dict[str, Any], + node_params: dict[str, Any], + workflow_state: dict[str, Any], +) -> dict[str, Any]: + """L0 tool: hydrate record + cross-source hints, normalize names/countries, short-circuit cached terminals.""" + first = targets[0] if targets else {} + props = first.get("properties") if isinstance(first.get("properties"), dict) else {} + raw_sid = coerce_str( + first.get("entity_id") or first.get("id") or earth_context.get("source_id") + ) + source_id = "" if raw_sid == "unresolved" else raw_sid + entity_type = coerce_str( + earth_context.get("entity_type") or first.get("entity_type") or "compute_center" + ).lower() + if entity_type not in {"bgp_collector", "compute_center"}: + entity_type = "bgp_collector" if "collector" in entity_type else "compute_center" + + pre_query = workflow_state.get("preset_query") + if isinstance(pre_query, LocationQuery): + query = pre_query + source_id = coerce_str((query.extra or {}).get("source_id")) or source_id + elif entity_type == "bgp_collector": + collector_id = coerce_str(earth_context.get("collector_id") or source_id or first.get("label") or question) + legacy = get_bgp_collector_location_dict(collector_id) or {} + query = build_bgp_collector_location_query( + collector=collector_id, + site=coerce_str(earth_context.get("site")) or legacy.get("matched_location_name") or None, + city=coerce_str(earth_context.get("city")) or legacy.get("city") or None, + country=coerce_str(earth_context.get("country")) or legacy.get("country") or None, + operator=coerce_str(earth_context.get("operator")) or "RIPE NCC", + ) + source_id = collector_id + else: + record = await _load_compute_record_by_source_id(db, source_id) + meta = (record.extra_data or {}) if record and isinstance(record.extra_data, dict) else {} + clean_q = coerce_str(question) + if clean_q.startswith("/locate"): + clean_q = clean_q[len("/locate") :].strip() + name = ( + coerce_str(earth_context.get("name")) + or coerce_str(first.get("label")) + or (coerce_str(getattr(record, "name", None)) if record else "") + or coerce_str(props.get("name")) + or clean_q + or source_id + or "Unknown Facility" + ) + source = coerce_str(earth_context.get("source")) or (coerce_str(getattr(record, "source", None)) if record else "") + operator = ( + coerce_str(earth_context.get("operator")) + or coerce_str(props.get("operator")) + or coerce_str(meta.get("operator") or meta.get("organization") or meta.get("owner")) + ) + site = coerce_str(earth_context.get("site") or props.get("site") or meta.get("site")) + organization = coerce_str(earth_context.get("organization") or meta.get("organization")) + city = coerce_str( + earth_context.get("city") + or props.get("city") + or (get_record_field(record, "city") if record else "") + ) + country = coerce_str( + earth_context.get("country") + or props.get("country") + or (get_record_field(record, "country") if record else "") + ) + raw_sources = [ + coerce_str(u) + for u in ( + earth_context.get("sources") + or props.get("sources") + or (meta.get("sources") if isinstance(meta.get("sources"), list) else []) + ) + if coerce_str(u) + ] + source_url = coerce_str( + earth_context.get("source_url") + or props.get("source_url") + or meta.get("source_url") + or meta.get("detail_url") + ) + builds_upon = coerce_str(earth_context.get("builds_upon") or meta.get("builds_upon")) + source_raw_country = coerce_str(earth_context.get("source_raw_country") or meta.get("raw_country")) + + sib_sources, sib_url, sib_builds_upon, cross_source_hints = await load_cross_source_compute_hints( + db, name=name, source=source or None, source_id=source_id + ) + for u in sib_sources: + if u not in raw_sources: + raw_sources.append(u) + if (not source_url or is_tabular_dataset_url(source_url)) and sib_url: + source_url = sib_url + if not builds_upon and sib_builds_upon: + builds_upon = sib_builds_upon + + query = build_compute_center_location_query( + name=name, + source=source or None, + source_id=source_id or None, + operator=operator or None, + site=site or None, + city=city or None, + country=country or None, + organization=organization or None, + sources=raw_sources, + source_url=source_url or None, + builds_upon=builds_upon or None, + source_raw_country=source_raw_country or None, + cross_source_hints=cross_source_hints, + ) + + extra = dict(query.extra or {}) + extra_source = coerce_str(extra.get("source")) + extra_sid = coerce_str(extra.get("source_id")) or source_id + force = bool(earth_context.get("force", False)) + short_circuit = bool(node_params.get("short_circuit_terminal_statuses", True)) + + if entity_type == "compute_center" and not COMPUTE_CENTER_LOCATION_CACHE and db is not None: + try: + await refresh_compute_center_location_cache(db) + except Exception: + pass + + terminal_status: str | None = None + terminal_note = "" + if entity_type == "compute_center" and not force and short_circuit and extra_source and extra_sid: + cached = get_compute_center_location_dict(extra_source, extra_sid) + cached_status = coerce_str(cached.get("verification_status")).lower() + if cached_status in TERMINAL_UNLOCATABLE_STATUSES: + terminal_status = cached_status + terminal_note = coerce_str(cached.get("source_note")) or f"Marked as {cached_status}" + + raw_urls = [ + coerce_str(u) + for u in [*([extra.get("source_url")] if extra.get("source_url") else []), *(extra.get("sources") or [])] + if coerce_str(u).startswith(("http://", "https://")) and not is_tabular_dataset_url(u) + ] + dedup_urls: list[str] = [] + seen_norm: set[str] = set() + for u in raw_urls: + nu = normalize_evidence_url(u) + if nu and nu not in seen_norm: + seen_norm.add(nu) + dedup_urls.append(u) + + ctx_payload = { + "entity_type": entity_type, + "source": extra_source or None, + "source_id": extra_sid or None, + "record_id": earth_context.get("record_id"), + "name": query.name, + "name_short": query.aliases[0] if query.aliases else query.name, + "operator": extra.get("operator") or None, + "site": extra.get("site") or None, + "city": query.city, + "country": query.country, + "country_en": english_country_name(query.country), + "raw_country": extra.get("source_raw_country") or None, + "primary_source_urls": dedup_urls[:5], + "cross_source_hints": list(extra.get("cross_source_hints") or [])[:4], + } + + workflow_state["entity_type"] = entity_type + workflow_state["location_query"] = query + workflow_state["location_ctx"] = ctx_payload + workflow_state.setdefault("attempted_queries", []) + if terminal_status: + workflow_state["terminal_status"] = terminal_status + workflow_state["failure_reason"] = terminal_note + workflow_state["resolution_stage"] = f"l0_short_circuit:{terminal_status}" + + return { + "is_terminal": bool(terminal_status), + "terminal_status": terminal_status, + "source_note": terminal_note, + "context": ctx_payload, + } + + +async def tool_location_knowledge_lookup( + db: Any, + *, + question: str, + targets: list[dict[str, Any]], + earth_context: dict[str, Any], + node_params: dict[str, Any], + workflow_state: dict[str, Any], +) -> dict[str, Any]: + """L1 deterministic lookup: builds_upon, ROR, parallel Wikidata(P17) & PeeringDB; Nominatim only when city exists.""" + query = workflow_state.get("location_query") + if not isinstance(query, LocationQuery): + norm = await tool_location_normalize_context( + db, + question=question, + targets=targets, + earth_context=earth_context, + node_params={}, + workflow_state=workflow_state, + ) + if norm.get("is_terminal"): + return {"high_confidence_hit": False, "candidates_count": 0, "candidates": [], "resolver_log": []} + query = workflow_state["location_query"] + + entity_type = str(workflow_state.get("entity_type") or "compute_center") + attempted: list[str] = list(workflow_state.get("attempted_queries") or []) + resolver_log: list[str] = [] + candidates: list[LocationCandidate] = [] + extra = dict(query.extra or {}) + + if entity_type == "bgp_collector": + bgp_cands, bgp_queries = await asyncio.to_thread( + collect_bgp_collector_location_candidates, + collector=coerce_str(extra.get("collector") or query.name), + site=coerce_str(extra.get("site")) or None, + city=query.city, + country=query.country, + operator=coerce_str(extra.get("operator")) or "RIPE NCC", + ) + attempted.extend(bgp_queries) + candidates = list(bgp_cands) + resolver_log.append("l1_knowledge:bgp_collector") + else: + raw_sources = list(extra.get("sources") or []) + local_cands, local_queries = await asyncio.to_thread( + collect_location_candidates, + name=query.name, + source=coerce_str(extra.get("source")) or None, + source_id=coerce_str(extra.get("source_id")) or None, + operator=coerce_str(extra.get("operator")) or None, + site=coerce_str(extra.get("site")) or None, + organization=coerce_str(extra.get("organization")) or None, + city=query.city, + country=query.country, + sources=raw_sources, + source_url=coerce_str(extra.get("source_url")) or None, + builds_upon=coerce_str(extra.get("builds_upon")) or None, + source_raw_country=coerce_str(extra.get("source_raw_country")) or None, + include_builds_upon=bool(node_params.get("builds_upon_enabled", True)), + include_ror=bool(node_params.get("ror_enabled", True)), + include_nominatim=False, + ) + attempted.extend(local_queries) + if extra.get("builds_upon"): + resolver_log.append("l1_knowledge:builds_upon_inherit") + if node_params.get("ror_enabled", True): + resolver_log.append("l1_knowledge:ror_lookup") + candidates = list(local_cands) + + if not candidates: + tasks = [] + if node_params.get("wikidata_enabled", True): + tasks.append(lookup_wikidata_facility(query)) + resolver_log.append("l1_knowledge:wikidata_lookup") + if node_params.get("peeringdb_enabled", True): + tasks.append(lookup_peeringdb_facility(query)) + resolver_log.append("l1_knowledge:peeringdb_fac_lookup") + if tasks: + for out in await asyncio.gather(*tasks, return_exceptions=True): + if isinstance(out, Exception): + continue + attempted.extend(out.attempted_queries) + candidates.extend(out.candidates) + + # Only run fast city Nominatim lookup if metadata already supplies an explicit city. + if not candidates and coerce_str(query.city): + nom_cands, nom_queries = await asyncio.to_thread( + collect_location_candidates, + name=query.name, + source=coerce_str(extra.get("source")) or None, + source_id=coerce_str(extra.get("source_id")) or None, + operator=coerce_str(extra.get("operator")) or None, + site=coerce_str(extra.get("site")) or None, + organization=coerce_str(extra.get("organization")) or None, + city=query.city, + country=query.country, + sources=raw_sources, + source_url=coerce_str(extra.get("source_url")) or None, + builds_upon=coerce_str(extra.get("builds_upon")) or None, + source_raw_country=coerce_str(extra.get("source_raw_country")) or None, + include_builds_upon=False, + include_ror=False, + include_nominatim=True, + ) + attempted.extend(nom_queries) + candidates = list(nom_cands) + resolver_log.append("l1_knowledge:explicit_city_nominatim") + + workflow_state["attempted_queries"] = list(dict.fromkeys(attempted)) + workflow_state["l1_candidates"] = candidates + if candidates: + workflow_state["resolution_stage"] = "l1_knowledge" + + return { + "high_confidence_hit": bool(candidates), + "candidates_count": len(candidates), + "candidates": [c.to_dict() for c in candidates[:5]], + "resolver_log": resolver_log, + } + + +async def _fetch_one_url(url: str, ledger: EvidenceLedger, attempted: list[str]) -> str | None: + attempted.append(f"fetch_url:{url}") + try: + fetched = await safe_web_fetch(url) + isolated = isolate_untrusted_external_text( + fetched.final_url or fetched.url, + fetched.title, + fetched.text, + max_chars=1800, + ) + excerpt = coerce_str(isolated.get("excerpt") or isolated.get("title")) + if excerpt: + ledger.record_call() + return ledger.add( + url=str(fetched.final_url or fetched.url or url), + title=str(fetched.title or ""), + snippet=excerpt, + tool="fetch_source_url", + ) + except Exception: + return None + return None + + +async def _search_one_query(q: str, client: Any, ledger: EvidenceLedger, attempted: list[str]) -> list[str]: + attempted.append(f"web_search:{q}") + added: list[str] = [] + try: + results = await client.search(q, max_results=5) + if results: + ledger.record_call() + for item in results: + eid = ledger.add( + url=coerce_str(getattr(item, "url", "")), + title=coerce_str(getattr(item, "title", "")), + snippet=coerce_str(getattr(item, "snippet", "") or getattr(item, "content", ""))[:500], + tool="web_search", + query=q, + ) + if eid: + added.append(eid) + except Exception: + return [] + return added + + +async def _resolve_web_search_client(db: Any, workflow_state: dict[str, Any]) -> tuple[Any | None, str]: + if "web_search_client" in workflow_state: + client = workflow_state["web_search_client"] + return client, "" if client is not None else "WebSearch unavailable" + if db is None or not hasattr(db, "execute"): + return None, "WebSearch database config unavailable" + try: + from app.api.v1.settings import get_runtime_web_search_config, get_web_search_client + + config = await get_runtime_web_search_config(db) + provider_cfg = config.active_provider_config + provider_name = normalize_web_search_provider(provider_cfg.provider) + has_key = provider_name == "searxng" or bool((provider_cfg.api_key or "").strip()) + if not config.enabled: + return None, "WebSearch 未开启,无法检索外部公开依据。" + if not has_key: + return None, f"WebSearch Provider {config.default_provider} 未配置 API Key。" + client = await get_web_search_client(db) + return client, "" + except Exception as exc: + return None, f"WebSearch 初始化失败:{exc}" + + +def _build_r1_search_queries(ctx: dict[str, Any], entity_type: str) -> list[str]: + name_short = coerce_str(ctx.get("name_short") or ctx.get("name")) + operator = coerce_str(ctx.get("operator")) + site = coerce_str(ctx.get("site")) + country_en = coerce_str(ctx.get("country_en")) + queries: list[str] = [] + if entity_type == "bgp_collector": + q1 = " ".join(p for p in [f'"{name_short}"', "route collector IXP location city", country_en] if p) + q2 = " ".join(p for p in [name_short, operator, site, "city facility"] if p) + queries = [q1, q2] + else: + op_token = operator if operator and normalize_text(operator) != normalize_text(name_short) else "" + q1 = " ".join(p for p in [f'"{name_short}"', op_token, "data center OR supercomputer location city"] if p) + q2 = " ".join( + p + for p in [ + f'"{name_short}"', + site or op_token or country_en, + "facility campus", + ] + if p + ) + queries = [q1, q2] + dedup: list[str] = [] + for q in queries: + cleaned = " ".join(q.split()) + if cleaned and cleaned not in dedup: + dedup.append(cleaned) + return dedup[:2] + + +async def tool_location_web_research( + db: Any, + *, + node_params: dict[str, Any], + workflow_state: dict[str, Any], + allow_external_tools: bool, +) -> dict[str, Any]: + """L2 tool: execute parallel web research (Round 1 default queries + primary URLs, Round 2 targeted followups).""" + ledger = get_evidence_ledger(workflow_state) + ctx = workflow_state.get("location_ctx") or {} + entity_type = str(workflow_state.get("entity_type") or "compute_center") + attempted: list[str] = list(workflow_state.get("attempted_queries") or []) + round_num = int(node_params.get("round") or 1) + max_queries = max(1, min(int(node_params.get("max_search_queries") or 2), 3)) + max_fetches = max(0, min(int(node_params.get("max_fetch_urls") or 2), 4)) + + if not allow_external_tools: + return { + "round": round_num, + "skipped": "external_tools_disabled", + "evidence_count": len(ledger.items), + "new_ids": [], + "evidence": ledger.to_evidence_dict(), + } + + search_client, cap_reason = await _resolve_web_search_client(db, workflow_state) + if cap_reason: + workflow_state.setdefault("capability_reason", cap_reason) + + queries: list[str] = [] + urls_to_fetch: list[str] = [] + if round_num == 1: + urls_to_fetch = [ + coerce_str(u) + for u in (ctx.get("primary_source_urls") or []) + if coerce_str(u) and not is_tabular_dataset_url(u) + ][:max_fetches] + if search_client is not None: + queries = _build_r1_search_queries(ctx, entity_type)[:max_queries] + else: + latest = workflow_state.get("latest_llm_data") or {} + if search_client is not None: + queries = [ + coerce_str(q) + for q in (latest.get("followup_queries") or []) + if coerce_str(q) + ][:max_queries] + allowed_urls = { + normalize_evidence_url(u): u + for u in [*(ctx.get("primary_source_urls") or []), *(e["url"] for e in ledger.items)] + if u + } + for raw_u in latest.get("fetch_urls") or []: + nu = normalize_evidence_url(raw_u) + if nu and nu in allowed_urls and not is_tabular_dataset_url(raw_u): + urls_to_fetch.append(allowed_urls[nu]) + urls_to_fetch = urls_to_fetch[:max_fetches] + + tasks = [ + *[_fetch_one_url(u, ledger, attempted) for u in urls_to_fetch], + *[ + _search_one_query(q, search_client, ledger, attempted) + for q in queries + if search_client is not None + ], + ] + new_ids: list[str] = [] + if tasks: + for res in await asyncio.gather(*tasks, return_exceptions=True): + if isinstance(res, Exception) or not res: + continue + if isinstance(res, list): + new_ids.extend(res) + elif isinstance(res, str): + new_ids.append(res) + + workflow_state["attempted_queries"] = list(dict.fromkeys(attempted)) + return { + "round": round_num, + "evidence_count": len(ledger.items), + "new_ids": new_ids, + "capability_reason": cap_reason, + "evidence": ledger.to_evidence_dict(), + } + + +async def _geocode_verify_single( + place_q: str, + expected_country: str | None, +) -> tuple[dict[str, Any], dict[str, Any] | None]: + if not place_q: + return {"found": False, "reason": "place_query is required"}, None + try: + geo_res = await asyncio.to_thread(_agent_geocoder, place_q) + except Exception as exc: + logger.warning_event( + "Location workflow geocode_verify failed", + event="location_workflow.geocode_verify.failed", + context={"place_query": place_q, "error": str(exc)}, + ) + return {"found": False, "reason": f"geocoder request failed: {exc}"}, None + + if not isinstance(geo_res, dict): + return {"found": False, "reason": "No geocoder match"}, None + + lat = parse_float(geo_res.get("lat") if geo_res.get("lat") is not None else geo_res.get("latitude")) + lon = parse_float(geo_res.get("lon") if geo_res.get("lon") is not None else geo_res.get("longitude")) + if ( + lat in (None, 0.0) + or lon in (None, 0.0) + or not (-90.0 <= lat <= 90.0) + or not (-180.0 <= lon <= 180.0) + ): + return {"found": False, "reason": "Invalid geocoder coordinates"}, None + + addr = geo_res.get("address") if isinstance(geo_res.get("address"), dict) else {} + city = coerce_str( + addr.get("city") + or addr.get("town") + or addr.get("village") + or addr.get("municipality") + or addr.get("suburb") + or addr.get("hamlet") + or geo_res.get("city") + ) + osm_class = str(geo_res.get("class") or "").lower() + osm_type = str(geo_res.get("type") or "").lower() + is_site_like = osm_class in _DEFAULT_SITE_CATEGORIES or osm_type in _DEFAULT_SITE_CATEGORIES + explicit_precision = coerce_str(geo_res.get("precision")).lower() + has_explicit_renderable = explicit_precision in {"precise", "site", "city"} + + if not (city or is_site_like or has_explicit_renderable): + return { + "found": False, + "reason": "Geocoder result is only country or region/state level; provide a city, town, or facility address.", + }, None + + if has_explicit_renderable: + geo_precision = explicit_precision + elif addr.get("house_number") or addr.get("road"): + geo_precision = "precise" + elif is_site_like: + geo_precision = "site" + else: + geo_precision = "city" + + res_country = resolve_geocoder_country(addr, geo_res) + norm_expected = normalize_country_text(expected_country) + if norm_expected and res_country and normalize_text(res_country) != normalize_text(norm_expected): + return { + "found": False, + "reason": f"Country mismatch: got {res_country}, expected {norm_expected}", + }, None + + entry = { + "found": True, + "latitude": float(lat), + "longitude": float(lon), + "display_name": coerce_str(geo_res.get("display_name")) or place_q, + "city": city, + "region": coerce_str(addr.get("state") or addr.get("region") or geo_res.get("region")), + "country": res_country or norm_expected or coerce_str(expected_country), + "geo_precision": geo_precision, + } + return entry, entry + + +async def tool_location_geocode_verify( + *, + workflow_state: dict[str, Any], +) -> dict[str, Any]: + """L3 deterministic geocoder cascade: street address -> facility -> city+region -> city.""" + llm_data = workflow_state.get("latest_llm_data") or {} + ctx = workflow_state.get("location_ctx") or {} + decision = coerce_str(llm_data.get("decision")).lower() + if decision != "located": + result = {"found": False, "skipped": True, "reason": f"decision={decision or 'none'}"} + workflow_state["geocode_result"] = result + return result + + address = coerce_str(llm_data.get("address")) + facility_name = coerce_str(llm_data.get("facility_name")) + city = coerce_str(llm_data.get("city")) + region = coerce_str(llm_data.get("region")) + country_raw = coerce_str(llm_data.get("country")) or coerce_str(ctx.get("country")) + country_en = english_country_name(country_raw) or country_raw + + queries: list[str] = [] + candidates_parts = [ + [address, city, country_en] if address else [], + [facility_name, city, country_en] if facility_name else [], + [city, region, country_en] if (city and region) else [], + [city, country_en] if city else [], + [facility_name, country_en] if (facility_name and not city) else [], + ] + for parts in candidates_parts: + q = ", ".join(p for p in parts if p) + if q and q not in queries: + queries.append(q) + + attempted = list(workflow_state.get("attempted_queries") or []) + last_reason = "No geocoder query could be formed from LLM city/facility fields" + for q in queries: + attempted.append(f"geocode_verify:{q}") + res, entry = await _geocode_verify_single(q, country_raw) + if entry is not None: + workflow_state["attempted_queries"] = list(dict.fromkeys(attempted)) + workflow_state["geocode_result"] = entry + return entry + last_reason = coerce_str(res.get("reason")) or last_reason + + workflow_state["attempted_queries"] = list(dict.fromkeys(attempted)) + fail = {"found": False, "reason": last_reason} + workflow_state["geocode_result"] = fail + return fail + + +def evaluate_location_geo_guardrail( + guardrails: dict[str, Any], + workflow_state: dict[str, Any], +) -> dict[str, Any]: + """L3 hard anti-hallucination guardrails: geocoder >= city, real evidence_ids, confidence & country override.""" + if workflow_state.get("l1_candidates"): + return {"passed": True, "errors": [], "warnings": [], "stage": "l1_knowledge"} + + ledger = get_evidence_ledger(workflow_state) + llm_data = workflow_state.get("latest_llm_data") or {} + ctx = workflow_state.get("location_ctx") or {} + query = workflow_state.get("location_query") + entity_type = str(workflow_state.get("entity_type") or "compute_center") + + min_confidence = float(guardrails.get("min_confidence") or DEFAULT_MIN_CONFIDENCE) + enforce_country_match = bool(guardrails.get("enforce_country_match", True)) + require_tool_urls = bool(guardrails.get("require_tool_cited_urls", True)) + downgrade_to_city = bool(guardrails.get("downgrade_geocoded_site_to_city", True)) + + decision = coerce_str(llm_data.get("decision")).lower() or "unresolved" + reasoning = sanitize_user_facing_reasoning(coerce_str(llm_data.get("reasoning"))) + extra = (query.extra or {}) if isinstance(query, LocationQuery) else {} + + def _fail(msg: str, *, terminal: str | None = None) -> dict[str, Any]: + cleaned_msg = sanitize_user_facing_reasoning(msg) or msg + workflow_state["guardrail_passed"] = False + workflow_state["failure_reason"] = cleaned_msg + workflow_state["terminal_status"] = terminal + workflow_state["resolution_stage"] = "l3_geo_guardrail" + return {"passed": False, "errors": [cleaned_msg], "warnings": [cleaned_msg], "decision": decision} + + if decision in TERMINAL_UNLOCATABLE_STATUSES: + is_explicit_anonymous = bool(extra.get("anonymous")) and decision == "anonymous" + if ledger.evidence_calls == 0 and not is_explicit_anonymous: + return _fail("Cannot confirm terminal unlocatable status without tool evidence.") + cleaned_terminal_reason = sanitize_user_facing_reasoning(reasoning) or f"Facility confirmed as {decision}." + workflow_state["guardrail_passed"] = True + workflow_state["terminal_status"] = decision + workflow_state["failure_reason"] = cleaned_terminal_reason + workflow_state["resolution_stage"] = f"terminal_{decision}" + return { + "passed": True, + "errors": [], + "warnings": [], + "decision": decision, + "terminal_status": decision, + "reasoning": workflow_state["failure_reason"], + } + + if decision != "located": + reason = reasoning or coerce_str(workflow_state.get("capability_reason")) or "公开证据不足以确认具体城市" + return _fail(reason) + + geo = workflow_state.get("geocode_result") or {} + if not geo.get("found"): + geo_err = coerce_str(geo.get("reason")) or "未命中城市级地理编码坐标" + return _fail(f"地理编码未通过 ({geo_err})") + + refs = [*(llm_data.get("evidence_ids") or []), *(llm_data.get("citations") or [])] + verified_ids, verified_urls = ledger.resolve_refs(refs) + if require_tool_urls and not verified_urls: + return _fail("No verified citation URLs observed in tool outputs") + + raw_conf = parse_float(llm_data.get("confidence")) + confidence = min(max(raw_conf if raw_conf is not None else 0.0, 0.0), 1.0) + if confidence < min_confidence: + return _fail(f"Agent confidence {confidence:.2f} is below minimum {min_confidence:.2f}") + + expected_country = normalize_country_text(ctx.get("country")) + resolved_country = normalize_country_text(llm_data.get("country") or geo.get("country")) + override_meta: dict[str, str] | None = None + if ( + enforce_country_match + and expected_country + and resolved_country + and normalize_text(resolved_country) != normalize_text(expected_country) + ): + override_reason = sanitize_user_facing_reasoning(coerce_str(llm_data.get("country_override_reason"))) + hint_countries = { + normalize_text(normalize_country_text(h.get("country") or h.get("raw_country"))) + for h in (ctx.get("cross_source_hints") or []) + if isinstance(h, dict) + } + has_cross_hint = normalize_text(resolved_country) in hint_countries + if override_reason and (len(verified_urls) >= 1 or has_cross_hint): + override_meta = { + "source_country": expected_country, + "resolved_country": resolved_country, + "reason": override_reason[:300], + } + else: + return _fail(f"Country mismatch ({resolved_country} != {expected_country})") + + raw_precision = coerce_str(llm_data.get("precision")).lower() + precision = raw_precision if raw_precision in {"precise", "site", "city"} else "city" + geo_precision = coerce_str(geo.get("geo_precision")).lower() + if downgrade_to_city and geo_precision == "city" and precision in {"precise", "site"}: + precision = "city" + + label = ( + coerce_str(llm_data.get("facility_name")) + or coerce_str(geo.get("display_name")) + or coerce_str(ctx.get("name")) + ) + source_note = sanitize_user_facing_reasoning(reasoning) or f"Verified via location workflow ({len(verified_urls)} citations)" + if override_meta: + source_note = sanitize_user_facing_reasoning( + f"[跨国部署核验提醒:源登记国 {override_meta['source_country']} → " + f"实证部署国 {override_meta['resolved_country']};依据:{override_meta['reason']}] " + f"{source_note}" + ) + + raw_payload: dict[str, Any] = { + "evidence_ids": verified_ids, + "citations": verified_urls, + "geocode_precision": geo_precision, + } + if override_meta: + raw_payload["country_mismatch_override"] = override_meta + + cand = LocationCandidate( + latitude=float(geo["latitude"]), + longitude=float(geo["longitude"]), + display_name=label, + precision=precision, + confidence=confidence, + query=f"location_workflow:{entity_type}:{ctx.get('name') or ctx.get('source_id') or 'unknown'}", + source="llm_location_factcheck", + source_note=source_note, + matched_fields=("name", "location_workflow"), + needs_confirmation=True, + city=coerce_str(llm_data.get("city")) or geo.get("city") or ctx.get("city") or None, + region=coerce_str(llm_data.get("region")) or geo.get("region") or None, + country=resolved_country or expected_country or coerce_str(ctx.get("country")) or None, + matched_location_name=label, + raw_payload=raw_payload, + ) + workflow_state["guardrail_passed"] = True + workflow_state["validated_candidates"] = [cand] + workflow_state["resolution_stage"] = "l3_geo_guardrail:located" + return { + "passed": True, + "errors": [], + "warnings": [], + "decision": "located", + "candidate": cand.to_dict(), + } + + +async def _persist_terminal_location_status( + db: Any, + *, + ctx: dict[str, Any], + terminal_status: str, + reasoning: str, +) -> None: + if db is None or not hasattr(db, "execute"): + return + source = coerce_str(ctx.get("source")) + source_id = coerce_str(ctx.get("source_id")) + if not source or not source_id: + return + try: + sanitized_note = sanitize_user_facing_reasoning(reasoning)[:500] + existing = await db.scalar( + select(ComputeCenterLocationRecord) + .where(ComputeCenterLocationRecord.source == source) + .where(ComputeCenterLocationRecord.source_id == source_id) + ) + if existing is None: + existing = ComputeCenterLocationRecord( + source=source, + source_id=source_id, + name=coerce_str(ctx.get("name")) or source_id, + operator=coerce_str(ctx.get("operator")) or None, + site=coerce_str(ctx.get("site")) or None, + city=coerce_str(ctx.get("city")) or None, + country=coerce_str(ctx.get("country")) or None, + latitude=None, + longitude=None, + precision="unknown", + confidence=0.0, + location_source=f"agent_terminal_{terminal_status}", + source_note=sanitized_note or f"Marked {terminal_status} by location workflow", + needs_confirmation=False, + verification_status=terminal_status, + verified_at=datetime.now(UTC), + ) + db.add(existing) + else: + existing.precision = "unknown" + existing.latitude = None + existing.longitude = None + existing.verification_status = terminal_status + existing.location_source = f"agent_terminal_{terminal_status}" + existing.source_note = sanitized_note or existing.source_note + existing.verified_at = datetime.now(UTC) + await db.commit() + await refresh_compute_center_location_cache(db) + try: + invalidate_earth_layer_cache_for_source("compute_center_locations") + cache.delete_pattern("data_ledger:*") + except Exception: + pass + except Exception as exc: + logger.warning_event( + "Failed to persist terminal unlocatable status", + event="location_workflow.persist_terminal_failed", + context={"source_id": source_id, "status": terminal_status, "error": str(exc)}, + ) + + +async def tool_location_persist_outcome( + db: Any, + *, + node_params: dict[str, Any], + workflow_state: dict[str, Any], +) -> dict[str, Any]: + """L4 output tool: emit standardized `structured_output`, persist verified terminal status, render markdown/scene.""" + ctx = workflow_state.get("location_ctx") or {} + entity_type = str(workflow_state.get("entity_type") or "compute_center") + attempted = list(workflow_state.get("attempted_queries") or []) + l1_candidates: list[LocationCandidate] = list(workflow_state.get("l1_candidates") or []) + validated_candidates: list[LocationCandidate] = list(workflow_state.get("validated_candidates") or []) + candidates = validated_candidates or l1_candidates + terminal_status = workflow_state.get("terminal_status") + failure_reason = sanitize_user_facing_reasoning(coerce_str(workflow_state.get("failure_reason"))) + target_name = coerce_str(ctx.get("name")) or coerce_str(ctx.get("source_id")) or "Unknown Facility" + + if terminal_status and not str(workflow_state.get("resolution_stage") or "").startswith("l0_short_circuit"): + if bool(node_params.get("persist_terminal_statuses", True)) and entity_type == "compute_center": + await _persist_terminal_location_status( + db, + ctx=ctx, + terminal_status=terminal_status, + reasoning=failure_reason, + ) + + scene_spec: dict[str, Any] | None = None + if candidates: + best = candidates[0] + raw_p = best.raw_payload if isinstance(best.raw_payload, dict) else {} + cites = [str(u) for u in (raw_p.get("citations") or []) if u] + cleaned_note = sanitize_user_facing_reasoning(best.source_note) + lines = [ + f"### {best.display_name} 物理位置核验结果", + "", + f"- **目标实体**:{target_name}", + f"- **国家/地区**:{best.country or '-'}", + f"- **城市/区域**:{best.city or '-'}{f' ({best.region})' if best.region else ''}", + f"- **核验坐标**:`{best.latitude:.5f}, {best.longitude:.5f}`(精度 `{best.precision}`,置信度 `{float(best.confidence or 0):.2f}`)", + f"- **解析来源**:`{best.source}`", + ] + if cleaned_note: + lines.append(f"- **依据说明**:{cleaned_note}") + if cites: + lines.extend(["", "**核验引用来源**", *[f"- {u}" for u in cites[:5]]]) + answer_md = "\n".join(lines) + sid = coerce_str(ctx.get("source_id")) + scene_spec = { + "fly_to": {"lat": float(best.latitude), "lon": float(best.longitude), "zoom": 1.45}, + **({"highlight_entities": [sid]} if sid else {}), + } + workflow_state["outcome_tag"] = "located" + elif terminal_status: + answer_md = ( + f"### {target_name} 位置核验终态:`{terminal_status}`\n\n" + f"{failure_reason or '依据公开工具证据,该设施属于不可单点定位的终态类型。'}" + ) + workflow_state["outcome_tag"] = terminal_status + else: + diag = sanitize_user_facing_reasoning(failure_reason or coerce_str(workflow_state.get("capability_reason"))) or "暂无足够公开证据" + answer_md = f"### 未能确认「{target_name}」的物理位置\n\n- **诊断原因**:{diag}" + workflow_state["outcome_tag"] = "unresolved" + + structured_output = { + "success": bool(candidates), + "entity_type": entity_type, + "candidates": [c.to_dict() for c in candidates], + "best_candidate": candidates[0].to_dict() if candidates else None, + "candidate_objects": candidates, + "terminal_status": terminal_status, + "failure_reason": None if candidates else (failure_reason or "未能确认可信城市级坐标"), + "attempted_queries": attempted, + "resolution_stage": str(workflow_state.get("resolution_stage") or ""), + "context": ctx, + } + workflow_state["structured_output"] = structured_output + workflow_state["final_answer_markdown"] = answer_md + workflow_state["final_scene_spec"] = scene_spec + return { + "outcome": workflow_state["outcome_tag"], + "success": bool(candidates), + "candidates_count": len(candidates), + "terminal_status": terminal_status, + "failure_reason": structured_output["failure_reason"], + } + + +async def _resolve_active_workflow_revision(db: Any) -> int: + if db is None or not hasattr(db, "execute"): + return 1 + try: + res = await db.execute( + select(AIWorkflow.active_revision).where(AIWorkflow.workflow_id == "location.resolve_unknown") + ) + val = res.scalar_one_or_none() + if isinstance(val, int) and val >= 1: + return val + except Exception: + pass + return 1 + + +async def record_location_workflow_run( + db: Any, + *, + question: str, + status_value: str, + tool_trace: list[str], + steps_used: int, + started_at: datetime | None = None, + model_used: str = "", + provider_used: str = "", + resolution_stage: str = "", + source_id: str = "", + error_message: str = "", + node_traces: list[dict[str, Any]] | None = None, + trigger_evolution: bool = True, +) -> str | None: + """Persist one `WorkflowRun` telemetry record and optionally schedule post-run evolution.""" + if db is None or not hasattr(db, "add"): + return None + run_id = f"run_{uuid4().hex[:16]}" + started = started_at or datetime.now(UTC) + completed = datetime.now(UTC) + latency_ms = max(0, int((completed - started).total_seconds() * 1000)) + workflow_revision = await _resolve_active_workflow_revision(db) + deduped_trace: list[str] = [] + for item in tool_trace: + token = str(item or "").strip() + if token and token not in deduped_trace: + deduped_trace.append(token) + try: + db.add( + WorkflowRun( + id=run_id, + workflow_id="location.resolve_unknown", + status=status_value, + access_tier="admin", + actor_key="admin:collect-location", + question=question[:500], + input_params={"source_id": source_id} if source_id else {}, + tool_trace=deduped_trace, + budget_used={ + "steps": steps_used, + "workflow_revision": workflow_revision, + "model_used": model_used, + "provider_used": provider_used, + "latency_ms": latency_ms, + "resolution_stage": resolution_stage, + "source_id": source_id, + **({"node_traces": node_traces} if node_traces else {}), + }, + error_message=error_message[:500], + started_at=started, + completed_at=completed, + ) + ) + await db.commit() + except Exception: + try: + await db.rollback() + except Exception: + pass + return None + + if trigger_evolution: + try: + from app.services.ai.workflow_evolver import schedule_post_run_evolution + + schedule_post_run_evolution("location.resolve_unknown", run_id) + except Exception: + pass + return run_id + + +async def _load_location_workflow_def( + db: Any, + *, + use_draft: bool = False, + override_graph: dict[str, Any] | None = None, +) -> dict[str, Any]: + from app.services.ai.workflow_registry import BUILTIN_WORKFLOWS, get_workflow_detail + + wf_dict: dict[str, Any] | None = None + if db is not None and hasattr(db, "execute"): + try: + detail = await get_workflow_detail(db, "location.resolve_unknown") + wf_dict = dict(detail["workflow"]) + except Exception: + wf_dict = None + if hasattr(db, "rollback"): + try: + await db.rollback() + except Exception: + pass + if wf_dict is None: + builtin = next(w for w in BUILTIN_WORKFLOWS if w["workflow_id"] == "location.resolve_unknown") + wf_dict = { + "workflow_id": builtin["workflow_id"], + "name": builtin["name"], + "active_revision": 1, + "published_graph": copy.deepcopy(builtin["graph"]), + "draft_graph": None, + "bindings": copy.deepcopy(builtin.get("bindings") or {}), + } + if isinstance(override_graph, dict): + wf_dict["published_graph"] = copy.deepcopy(override_graph) + wf_dict["draft_graph"] = copy.deepcopy(override_graph) + elif use_draft and not isinstance(wf_dict.get("draft_graph"), dict): + wf_dict["draft_graph"] = copy.deepcopy(wf_dict.get("published_graph") or {}) + return wf_dict + + +async def run_location_workflow( + *, + db: Any, + query: LocationQuery | None = None, + entity_type: str = "compute_center", + earth_context: dict[str, Any] | None = None, + targets: list[dict[str, Any]] | None = None, + provider_client: Any = None, + web_search_client: Any = None, + use_draft: bool = False, + override_graph: dict[str, Any] | None = None, + record_run: bool = True, + trigger_evolution: bool = True, +) -> dict[str, Any]: + """Run `location.resolve_unknown` through the generic DAG executor and record one unified WorkflowRun.""" + from app.services.ai.dag_executor import run_workflow_dag_stream + + started_at = datetime.now(UTC) + wf = await _load_location_workflow_def(db, use_draft=use_draft, override_graph=override_graph) + + ai_client = provider_client + if ai_client is None and db is not None and hasattr(db, "execute"): + try: + from app.api.v1.settings import get_ai_provider_client + + ai_client = await get_ai_provider_client(db) + except Exception: + ai_client = None + + runtime_ctx = dict(earth_context or {}) + runtime_ctx["entity_type"] = entity_type + runtime_ctx["_location_runtime"] = { + **({"preset_query": query} if isinstance(query, LocationQuery) else {}), + **({"web_search_client": web_search_client} if web_search_client is not None else {}), + } + + question = coerce_str((query.name if isinstance(query, LocationQuery) else None) or runtime_ctx.get("name") or runtime_ctx.get("source_id") or "定位设施") + done_data: dict[str, Any] = {} + async for ev in run_workflow_dag_stream( + db=db, + workflow=wf, + question=question, + use_draft=use_draft, + targets=targets, + earth_context=runtime_ctx, + ai_client=ai_client, + allow_external_tools=True, + ): + if ev.get("event") == "done" and isinstance(ev.get("data"), dict): + done_data = ev["data"] + + structured = done_data.get("structured_output") if isinstance(done_data.get("structured_output"), dict) else {} + cand_objs = [c for c in (structured.get("candidate_objects") or []) if isinstance(c, LocationCandidate)] + terminal_status = structured.get("terminal_status") + verif_warnings = (done_data.get("verification") or {}).get("warnings") or [] + failure_reason = structured.get("failure_reason") or ( + None if cand_objs else ("; ".join(str(w) for w in verif_warnings if w) or None) + ) + attempted_queries = list(structured.get("attempted_queries") or []) + node_traces = list(done_data.get("node_traces") or []) + llm_steps = sum(1 for t in node_traces if t.get("node_type") in {"llm_agent", "tool_agent"} and t.get("status") == "completed") + run_status = "completed" if (cand_objs or terminal_status) else "failed" + + extra = (query.extra or {}) if isinstance(query, LocationQuery) else {} + source_id = coerce_str(extra.get("source_id") or runtime_ctx.get("source_id")) + workflow_run_id: str | None = None + if record_run: + workflow_run_id = await record_location_workflow_run( + db, + question=question, + status_value=run_status, + tool_trace=list(done_data.get("nodes") or []), + steps_used=llm_steps, + started_at=started_at, + model_used=coerce_str(done_data.get("model")), + provider_used=coerce_str(done_data.get("provider")), + resolution_stage=coerce_str(structured.get("resolution_stage")), + source_id=source_id, + error_message="" if run_status == "completed" else coerce_str(failure_reason), + node_traces=node_traces, + trigger_evolution=trigger_evolution, + ) + if workflow_run_id and terminal_status and source_id and entity_type == "compute_center" and hasattr(db, "execute"): + try: + loc_row = await db.scalar( + select(ComputeCenterLocationRecord) + .where(ComputeCenterLocationRecord.source_id == source_id) + .limit(1) + ) + if loc_row is not None and (loc_row.verification_status or "").lower() in TERMINAL_UNLOCATABLE_STATUSES: + payload_copy = dict(loc_row.raw_payload or {}) + payload_copy["workflow_run_id"] = workflow_run_id + loc_row.raw_payload = payload_copy + await db.commit() + await refresh_compute_center_location_cache(db) + except Exception: + pass + + return { + **structured, + "candidates": cand_objs, + "candidates_dicts": [c.to_dict() for c in cand_objs], + "workflow_run_id": workflow_run_id, + "terminal_status": terminal_status, + "failure_reason": failure_reason, + "attempted_queries": attempted_queries, + "answer_markdown": coerce_str(done_data.get("answer_markdown")), + "tool_trace": list(done_data.get("nodes") or []), + "node_traces": node_traces, + } diff --git a/backend/app/services/scheduler.py b/backend/app/services/scheduler.py index 5af7f60f..23d669f4 100644 --- a/backend/app/services/scheduler.py +++ b/backend/app/services/scheduler.py @@ -60,6 +60,8 @@ _HEAVY_COLLECTOR_SEMAPHORES: weakref.WeakKeyDictionary[ EARTH_NEWS_REFRESH_JOB_ID = "earth_news_rss_refresh" STORAGE_RETENTION_JOB_ID = "storage_retention_maintenance" STORAGE_RETENTION_INTERVAL_HOURS = 6 +COMPUTE_PRESENTATION_RETRY_JOB_ID = "compute_revision_presentation_retry" +COMPUTE_PRESENTATION_RETRY_INTERVAL_MINUTES = 5 SCHEDULER_LEADER_LOCK_KEY = (17001613, 3) _leader_lock_conn: Optional[asyncpg.Connection] = None _pending_earth_news_refreshes: dict[str, dict[str, Any]] = {} @@ -531,6 +533,23 @@ async def release_scheduler_leader_lock() -> None: await conn.close() +async def run_compute_presentation_retry_job() -> None: + """Retry pending or failed compute revision stage presentations.""" + from app.services.ai.proactive_pipeline import retry_pending_compute_presentations + + async with async_session_factory() as db: + try: + await retry_pending_compute_presentations(db) + await db.commit() + except Exception as exc: + await db.rollback() + logger.warning_event( + "Scheduled compute presentation retry failed", + event="compute.revision.presentation_failed", + context={"phase": "scheduler", "error": str(exc)}, + ) + + def start_scheduler() -> None: """Start the scheduler.""" if not scheduler.running: @@ -555,6 +574,16 @@ def start_scheduler() -> None: coalesce=True, misfire_grace_time=300, ) + scheduler.add_job( + run_compute_presentation_retry_job, + trigger=IntervalTrigger(minutes=COMPUTE_PRESENTATION_RETRY_INTERVAL_MINUTES), + id=COMPUTE_PRESENTATION_RETRY_JOB_ID, + name="Compute revision presentation retry", + replace_existing=True, + max_instances=1, + coalesce=True, + misfire_grace_time=120, + ) scheduler.start() logger.info_event("Scheduler started", event="scheduler.started") @@ -780,6 +809,7 @@ async def sync_scheduler_with_datasources() -> None: job.id not in configured_sources and not is_earth_news_refresh and job.id != STORAGE_RETENTION_JOB_ID + and job.id != COMPUTE_PRESENTATION_RETRY_JOB_ID ): scheduler.remove_job(job.id) diff --git a/backend/app/services/storage_maintenance.py b/backend/app/services/storage_maintenance.py index bb1c4363..ddbe5cbd 100644 --- a/backend/app/services/storage_maintenance.py +++ b/backend/app/services/storage_maintenance.py @@ -302,6 +302,17 @@ async def _run_maintenance_with_session( where_clause=[ObservabilityEvent.occurred_at < history_cutoff], batch_size=batch_size, ) + from app.services.earth_clouds import prune_cloud_map_artifacts, read_cloud_map_configuration + from app.services.earth_tiles import prune_all_tile_caches + from app.services.earth_wind import prune_wind_artifacts, read_wind_configuration + + cloud_env = await read_cloud_map_configuration(db) + max_cloud_frames = int((cloud_env.get("config") or {}).get("max_history_frames") or 24) + pruned_cloud_artifacts = prune_cloud_map_artifacts(max_frames=max_cloud_frames) + pruned_tile_files = await prune_all_tile_caches(db) + wind_env = await read_wind_configuration(db) + max_wind_runs = int((wind_env.get("config") or {}).get("max_history_runs") or 12) + pruned_wind_artifacts = prune_wind_artifacts(max_runs=max_wind_runs) deleted_counts = { "collected_data": deleted_collected, @@ -312,6 +323,9 @@ async def _run_maintenance_with_session( "earth_news_items": deleted_news_items, "system_logs": deleted_system_logs, "observability_events": deleted_observability_events, + "cloud_map_artifacts": pruned_cloud_artifacts, + "tile_cache_files": pruned_tile_files, + "wind_artifacts": pruned_wind_artifacts, } logger.info_event( "Completed storage retention maintenance", diff --git a/backend/tests/fixtures/compute_revision_case.json b/backend/tests/fixtures/compute_revision_case.json new file mode 100644 index 00000000..b82e9096 --- /dev/null +++ b/backend/tests/fixtures/compute_revision_case.json @@ -0,0 +1,31 @@ +{ + "case_id": "epoch-ai-2026-11-restates-2025-chip-inflow-cn", + "metric": "chip_inflow_share", + "year": 2025, + "period_label": null, + "old": { + "source_id": "epoch-chip-imports-2026", + "values": { + "US": 72, + "CN": 11 + }, + "locator": "Regional H100-equivalent AI Accelerator Inflow(2022.10 先进芯片管制及北美云厂商每年超 2000 亿美元 CapEx 驱动下,高端 AI 算力芯片新增流向美国约 72%、中国约 10%–12%)" + }, + "new": { + "source_id": "epoch-chip-imports-2026-11", + "title": "Epoch AI: Data on AI Chip Imports (2026-11-12 Revision)", + "url": "https://epoch.ai/data/ai-chip-imports-documentation/changelog", + "publisher": "Epoch AI", + "report_year": 2026, + "published_at": "2026-11-12", + "locator": "AI chip imports documentation — Changelog (2026-11-12) & Overview (Key takeaways); ai_chip_trade_by_country.csv", + "excerpt": "2026-11-12: We now assume Nvidia's H20 arrived in the quarter it was sold. Other chips are still assumed to arrive two months after sale. This moves about 216,000 H20s in China from 2025 to 2024. It also raises China's share of cumulative world arrivals through June 2026 from 9.6% to 9.9% (69,000 H100e).", + "values": { + "CN": 9.9 + } + }, + "unchanged_codes": [ + "US" + ], + "notes": "真实公开修订案例(非演练)。同一机构(Epoch AI)、同一口径(全球 H100e 等效 AI 加速芯片新增/累计流向份额,分母 ai_chip_inflow):内置台账 epoch-chip-imports-2026(2026-04-10)记录美国 72%、中国约 10%–12%(取中值 11%);Epoch AI 官方 AI Chip Imports 数据集于 2026-10-27 正式发布并于 2026-11-12 修订,在 Changelog 中明确因将约 216,000 颗中国 H20 芯片到货时点由 2025 年调回 2024 年并结合海关/国产产量核算,将中国全球累计到货算力份额更新为 9.9%(相对原台账 11% 为 -1.1 个百分点),同期同句给出美国份额 72.0%(与原台账 72% 持平,故只修订中国时美国保留原来源 epoch-chip-imports-2026)。附注:已核查 CAICT 2021–2025 五版白皮书/蓝皮书原件 PDF(含正文与图表),CAICT 2025 未对 2023 年全球总份额(美 41%/中 31%)与总规模(1397/435 EFlops)做修订。" +} diff --git a/backend/tests/test_ai_workflows.py b/backend/tests/test_ai_workflows.py index 59b262a2..e908b652 100644 --- a/backend/tests/test_ai_workflows.py +++ b/backend/tests/test_ai_workflows.py @@ -197,13 +197,13 @@ async def test_ai_workflow_optimize_whitelist_and_playground_sse_runs(monkeypatc "summary": "Add fetch tool & block bad tool", "node_patches": [ { - "node_id": "l2_agent_research", + "node_id": "l2_judge_r1", "field": "tools", "after": ["fetch_source_url", "evil_rm_rf_tool"], "reason": "Keep only whitelisted tool", }, { - "node_id": "l2_agent_research", + "node_id": "l2_judge_r1", "field": "max_steps", "after": 5, "reason": "Allow 5 steps", @@ -306,9 +306,23 @@ async def test_ensure_builtin_workflows_upgrades_untouched_legacy_positions_only loc_spec = next( item for item in BUILTIN_WORKFLOWS if item["workflow_id"] == "location.resolve_unknown" ) - legacy_loc_graph = copy.deepcopy(loc_spec["graph"]) - for node in legacy_loc_graph["nodes"]: - lx, ly = _LEGACY_BUILTIN_POSITIONS["location.resolve_unknown"][node["id"]] + legacy_loc_graph = { + "nodes": [ + {"id": "l0_normalize", "node_type": "trigger", "position": {"x": 40, "y": 140}}, + {"id": "l1_knowledge", "node_type": "deterministic", "position": {"x": 320, "y": 60}}, + {"id": "l2_agent_research", "node_type": "llm_agent", "position": {"x": 320, "y": 250}}, + {"id": "l3_geo_guardrail", "node_type": "guardrail", "position": {"x": 640, "y": 140}}, + {"id": "l4_persist_outcome", "node_type": "output", "position": {"x": 940, "y": 140}}, + ], + "edges": [], + } + + wg_spec = next( + item for item in BUILTIN_WORKFLOWS if item["workflow_id"] == "wargame.infrastructure" + ) + legacy_wg_graph = copy.deepcopy(wg_spec["graph"]) + for node in legacy_wg_graph["nodes"]: + lx, ly = _LEGACY_BUILTIN_POSITIONS["wargame.infrastructure"][node["id"]] node["position"] = {"x": lx, "y": ly} gen_spec = next( @@ -333,6 +347,22 @@ async def test_ensure_builtin_workflows_upgrades_untouched_legacy_positions_only updated_by="system", ) ) + session.add( + AIWorkflow( + workflow_id="wargame.infrastructure", + name=wg_spec["name"], + name_en=wg_spec["name_en"], + category=wg_spec["category"], + description=wg_spec["description"], + description_en=wg_spec["description_en"], + is_default=False, + is_builtin=True, + active_revision=1, + published_graph=legacy_wg_graph, + draft_graph=None, + updated_by="system", + ) + ) session.add( AIWorkflow( workflow_id="default.general", @@ -360,9 +390,19 @@ async def test_ensure_builtin_workflows_upgrades_untouched_legacy_positions_only select(AIWorkflow).where(AIWorkflow.workflow_id == "location.resolve_unknown") ) ).scalar_one() - l1 = next(n for n in upgraded_loc.published_graph["nodes"] if n["id"] == "l1_knowledge") - l2 = next(n for n in upgraded_loc.published_graph["nodes"] if n["id"] == "l2_agent_research") - assert l2["position"]["x"] > l1["position"]["x"] + loc_ids = [n["id"] for n in upgraded_loc.published_graph["nodes"]] + assert "l2_research_r1" in loc_ids + assert "l2_judge_r1" in loc_ids + assert "l3_geocode" in loc_ids + + upgraded_wg = ( + await session.execute( + select(AIWorkflow).where(AIWorkflow.workflow_id == "wargame.infrastructure") + ) + ).scalar_one() + wg_trig = next(n for n in upgraded_wg.published_graph["nodes"] if n["id"] == "wg_trigger") + wg_inv = next(n for n in upgraded_wg.published_graph["nodes"] if n["id"] == "wg_investigator") + assert wg_inv["position"]["x"] - wg_trig["position"]["x"] >= 700 untouched_gen = ( await session.execute( diff --git a/backend/tests/test_bgp_collector_locations.py b/backend/tests/test_bgp_collector_locations.py index 585cdd03..01161bc0 100644 --- a/backend/tests/test_bgp_collector_locations.py +++ b/backend/tests/test_bgp_collector_locations.py @@ -8,7 +8,6 @@ import pytest from app.api.v1 import bgp as bgp_api from app.services import bgp_collector_locations -from app.services.location.llm_fallback import LocationLLMFallbackResult from app.services.bgp_collector_locations import ( RIPE_RIS_COLLECTOR_COORDS, collect_bgp_collector_location_candidates, @@ -118,9 +117,9 @@ async def test_collect_bgp_collector_location_uses_llm_when_candidates_empty(mon display_name="Lyon, France", precision="city", confidence=0.74, - query="llm_factcheck:bgp_collector:rrc-mystery", + query="location_workflow:bgp_collector:rrc-mystery", source="llm_location_factcheck", - source_note="LLM location factcheck fallback", + source_note="Controlled workflow factcheck", matched_fields=("collector",), needs_confirmation=True, city="Lyon", @@ -131,36 +130,21 @@ async def test_collect_bgp_collector_location_uses_llm_when_candidates_empty(mon "get_bgp_collector_location_dict", lambda _collector: {}, ) - monkeypatch.setattr( - bgp_api, - "collect_bgp_collector_location_candidates", - lambda **_kwargs: ([], ["Lyon, France"]), - ) - from app.services.location.llm_fallback import LocationSearchEvidenceResult - - async def _search_evidence(**_kwargs): - return LocationSearchEvidenceResult( - evidence=[ - { - "title": "RRC source", - "url": "https://example.test/rrc", - "snippet": "rrc-mystery is in Lyon.", - } + async def _run_wf(**kwargs): + assert kwargs.get("entity_type") == "bgp_collector" + assert kwargs.get("query").name == "rrc-mystery" + return { + "candidates": [llm_candidate], + "attempted_queries": [ + "Lyon, France", + "web_search:rrc-mystery Lyon France", ], - attempted_queries=["web_search:bgp_collector:rrc-mystery Lyon France physical location route collector city"], - ) + "workflow_run_id": "run_bgp_1", + "failure_reason": None, + } - async def _fallback(**_kwargs): - return LocationLLMFallbackResult( - candidates=[llm_candidate], - attempted_queries=["llm_factcheck:bgp_collector:rrc-mystery"], - ) - - monkeypatch.setattr(bgp_api, "get_ai_provider_client", AsyncMock(return_value=object())) - monkeypatch.setattr(bgp_api, "get_web_search_client", AsyncMock(return_value=object())) - monkeypatch.setattr(bgp_api, "collect_location_search_evidence", _search_evidence) - monkeypatch.setattr(bgp_api, "collect_llm_location_fallback_candidate", _fallback) + monkeypatch.setattr(bgp_api, "run_location_workflow", _run_wf) response = await bgp_api.collect_bgp_collector_location( "rrc-mystery", @@ -172,10 +156,10 @@ async def test_collect_bgp_collector_location_uses_llm_when_candidates_empty(mon assert response["success"] is True assert response["best_candidate"]["source"] == "llm_location_factcheck" assert response["best_candidate"]["needs_confirmation"] is True + assert response["workflow_run_id"] == "run_bgp_1" assert response["attempted_queries"] == [ "Lyon, France", - "web_search:bgp_collector:rrc-mystery Lyon France physical location route collector city", - "llm_factcheck:bgp_collector:rrc-mystery", + "web_search:rrc-mystery Lyon France", ] diff --git a/backend/tests/test_collected_data_api.py b/backend/tests/test_collected_data_api.py new file mode 100644 index 00000000..5a20e07c --- /dev/null +++ b/backend/tests/test_collected_data_api.py @@ -0,0 +1,245 @@ +"""Unit tests for optimized /api/v1/collected endpoints, summary facets, and Redis cache.""" + +from __future__ import annotations + +from datetime import UTC, datetime + +from httpx import ASGITransport, AsyncClient +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from app.api.v1 import collected_data as collected_api +from app.core.security import get_current_user +from app.db.session import Base, get_db +from app.main import app +from app.models.collected_data import CollectedData +from app.models.data_snapshot import DataSnapshot +from app.models.datasource import DataSource +from app.models.task import CollectionTask +from app.models.user import User, UserRole + + +class _MemoryCache: + def __init__(self) -> None: + self.store: dict[str, object] = {} + self.gets: list[str] = [] + self.sets: list[str] = [] + + def get(self, key: str): + self.gets.append(key) + return self.store.get(key) + + def set(self, key: str, value, expire_seconds: int = 300) -> bool: + self.sets.append(key) + self.store[key] = value + return True + + +class _SyncAsAsyncSession: + def __init__(self, sync_session): + self._s = sync_session + + def add_all(self, objs): + return self._s.add_all(objs) + + async def execute(self, stmt, *args, **kwargs): + return self._s.execute(stmt, *args, **kwargs) + + async def commit(self): + return self._s.commit() + + async def close(self): + return self._s.close() + + +def _make_test_session(): + engine = create_engine("sqlite:///:memory:") + Base.metadata.create_all( + engine, + tables=[ + DataSource.__table__, + DataSnapshot.__table__, + CollectionTask.__table__, + CollectedData.__table__, + ], + ) + sync_factory = sessionmaker(engine, expire_on_commit=False) + with sync_factory() as session: + session.add_all( + [ + DataSource(name="TOP500", source="top500", module="L4", collector_class="Top500Collector"), + DataSource(name="IPtoASN", source="iptoasn_prefix_geo", module="L1", collector_class="IPtoASNCollector"), + ] + ) + now = datetime.now(UTC) + session.add_all( + [ + CollectedData( + source="top500", + source_id="t1", + entity_key="top500:t1", + data_type="supercomputer", + name="Frontier", + extra_data={"country": "美国"}, + collected_at=now, + is_current=True, + ), + CollectedData( + source="top500", + source_id="t2", + entity_key="top500:t2", + data_type="supercomputer", + name="Aurora", + extra_data={"country": "美国"}, + collected_at=now, + is_current=True, + ), + CollectedData( + source="top500", + source_id="t1_old", + entity_key="top500:t1_old", + data_type="supercomputer", + name="Old Frontier", + extra_data={"country": "美国"}, + collected_at=now, + is_current=False, + ), + CollectedData( + source="iptoasn_prefix_geo", + source_id="p1", + entity_key="iptoasn_prefix_geo:p1", + data_type="prefix_geography", + name="1.1.1.0/24", + extra_data={"country": "澳大利亚"}, + collected_at=now, + is_current=True, + ), + ] + ) + session.commit() + + class _Ctx: + def __call__(self): + return self + + async def __aenter__(self): + self._s = sync_factory() + return _SyncAsAsyncSession(self._s) + + async def __aexit__(self, exc_type, exc, tb): + self._s.close() + return False + + return engine, _Ctx() + + +def _fake_admin_user() -> User: + return User( + id=1, + username="collected_tester", + email="collected_tester@example.com", + role=UserRole.ADMIN, + is_active=True, + ) + + +@pytest.mark.asyncio +async def test_collected_summary_excludes_prefix_geography_by_default_and_includes_explicitly( + monkeypatch, +): + engine, session_factory = _make_test_session() + mem_cache = _MemoryCache() + monkeypatch.setattr(collected_api, "cache", mem_cache) + + async def override_get_db(): + async with session_factory() as session: + yield session + + app.dependency_overrides.update({get_db: override_get_db, get_current_user: _fake_admin_user}) + try: + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + list_res = await client.get("/api/v1/collected?page=1&page_size=20&include_metadata=false") + assert list_res.status_code == 200 + list_body = list_res.json() + assert list_body["total"] == 2 + assert {item["source"] for item in list_body["data"]} == {"top500"} + + explicit_res = await client.get("/api/v1/collected?data_type=prefix_geography&include_metadata=false") + assert explicit_res.status_code == 200 + explicit_body = explicit_res.json() + assert explicit_body["total"] == 1 + assert explicit_body["data"][0]["source"] == "iptoasn_prefix_geo" + + summary_res = await client.get("/api/v1/collected/summary") + assert summary_res.status_code == 200 + summary = summary_res.json() + assert summary["total_records"] == 2 + assert summary["overall_total_records"] == 2 + assert summary["by_source"] == {"TOP500": {"supercomputer": 2}} + assert summary["source_totals"] == [{"source": "top500", "source_name": "TOP500", "count": 2}] + assert summary["type_totals"] == [{"data_type": "supercomputer", "count": 2}] + + explicit_summary_res = await client.get("/api/v1/collected/summary?data_type=prefix_geography") + assert explicit_summary_res.status_code == 200 + explicit_summary = explicit_summary_res.json() + assert explicit_summary["total_records"] == 1 + assert explicit_summary["overall_total_records"] == 3 + assert explicit_summary["source_totals"] == [ + {"source": "iptoasn_prefix_geo", "source_name": "IPtoASN", "count": 1} + ] + + sources_res = await client.get("/api/v1/collected/sources") + assert sources_res.status_code == 200 + assert {s["source"] for s in sources_res.json()["sources"]} == {"iptoasn_prefix_geo", "top500"} + + types_res = await client.get("/api/v1/collected/types") + assert types_res.status_code == 200 + assert set(types_res.json()["data_types"]) == {"prefix_geography", "supercomputer"} + finally: + app.dependency_overrides.clear() + engine.dispose() + + +@pytest.mark.asyncio +async def test_collected_summary_and_facets_use_redis_cache_without_hitting_db_on_repeat( + monkeypatch, +): + engine, session_factory = _make_test_session() + mem_cache = _MemoryCache() + monkeypatch.setattr(collected_api, "cache", mem_cache) + fail_db = {"enabled": False} + + async def override_get_db(): + async with session_factory() as session: + if fail_db["enabled"]: + async def _boom(*_args, **_kwargs): + raise AssertionError("DB should not be queried on cache hit") + monkeypatch.setattr(session, "execute", _boom) + yield session + + app.dependency_overrides.update({get_db: override_get_db, get_current_user: _fake_admin_user}) + try: + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + r1 = await client.get("/api/v1/collected/summary") + assert r1.status_code == 200 + assert "collected:facets:v1" in mem_cache.sets + assert any(k.startswith("collected:summary:v1:") for k in mem_cache.sets) + + fail_db["enabled"] = True + r2 = await client.get("/api/v1/collected/summary") + assert r2.status_code == 200 + assert r2.json() == r1.json() + + s_res = await client.get("/api/v1/collected/sources") + assert s_res.status_code == 200 + assert len(s_res.json()["sources"]) == 2 + + t_res = await client.get("/api/v1/collected/types") + assert t_res.status_code == 200 + assert len(t_res.json()["data_types"]) == 2 + finally: + app.dependency_overrides.clear() + engine.dispose() diff --git a/backend/tests/test_collectors.py b/backend/tests/test_collectors.py index 96860652..f0b8d542 100644 --- a/backend/tests/test_collectors.py +++ b/backend/tests/test_collectors.py @@ -345,3 +345,61 @@ def test_supported_credential_collectors_have_guides_and_connectivity_provider() missing.append(f"{source}: missing connectivity provider for {provider}") assert missing == [] + + +def test_app_main_imports_and_all_collectors_satisfy_base_contract(): + import importlib + import inspect + import pkgutil + + import app.main # noqa: F401 + import app.services.collectors as collectors_pkg + from app.services.collectors import BaseCollector, HTTPCollector, IntervalCollector + from app.services.collectors.compute_base import ComputeCollector + + abstract_bases = (BaseCollector, HTTPCollector, IntervalCollector, ComputeCollector) + checked = 0 + for mod in pkgutil.iter_modules(collectors_pkg.__path__, collectors_pkg.__name__ + "."): + module = importlib.import_module(mod.name) + for attr_name, obj in inspect.getmembers(module, inspect.isclass): + if obj.__module__ != mod.name or not issubclass(obj, BaseCollector): + continue + if obj in abstract_bases or attr_name.startswith("_"): + continue + assert not inspect.isabstract(obj), ( + f"{mod.name}.{attr_name} still has abstract methods: {sorted(obj.__abstractmethods__)}" + ) + inst = obj() + assert str(getattr(inst, "name", "") or "").strip(), f"{mod.name}.{attr_name} missing name" + assert callable(getattr(inst, "fetch", None)), f"{mod.name}.{attr_name} missing fetch()" + run_fn = getattr(inst, "run", None) + assert callable(run_fn) and "db" in inspect.signature(run_fn).parameters + checked += 1 + + assert checked > 0 + registered = collector_registry.all() + assert len(registered) > 0 + for key, col in registered.items(): + assert isinstance(col, BaseCollector) + assert col.name == key + assert callable(getattr(col, "fetch", None)) + assert "db" in inspect.signature(col.run).parameters + + +def test_earth_tile_collectors_registered_and_transform(): + sample_summary = { + "warmup_max_zoom": 2, + "fetched": 3, + "cached_hits": 2, + "cache_stats": {"tile_count": 5, "total_mb": 1.25}, + } + for source in ("cloud_hd_tiles", "earth_imagery_sentinel2", "earth_imagery_viirs_daily"): + collector = collector_registry.get(source) + assert collector is not None, f"Missing collector for {source}" + records = collector.transform([sample_summary]) + assert len(records) == 1 + record = records[0] + assert record["source_id"] == f"tile_pyramid:{source}" + assert record["value"] == 5 + assert record["unit"] == "tiles" + assert record["metadata"]["record_kind"] == "earth_tile_pyramid" diff --git a/backend/tests/test_compute_configuration.py b/backend/tests/test_compute_configuration.py index 139da820..fb3a3b49 100644 --- a/backend/tests/test_compute_configuration.py +++ b/backend/tests/test_compute_configuration.py @@ -133,24 +133,32 @@ async def test_publish_and_audit_are_one_transaction_and_conflicts_do_not_overwr db = fake_db(record) actor = SimpleNamespace(id=1, username="admin") old = deepcopy(record.payload) + edited_payload = default_config() + edited_payload["observations"][4]["values"]["CN"] = 24.5 + edited_config = ComputeConfiguration.model_validate(edited_payload) result = await publish_configuration( db, revision=old["revision"], - config=DEFAULT_CONFIGURATION, + config=edited_config, actor=actor, ) assert result["revision"] != old["revision"] + assert result["publish_id"] == result["revision"] + assert result["no_changes"] is False audit = db.add.call_args.args[0] assert isinstance(audit, AuditLog) - assert audit.details == {"before": old, "after": result} + assert audit.details["before"] == old + assert audit.details["after"] == result + assert audit.details["publish_id"] == result["publish_id"] + assert audit.details["parent_publish_id"] == old["revision"] assert audit.actor_id == actor.id db.commit.assert_awaited_once() with pytest.raises(HTTPException) as failure: await publish_configuration( - db, revision=old["revision"], config=DEFAULT_CONFIGURATION, actor=actor + db, revision=old["revision"], config=edited_config, actor=actor ) assert failure.value.status_code == 409 - assert record.payload == result + assert record.payload["revision"] == result["revision"] db.rollback.assert_awaited_once() db.commit.assert_awaited_once() @@ -207,15 +215,18 @@ async def test_http_configuration_auth_validation_and_public_series(): ) assert response.status_code == 422 db.commit.assert_not_awaited() + edited = deepcopy(loaded["config"]) + edited["observations"][4]["values"]["CN"] = 24.5 response = await client.put( "/configuration", json={ "revision": loaded["revision"], - "config": loaded["config"], + "config": edited, }, ) assert response.status_code == 200 assert response.json()["revision"] != loaded["revision"] + assert response.json()["no_changes"] is False assert ( await client.post( "/configuration/reset", diff --git a/backend/tests/test_compute_m2_candidates_and_sources.py b/backend/tests/test_compute_m2_candidates_and_sources.py new file mode 100644 index 00000000..39f7b773 --- /dev/null +++ b/backend/tests/test_compute_m2_candidates_and_sources.py @@ -0,0 +1,343 @@ +"""Tests for M2 candidate comparison, dedupe, review reason validation, per-country value_sources, and M0 real case.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock + +from fastapi import FastAPI +from httpx import ASGITransport, AsyncClient +from pydantic import ValidationError +import pytest +from sqlalchemy import create_engine, select +from sqlalchemy.orm import Session + +from app.api.v1 import compute_intelligence, situational_awareness +from app.core.security import get_current_user +from app.db.session import get_db +from app.models.compute_configuration_revision import ComputeConfigurationRevision +from app.models.situational_assessment import ( + ComputeEvidenceCandidate, + EvidenceRecord, + SituationalAssessment, +) +from app.models.system_log import AuditLog +from app.models.system_setting import SystemSetting +from app.schemas.compute_configuration import ComputeConfiguration +from app.services.ai.semantic_delta import extract_compute_candidates_deterministic +from app.services.ai.tool_registry import filter_compute_config_by_cutoff +from app.services.compute_configuration import ( + DEFAULT_CONFIGURATION, + ensure_compute_revision_baseline, +) +from app.services.compute_history import compute_history + +FIXTURE_PATH = Path(__file__).resolve().parent / "fixtures" / "compute_revision_case.json" + + +def _make_sqlite_db(): + engine = create_engine("sqlite://") + for model in ( + SystemSetting, + AuditLog, + ComputeConfigurationRevision, + ComputeEvidenceCandidate, + EvidenceRecord, + SituationalAssessment, + ): + model.__table__.create(engine) + raw = Session(engine) + db = SimpleNamespace( + execute=AsyncMock(side_effect=raw.execute), + add=raw.add, + delete=AsyncMock(side_effect=raw.delete), + flush=AsyncMock(side_effect=raw.flush), + commit=AsyncMock(side_effect=raw.commit), + rollback=AsyncMock(side_effect=raw.rollback), + refresh=AsyncMock(side_effect=raw.refresh), + get_bind=raw.get_bind, + bind=engine, + ) + return engine, raw, db + + +def test_value_sources_schema_validation_rejects_invalid_keys_and_sources(): + payload = DEFAULT_CONFIGURATION.model_dump(mode="json") + # Invalid key not present in values + bad_key = json.loads(json.dumps(payload)) + bad_key["observations"][4]["value_sources"] = {"DE": "caict-2025"} + with pytest.raises(ValidationError, match="subset"): + ComputeConfiguration.model_validate(bad_key) + + # Unknown source ID + bad_src = json.loads(json.dumps(payload)) + bad_src["observations"][4]["value_sources"] = {"CN": "nonexistent-report"} + with pytest.raises(ValidationError, match="Missing report source"): + ComputeConfiguration.model_validate(bad_src) + + # Report year earlier than observation year + bad_year = json.loads(json.dumps(payload)) + bad_year["observations"][4]["value_sources"] = {"CN": "caict-2021"} + with pytest.raises(ValidationError, match="after its report year"): + ComputeConfiguration.model_validate(bad_year) + + +def test_extractor_handles_real_m0_epoch_ai_fixture_and_chinese_chip_inflow(): + case = json.loads(FIXTURE_PATH.read_text(encoding="utf-8")) + extracted = extract_compute_candidates_deterministic( + case["new"]["excerpt"], + year=case["year"], + source_meta={"id": case["new"]["source_id"]}, + period_label=case["period_label"], + ) + assert len(extracted) == 1 + item = extracted[0] + assert item["proposed_payload"]["metric"] == "chip_inflow_share" + assert item["proposed_payload"]["year"] == 2025 + assert item["proposed_payload"]["values"] == {"CN": 9.9} + + # Full sentence with both China and United States + full_excerpt = ( + case["new"]["excerpt"] + + " and lowers the United States' share from 72.2% to 72.0% (53,000 H100e)." + ) + both = extract_compute_candidates_deterministic( + full_excerpt, year=2025, source_meta={"id": "epoch-both"} + ) + assert both[0]["proposed_payload"]["values"] == {"CN": 9.9, "US": 72.0} + + # Chinese chip inflow phrasing + zh = extract_compute_candidates_deterministic( + "报告指出中国高端AI芯片新增流向份额为 9.9%。", + year=2025, + source_meta={"id": "zh-chip"}, + ) + assert zh[0]["proposed_payload"]["metric"] == "chip_inflow_share" + assert zh[0]["proposed_payload"]["values"] == {"CN": 9.9} + + +def test_as_known_then_cutoff_drops_only_post_cutoff_country_in_mixed_source_row(): + case = json.loads(FIXTURE_PATH.read_text(encoding="utf-8")) + payload = DEFAULT_CONFIGURATION.model_dump(mode="json") + payload["sources"].append( + { + "id": case["new"]["source_id"], + "title": case["new"]["title"], + "url": case["new"]["url"], + "publisher": case["new"]["publisher"], + "report_year": case["new"]["report_year"], + "published_at": case["new"]["published_at"], + "locator": case["new"]["locator"], + } + ) + for obs in payload["observations"]: + if obs["metric"] == "chip_inflow_share" and obs["year"] == 2025: + obs["values"]["CN"] = 9.9 + obs["value_sources"] = {"CN": case["new"]["source_id"]} + break + + cfg = ComputeConfiguration.model_validate(payload) + # Full view: CN cites new report, US cites old report + full_series = compute_history(["CN", "US"], "chip_inflow_share", cfg) + row_2025 = next(r for r in full_series["compute"] if r["year"] == 2025) + assert row_2025["values"] == {"CN": 9.9, "US": 72.0} + assert row_2025["evidence_by_code"] == { + "CN": [case["new"]["source_id"]], + "US": ["epoch-chip-imports-2026"], + } + assert row_2025["mixed_sources"] is True + chip_rpi = full_series["bilateral_rpi"]["latest_chip_inflow"] + assert chip_rpi["cn_evidence_id"] == case["new"]["source_id"] + assert chip_rpi["us_evidence_id"] == "epoch-chip-imports-2026" + + # Cut off at 2026-06-01: cuts off epoch-chip-imports-2026-11 (2026-11-12) while keeping epoch-chip-imports-2026 (2026-04-10) + filtered_cfg, withheld = filter_compute_config_by_cutoff( + cfg, time_basis="as_known_then", cutoff_at="2026-06-01" + ) + assert case["new"]["source_id"] in withheld + assert "epoch-chip-imports-2026" not in withheld + cut_obs = next( + obs for obs in filtered_cfg.observations if obs.metric == "chip_inflow_share" and obs.year == 2025 + ) + assert "CN" not in cut_obs.values + assert cut_obs.values == {"US": 72.0} + assert cut_obs.source_id == "epoch-chip-imports-2026" + assert cut_obs.value_sources is None + + +@pytest.mark.asyncio +async def test_m2_full_extract_dedupe_review_mixed_source_guard_and_publish(): + case = json.loads(FIXTURE_PATH.read_text(encoding="utf-8")) + engine, raw, db = _make_sqlite_db() + try: + await ensure_compute_revision_baseline(db) + actor = SimpleNamespace(id=1, username="admin", role="admin") + app = FastAPI() + app.include_router(compute_intelligence.router, prefix="/data-products/compute") + app.include_router(situational_awareness.router, prefix="/situational-awareness") + app.dependency_overrides[get_db] = lambda: db + app.dependency_overrides[get_current_user] = lambda: actor + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + extract_body = { + "year": case["year"], + "excerpt": case["new"]["excerpt"], + "source_id": case["new"]["source_id"], + "source_title": case["new"]["title"], + "source_url": case["new"]["url"], + "publisher": case["new"]["publisher"], + "locator": case["new"]["locator"], + "period_label": case["period_label"], + "published_at": case["new"]["published_at"], + "report_year": case["new"]["report_year"], + } + # 1. Extract real M0 case + res1 = await client.post("/situational-awareness/candidates/extract", json=extract_body) + assert res1.status_code == 200 + items1 = res1.json()["items"] + assert len(items1) == 1 + cand = items1[0] + assert cand["duplicate"] is False + assert cand["comparison"]["has_historical_revision"] is True + assert cand["comparison"]["denominator"] == "ai_chip_inflow" + cn_cmp = cand["comparison"]["codes"]["CN"] + assert cn_cmp["old_value"] == 11.0 + assert cn_cmp["new_value"] == 9.9 + assert cn_cmp["delta"] == -1.1 + assert cn_cmp["change_kind"] == "historical_revision" + assert cn_cmp["old_source_id"] == "epoch-chip-imports-2026" + + # Verify immutable EvidenceRecord persisted with excerpt sha256 + ev_row = raw.execute( + select(EvidenceRecord).where(EvidenceRecord.id == case["new"]["source_id"]) + ).scalar_one() + assert ev_row.excerpt == case["new"]["excerpt"] + assert ev_row.content_sha256 == hashlib.sha256(case["new"]["excerpt"].encode("utf-8")).hexdigest() + + # 2. Duplicate extraction returns existing candidate with duplicate=True + res2 = await client.post("/situational-awareness/candidates/extract", json=extract_body) + assert res2.status_code == 200 + items2 = res2.json()["items"] + assert len(items2) == 1 + assert items2[0]["id"] == cand["id"] + assert items2[0]["duplicate"] is True + assert len(raw.execute(select(ComputeEvidenceCandidate)).scalars().all()) == 1 + + # 3. Review validation: missing reason / mismatched reason_code -> 422 + bad_missing = await client.post( + f"/situational-awareness/candidates/{cand['id']}/review", + json={"decision": "approved"}, + ) + assert bad_missing.status_code == 422 + + bad_mismatch = await client.post( + f"/situational-awareness/candidates/{cand['id']}/review", + json={ + "decision": "approved", + "reason_code": "extraction_error", + "reason": "Wrong code for approval", + }, + ) + assert bad_mismatch.status_code == 422 + + # Viewer -> 403 + app.dependency_overrides[get_current_user] = lambda: SimpleNamespace( + id=2, username="viewer", role="viewer" + ) + forbidden = await client.post( + f"/situational-awareness/candidates/{cand['id']}/review", + json={ + "decision": "approved", + "reason_code": "methodology_update", + "reason": "Viewer cannot approve", + }, + ) + assert forbidden.status_code == 403 + app.dependency_overrides[get_current_user] = lambda: actor + + # Valid approval + approved = await client.post( + f"/situational-awareness/candidates/{cand['id']}/review", + json={ + "decision": "approved", + "reason_code": "methodology_update", + "reason": "Epoch AI 2026-11-12 修订中国 H20 到货时点并更新全球累计份额为 9.9%。", + }, + ) + assert approved.status_code == 200 + assert approved.json()["status"] == "approved" + assert approved.json()["review_reason_code"] == "methodology_update" + + # 4. Publish China-only mixed-source revision: empty publish_note -> 422 + cfg_res = (await client.get("/data-products/compute/configuration")).json() + edited = json.loads(json.dumps(cfg_res["config"])) + edited["sources"].append( + { + "id": case["new"]["source_id"], + "title": case["new"]["title"], + "url": case["new"]["url"], + "publisher": case["new"]["publisher"], + "report_year": case["new"]["report_year"], + "published_at": case["new"]["published_at"], + "locator": case["new"]["locator"], + } + ) + for obs in edited["observations"]: + if obs["metric"] == "chip_inflow_share" and obs["year"] == 2025: + obs["values"]["CN"] = 9.9 + obs["value_sources"] = {"CN": case["new"]["source_id"]} + break + + no_note_res = await client.put( + "/data-products/compute/configuration", + json={ + "revision": cfg_res["revision"], + "config": edited, + "publish_note": "", + "source_candidate_ids": [cand["id"]], + }, + ) + assert no_note_res.status_code == 422 + + # With publish_note -> 200, backfills published_publish_id + pub_res = await client.put( + "/data-products/compute/configuration", + json={ + "revision": cfg_res["revision"], + "config": edited, + "publish_note": "同分母依据:两版均采用 Epoch AI 全球累计 H100e 到货算力总盘子,美国维持 72.0% 未变。", + "source_candidate_ids": [cand["id"]], + }, + ) + assert pub_res.status_code == 200 + pub_pid = pub_res.json()["publish_id"] + + # Candidate now locked (published_publish_id set) -> re-review returns 409 + locked_res = await client.post( + f"/situational-awareness/candidates/{cand['id']}/review", + json={ + "decision": "rejected", + "reason_code": "superseded", + "reason": "Cannot alter after publish", + }, + ) + assert locked_res.status_code == 409 + + # Verify /series reflects CN->new source, US->old source + series = ( + await client.get("/data-products/compute/series?countries=CN,US&mode=chip_inflow_share") + ).json() + assert series["publish_id"] == pub_pid + row = next(r for r in series["compute"] if r["year"] == 2025) + assert row["values"] == {"CN": 9.9, "US": 72.0} + assert row["evidence_by_code"] == { + "CN": [case["new"]["source_id"]], + "US": ["epoch-chip-imports-2026"], + } + assert row["mixed_sources"] is True + finally: + raw.close() + engine.dispose() diff --git a/backend/tests/test_compute_m3_presentations.py b/backend/tests/test_compute_m3_presentations.py new file mode 100644 index 00000000..4394a92f --- /dev/null +++ b/backend/tests/test_compute_m3_presentations.py @@ -0,0 +1,231 @@ +"""Tests for M3 revision-driven compute stage presentations, failure retry, idempotency, B->A reset, and small revisions.""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import AsyncMock + +from fastapi import FastAPI +from httpx import ASGITransport, AsyncClient +import pytest +from sqlalchemy import create_engine, select +from sqlalchemy.orm import Session + +from app.api.v1 import compute_intelligence, situational_awareness +from app.core.security import get_current_user +from app.db.session import get_db +from app.models.compute_configuration_revision import ComputeConfigurationRevision +from app.models.situational_assessment import ( + ComputeEvidenceCandidate, + EvidenceRecord, + SituationalAssessment, + StagePresentation, + TopicWatch, +) +from app.models.system_log import AuditLog +from app.models.system_setting import SystemSetting +from app.schemas.compute_configuration import ComputeConfiguration +from app.services.ai import proactive_pipeline +from app.services.ai.proactive_pipeline import ( + process_compute_revision_presentation, + retry_pending_compute_presentations, +) +from app.services.compute_configuration import ( + DEFAULT_CONFIGURATION, + ensure_compute_revision_baseline, + publish_configuration, +) + + +def _make_sqlite_db(): + engine = create_engine("sqlite://") + for model in ( + SystemSetting, + AuditLog, + ComputeConfigurationRevision, + ComputeEvidenceCandidate, + EvidenceRecord, + SituationalAssessment, + StagePresentation, + TopicWatch, + ): + model.__table__.create(engine) + raw = Session(engine) + db = SimpleNamespace( + execute=AsyncMock(side_effect=raw.execute), + add=raw.add, + delete=AsyncMock(side_effect=raw.delete), + flush=AsyncMock(side_effect=raw.flush), + commit=AsyncMock(side_effect=raw.commit), + rollback=AsyncMock(side_effect=raw.rollback), + refresh=AsyncMock(side_effect=raw.refresh), + get_bind=raw.get_bind, + bind=engine, + ) + return engine, raw, db + + +def _edit_cn_2024(value: float) -> ComputeConfiguration: + payload = DEFAULT_CONFIGURATION.model_dump(mode="json") + for obs in payload["observations"]: + if obs["metric"] == "global_share" and obs["year"] == 2024: + obs["values"]["CN"] = value + break + return ComputeConfiguration.model_validate(payload) + + +@pytest.mark.asyncio +async def test_failure_during_publish_marks_failed_and_retry_delivers_exactly_once(monkeypatch): + engine, raw, db = _make_sqlite_db() + try: + baseline = await ensure_compute_revision_baseline(db) + assert baseline is not None + actor = SimpleNamespace(id=1, username="admin", role="admin") + + app = FastAPI() + app.include_router(compute_intelligence.router, prefix="/data-products/compute") + app.include_router(situational_awareness.router, prefix="/situational-awareness") + app.dependency_overrides[get_db] = lambda: db + app.dependency_overrides[get_current_user] = lambda: actor + + # Force presentation delivery to fail during PUT /configuration + real_fn = proactive_pipeline.process_compute_revision_presentation + + async def _boom(*_args, **_kwargs): + raise RuntimeError("Simulated presentation failure") + + monkeypatch.setattr(proactive_pipeline, "process_compute_revision_presentation", _boom) + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + put_res = await client.put( + "/data-products/compute/configuration", + json={ + "revision": baseline.publish_id, + "config": _edit_cn_2024(24.5).model_dump(mode="json"), + "publish_note": "1.5pp historical revision", + }, + ) + # Publish itself still returns 200 with presentation_status='failed' + assert put_res.status_code == 200 + body = put_res.json() + assert body["presentation_status"] == "failed" + pid = body["publish_id"] + + rev_row = raw.execute( + select(ComputeConfigurationRevision).where( + ComputeConfigurationRevision.publish_id == pid + ) + ).scalar_one() + assert rev_row.presentation_status == "failed" + assert rev_row.presentation_attempts == 1 + assert "Simulated presentation failure" in rev_row.presentation_error + assert len(raw.execute(select(StagePresentation)).scalars().all()) == 0 + + # Restore real function and trigger retry via /proactive/evaluate + monkeypatch.setattr(proactive_pipeline, "process_compute_revision_presentation", real_fn) + eval_res = await client.post( + "/situational-awareness/proactive/evaluate", + json={"domain": "compute"}, + ) + assert eval_res.status_code == 200 + assert eval_res.json()["delivered"] == 1 + + raw.refresh(rev_row) + assert rev_row.presentation_status == "delivered" + assert rev_row.presentation_delivered_at is not None + assert rev_row.presentation_error == "" + + presentations = raw.execute(select(StagePresentation)).scalars().all() + assert len(presentations) == 1 + pres = presentations[0] + assert pres.presentation_key == "compute-revision-notice" + assert pres.revision == rev_row.id + assert pres.contract["publish_id"] == pid + assert "2024 年全球总算力份额数据获修订" in pres.title + assert "这是对历史数据的修订,不代表当期算力跃升" in pres.summary + step1 = pres.contract["steps"][0] + assert step1["compute_mode"] == "global_share" + assert step1["focus_year"] == 2024 + assert step1["spotlight_Statistic_codes"] == ["CN"] + + # Re-running presentation for the same revision is strictly idempotent (no duplicate row) + dup_res = await process_compute_revision_presentation(db, rev_row.id) + assert dup_res["idempotent"] is True + retry_again = await retry_pending_compute_presentations(db) + assert retry_again["processed"] == 0 + assert len(raw.execute(select(StagePresentation)).scalars().all()) == 1 + finally: + raw.close() + engine.dispose() + + +@pytest.mark.asyncio +async def test_aba_reset_emits_new_presentation_and_milestone_only_edit_is_skipped(): + engine, raw, db = _make_sqlite_db() + try: + baseline = await ensure_compute_revision_baseline(db) + assert baseline is not None + actor = SimpleNamespace(id=1, username="admin", role="admin") + + # 1. Publish B (+1.5pp small revision) + env_b = await publish_configuration( + db, + revision=baseline.publish_id, + config=_edit_cn_2024(24.5), + actor=actor, + ) + rev_b = raw.execute( + select(ComputeConfigurationRevision).where( + ComputeConfigurationRevision.publish_id == env_b["publish_id"] + ) + ).scalar_one() + res_b = await process_compute_revision_presentation(db, rev_b.id) + await db.commit() + assert res_b["status"] == "delivered" + + # 2. Reset B -> A must ALSO emit a new presentation (no seen_fingerprints suppression!) + env_a2 = await publish_configuration( + db, + revision=env_b["publish_id"], + config=DEFAULT_CONFIGURATION, + actor=actor, + reset=True, + ) + rev_a2 = raw.execute( + select(ComputeConfigurationRevision).where( + ComputeConfigurationRevision.publish_id == env_a2["publish_id"] + ) + ).scalar_one() + res_a2 = await process_compute_revision_presentation(db, rev_a2.id) + await db.commit() + assert res_a2["status"] == "delivered" + + presentations = raw.execute( + select(StagePresentation).order_by(StagePresentation.id.asc()) + ).scalars().all() + assert len(presentations) == 2 + assert presentations[0].contract["publish_id"] == env_b["publish_id"] + assert presentations[1].contract["publish_id"] == env_a2["publish_id"] + assert presentations[1].revision > presentations[0].revision + + # 3. Milestone-only edit has no observation delta -> presentation_status='skipped', no presentation added + ms_payload = DEFAULT_CONFIGURATION.model_dump(mode="json") + ms_payload["milestones"][0]["title"] = "修订里程碑文案" + env_ms = await publish_configuration( + db, + revision=env_a2["publish_id"], + config=ComputeConfiguration.model_validate(ms_payload), + actor=actor, + ) + assert env_ms["presentation_status"] == "skipped" + rev_ms = raw.execute( + select(ComputeConfigurationRevision).where( + ComputeConfigurationRevision.publish_id == env_ms["publish_id"] + ) + ).scalar_one() + res_ms = await process_compute_revision_presentation(db, rev_ms.id) + assert res_ms["status"] == "skipped" + assert len(raw.execute(select(StagePresentation)).scalars().all()) == 2 + finally: + raw.close() + engine.dispose() diff --git a/backend/tests/test_compute_m4_lineage_and_copilot.py b/backend/tests/test_compute_m4_lineage_and_copilot.py new file mode 100644 index 00000000..87fbb69c --- /dev/null +++ b/backend/tests/test_compute_m4_lineage_and_copilot.py @@ -0,0 +1,758 @@ +"""M4 tests: read-time lineage derivation, redaction, public revisions, Copilot same-source, and 9-point E2E.""" + +from __future__ import annotations + +import copy +from datetime import UTC, datetime, timedelta +import json +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock, patch + +import httpx +import pytest +from sqlalchemy import create_engine, select +from sqlalchemy.orm import Session + +from app.api.v1 import compute_intelligence as ci_api +from app.core.enums import UserRole +from app.core.security import create_access_token, get_password_hash +from app.db.session import get_db +from app.main import app +from app.models.compute_configuration_revision import ComputeConfigurationRevision +from app.models.situational_assessment import ( + ComputeEvidenceCandidate, + EvidenceRecord, + InvestigationSession, + SituationalAssessment, + StagePresentation, + TopicWatch, + WorkflowRun, +) +from app.models.system_log import AuditLog +from app.models.system_setting import SystemSetting +from app.models.user import User +from app.services.compute_configuration import ensure_compute_revision_baseline + + +FIXTURE_PATH = Path(__file__).parent / "fixtures" / "compute_revision_case.json" + + +async def _build_m4_harness(): + engine = create_engine("sqlite://", connect_args={"check_same_thread": False}) + for model in ( + User, + SystemSetting, + AuditLog, + ComputeConfigurationRevision, + ComputeEvidenceCandidate, + EvidenceRecord, + SituationalAssessment, + StagePresentation, + TopicWatch, + InvestigationSession, + WorkflowRun, + ): + model.__table__.create(engine) + + def _new_db(): + raw = Session(engine) + + def _add_all(items): + raw.add_all(items) + + return SimpleNamespace( + execute=AsyncMock(side_effect=raw.execute), + add=raw.add, + add_all=_add_all, + delete=AsyncMock(side_effect=raw.delete), + flush=AsyncMock(side_effect=raw.flush), + commit=AsyncMock(side_effect=raw.commit), + rollback=AsyncMock(side_effect=raw.rollback), + refresh=AsyncMock(side_effect=raw.refresh), + close=raw.close, + bind=engine, + ) + + init_db = _new_db() + try: + await ensure_compute_revision_baseline(init_db) + admin = User( + username="admin_m4", + email="admin_m4@planet.local", + password_hash=get_password_hash("AdminPass123!"), + role=UserRole.ADMIN.value, + is_active=True, + ) + viewer = User( + username="viewer_m4", + email="viewer_m4@planet.local", + password_hash=get_password_hash("ViewerPass123!"), + role=UserRole.VIEWER.value, + gatekeeper_groups=["api_access"], + is_active=True, + ) + init_db.add_all([admin, viewer]) + await init_db.commit() + await init_db.refresh(admin) + await init_db.refresh(viewer) + admin_token = create_access_token({"sub": str(admin.id)}) + viewer_token = create_access_token({"sub": str(viewer.id)}) + finally: + init_db.close() + + async def override_get_db(): + db = _new_db() + try: + yield db + finally: + db.close() + + app.dependency_overrides[get_db] = override_get_db + return engine, _new_db, admin_token, viewer_token + + +def _load_m0_case() -> dict: + return json.loads(FIXTURE_PATH.read_text(encoding="utf-8")) + + +async def _publish_m0_revision_via_http( + client: httpx.AsyncClient, + admin_headers: dict[str, str], + m0: dict, + *, + review_reason: str = "Epoch AI 2026-11-12 官方变更日志将约 21.6 万颗 H20 由 2025 重分配至 2024,中国份额修订为 9.9%。", + publish_note: str = "同为 Epoch AI 累计芯片算力流入全球分母,仅将中国 2025 重述为 9.9%,美国保持原报告 72%。", +) -> tuple[str, str, int]: + """Extract, approve, and publish the real Epoch AI M0 case; returns (rev_a, rev_b, candidate_id).""" + cfg_before = ( + await client.get("/api/v1/data-products/compute/configuration", headers=admin_headers) + ).json() + rev_a = cfg_before["publish_id"] + + new_meta = m0["new"] + extract_resp = await client.post( + "/api/v1/situational-awareness/candidates/extract", + headers=admin_headers, + json={ + "year": m0["year"], + "excerpt": new_meta["excerpt"], + "source_id": new_meta["source_id"], + "source_title": new_meta["title"], + "source_url": new_meta["url"], + "publisher": new_meta["publisher"], + "locator": new_meta["locator"], + "published_at": new_meta["published_at"], + "report_year": new_meta["report_year"], + "period_label": m0["period_label"], + }, + ) + assert extract_resp.status_code == 200, extract_resp.text + extract_body = extract_resp.json() + assert len(extract_body["items"]) == 1 + cand = extract_body["items"][0] + cand_id = cand["id"] + + review_resp = await client.post( + f"/api/v1/situational-awareness/candidates/{cand_id}/review", + headers=admin_headers, + json={ + "decision": "approved", + "reason_code": "newer_authoritative_report", + "reason": review_reason, + }, + ) + assert review_resp.status_code == 200, review_resp.text + + cfg_next = copy.deepcopy(cfg_before["config"]) + cfg_next["sources"].append( + { + "id": new_meta["source_id"], + "title": new_meta["title"], + "publisher": new_meta["publisher"], + "url": new_meta["url"], + "locator": new_meta["locator"], + "report_year": new_meta["report_year"], + "published_at": new_meta["published_at"], + } + ) + for obs in cfg_next["observations"]: + if obs["metric"] == m0["metric"] and obs["year"] == m0["year"]: + obs["values"]["CN"] = float(new_meta["values"]["CN"]) + obs["value_sources"] = {"CN": new_meta["source_id"]} + break + + pub_resp = await client.put( + "/api/v1/data-products/compute/configuration", + headers=admin_headers, + json={ + "revision": cfg_before["revision"], + "config": cfg_next, + "publish_note": publish_note, + "source_candidate_ids": [cand_id], + }, + ) + assert pub_resp.status_code == 200, pub_resp.text + rev_b = pub_resp.json()["publish_id"] + return rev_a, rev_b, cand_id + + +@pytest.mark.asyncio +async def test_m4_public_revisions_and_lineage_redaction(): + engine, _sf, admin_token, viewer_token = await _build_m4_harness() + m0 = _load_m0_case() + admin_headers = {"Authorization": f"Bearer {admin_token}"} + viewer_headers = {"Authorization": f"Bearer {viewer_token}"} + + try: + with patch.object(ci_api, "_broadcast_compute_configuration_update", new=AsyncMock()): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + raw_reason = "内部核验备注:Epoch AI 2026-11-12 修订了 H20 发货年份归属,CN 降为 9.9%。" + raw_note = "内部发布说明:保持同分母仅更新中国 2025 芯片流向占比。" + _rev_a, rev_b, _cand_id = await _publish_m0_revision_via_http( + client, + admin_headers, + m0, + review_reason=raw_reason, + publish_note=raw_note, + ) + + # 1. Public revisions endpoint redacts raw publish_note and actor name + pub_revs = await client.get("/api/v1/data-products/compute/revisions/public?limit=10") + assert pub_revs.status_code == 200 + pub_items = pub_revs.json()["items"] + assert len(pub_items) >= 2 + latest_pub = pub_items[0] + assert latest_pub["publish_id"] == rev_b + assert "publish_note" not in latest_pub + assert "published_by_name" not in latest_pub + assert "published_by_role" not in latest_pub + assert latest_pub["summary"] + assert raw_note not in latest_pub["summary"] + + # Admin revisions endpoint exposes full note & actor + adm_revs = await client.get( + "/api/v1/data-products/compute/revisions?limit=10", + headers=admin_headers, + ) + assert adm_revs.status_code == 200 + latest_adm = adm_revs.json()["items"][0] + assert latest_adm["publish_note"] == raw_note + assert latest_adm["published_by_name"] == "admin_m4" + assert latest_adm["published_by_role"] == "admin" + + # Viewer blocked on admin revisions + viewer_revs = await client.get( + "/api/v1/data-products/compute/revisions", + headers=viewer_headers, + ) + assert viewer_revs.status_code == 403 + + # 2. Public lineage on CN 2025 chip_inflow_share -> redacted + cn_pub_resp = await client.get( + "/api/v1/data-products/compute/lineage", + params={"code": "CN", "metric": "chip_inflow_share", "year": 2025}, + ) + assert cn_pub_resp.status_code == 200 + cn_pub = cn_pub_resp.json() + assert cn_pub["redacted"] is True + assert cn_pub["publish_id"] == rev_b + assert cn_pub["current"]["value"] == 9.9 + assert cn_pub["current"]["source"]["id"] == "epoch-chip-imports-2026-11" + assert cn_pub["current"]["source"]["published_at"] == "2026-11-12" + assert cn_pub["current"]["source"]["locator"] == m0["new"]["locator"] + assert len(cn_pub["current"]["source"]["content_sha256"]) == 64 + assert "9.9%" in cn_pub["current"]["source"]["excerpt"] + assert cn_pub["timestamps"]["observation_period"] == "2025" + assert cn_pub["timestamps"]["report_published_at"] == "2026-11-12" + assert cn_pub["timestamps"]["ingested_at"] is not None + assert cn_pub["timestamps"]["effective_published_at"] is not None + + assert len(cn_pub["timeline"]) == 1 + t0_pub = cn_pub["timeline"][0] + assert t0_pub["old_value"] == 11.0 + assert t0_pub["new_value"] == 9.9 + assert t0_pub["delta"] == -1.1 + assert t0_pub["change_kind"] == "historical_revision" + assert t0_pub["review_reason_code"] == "newer_authoritative_report" + assert t0_pub["review_reason_label"] == "更权威新版报告更新" + assert t0_pub["review_reason"] is None + assert t0_pub["publish_note"] is None + assert t0_pub["reviewed_by"] == "已人工复核" + assert t0_pub["published_by_name"] == "已人工复核" + assert "published_by_role" not in t0_pub + assert raw_reason not in json.dumps(cn_pub, ensure_ascii=False) + assert raw_note not in json.dumps(cn_pub, ensure_ascii=False) + assert "admin_m4" not in json.dumps(cn_pub, ensure_ascii=False) + + # 3. Logged-in viewer ALSO gets redacted lineage + cn_viewer = ( + await client.get( + "/api/v1/data-products/compute/lineage", + params={"code": "CN", "metric": "chip_inflow_share", "year": 2025}, + headers=viewer_headers, + ) + ).json() + assert cn_viewer["redacted"] is True + assert cn_viewer["timeline"][0]["reviewed_by"] == "已人工复核" + assert cn_viewer["timeline"][0]["review_reason"] is None + + # 4. Logged-in admin sees full reviewer username, raw reason & publish_note + cn_adm = ( + await client.get( + "/api/v1/data-products/compute/lineage", + params={"code": "CN", "metric": "chip_inflow_share", "year": 2025}, + headers=admin_headers, + ) + ).json() + assert cn_adm["redacted"] is False + t0_adm = cn_adm["timeline"][0] + assert t0_adm["reviewed_by"] == "admin_m4" + assert t0_adm["review_reason"] == raw_reason + assert t0_adm["publish_note"] == raw_note + assert t0_adm["published_by_name"] == "admin_m4" + assert t0_adm["published_by_role"] == "admin" + + # 5. US unchanged value still cites original report (epoch-chip-imports-2026) + us_pub = ( + await client.get( + "/api/v1/data-products/compute/lineage", + params={"code": "US", "metric": "chip_inflow_share", "year": 2025}, + ) + ).json() + assert us_pub["current"]["value"] == 72.0 + assert us_pub["current"]["source_id"] == "epoch-chip-imports-2026" + assert us_pub["current"]["source"]["id"] == "epoch-chip-imports-2026" + assert us_pub["timeline"] == [] + assert us_pub["timestamps"]["ingested_at"] is None + finally: + app.dependency_overrides.clear() + engine.dispose() + + +@pytest.mark.asyncio +async def test_m4_copilot_same_source_as_of_and_why_changed(): + engine, _sf, admin_token, _viewer_token = await _build_m4_harness() + m0 = _load_m0_case() + admin_headers = {"Authorization": f"Bearer {admin_token}"} + + try: + with patch.object(ci_api, "_broadcast_compute_configuration_update", new=AsyncMock()): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + raw_reason = "敏感复核原话:依据 Epoch AI 2026-11-12 勘误重述 CN=9.9%。" + rev_a, rev_b, _cand_id = await _publish_m0_revision_via_http( + client, + admin_headers, + m0, + review_reason=raw_reason, + ) + + # 1. Create public Copilot session pinned to current post-revision rev_b + sess_resp = await client.post( + "/api/v1/situational-awareness/sessions", + json={ + "domain": "compute", + "selected_codes": ["CN", "US"], + "mode": "chip_inflow_share", + "focus_year": 2025, + "publish_id": rev_b, + }, + ) + assert sess_resp.status_code == 200, sess_resp.text + sess = sess_resp.json() + sess_id = sess["id"] + sess_headers = {"X-Planet-Session-Token": sess["session_token"]} + + # Turn 1: overview under rev_b + turn_b = await client.post( + f"/api/v1/situational-awareness/sessions/{sess_id}/turns", + headers=sess_headers, + json={ + "question": "当前中美芯片流向份额是多少?", + "mode": "chip_inflow_share", + "focus_year": 2025, + "publish_id": rev_b, + }, + ) + assert turn_b.status_code == 200, turn_b.text + tb = turn_b.json() + assert tb["view_spec"]["publish_id"] == rev_b + assert tb["view_spec"]["mode"] == "chip_inflow_share" + assert tb["view_spec"]["focus_year"] == 2025 + assert "9.9%" in tb["reply"]["answer_markdown"] + assert "epoch-chip-imports-2026-11" in tb["evidence"] + + # Turn 2: follow-up "这次为什么变了" under rev_b (public tier -> redacted, same publish_id evidence) + turn_why = await client.post( + f"/api/v1/situational-awareness/sessions/{sess_id}/turns", + headers=sess_headers, + json={ + "question": "这次为什么变了?", + "mode": "chip_inflow_share", + "focus_year": 2025, + "publish_id": rev_b, + }, + ) + assert turn_why.status_code == 200, turn_why.text + tw = turn_why.json() + assert tw["view_spec"]["publish_id"] == rev_b + ans_why = tw["reply"]["answer_markdown"] + assert "9.9" in ans_why and "11" in ans_why + assert "历史" in ans_why + assert "更权威新版报告更新" in ans_why + assert raw_reason not in ans_why + for eid in tw["reply"]["evidence_ids"]: + assert eid in tw["evidence"] + + # Turn 3: switch back to pre-revision rev_a -> old values (11%) & old evidence + turn_a = await client.post( + f"/api/v1/situational-awareness/sessions/{sess_id}/turns", + headers=sess_headers, + json={ + "question": "切回修订前的中美芯片流向份额对照", + "mode": "chip_inflow_share", + "focus_year": 2025, + "publish_id": rev_a, + }, + ) + assert turn_a.status_code == 200, turn_a.text + ta = turn_a.json() + assert ta["view_spec"]["publish_id"] == rev_a + assert ("11%" in ta["reply"]["answer_markdown"] or "11.0%" in ta["reply"]["answer_markdown"]) + assert "9.9%" not in ta["reply"]["answer_markdown"] + assert "epoch-chip-imports-2026" in ta["evidence"] + assert "epoch-chip-imports-2026-11" not in ta["evidence"] + + # Turn 4: as_of earlier than baseline -> snapshot_unavailable notice + turn_pre = await client.post( + f"/api/v1/situational-awareness/sessions/{sess_id}/turns", + headers=sess_headers, + json={ + "question": "查看 2020 年历史版本算力份额", + "mode": "chip_inflow_share", + "focus_year": 2025, + "as_of": "2020-01-01T00:00:00Z", + }, + ) + assert turn_pre.status_code == 200, turn_pre.text + tp = turn_pre.json() + assert tp["view_spec"]["replay_supported"] is False + assert tp["view_spec"]["publish_id"] is None + assert "历史快照不完整" in tp["reply"]["answer_markdown"] + finally: + app.dependency_overrides.clear() + engine.dispose() + + +@pytest.mark.asyncio +async def test_m4_end_to_end_all_9_acceptance_checks(): + """Verify all 9 Phase 1 acceptance criteria (Plan §7.5) with the real Epoch AI M0 case.""" + engine, session_factory, admin_token, viewer_token = await _build_m4_harness() + m0 = _load_m0_case() + admin_headers = {"Authorization": f"Bearer {admin_token}"} + viewer_headers = {"Authorization": f"Bearer {viewer_token}"} + + try: + with patch.object(ci_api, "_broadcast_compute_configuration_update", new=AsyncMock()): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + # ── Check 1: 修订识别 ── + new_meta = m0["new"] + ext1 = await client.post( + "/api/v1/situational-awareness/candidates/extract", + headers=admin_headers, + json={ + "year": m0["year"], + "excerpt": new_meta["excerpt"], + "source_id": new_meta["source_id"], + "source_title": new_meta["title"], + "source_url": new_meta["url"], + "publisher": new_meta["publisher"], + "locator": new_meta["locator"], + "published_at": new_meta["published_at"], + "report_year": new_meta["report_year"], + }, + ) + assert ext1.status_code == 200 + cand_ok = ext1.json()["items"][0] + comp = cand_ok["comparison"] + assert comp["has_historical_revision"] is True + assert comp["metric"] == "chip_inflow_share" + assert comp["denominator"] == "ai_chip_inflow" + assert comp["codes"]["CN"]["old_value"] == 11.0 + assert comp["codes"]["CN"]["new_value"] == 9.9 + assert comp["codes"]["CN"]["delta"] == -1.1 + assert comp["codes"]["CN"]["change_kind"] == "historical_revision" + assert cand_ok["source_payload"]["locator"] == new_meta["locator"] + + # Duplicate extraction does NOT create a new candidate (Check 3 dedupe part) + ext_dup = await client.post( + "/api/v1/situational-awareness/candidates/extract", + headers=admin_headers, + json={ + "year": m0["year"], + "excerpt": new_meta["excerpt"], + "source_id": new_meta["source_id"], + "source_title": new_meta["title"], + "source_url": new_meta["url"], + "publisher": new_meta["publisher"], + "locator": new_meta["locator"], + "published_at": new_meta["published_at"], + "report_year": new_meta["report_year"], + }, + ) + assert ext_dup.status_code == 200 + assert ext_dup.json()["items"][0]["duplicate"] is True + assert ext_dup.json()["items"][0]["id"] == cand_ok["id"] + + # ── Check 2: 人工决策留痕 + viewer 403 ── + # Extract a second candidate to reject + ext_rej = await client.post( + "/api/v1/situational-awareness/candidates/extract", + headers=admin_headers, + json={ + "year": 2024, + "excerpt": "2024年,美国全球算力份额为45%,中国全球算力份额为22%。", + "source_id": "unverified-blog-2026", + "source_title": "Unverified Blog", + "source_url": "https://example.invalid/blog", + "publisher": "Unknown", + "locator": "Paragraph 1", + }, + ) + assert ext_rej.status_code == 200 + rej_id = ext_rej.json()["items"][0]["id"] + + # Viewer gets 403 on review and publish + assert ( + await client.post( + f"/api/v1/situational-awareness/candidates/{cand_ok['id']}/review", + headers=viewer_headers, + json={ + "decision": "approved", + "reason_code": "newer_authoritative_report", + "reason": "Viewer attempt", + }, + ) + ).status_code == 403 + cfg_a = ( + await client.get("/api/v1/data-products/compute/configuration", headers=admin_headers) + ).json() + assert ( + await client.put( + "/api/v1/data-products/compute/configuration", + headers=viewer_headers, + json={"revision": cfg_a["revision"], "config": cfg_a["config"]}, + ) + ).status_code == 403 + + # Admin rejects invalid candidate with recorded reason + rej_resp = await client.post( + f"/api/v1/situational-awareness/candidates/{rej_id}/review", + headers=admin_headers, + json={ + "decision": "rejected", + "reason_code": "unverifiable_source", + "reason": "博客二手引用无法核验原始口径与分母。", + }, + ) + assert rej_resp.status_code == 200 + assert rej_resp.json()["review_reason_code"] == "unverifiable_source" + assert "无法核验" in rej_resp.json()["review_reason"] + + # Admin approves real M0 candidate & publishes rev B + appr_resp = await client.post( + f"/api/v1/situational-awareness/candidates/{cand_ok['id']}/review", + headers=admin_headers, + json={ + "decision": "approved", + "reason_code": "newer_authoritative_report", + "reason": "Epoch AI 官方 2026-11-12 Changelog 明确修订 CN=9.9%。", + }, + ) + assert appr_resp.status_code == 200 + + cfg_b_payload = copy.deepcopy(cfg_a["config"]) + cfg_b_payload["sources"].append( + { + "id": new_meta["source_id"], + "title": new_meta["title"], + "publisher": new_meta["publisher"], + "url": new_meta["url"], + "locator": new_meta["locator"], + "report_year": new_meta["report_year"], + "published_at": new_meta["published_at"], + } + ) + for obs in cfg_b_payload["observations"]: + if obs["metric"] == "chip_inflow_share" and obs["year"] == 2025: + obs["values"]["CN"] = 9.9 + obs["value_sources"] = {"CN": new_meta["source_id"]} + break + + rev_a = cfg_a["publish_id"] + pub_b = await client.put( + "/api/v1/data-products/compute/configuration", + headers=admin_headers, + json={ + "revision": cfg_a["revision"], + "config": cfg_b_payload, + "publish_note": "采用 Epoch AI 2026-11-12 同分母修订值更新中国 2025 份额。", + "source_candidate_ids": [cand_ok["id"]], + }, + ) + assert pub_b.status_code == 200 + rev_b_body = pub_b.json() + rev_b = rev_b_body["publish_id"] + assert rev_b_body["presentation_status"] == "delivered" + + # ── Check 3: 主动演播内容 ── + pres_resp = await client.get("/api/v1/situational-awareness/presentations") + assert pres_resp.status_code == 200 + rev_pres = [ + p + for p in pres_resp.json()["items"] + if p.get("presentation_key") == "compute-revision-notice" + ] + assert len(rev_pres) == 1 + contract_b = rev_pres[0]["contract"] + assert contract_b["publish_id"] == rev_b + assert "2025" in contract_b["title"] and "获修订" in contract_b["title"] + assert "历史数据的修订" in contract_b["steps"][0]["caption"] + + # ── Check 4, 5, 6, 7: 同源、血缘脱敏、切回发布前、只修订中国 ── + series_b = ( + await client.get( + "/api/v1/data-products/compute/series", + params={"countries": "CN,US", "mode": "chip_inflow_share"}, + ) + ).json() + assert series_b["publish_id"] == rev_b + row_2025_b = next(r for r in series_b["compute"] if r["year"] == 2025) + assert row_2025_b["values"] == {"CN": 9.9, "US": 72.0} + assert row_2025_b["evidence_by_code"]["CN"] == ["epoch-chip-imports-2026-11"] + assert row_2025_b["evidence_by_code"]["US"] == ["epoch-chip-imports-2026"] + + # Switch back to rev_a -> old values in both /series and Copilot + series_a = ( + await client.get( + "/api/v1/data-products/compute/series", + params={"countries": "CN,US", "mode": "chip_inflow_share", "publish_id": rev_a}, + ) + ).json() + assert series_a["publish_id"] == rev_a + row_2025_a = next(r for r in series_a["compute"] if r["year"] == 2025) + assert row_2025_a["values"] == {"CN": 11.0, "US": 72.0} + + # ── Check 8: A -> B -> A + stale revision 409 ── + stale_resp = await client.put( + "/api/v1/data-products/compute/configuration", + headers=admin_headers, + json={ + "revision": cfg_a["revision"], # stale token! + "config": cfg_b_payload, + "publish_note": "stale write", + }, + ) + assert stale_resp.status_code == 409 + + # Reset back to A with simulated presentation failure (also exercises Check 9!) + with patch( + "app.services.ai.proactive_pipeline.process_compute_revision_presentation", + side_effect=RuntimeError("simulated outage during reset"), + ): + reset_resp = await client.post( + "/api/v1/data-products/compute/configuration/reset", + headers=admin_headers, + json={ + "revision": rev_b, + "publish_note": "回退至内置基线口径以便对照验证。", + }, + ) + assert reset_resp.status_code == 200 + rev_a2 = reset_resp.json()["publish_id"] + assert rev_a2 != rev_a and rev_a2 != rev_b + assert reset_resp.json()["presentation_status"] == "failed" + + # Verify 3 distinct points A, B, A2 + s_a = ( + await client.get( + "/api/v1/data-products/compute/series", + params={"countries": "CN,US", "mode": "chip_inflow_share", "publish_id": rev_a}, + ) + ).json() + s_b = ( + await client.get( + "/api/v1/data-products/compute/series", + params={"countries": "CN,US", "mode": "chip_inflow_share", "publish_id": rev_b}, + ) + ).json() + s_a2 = ( + await client.get( + "/api/v1/data-products/compute/series", + params={"countries": "CN,US", "mode": "chip_inflow_share", "publish_id": rev_a2}, + ) + ).json() + assert next(r for r in s_a["compute"] if r["year"] == 2025)["values"]["CN"] == 11.0 + assert next(r for r in s_b["compute"] if r["year"] == 2025)["values"]["CN"] == 9.9 + assert next(r for r in s_a2["compute"] if r["year"] == 2025)["values"]["CN"] == 11.0 + + # ── Check 9: 中断补播 + 幂等 ── + retry_resp = await client.post( + "/api/v1/situational-awareness/proactive/evaluate", + headers=admin_headers, + json={"domain": "compute"}, + ) + assert retry_resp.status_code == 200 + assert retry_resp.json()["delivered"] == 1 + + db_check = session_factory() + try: + all_rev_pres = ( + await db_check.execute( + select(StagePresentation) + .where(StagePresentation.presentation_key == "compute-revision-notice") + .order_by(StagePresentation.revision.asc()) + ) + ).scalars().all() + # One for rev_b, one for rev_a2 (B->A) + assert len(all_rev_pres) == 2 + assert all_rev_pres[0].contract["publish_id"] == rev_b + assert all_rev_pres[1].contract["publish_id"] == rev_a2 + assert all_rev_pres[1].revision > all_rev_pres[0].revision + finally: + db_check.close() + + # Running retry again creates zero duplicate presentations + retry_again = await client.post( + "/api/v1/situational-awareness/proactive/evaluate", + headers=admin_headers, + json={"domain": "compute"}, + ) + assert retry_again.status_code == 200 + assert retry_again.json()["delivered"] == 0 + db_check2 = session_factory() + try: + count_after = len( + ( + await db_check2.execute( + select(StagePresentation).where( + StagePresentation.presentation_key == "compute-revision-notice" + ) + ) + ).scalars().all() + ) + assert count_after == 2 + finally: + db_check2.close() + finally: + app.dependency_overrides.clear() + engine.dispose() diff --git a/backend/tests/test_compute_revisions.py b/backend/tests/test_compute_revisions.py new file mode 100644 index 00000000..025cb924 --- /dev/null +++ b/backend/tests/test_compute_revisions.py @@ -0,0 +1,440 @@ +"""Tests for M1 compute configuration revision ledger, ABA protection, as-of replay, diff, and migration 0007.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from copy import deepcopy +from datetime import UTC, datetime, timedelta +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock + +from fastapi import FastAPI +from httpx import ASGITransport, AsyncClient +import pytest +from sqlalchemy import create_engine, select, text +from sqlalchemy.orm import Session + +from app.api.v1 import compute_intelligence, situational_awareness +from app.core.security import get_current_user +from app.db.migration_steps import __file__ as migration_steps_init +from app.db.migrations import run_migrations +from app.db.session import get_db +from app.models.compute_configuration_revision import ComputeConfigurationRevision +from app.models.situational_assessment import ( + ComputeEvidenceCandidate, + EvidenceRecord, + SituationalAssessment, +) +from app.models.system_log import AuditLog +from app.models.system_setting import SystemSetting +from app.schemas.compute_configuration import ComputeConfiguration +from app.services.ai_client import get_ai_provider_client +from app.services.compute_configuration import ( + DEFAULT_CONFIGURATION, + DEFAULT_REVISION, + default_envelope, + ensure_compute_revision_baseline, + list_configuration_revisions, + publish_configuration, + read_configuration, +) +from app.services.compute_revision_diff import ( + diff_compute_configurations, + has_observation_value_delta, +) + + +def _make_sqlite_async_session(): + engine = create_engine("sqlite://") + for model in ( + SystemSetting, + AuditLog, + ComputeConfigurationRevision, + ComputeEvidenceCandidate, + EvidenceRecord, + SituationalAssessment, + ): + model.__table__.create(engine) + raw = Session(engine) + session = SimpleNamespace( + execute=AsyncMock(side_effect=raw.execute), + add=raw.add, + delete=AsyncMock(side_effect=raw.delete), + flush=AsyncMock(side_effect=raw.flush), + commit=AsyncMock(side_effect=raw.commit), + rollback=AsyncMock(side_effect=raw.rollback), + refresh=AsyncMock(side_effect=raw.refresh), + get_bind=raw.get_bind, + bind=engine, + ) + return engine, raw, session + + +def _mutated_config(cn_2024: float = 24.5) -> ComputeConfiguration: + payload = DEFAULT_CONFIGURATION.model_dump(mode="json") + for obs in payload["observations"]: + if obs["metric"] == "global_share" and obs["year"] == 2024: + obs["values"]["CN"] = cn_2024 + break + return ComputeConfiguration.model_validate(payload) + + +def _cn_2024(envelope: dict) -> float: + for obs in envelope["config"]["observations"]: + if obs["metric"] == "global_share" and obs["year"] == 2024: + return float(obs["values"]["CN"]) + raise AssertionError("2024 global_share row not found") + + +@pytest.mark.asyncio +async def test_aba_history_as_of_replay_and_stale_token_conflict(): + engine, raw, db = _make_sqlite_async_session() + try: + actor = SimpleNamespace(id=1, username="admin", role="admin") + t_before_baseline = datetime.now(UTC) - timedelta(seconds=10) + baseline = await ensure_compute_revision_baseline( + db, published_at=datetime.now(UTC) - timedelta(seconds=5) + ) + assert baseline is not None + t0_token = baseline.publish_id + assert t0_token == DEFAULT_REVISION + t_after_a = datetime.now(UTC) - timedelta(seconds=3) + + # Publish B (CN 2024: 23 -> 24.5) + env_b = await publish_configuration( + db, + revision=t0_token, + config=_mutated_config(24.5), + actor=actor, + publish_note="Revise 2024 CN share", + ) + assert env_b["no_changes"] is False + assert env_b["publish_id"] != t0_token + assert env_b["presentation_status"] == "pending" + + # Separate timestamps cleanly for deterministic as_of checks. + rows = raw.execute( + select(ComputeConfigurationRevision).order_by(ComputeConfigurationRevision.id.asc()) + ).scalars().all() + assert len(rows) == 2 + rows[1].published_at = (datetime.now(UTC) - timedelta(seconds=2)).replace(tzinfo=None) + raw.commit() + t_after_b = datetime.now(UTC) - timedelta(seconds=1) + + # Reset B -> A (creates a 3rd revision with a brand new publish_id, never reusing DEFAULT_REVISION) + env_a2 = await publish_configuration( + db, + revision=env_b["publish_id"], + config=DEFAULT_CONFIGURATION, + actor=actor, + reset=True, + ) + assert env_a2["is_default"] is True + assert env_a2["publish_id"] not in {t0_token, env_b["publish_id"]} + assert env_a2["publish_id"] != DEFAULT_REVISION + assert env_a2["action"] == "reset" + assert env_a2["presentation_status"] == "pending" + t_after_a2 = datetime.now(UTC) + timedelta(seconds=2) + + # Verify 3 distinct revisions exist + revisions = await list_configuration_revisions(db, limit=10) + assert len(revisions) == 3 + assert len({r["publish_id"] for r in revisions}) == 3 + + # Verify as_of returns A, B, A at the three timestamps + snap_before = await read_configuration(db, as_of=t_before_baseline) + assert snap_before["snapshot_unavailable"] is True + assert snap_before["publish_id"] is None + + snap_a1 = await read_configuration(db, as_of=t_after_a) + assert snap_a1["snapshot_unavailable"] is False + assert snap_a1["publish_id"] == t0_token + assert _cn_2024(snap_a1) == 23.0 + + snap_b = await read_configuration(db, as_of=t_after_b) + assert snap_b["publish_id"] == env_b["publish_id"] + assert _cn_2024(snap_b) == 24.5 + + snap_a2 = await read_configuration(db, as_of=t_after_a2) + assert snap_a2["publish_id"] == env_a2["publish_id"] + assert _cn_2024(snap_a2) == 23.0 + + # ABA conflict: stale client holding T0 after B -> A reset must receive 409! + from fastapi import HTTPException + + with pytest.raises(HTTPException) as conflict: + await publish_configuration( + db, + revision=t0_token, + config=_mutated_config(26.0), + actor=actor, + ) + assert conflict.value.status_code == 409 + + # Direct publish_id lookup + pinned_b = await read_configuration(db, publish_id=env_b["publish_id"]) + assert _cn_2024(pinned_b) == 24.5 + with pytest.raises(HTTPException) as missing: + await read_configuration(db, publish_id="nonexistent-pid") + assert missing.value.status_code == 404 + finally: + raw.close() + engine.dispose() + + +@pytest.mark.asyncio +async def test_no_changes_publish_and_baseline_idempotency(): + engine, raw, db = _make_sqlite_async_session() + try: + # Pre-seed an existing custom SystemSetting to test baseline preserves pre-upgrade revision + custom_env = default_envelope() + custom_env["revision"] = "legacy-pre-upgrade-rev-123" + custom_env["is_default"] = False + raw.add(SystemSetting(category="compute_comparison", payload=custom_env)) + raw.commit() + + b1 = await ensure_compute_revision_baseline(db) + b2 = await ensure_compute_revision_baseline(db) + assert b1 is not None and b2 is not None + assert b1.id == b2.id + assert b1.publish_id == "legacy-pre-upgrade-rev-123" + count = raw.execute(select(ComputeConfigurationRevision)).scalars().all() + assert len(count) == 1 + + # Submitting unchanged content returns no_changes=True and inserts no new revision + actor = SimpleNamespace(id=1, username="admin", role="admin") + res = await publish_configuration( + db, + revision="legacy-pre-upgrade-rev-123", + config=DEFAULT_CONFIGURATION, + actor=actor, + ) + assert res["no_changes"] is True + assert res["publish_id"] == "legacy-pre-upgrade-rev-123" + assert len(raw.execute(select(ComputeConfigurationRevision)).scalars().all()) == 1 + finally: + raw.close() + engine.dispose() + + +def test_diff_compute_configurations_captures_small_revisions_new_years_and_non_obs(): + old = DEFAULT_CONFIGURATION + new_payload = old.model_dump(mode="json") + # 1.5pp revision on 2024 CN global_share (below legacy 2.0pp threshold) + for obs in new_payload["observations"]: + if obs["metric"] == "global_share" and obs["year"] == 2024: + obs["values"]["CN"] = 24.5 + # Add new year observation + new_payload["sources"].append( + { + "id": "caict-2026-test", + "title": "CAICT 2026 Test", + "url": "https://www.caict.ac.cn/test", + "publisher": "CAICT", + "report_year": 2026, + "published_at": "2026-10-01", + "locator": "Page 10", + } + ) + new_payload["observations"].append( + { + "year": 2025, + "metric": "global_share", + "source_id": "caict-2026-test", + "values": {"CN": 25.0, "US": 43.0}, + } + ) + new_cfg = ComputeConfiguration.model_validate(new_payload) + diffs = diff_compute_configurations(old, new_cfg) + + rev_entry = next( + d + for d in diffs + if d["kind"] == "observation_value" + and d["metric"] == "global_share" + and d["year"] == 2024 + and d["code"] == "CN" + ) + assert rev_entry["old_value"] == 23.0 + assert rev_entry["new_value"] == 24.5 + assert rev_entry["delta"] == 1.5 + assert rev_entry["change_kind"] == "historical_revision" + assert has_observation_value_delta(diffs) is True + + new_year_entry = next( + d + for d in diffs + if d["kind"] == "observation_value" + and d["metric"] == "global_share" + and d["year"] == 2025 + and d["code"] == "CN" + ) + assert new_year_entry["change_kind"] == "new_observation" + assert new_year_entry["new_source_id"] == "caict-2026-test" + + # Milestone-only edit has no observation value delta + ms_payload = old.model_dump(mode="json") + ms_payload["milestones"][0]["title"] = "Updated milestone title" + ms_diffs = diff_compute_configurations(old, ComputeConfiguration.model_validate(ms_payload)) + assert has_observation_value_delta(ms_diffs) is False + assert any(d["kind"] == "section_changed" and d["section"] == "milestones" for d in ms_diffs) + + +@pytest.mark.asyncio +async def test_series_posture_and_revisions_http_endpoints_with_as_of(): + engine, raw, db = _make_sqlite_async_session() + try: + actor = SimpleNamespace(id=1, username="admin", role="admin") + baseline = await ensure_compute_revision_baseline( + db, published_at=datetime.now(UTC) - timedelta(seconds=10) + ) + assert baseline is not None + env_b = await publish_configuration( + db, + revision=baseline.publish_id, + config=_mutated_config(24.5), + actor=actor, + publish_note="HTTP test revision", + ) + + app = FastAPI() + app.include_router(compute_intelligence.router, prefix="/data-products/compute") + app.include_router(situational_awareness.router, prefix="/situational-awareness") + app.dependency_overrides[get_db] = lambda: db + app.dependency_overrides[get_ai_provider_client] = lambda: SimpleNamespace(service_url="") + app.dependency_overrides[get_current_user] = lambda: actor + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + # Admin revisions endpoint + rev_resp = await client.get("/data-products/compute/revisions?limit=10") + assert rev_resp.status_code == 200 + items = rev_resp.json()["items"] + assert len(items) == 2 + assert items[0]["publish_id"] == env_b["publish_id"] + assert items[0]["publish_note"] == "HTTP test revision" + + # Series pinned to baseline publish_id shows 23.0, current shows 24.5 + cur_series = (await client.get("/data-products/compute/series")).json() + assert cur_series["publish_id"] == env_b["publish_id"] + row_cur = next(r for r in cur_series["compute"] if r["year"] == 2024) + assert row_cur["values"]["CN"] == 24.5 + + old_series = ( + await client.get( + f"/data-products/compute/series?publish_id={baseline.publish_id}" + ) + ).json() + assert old_series["publish_id"] == baseline.publish_id + row_old = next(r for r in old_series["compute"] if r["year"] == 2024) + assert row_old["values"]["CN"] == 23.0 + + # Pre-baseline as_of returns snapshot_unavailable=True on both /series and /posture/compute + early_iso = (datetime.now(UTC) - timedelta(days=1)).isoformat() + unavail_series = ( + await client.get(f"/data-products/compute/series?as_of={early_iso}") + ).json() + assert unavail_series["snapshot_unavailable"] is True + assert unavail_series["publish_id"] is None + + unavail_posture = ( + await client.get(f"/situational-awareness/posture/compute?as_of={early_iso}") + ).json() + assert unavail_posture["snapshot_unavailable"] is True + assert "历史快照不完整" in unavail_posture["payload"]["headline"] + + # Posture pinned to baseline vs current have different publish_id & distinct content + p_old = ( + await client.get( + f"/situational-awareness/posture/compute?publish_id={baseline.publish_id}" + ) + ).json() + p_new = ( + await client.get( + f"/situational-awareness/posture/compute?publish_id={env_b['publish_id']}" + ) + ).json() + assert p_old["publish_id"] == baseline.publish_id + assert p_new["publish_id"] == env_b["publish_id"] + assert p_old["input_fingerprint"] != p_new["input_fingerprint"] + finally: + raw.close() + engine.dispose() + + +@pytest.mark.asyncio +async def test_migration_0007_idempotent_on_sqlite_and_postgresql_path(): + steps_dir = Path(migration_steps_init).resolve().parent + migration_file = steps_dir / "0007_add_compute_configuration_revisions.py" + assert migration_file.exists() + + import importlib.util + + spec = importlib.util.spec_from_file_location("m0007_test", migration_file) + assert spec and spec.loader + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + + # 1. SQLite path: run upgrade twice idempotently on pre-existing candidate table + sync_engine = create_engine("sqlite://") + with sync_engine.begin() as conn: + conn.execute( + text( + """ + CREATE TABLE compute_evidence_candidates ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + status VARCHAR(24) NOT NULL DEFAULT 'pending', + candidate_type VARCHAR(40) NOT NULL DEFAULT 'observation', + proposed_payload JSON NOT NULL DEFAULT '{}', + source_payload JSON NOT NULL DEFAULT '{}', + confidence FLOAT NOT NULL DEFAULT 0.8, + extractor_note TEXT NOT NULL DEFAULT '', + reviewed_by VARCHAR(120), + reviewed_at TIMESTAMP, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + ) + """ + ) + ) + + class _ConnAdapter: + def __init__(self, conn): + self._conn = conn + self.dialect = conn.dialect + + async def execute(self, stmt, params=None): + return self._conn.execute(stmt, params) if params is not None else self._conn.execute(stmt) + + class _EngineAdapter: + @asynccontextmanager + async def begin(self): + with sync_engine.begin() as c: + yield _ConnAdapter(c) + + async with _EngineAdapter().begin() as conn: + await mod.upgrade(conn) + await mod.upgrade(conn) # idempotent second run + + with sync_engine.connect() as conn: + rev_cols = {row[1] for row in conn.execute(text("PRAGMA table_info(compute_configuration_revisions)")).fetchall()} + assert {"id", "publish_id", "content_fingerprint", "config_payload", "diff_summary", "presentation_status"}.issubset(rev_cols) + cand_cols = {row[1] for row in conn.execute(text("PRAGMA table_info(compute_evidence_candidates)")).fetchall()} + assert {"comparison", "dedupe_fingerprint", "review_reason_code", "review_reason", "published_publish_id"}.issubset(cand_cols) + + # Also test migration runner picks up 0007 cleanly in an isolated steps copy + sync_engine.dispose() + + # 2. PostgreSQL dialect SQL path verification (idempotent DDL statements emitted) + pg_statements: list[str] = [] + + class _FakePgConn: + dialect = SimpleNamespace(name="postgresql") + + async def execute(self, stmt, _params=None): + pg_statements.append(str(stmt)) + return SimpleNamespace(fetchall=lambda: []) + + await mod.upgrade(_FakePgConn()) + await mod.upgrade(_FakePgConn()) + assert any("CREATE TABLE IF NOT EXISTS compute_configuration_revisions" in s for s in pg_statements) + assert any("ALTER TABLE compute_evidence_candidates" in s and "IF NOT EXISTS" in s for s in pg_statements) diff --git a/backend/tests/test_dag_executor.py b/backend/tests/test_dag_executor.py index a566d7a8..2e8cf59c 100644 --- a/backend/tests/test_dag_executor.py +++ b/backend/tests/test_dag_executor.py @@ -2,6 +2,7 @@ from __future__ import annotations +import copy import json from types import SimpleNamespace @@ -362,3 +363,212 @@ async def test_earth_stateless_stream_executes_published_custom_workflow_and_blo finally: app.dependency_overrides.clear() engine.dispose() + + +@pytest.mark.asyncio +async def test_generic_dag_supports_output_schema_field_routing_and_guardrail_edges(): + from app.services.ai import dag_executor + + class _RepairAI: + def __init__(self): + self.calls = 0 + + async def analyze(self, _req): + self.calls += 1 + if self.calls == 1: + return SimpleNamespace(content="暂时分析完成,结论是需要补查 need_followup。", model="m1", provider="p1") + return SimpleNamespace( + content=json.dumps({"decision": "need_followup", "reason": "need extra proof"}), + model="m1", + provider="p1", + ) + + workflow = { + "workflow_id": "custom.routing_test", + "name": "Generic Routing Test", + "published_graph": { + "nodes": [ + {"id": "t", "node_type": "trigger", "title": "Start"}, + { + "id": "judge", + "node_type": "llm_agent", + "title": "Judge", + "params": { + "output_schema": { + "type": "object", + "properties": { + "decision": {"type": "string", "enum": ["direct", "need_followup"]}, + "reason": {"type": "string"}, + }, + "required": ["decision", "reason"], + } + }, + }, + {"id": "branch_direct", "node_type": "output", "title": "Direct Branch"}, + {"id": "branch_followup", "node_type": "output", "title": "Followup Branch"}, + ], + "edges": [ + {"id": "e1", "source": "t", "target": "judge", "condition": "always"}, + { + "id": "e2", + "source": "judge", + "target": "branch_direct", + "condition": "on_field_equals", + "condition_value": "decision=direct", + }, + { + "id": "e3", + "source": "judge", + "target": "branch_followup", + "condition": "on_field_equals", + "condition_value": "decision=need_followup", + }, + ], + }, + "bindings": {}, + } + + ai = _RepairAI() + events = [] + async for evt in dag_executor.run_workflow_dag_stream( + db=None, + workflow=workflow, + question="Route test", + ai_client=ai, + ): + events.append(evt) + + assert ai.calls == 2 + node_statuses = { + e["data"]["node_id"]: e["data"]["status"] + for e in events + if e.get("event") == "node" and e["data"]["status"] in {"completed", "skipped"} + } + assert node_statuses["branch_direct"] == "skipped" + assert node_statuses["branch_followup"] == "completed" + + +@pytest.mark.asyncio +async def test_location_resolve_unknown_runs_real_generic_dag(monkeypatch): + from app.services.ai import dag_executor + from app.services.ai.workflow_registry import BUILTIN_WORKFLOWS + from app.services.location import workflow_tools + + monkeypatch.setattr( + workflow_tools, + "lookup_wikidata_facility", + lambda _q: _async_val(SimpleNamespace(candidates=(), attempted_queries=())), + ) + monkeypatch.setattr( + workflow_tools, + "lookup_peeringdb_facility", + lambda _q: _async_val(SimpleNamespace(candidates=(), attempted_queries=())), + ) + monkeypatch.setattr( + "app.services.compute_center_locations._lookup_ror_organization", + lambda _q: None, + ) + monkeypatch.setattr( + workflow_tools, + "_agent_geocoder", + lambda _q: { + "lat": "64.0025", + "lon": "-22.5594", + "display_name": "Keflavik, Iceland", + "address": {"city": "Keflavik", "country": "Iceland"}, + }, + ) + + class _Search: + async def search(self, _q, max_results=5): + return [ + SimpleNamespace( + title="ISEG2 Verne Global", + url="https://verneglobal.com/iseg2", + snippet="Nebius ISEG2 sits in Keflavik, Iceland.", + source_provider="tavily", + ) + ] + + class _JudgeAI: + def __init__(self): + self.calls = 0 + + async def is_ready(self): + return True, "minimax", "MiniMax-M3.1-Flash" + + async def analyze(self, req): + self.calls += 1 + items = (req.context or {}).get("evidence_items") or [] + assert items and items[0]["id"] == "E1" + return SimpleNamespace( + content=json.dumps( + { + "decision": "located", + "facility_name": "Verne Global", + "city": "Keflavik", + "country": "Iceland", + "precision": "city", + "confidence": 0.92, + "evidence_ids": ["E1"], + "country_override_reason": "Nebius HQ is NL while cluster sits in Iceland.", + "reasoning": "E1 confirms Keflavik, Iceland.", + } + ), + model="MiniMax-M3.1-Flash", + provider="minimax", + ) + + builtin_loc = copy.deepcopy(next(w for w in BUILTIN_WORKFLOWS if w["workflow_id"] == "location.resolve_unknown")) + workflow = { + "workflow_id": builtin_loc["workflow_id"], + "name": builtin_loc["name"], + "published_graph": builtin_loc["graph"], + "bindings": builtin_loc["bindings"], + } + + ai = _JudgeAI() + events = [] + async for evt in dag_executor.run_workflow_dag_stream( + db=None, + workflow=workflow, + question="定位 ISEG2", + targets=[{"entity_type": "compute_center", "entity_id": "top500_13", "label": "ISEG2"}], + earth_context={ + "name": "ISEG2", + "operator": "Nebius", + "country": "荷兰", + "_location_runtime": {"web_search_client": _Search()}, + }, + ai_client=ai, + allow_external_tools=True, + ): + events.append(evt) + + assert ai.calls == 1 + statuses = { + e["data"]["node_id"]: e["data"]["status"] + for e in events + if e.get("event") == "node" and e["data"]["status"] in {"completed", "skipped"} + } + assert statuses["l0_normalize"] == "completed" + assert statuses["l1_knowledge"] == "completed" + assert statuses["l2_research_r1"] == "completed" + assert statuses["l2_judge_r1"] == "completed" + assert statuses["l2_research_r2"] == "skipped" + assert statuses["l2_judge_r2"] == "skipped" + assert statuses["l3_geocode"] == "completed" + assert statuses["l3_geo_guardrail"] == "completed" + assert statuses["l4_persist_outcome"] == "completed" + + done_ev = next(e["data"] for e in events if e.get("event") == "done") + so = done_ev["structured_output"] + assert so["success"] is True + assert so["best_candidate"]["city"] == "Keflavik" + assert so["best_candidate"]["country"] == "冰岛" + assert so["best_candidate"]["raw_payload"]["citations"] == ["https://verneglobal.com/iseg2"] + assert done_ev["scene_spec"]["fly_to"]["lat"] == pytest.approx(64.0025) + + +async def _async_val(v): + return v diff --git a/backend/tests/test_data_ledger.py b/backend/tests/test_data_ledger.py new file mode 100644 index 00000000..1228e98c --- /dev/null +++ b/backend/tests/test_data_ledger.py @@ -0,0 +1,468 @@ +"""Tests for admin layer-based data ledger endpoints.""" + +from datetime import UTC, datetime + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from app.api.v1 import data_ledger as ledger_api +from app.core.security import get_current_user +from app.db.session import get_db +from app.main import app +from app.models.bgp_collector_location import BGPCollectorLocation +from app.models.bgp_incident import BGPIncident +from app.models.collected_data import CollectedData +from app.models.compute_center_location import ComputeCenterLocationRecord +from app.models.data_snapshot import DataSnapshot +from app.models.datasource import DataSource +from app.models.earth_news import EarthNewsItem +from app.models.situational_assessment import WorkflowRun +from app.models.task import CollectionTask +from app.models.user import User, UserRole +from app.models.vessel import VesselCurrentState + + +class _MemoryCache: + def __init__(self): + self.store = {} + + def get(self, key): + return self.store.get(key) + + def set(self, key, value, expire_seconds=300): + self.store[key] = value + return True + + +class _SyncAsAsyncSession: + def __init__(self, session): + self._session = session + + async def execute(self, stmt, params=None): + return self._session.execute(stmt, params or {}) + + async def scalar(self, stmt): + return self._session.scalar(stmt) + + +def _fake_admin_user() -> User: + return User( + id=1, + username="ledger_admin", + email="ledger@example.com", + role=UserRole.ADMIN, + is_active=True, + ) + + +def _seed_ledger_db(): + engine = create_engine("sqlite:///:memory:", future=True) + CollectedData.metadata.create_all( + engine, + tables=[ + DataSource.__table__, + DataSnapshot.__table__, + CollectionTask.__table__, + CollectedData.__table__, + ComputeCenterLocationRecord.__table__, + VesselCurrentState.__table__, + BGPCollectorLocation.__table__, + BGPIncident.__table__, + EarthNewsItem.__table__, + WorkflowRun.__table__, + ], + ) + sync_factory = sessionmaker(engine, expire_on_commit=False) + now = datetime(2026, 12, 3, 12, 0, tzinfo=UTC) + with sync_factory() as s: + s.add_all( + [ + DataSource( + name="CelesTrak TLE", + source="celestrak_tle", + module="L1", + collector_class="celestrak_tle", + ), + CollectedData( + source="top500", + source_id="top500_1", + entity_key="top500:top500_1", + data_type="supercomputer", + name="Frontier", + extra_data={"country": "美国", "city": "Oak Ridge", "organization": "ORNL"}, + collected_at=now, + is_current=True, + ), + CollectedData( + source="epoch_ai_gpu", + source_id="epoch_gpu_unverified", + entity_key="epoch_ai_gpu:epoch_gpu_unverified", + data_type="gpu_cluster", + name="Candidate Cluster", + extra_data={"country": "United States", "operator": "Acme"}, + collected_at=now, + is_current=True, + ), + CollectedData( + source="epoch_ai_gpu", + source_id="epoch_ibm_dyeus", + entity_key="epoch_ai_gpu:epoch_ibm_dyeus", + data_type="gpu_cluster", + name="IBM DYEUS", + extra_data={ + "country": "Россия", + "site_type": "data_center", + "location": "3231 Riverport Rd, Memphis, TN 38109", + }, + collected_at=now, + is_current=True, + ), + CollectedData( + source="epoch_ai_gpu", + source_id="epoch_pending_edge", + entity_key="epoch_ai_gpu:epoch_pending_edge", + data_type="edge_node", + name="Edge Node One", + extra_data={"country": "ישראל", "location": "Jülich Supercomputing Centre\n52428 Jülich, Germany"}, + collected_at=now, + is_current=True, + ), + CollectedData( + source="epoch_ai_gpu", + source_id="epoch_cloud_known", + entity_key="epoch_ai_gpu:epoch_cloud_known", + data_type="cloud_center", + name="Cloud Region Alpha", + extra_data={"country": "日本", "city": "Tokyo", "latitude": 35.68, "longitude": 139.76}, + collected_at=now, + is_current=True, + ), + CollectedData( + source="epoch_ai_gpu", + source_id="epoch_anon_placeholder", + entity_key="epoch_ai_gpu:epoch_anon_placeholder", + data_type="gpu_cluster", + name="Anonymized Chinese System", + extra_data={ + "compute_contract": "v1", + "anonymous": True, + "country": "中国", + "location": "China", + "sources": [], + }, + collected_at=now, + is_current=True, + ), + ComputeCenterLocationRecord( + source="top500", + source_id="top500_1", + name="Frontier", + city="Oak Ridge", + country="美国", + latitude=35.93, + longitude=-84.31, + precision="site", + location_source="official_facility_registry", + verification_status="verified", + source_note="ORNL 官方页面确认。", + ), + ComputeCenterLocationRecord( + source="epoch_ai_gpu", + source_id="epoch_cloud_known", + name="Cloud Region Alpha", + city="Tokyo", + country="日本", + latitude=35.68, + longitude=139.76, + precision="city", + location_source="source_coordinates", + verification_status="source_provided", + source_note="源数据自带城市级坐标。", + ), + ComputeCenterLocationRecord( + source="epoch_ai_gpu", + source_id="epoch_gpu_unverified", + name="Candidate Cluster", + city="Dallas", + country="美国", + latitude=32.77, + longitude=-96.79, + precision="city", + location_source="llm_location_factcheck", + verification_status="unverified", + needs_confirmation=True, + source_note="待人工确认候选取样(E1)。", + ), + ComputeCenterLocationRecord( + source="epoch_ai_gpu", + source_id="epoch_ibm_dyeus", + name="IBM DYEUS", + country="Россия", + precision="unknown", + location_source="agent_terminal_undisclosed", + verification_status="undisclosed", + needs_confirmation=False, + source_note="E6 confirms DYEUS location is undisclosed (E1-E5).", + raw_payload={"workflow_run_id": "run_dyeus_99"}, + ), + CollectedData( + source="celestrak_tle", + source_id="25544", + entity_key="celestrak_tle:25544", + data_type="satellite_tle", + name="ISS (ZARYA)", + extra_data={ + "international_designator": "1998-067A", + "constellation_group": "stations", + "inclination": 51.6416, + }, + collected_at=now, + is_current=True, + ), + CollectedData( + source="spacetrack_tle", + source_id="", + entity_key="spacetrack_tle:", + data_type="satellite_tle", + name="Unknown", + extra_data={}, + collected_at=now, + is_current=True, + ), + CollectedData( + source="arcgis_cables", + source_id="cable_1", + entity_key="arcgis_cables:cable_1", + data_type="submarine_cable", + name="Asia-America Gateway", + extra_data={"country": "国际"}, + collected_at=now, + is_current=True, + ), + CollectedData( + source="arcgis_landing_points", + source_id="lp_1", + entity_key="arcgis_landing_points:lp_1", + data_type="landing_point", + name="Changi", + extra_data={"country": "新加坡"}, + collected_at=now, + is_current=True, + ), + CollectedData( + source="news_live_streams", + source_id="stream_1", + entity_key="news_live_streams:stream_1", + data_type="news_live_stream", + name="ABC News", + extra_data={"region": "全球", "language": "en"}, + collected_at=now, + is_current=True, + ), + CollectedData( + source="global_cloud_map", + source_id="cloud_1", + entity_key="global_cloud_map:cloud_1", + data_type="cloud_map_record", + name="Global Cloud Frame", + extra_data={}, + collected_at=now, + is_current=True, + ), + CollectedData( + source="earth_imagery_sentinel2", + source_id="tile_1", + entity_key="earth_imagery_sentinel2:tile_1", + data_type="earth_tile_pyramid", + name="Sentinel-2 Global", + extra_data={}, + collected_at=now, + is_current=True, + ), + VesselCurrentState( + mmsi=413000001, + lat=31.2, + lon=121.5, + sog=12.4, + name="COSCO STAR", + vessel_type_name="Cargo", + flag="CN", + source="aisstream_vessels", + observed_at=now, + ), + BGPCollectorLocation( + collector_id="rrc00", + operator="RIPE NCC", + city="Amsterdam", + country="荷兰", + verification_status="verified", + updated_at=now, + ), + BGPIncident( + source="ris_live_bgp", + incident_key="inc_1", + incident_type="route_leak", + title="Test Route Leak", + summary="Summary", + severity="high", + status="active", + started_at=now, + created_at=now, + ), + EarthNewsItem( + id="news_1", + title="海底光缆维护通告", + url="https://example.com/news/1", + source="Reuters", + region="亚太", + latitude=1.35, + longitude=103.82, + location_label="Singapore", + published_at=now, + ), + ] + ) + s.commit() + + class _Ctx: + def __call__(self): + return self + + async def __aenter__(self): + self._s = sync_factory() + return _SyncAsAsyncSession(self._s) + + async def __aexit__(self, exc_type, exc, tb): + self._s.close() + return False + + return engine, _Ctx() + + +@pytest.mark.asyncio +async def test_data_ledger_layers_compute_buckets_sanitization_and_layer_items(monkeypatch): + engine, session_factory = _seed_ledger_db() + mem_cache = _MemoryCache() + monkeypatch.setattr(ledger_api, "cache", mem_cache) + monkeypatch.setattr("app.api.v1.collected_data.cache", mem_cache) + + async def override_get_db(): + async with session_factory() as session: + yield session + + app.dependency_overrides.update({get_db: override_get_db, get_current_user: _fake_admin_user}) + try: + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + layers_res = await client.get("/api/v1/data-ledger/layers") + assert layers_res.status_code == 200 + layers = {item["id"]: item for item in layers_res.json()["layers"]} + assert set(["compute", "satellites", "cables", "vessels", "bgp", "news", "weather", "geo", "raw"]).issubset(layers.keys()) + assert layers["compute"]["count"] == 6 + assert layers["vessels"]["count"] == 1 + assert layers["news"]["name"] == "新闻与直播" + assert layers["news"]["count"] == 2 + + cc_res = await client.get("/api/v1/data-ledger/compute-centers") + assert cc_res.status_code == 200 + cc = cc_res.json() + assert cc["total"] == 6 + assert cc["counts"]["by_status"] == { + "located": 2, + "needs_confirmation": 1, + "terminal": 2, + "pending": 1, + } + assert cc["counts"]["by_site_type"] == { + "supercomputer": 1, + "gpu_cluster": 2, + "data_center": 1, + "cloud_center": 1, + "edge_node": 1, + } + ordered_ids = [row["source_id"] for row in cc["items"]] + assert ordered_ids[0] == "epoch_pending_edge" + assert ordered_ids[1] == "epoch_gpu_unverified" + assert ordered_ids[-2:] == ["epoch_ibm_dyeus", "epoch_anon_placeholder"] + + by_sid = {row["source_id"]: row for row in cc["items"]} + assert by_sid["epoch_anon_placeholder"]["is_anonymous_placeholder"] is True + assert by_sid["epoch_anon_placeholder"]["city"] is None + assert by_sid["epoch_gpu_unverified"]["city"] == "Dallas" + assert by_sid["epoch_gpu_unverified"]["country"] == "美国" + assert by_sid["epoch_ibm_dyeus"]["city"] == "Memphis" + assert by_sid["epoch_pending_edge"]["city"] == "Jülich" + assert by_sid["epoch_pending_edge"]["country"] == "以色列" + assert by_sid["epoch_ibm_dyeus"]["country"] == "俄罗斯" + assert layers["satellites"]["count"] == 1 + assert by_sid["epoch_ibm_dyeus"]["is_anonymous_placeholder"] is False + assert by_sid["epoch_ibm_dyeus"]["terminal_status"] == "undisclosed" + assert by_sid["epoch_ibm_dyeus"]["workflow_run_id"] == "run_dyeus_99" + assert "E6" not in (by_sid["epoch_ibm_dyeus"]["source_note"] or "") + assert "E1" not in (by_sid["epoch_gpu_unverified"]["source_note"] or "") + + sat_res = await client.get("/api/v1/data-ledger/satellites/items?page=1&page_size=10") + assert sat_res.status_code == 200 + sat_body = sat_res.json() + assert sat_body["total"] == 1 + assert sat_body["rows"][0]["source"] == "CelesTrak TLE" + assert sat_body["rows"][0]["international_designator"] == "1998-067A" + assert sat_body["rows"][0]["constellation_group"] == "stations" + assert sat_body["rows"][0]["inclination"] == "51.64°" + + status_res = await client.get("/api/v1/data-ledger/compute-centers?status=terminal") + assert status_res.status_code == 200 + assert status_res.json()["total"] == 2 + assert [r["source_id"] for r in status_res.json()["items"]] == [ + "epoch_ibm_dyeus", + "epoch_anon_placeholder", + ] + + for path in ( + "/api/v1/data-ledger/satellites/items?page=1&page_size=1", + "/api/v1/data-ledger/cables/items?kind=landing_point", + "/api/v1/data-ledger/vessels/items?page=1&page_size=1", + "/api/v1/data-ledger/bgp/items?kind=incidents", + "/api/v1/data-ledger/news/items?kind=items", + "/api/v1/data-ledger/news/items?kind=live_streams", + "/api/v1/data-ledger/weather/items", + "/api/v1/data-ledger/geo/items", + ): + r = await client.get(path) + assert r.status_code == 200, f"{path} failed: {r.text}" + body = r.json() + assert body["total"] == 1 + assert len(body["rows"]) == 1 + assert len(body["columns"]) >= 4 + + missing = await client.get("/api/v1/data-ledger/nonexistent/items") + assert missing.status_code == 404 + finally: + app.dependency_overrides.clear() + engine.dispose() + + +def test_extract_city_from_location_cases(): + assert ledger_api._normalize_ledger_country("Philippines (the)") == "菲律宾" + assert ledger_api._extract_city_from_location("Tsukuba, Japan", "日本") == "Tsukuba" + assert ledger_api._extract_city_from_location("3231 Riverport Rd, Memphis, TN 38109", "美国") == "Memphis" + assert ( + ledger_api._extract_city_from_location( + "33°24'28.7\"N 112°21'54.3\"W\nGoodyear, Arizona, USA", + "美国", + ) + == "Goodyear" + ) + assert ( + ledger_api._extract_city_from_location( + "Jülich Supercomputing Centre (JSC)\n52428 Jülich, Germany", + "德国", + ) + == "Jülich" + ) + assert ledger_api._extract_city_from_location("Follummoveien 94, 3516 Hønefoss, Norway", "挪威") == "Hønefoss" + assert ledger_api._extract_city_from_location("United States of America", "美国") is None + assert ledger_api._extract_city_from_location('"on prem" for Tesla', "美国") is None + assert ledger_api._extract_city_from_location("The Nordics", None) is None diff --git a/backend/tests/test_datasource_config_masked_preview.py b/backend/tests/test_datasource_config_masked_preview.py new file mode 100644 index 00000000..0d447811 --- /dev/null +++ b/backend/tests/test_datasource_config_masked_preview.py @@ -0,0 +1,65 @@ +"""Unit tests for masked collector credential previews on dashboard config summaries.""" + +from __future__ import annotations + +from app.api.v1.datasource_config import ( + build_masked_credential_preview, + mask_credential_value, +) + + +def test_mask_credential_value_never_leaks_secrets() -> None: + assert mask_credential_value("") == "" + assert mask_credential_value("secret-pass", secret=True) == "••••••" + assert mask_credential_value("short", secret=True, reveal_edges=True) == "••••••" + assert mask_credential_value("tvly-dev-123456789a4f", secret=True, reveal_edges=True) == "tvl••••9a4f" + assert mask_credential_value("bw_client_82", secret=False) == "bw•••82" + assert mask_credential_value("ops", secret=False) == "•••" + + +def test_build_masked_credential_preview_variants() -> None: + assert build_masked_credential_preview( + requires_credentials=False, + auth_type="none", + auth_config={}, + ) == (True, "") + + has_creds, preview = build_masked_credential_preview( + requires_credentials=True, + auth_type="oauth2", + auth_config={}, + resolved_provider="barentswatch", + resolved_values={"client_id": "bw_client_82", "client_secret": "super-secret-xyz"}, + ) + assert has_creds is True + assert preview == "bw•••82 · ••••••" + assert "super-secret" not in preview + + has_creds, preview = build_masked_credential_preview( + requires_credentials=True, + auth_type="basic", + auth_config={"username": "ops_user_1", "password": "top_password"}, + resolved_provider="spacetrack", + ) + assert has_creds is True + assert preview == "op•••_1 · ••••••" + assert "top_password" not in preview + + has_creds, preview = build_masked_credential_preview( + requires_credentials=True, + auth_type="api_key", + auth_config={"api_key": "ais_key_abcdef12"}, + resolved_provider="aisstream", + ) + assert has_creds is True + assert preview == "ais••••ef12" + assert "abcdef" not in preview + + has_creds, preview = build_masked_credential_preview( + requires_credentials=True, + auth_type="api_key", + auth_config={}, + resolved_provider="aisstream", + ) + assert has_creds is False + assert preview == "" diff --git a/backend/tests/test_earth_api_access.py b/backend/tests/test_earth_api_access.py index 3000044f..f0f8f8c5 100644 --- a/backend/tests/test_earth_api_access.py +++ b/backend/tests/test_earth_api_access.py @@ -212,6 +212,8 @@ async def test_enforce_mode_blocks_anonymous_endpoints_and_allows_public_exempti "/api/v1/news/earth-feed", "/api/v1/data-products/compute/configuration", "/api/v1/earth/brand", + "/api/v1/earth/boundaries/manifest", + "/api/v1/earth/boundaries/files/earth-boundaries.test.pmtiles", "/api/v1/tv/streams", ]: resp = await client.get(protected_path) @@ -616,3 +618,165 @@ async def test_controlled_openapi_and_production_mode_defaults(monkeypatch, acce assert "/api/v1/visualization/geo/summary" in ext["paths"] assert "/api/v1/users" not in ext["paths"] assert "/api/v1/settings/integrations" not in ext["paths"] + + +@pytest.mark.asyncio +async def test_tile_rate_limit_tier_isolated_from_business_apis(monkeypatch, access_db): + monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce") + monkeypatch.setattr(settings, "TURNSTILE_SECRET_KEY", "") + monkeypatch.setattr(settings, "EARTH_SESSION_RATE_LIMIT_PER_MIN", 2) + monkeypatch.setattr(settings, "EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN", 3) + + from app.api.v1 import earth as earth_api + from app.api.v1 import visualization as visualization_api + + async def _mock_fetch_terrain_tile(_client, _z: int, _x: int, _y: int): + return b"png", "image/png", {} + + async def _mock_get_or_fetch_tile(_source_key: str, _z: int, _x: int, _y: int, **_kwargs): + return b"webp", True + + monkeypatch.setattr(visualization_api, "_fetch_terrain_tile", _mock_fetch_terrain_tile) + monkeypatch.setattr(earth_api, "resolve_boundary_artifact", lambda _name: None) + import app.services.earth_tiles as earth_tiles_service + monkeypatch.setattr(earth_tiles_service, "get_or_fetch_tile", _mock_get_or_fetch_tile) + + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + session_resp = await client.post( + "/api/v1/auth/earth-session", + json={"client_type": "web"}, + headers={"Origin": "http://test", "Sec-Fetch-Site": "same-origin"}, + ) + assert session_resp.status_code == 200 + + # Exhaust the tile bucket across boundaries, basemap tiles, and terrarium tiles (3 total). + assert ( + await client.get("/api/v1/earth/boundaries/files/missing.pmtiles") + ).status_code == 404 + assert ( + await client.get("/api/v1/earth/tiles/sentinel2_hd/2/1/1.webp") + ).status_code == 200 + assert ( + await client.get("/api/v1/visualization/terrain/terrarium/2/1/1.png") + ).status_code == 200 + assert ( + await client.get("/api/v1/earth/boundaries/files/missing.pmtiles") + ).status_code == 429 + + # Business API bucket remains completely unaffected until its own limit (2). + assert (await client.get("/api/v1/earth/brand")).status_code == 200 + assert (await client.get("/api/v1/earth/boundaries/status")).status_code == 200 + assert (await client.get("/api/v1/earth/brand")).status_code == 429 + + +@pytest.mark.asyncio +async def test_desktop_earth_session_rate_limit_isolated_by_client_ip(monkeypatch, access_db): + monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce") + secret = "desktop-shared-hmac-secret" + monkeypatch.setattr(settings, "EARTH_DESKTOP_HANDSHAKE_SECRET", secret) + monkeypatch.setattr(settings, "EARTH_SESSION_RATE_LIMIT_PER_MIN", 1) + + client_header = "planet-earth-desktop/0.82.0" + + def _signed_headers(nonce: str, client_ip: str) -> dict[str, str]: + ts = str(int(time.time())) + sig = hmac.new( + secret.encode("utf-8"), + f"{ts}.{nonce}.{client_header}".encode("utf-8"), + hashlib.sha256, + ).hexdigest() + return { + "X-Forwarded-For": client_ip, + "X-Planet-Client": client_header, + "X-Planet-Client-Timestamp": ts, + "X-Planet-Client-Nonce": nonce, + "X-Planet-Client-Signature": sig, + } + + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + r1 = await client.post( + "/api/v1/auth/earth-session", + json={"client_type": "desktop"}, + headers=_signed_headers("nonce-ip-1", "10.0.0.1"), + ) + r2 = await client.post( + "/api/v1/auth/earth-session", + json={"client_type": "desktop"}, + headers=_signed_headers("nonce-ip-2", "10.0.0.2"), + ) + assert r1.status_code == 200 and r2.status_code == 200 + tok1 = r1.json()["token"] + tok2 = r2.json()["token"] + + c1 = access_gate.verify_earth_session_token(tok1) + c2 = access_gate.verify_earth_session_token(tok2) + assert c1 is not None and c2 is not None + assert c1["cid"] != c2["cid"] + assert c1["cid"].startswith("10.0.0.1:") + assert c2["cid"].startswith("10.0.0.2:") + + assert ( + await client.get("/api/v1/earth/brand", headers={EARTH_TOKEN_HEADER: tok1}) + ).status_code == 200 + assert ( + await client.get("/api/v1/earth/brand", headers={EARTH_TOKEN_HEADER: tok1}) + ).status_code == 429 + # Second desktop client IP still has its own fresh quota. + assert ( + await client.get("/api/v1/earth/brand", headers={EARTH_TOKEN_HEADER: tok2}) + ).status_code == 200 + + +@pytest.mark.asyncio +async def test_redis_rate_limit_atomic_lua_and_negative_ttl_recovery(monkeypatch): + class _FakeLuaRedis: + def __init__(self): + self.counts: dict[str, int] = {} + self.ttls: dict[str, int] = {} + self.eval_calls = 0 + + async def eval(self, script: str, numkeys: int, key: str, window_seconds: int): + self.eval_calls += 1 + assert numkeys == 1 + assert "TTL" in script and "EXPIRE" in script + count = self.counts.get(key, 0) + 1 + self.counts[key] = count + if count == 1 or self.ttls.get(key, -1) < 0: + self.ttls[key] = int(window_seconds) + return count + + lua_redis = _FakeLuaRedis() + monkeypatch.setattr(access_gate, "_AsyncRedisClient", type("R", (), {"get_client": staticmethod(lambda: lua_redis)})) + await access_gate.check_sliding_rate_limit("earth:earth_web:1.2.3.4", limit=2, window_seconds=60) + assert lua_redis.eval_calls == 1 + assert lua_redis.ttls["access_gate:earth:earth_web:1.2.3.4"] == 60 + + class _LegacyRedisWithNegativeTtl: + def __init__(self): + self.counts = {"access_gate:stuck": 1} + self.ttls = {"access_gate:stuck": -1} + self.expired_with: list[int] = [] + + async def incr(self, key: str) -> int: + self.counts[key] = self.counts.get(key, 0) + 1 + return self.counts[key] + + async def ttl(self, key: str) -> int: + return self.ttls.get(key, -1) + + async def expire(self, key: str, seconds: int) -> bool: + self.ttls[key] = seconds + self.expired_with.append(seconds) + return True + + legacy_redis = _LegacyRedisWithNegativeTtl() + monkeypatch.setattr( + access_gate, + "_AsyncRedisClient", + type("R2", (), {"get_client": staticmethod(lambda: legacy_redis)}), + ) + await access_gate.check_sliding_rate_limit("stuck", limit=5, window_seconds=60) + assert legacy_redis.ttls["access_gate:stuck"] == 60 + assert legacy_redis.expired_with == [60] diff --git a/backend/tests/test_earth_boundaries.py b/backend/tests/test_earth_boundaries.py index 61fab024..1269f228 100644 --- a/backend/tests/test_earth_boundaries.py +++ b/backend/tests/test_earth_boundaries.py @@ -1,100 +1,107 @@ +import io import json +import zipfile from pathlib import Path import pytest +from httpx import ASGITransport, AsyncClient +from starlette.applications import Starlette +from starlette.routing import Route from app.core.datasource_defaults import DEFAULT_DATASOURCES from app.services.collectors.registry import collector_registry from app.services import earth_boundaries -def write_geojson(path, name="Test"): - names = [name] - if name == "earth_admin0_boundaries": - names = ["China", "India", "Japan", "Palestine", "Taiwan", "Hong Kong", "Macao", "Serbia", "Kosovo"] - codes = {"China": "CHN", "India": "IND", "Japan": "JPN", "Palestine": "PSE", "Taiwan": "TWN", "Hong Kong": "HKG", "Macao": "MAC", "Serbia": "SRB", "Kosovo": "KOS"} - path.write_text( - json.dumps( - { - "type": "FeatureCollection", - "features": [ - { - "type": "Feature", - "properties": { - "NAME": f"source renamed {item}" if item in {"Taiwan", "Kosovo"} else item, - "ISO_A3": "-99" if item == "Kosovo" else codes.get(item, "TEST"), - "ADM0_A3": "XKS" if item == "Kosovo" else codes.get(item, "TEST"), - }, - "geometry": { - "type": "Polygon", - "coordinates": [[[-1, -1], [1, -1], [1, 1], [-1, 1], [-1, -1]]], - }, - } - for item in names - ], - } - ), - encoding="utf-8", - ) +REPO = Path(__file__).resolve().parents[2] def patch_paths(monkeypatch, tmp_path): - repo = tmp_path - source_dir = repo / "data/earth-boundary-sources" - boundary_dir = repo / "frontend/public/earth/data/boundaries/v1" - pmtiles = repo / "frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles" - legacy = repo / "frontend/public/earth/data/countries-admin0.min.geojson" - config = repo / "config/earth-boundary-sources.local.json" - example = repo / "config/earth-boundary-sources.example.json" - policy = repo / "config/earth-boundary-pov-policy.china-v1.json" - geometry = repo / "resources/earth/boundary-pov-geometry.china-v1.json" - for path in (source_dir, boundary_dir, pmtiles.parent, legacy.parent, config.parent): + data_dir = tmp_path / "backend/data/earth-boundaries" + source_dir = data_dir / "sources" + artifact_dir = data_dir / "artifacts" + legacy = tmp_path / "frontend/public/earth/data/countries-admin0.china-pov-v1.geojson" + config = tmp_path / "config/earth-boundary-sources.local.json" + example = tmp_path / "config/earth-boundary-sources.example.json" + policy = tmp_path / "config/earth-boundary-pov-policy.china-v1.json" + geometry = tmp_path / "resources/earth/boundary-pov-geometry.china-v1.json" + for path in (source_dir, artifact_dir, legacy.parent, config.parent, geometry.parent): path.mkdir(parents=True, exist_ok=True) - source_policy = Path(__file__).resolve().parents[2] / "config/earth-boundary-pov-policy.china-v1.json" - policy.write_text(source_policy.read_text(encoding="utf-8"), encoding="utf-8") - geometry.parent.mkdir(parents=True, exist_ok=True) - source_geometry = Path(__file__).resolve().parents[2] / "resources/earth/boundary-pov-geometry.china-v1.json" - geometry.write_bytes(source_geometry.read_bytes()) + policy.write_bytes((REPO / "config/earth-boundary-pov-policy.china-v1.json").read_bytes()) + geometry.write_bytes((REPO / "resources/earth/boundary-pov-geometry.china-v1.json").read_bytes()) example.write_text('{"collectorConfigs":{}}\n', encoding="utf-8") - monkeypatch.setattr(earth_boundaries, "REPO_ROOT", repo) + monkeypatch.setattr(earth_boundaries, "REPO_ROOT", tmp_path) + monkeypatch.setattr(earth_boundaries, "BOUNDARY_DATA_DIR", data_dir) monkeypatch.setattr(earth_boundaries, "SOURCE_OUTPUT_DIR", source_dir) monkeypatch.setattr(earth_boundaries, "SOURCE_MANIFEST_PATH", source_dir / "manifest.json") - monkeypatch.setattr(earth_boundaries, "BUILD_RESULT_PATH", source_dir / "build-result.json") - monkeypatch.setattr(earth_boundaries, "BUILD_JOB_PATH", source_dir / "build-job.json") - monkeypatch.setattr(earth_boundaries, "BOUNDARY_OUTPUT_DIR", boundary_dir) - monkeypatch.setattr(earth_boundaries, "BOUNDARY_MANIFEST_PATH", boundary_dir / "manifest.json") - monkeypatch.setattr(earth_boundaries, "PMTILES_ARTIFACT_PATH", pmtiles) + monkeypatch.setattr(earth_boundaries, "BUILD_RESULT_PATH", data_dir / "build-result.json") + monkeypatch.setattr(earth_boundaries, "BUILD_JOB_PATH", data_dir / "build-job.json") + monkeypatch.setattr(earth_boundaries, "BOUNDARY_OUTPUT_DIR", artifact_dir) + monkeypatch.setattr(earth_boundaries, "BOUNDARY_MANIFEST_PATH", artifact_dir / "manifest.json") monkeypatch.setattr(earth_boundaries, "POLICY_FALLBACK_PATH", legacy) monkeypatch.setattr(earth_boundaries, "LOCAL_CONFIG_PATH", config) monkeypatch.setattr(earth_boundaries, "EXAMPLE_CONFIG_PATH", example) monkeypatch.setattr(earth_boundaries, "POV_POLICY_PATH", policy) monkeypatch.setattr(earth_boundaries, "POV_GEOMETRY_PATH", geometry) return { - "repo": repo, + "repo": tmp_path, "config": config, "legacy": legacy, - "pmtiles": pmtiles, - "manifest": boundary_dir / "manifest.json", + "artifacts": artifact_dir, + "sources": source_dir, + "manifest": artifact_dir / "manifest.json", } -def write_fallback(path, policy_path, geometry_path): - policy = earth_boundaries._read_json(policy_path) - geometry = earth_boundaries._read_json(geometry_path) - coverage = { +def verified_coverage(): + policy = earth_boundaries._read_json(earth_boundaries.POV_POLICY_PATH) + geometry = earth_boundaries._read_json(earth_boundaries.POV_GEOMETRY_PATH) + return { "profile": "china-pov-v1", "sha256": earth_boundaries._stable_json_hash(policy), "geometrySha256": earth_boundaries._stable_json_hash(geometry), "reviewedGeometrySourceCommit": geometry["sourceCommit"], "applied": True, - "appliedRuleIds": ["china-taiwan-penghu", "china-hong-kong", "china-macao", "kosovo"], + "appliedRuleIds": [ + "china-hong-kong", "china-macao", "china-maritime-claim-line", + "china-taiwan-penghu", "kosovo", + ], + "publicationReady": False, } - path.write_text(json.dumps({"type": "FeatureCollection", "features": [], "povPolicy": coverage}), encoding="utf-8") -def test_boundary_status_uses_legacy_provider_when_pmtiles_missing(monkeypatch, tmp_path): +def write_fallback(path): + path.write_text( + json.dumps({"type": "FeatureCollection", "features": [], "povPolicy": verified_coverage()}), + encoding="utf-8", + ) + + +def write_verified_artifacts(paths, *, pmtiles_bytes=b"PMTiles" + bytes(range(256))): + names = { + "pmtiles": "earth-boundaries.abc-def.pmtiles", + "hover": "hover-index.abc-def.json", + "borders": "hover-borders.abc-def.json", + } + (paths["artifacts"] / names["pmtiles"]).write_bytes(pmtiles_bytes) + (paths["artifacts"] / names["hover"]).write_text('{"type":"FeatureCollection","features":[]}', encoding="utf-8") + (paths["artifacts"] / names["borders"]).write_text('{"type":"FeatureCollection","features":[]}', encoding="utf-8") + manifest = { + "schema": earth_boundaries.MANIFEST_SCHEMA, + "tileProvider": "pmtiles-mvt", + "buildInputHash": "abc", + "pmtiles": {"path": names["pmtiles"], "sizeBytes": len(pmtiles_bytes)}, + "hoverIndex": names["hover"], + "hoverBorders": names["borders"], + "povPolicy": verified_coverage(), + } + paths["manifest"].write_text(json.dumps(manifest), encoding="utf-8") + return names + + +def test_boundary_status_uses_policy_fallback_when_no_artifact(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) - write_fallback(paths["legacy"], earth_boundaries.POV_POLICY_PATH, earth_boundaries.POV_GEOMETRY_PATH) + write_fallback(paths["legacy"]) status = earth_boundaries.get_boundary_status() @@ -105,7 +112,7 @@ def test_boundary_status_uses_legacy_provider_when_pmtiles_missing(monkeypatch, def test_boundary_status_rejects_unverified_fallback(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) - write_geojson(paths["legacy"]) + paths["legacy"].write_text('{"type":"FeatureCollection","features":[]}', encoding="utf-8") status = earth_boundaries.get_boundary_status() @@ -113,38 +120,100 @@ def test_boundary_status_rejects_unverified_fallback(monkeypatch, tmp_path): assert status["fallback_available"] is False -def test_boundary_status_prefers_high_precision_when_manifest_and_pmtiles_exist(monkeypatch, tmp_path): +def test_boundary_status_prefers_verified_pmtiles(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) - write_fallback(paths["legacy"], earth_boundaries.POV_POLICY_PATH, earth_boundaries.POV_GEOMETRY_PATH) - paths["pmtiles"].write_bytes(b"pmtiles") - (paths["manifest"].parent / "hover-index.geojson").write_text("{}", encoding="utf-8") - coverage = { - "profile": "china-pov-v1", - "sha256": earth_boundaries._stable_json_hash(earth_boundaries._read_json(earth_boundaries.POV_POLICY_PATH)), - "applied": True, - "appliedRuleIds": ["china-taiwan-penghu", "china-hong-kong", "china-macao", "kosovo"], - "reviewedGeometrySourceCommit": earth_boundaries._read_json(earth_boundaries.POV_GEOMETRY_PATH)["sourceCommit"], - "geometrySha256": earth_boundaries._stable_json_hash(earth_boundaries._read_json(earth_boundaries.POV_GEOMETRY_PATH)), - } - paths["manifest"].write_text(json.dumps({"tileProvider": "pmtiles-mvt", "hoverIndex": "hover-index.geojson", "povPolicy": coverage}), encoding="utf-8") + write_fallback(paths["legacy"]) + names = write_verified_artifacts(paths) status = earth_boundaries.get_boundary_status() assert status["provider"] == "pmtiles-mvt" assert status["high_precision_ready"] is True assert status["policy_publishable"] is False + assert status["pmtiles"]["path"] == names["pmtiles"] + assert earth_boundaries.get_public_boundary_manifest()["hoverIndex"] == names["hover"] -def test_boundary_status_rejects_unverified_high_precision(monkeypatch, tmp_path): +@pytest.mark.parametrize( + "mutate", + [ + lambda manifest: manifest["povPolicy"].update(applied=False), + lambda manifest: manifest["povPolicy"].update(geometrySha256="stale"), + lambda manifest: manifest.update(schema="planet-earth-boundaries/v1"), + lambda manifest: manifest.update(hoverBorders=None), + ], +) +def test_boundary_status_rejects_unverified_or_incomplete_manifest(monkeypatch, tmp_path, mutate): paths = patch_paths(monkeypatch, tmp_path) - write_fallback(paths["legacy"], earth_boundaries.POV_POLICY_PATH, earth_boundaries.POV_GEOMETRY_PATH) - paths["pmtiles"].write_bytes(b"pmtiles") - paths["manifest"].write_text('{"tileProvider":"pmtiles-mvt","povPolicy":{"applied":false}}', encoding="utf-8") + write_fallback(paths["legacy"]) + write_verified_artifacts(paths) + manifest = json.loads(paths["manifest"].read_text(encoding="utf-8")) + mutate(manifest) + paths["manifest"].write_text(json.dumps(manifest), encoding="utf-8") status = earth_boundaries.get_boundary_status() assert status["provider"] == "policy-geojson-fallback" assert status["high_precision_ready"] is False + assert earth_boundaries.get_public_boundary_manifest() is None + + +def test_resolve_boundary_artifact_only_serves_manifest_files(monkeypatch, tmp_path): + paths = patch_paths(monkeypatch, tmp_path) + names = write_verified_artifacts(paths) + (paths["artifacts"] / "other.json").write_text("{}", encoding="utf-8") + + assert earth_boundaries.resolve_boundary_artifact(names["pmtiles"]) is not None + assert earth_boundaries.resolve_boundary_artifact("other.json") is None + assert earth_boundaries.resolve_boundary_artifact("manifest.json") is None + assert earth_boundaries.resolve_boundary_artifact("../artifacts/" + names["hover"]) is None + assert earth_boundaries.resolve_boundary_artifact("") is None + + +@pytest.mark.asyncio +async def test_boundary_file_route_answers_range_requests(monkeypatch, tmp_path): + from app.api.v1 import earth as earth_api + + paths = patch_paths(monkeypatch, tmp_path) + payload = b"PMTiles" + bytes(range(256)) * 4 + names = write_verified_artifacts(paths, pmtiles_bytes=payload) + + async def endpoint(request): + return await earth_api.get_earth_boundary_file(request.path_params["name"]) + + app = Starlette(routes=[Route("/files/{name}", endpoint, methods=["GET", "HEAD"])]) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + head_resp = await client.head(f"/files/{names['pmtiles']}") + assert head_resp.status_code == 200 + assert head_resp.headers["accept-ranges"] == "bytes" + assert head_resp.headers["content-length"] == str(len(payload)) + assert head_resp.content == b"" + + partial = await client.get(f"/files/{names['pmtiles']}", headers={"Range": "bytes=0-15"}) + assert partial.status_code == 206 + assert partial.content == payload[:16] + assert partial.headers["content-range"] == f"bytes 0-15/{len(payload)}" + assert partial.headers["content-type"] == "application/vnd.pmtiles" + assert "immutable" in partial.headers["cache-control"] + + unsatisfiable = await client.get( + f"/files/{names['pmtiles']}", headers={"Range": f"bytes={len(payload) + 10}-"} + ) + assert unsatisfiable.status_code == 416 + + +@pytest.mark.asyncio +async def test_boundary_file_route_rejects_unlisted_files(monkeypatch, tmp_path): + from fastapi import HTTPException + + from app.api.v1 import earth as earth_api + + paths = patch_paths(monkeypatch, tmp_path) + write_verified_artifacts(paths) + + with pytest.raises(HTTPException) as exc_info: + await earth_api.get_earth_boundary_file("manifest.json") + assert exc_info.value.status_code == 404 def test_save_boundary_config_writes_local_config(monkeypatch, tmp_path): @@ -158,93 +227,131 @@ def test_save_boundary_config_writes_local_config(monkeypatch, tmp_path): assert status["config"] == payload -@pytest.mark.asyncio -async def test_build_reports_missing_tools_after_source_artifacts(monkeypatch, tmp_path): +def test_default_sources_use_osm_coastline_and_china_pov_claims(): + sources = earth_boundaries.DEFAULT_PUBLIC_BOUNDARY_SOURCES + assert set(sources) == set(earth_boundaries.BOUNDARY_SOURCE_KINDS) + assert sources["earth_coastline"]["endpoint"].startswith("https://osmdata.openstreetmap.de/") + assert "ODbL" in sources["earth_coastline"]["license"] + assert sources["earth_claim_lines"]["endpoint"].endswith("maritime_indicator_chn.geojson") + assert sources["earth_admin1_lines"]["endpoint"].endswith("admin_1_states_provinces_lines.geojson") + assert sources["earth_populated_places"]["endpoint"].endswith("ne_10m_populated_places.geojson") + + +def test_resolve_boundary_artifact_serves_geo_labels(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) - source_files = {} - for source in earth_boundaries.BOUNDARY_SOURCE_KINDS: - source_path = paths["repo"] / f"{source}.geojson" - write_geojson(source_path, name=source) - source_files[source] = source_path - paths["config"].write_text( - json.dumps( - { - "collectorConfigs": { - source: { - "sourceKind": kind, - "endpoint": str(source_files[source]), - "method": "GET", - } - for source, kind in earth_boundaries.BOUNDARY_SOURCE_KINDS.items() - } - } - ), - encoding="utf-8", - ) - monkeypatch.setattr(earth_boundaries.shutil, "which", lambda _tool: None) - progress_events = [] - - status = await earth_boundaries.build_boundary_assets( - lambda progress, phase, message, **_extra: progress_events.append((progress, phase, message)) - ) - - assert status["provider"] == "geojson-high-precision" - assert status["high_precision_ready"] is True - assert (paths["repo"] / "data/earth-boundary-sources/manifest.json").exists() - assert paths["manifest"].exists() + write_fallback(paths["legacy"]) + write_verified_artifacts(paths) + labels_name = "geo-labels.abc-def.json" + (paths["artifacts"] / labels_name).write_text('{"schema":"planet-earth-geo-labels/v1","places":[]}', encoding="utf-8") manifest = json.loads(paths["manifest"].read_text(encoding="utf-8")) - assert manifest["povPolicy"]["applied"] is True - assert manifest["povPolicy"]["coverage"] == "partial" - assert manifest["povPolicy"]["publicationReady"] is False - assert "china-south-china-sea-islands" in manifest["povPolicy"]["unresolvedRuleIds"] - hover = json.loads((paths["manifest"].parent / manifest["hoverIndex"]).read_text(encoding="utf-8")) - by_rule = { - feature["properties"].get("PLANET_POLICY_RULE"): feature - for feature in hover["features"] - } - assert by_rule["china-hong-kong"]["properties"]["ISO_A3"] == "CHN" - assert by_rule["china-macao"]["properties"]["ISO_A3"] == "CHN" - assert all( - feature["properties"].get("ADM0_A3") not in {"TWN", "KOS", "XKS"} - for feature in hover["features"] - ) - assert any(phase == "download" for _progress, phase, _message in progress_events) + manifest["geoLabels"] = labels_name + paths["manifest"].write_text(json.dumps(manifest), encoding="utf-8") + + assert earth_boundaries.resolve_boundary_artifact(labels_name) == paths["artifacts"] / labels_name + assert earth_boundaries.resolve_boundary_artifact("../manifest.json") is None @pytest.mark.asyncio -async def test_start_boundary_build_job_records_geojson_fallback_success(monkeypatch, tmp_path): +async def test_build_fails_loudly_when_tippecanoe_missing(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) + monkeypatch.setattr(earth_boundaries.shutil, "which", lambda _tool: None) + + async def unexpected_download(*_args, **_kwargs): + raise AssertionError("sources must not download without build tools") + + monkeypatch.setattr(earth_boundaries, "_download_source", unexpected_download) + + with pytest.raises(earth_boundaries.EarthBoundaryBuildError) as exc_info: + await earth_boundaries.build_boundary_assets() + + assert exc_info.value.code == "missing_tools" + assert exc_info.value.details == {"missing_tools": ["tippecanoe"]} + assert not paths["manifest"].exists() + assert earth_boundaries.get_boundary_status()["build_tools_ready"] is False + + +@pytest.mark.asyncio +async def test_start_build_job_rejects_missing_tools(monkeypatch, tmp_path): + patch_paths(monkeypatch, tmp_path) monkeypatch.setattr(earth_boundaries, "_build_task", None) monkeypatch.setattr(earth_boundaries, "_build_job_state", {}) - source_files = {} - for source in earth_boundaries.BOUNDARY_SOURCE_KINDS: - source_path = paths["repo"] / f"{source}.geojson" - write_geojson(source_path, name=source) - source_files[source] = source_path - paths["config"].write_text( - json.dumps( - { - "collectorConfigs": { - source: { - "sourceKind": kind, - "endpoint": str(source_files[source]), - "method": "GET", - } - for source, kind in earth_boundaries.BOUNDARY_SOURCE_KINDS.items() - } - } - ), - encoding="utf-8", - ) monkeypatch.setattr(earth_boundaries.shutil, "which", lambda _tool: None) - response = await earth_boundaries.start_boundary_build_job() - await earth_boundaries._build_task - status = earth_boundaries.get_boundary_build_status() + with pytest.raises(earth_boundaries.EarthBoundaryBuildError) as exc_info: + await earth_boundaries.start_boundary_build_job() - assert response["accepted"] is True - assert status["job"]["status"] == "succeeded" - assert status["job"]["result"]["provider"] == "geojson-high-precision" + assert exc_info.value.code == "missing_tools" + + +@pytest.mark.asyncio +async def test_build_rejects_artifact_without_verified_manifest(monkeypatch, tmp_path): + paths = patch_paths(monkeypatch, tmp_path) + monkeypatch.setattr(earth_boundaries.shutil, "which", lambda tool: f"/usr/bin/{tool}") + + async def fake_download(source_key, source_config, _progress=None): + return {"id": source_key, "kind": source_config["sourceKind"], "path": f"/tmp/{source_key}", "sha256": source_key} + + async def fake_builder(_args): + paths["manifest"].write_text('{"schema":"planet-earth-boundaries/v2","povPolicy":{"applied":false}}', encoding="utf-8") + return {"returncode": 0} + + monkeypatch.setattr(earth_boundaries, "_download_source", fake_download) + monkeypatch.setattr(earth_boundaries, "_run_builder", fake_builder) + + with pytest.raises(earth_boundaries.EarthBoundaryBuildError) as exc_info: + await earth_boundaries.build_boundary_assets() + + assert exc_info.value.code == "unverified_artifact" + + +@pytest.mark.asyncio +async def test_download_streams_zip_sources_and_counts_shapefile_records(monkeypatch, tmp_path): + paths = patch_paths(monkeypatch, tmp_path) + archive = tmp_path / "coast.zip" + shx = io.BytesIO(b"\0" * 100 + b"\0" * 8 * 3) + with zipfile.ZipFile(archive, "w") as zf: + zf.writestr("coastlines-split-4326/lines.shx", shx.getvalue()) + zf.writestr("coastlines-split-4326/lines.shp", b"shape") + + source = await earth_boundaries._download_source( + "earth_coastline", {"endpoint": str(archive), "sourceKind": "coastline"} + ) + + assert source["featureCount"] == 3 + assert source["path"].endswith(".zip") + stored = list((paths["sources"] / "earth_coastline").iterdir()) + assert [path.name for path in stored] == [Path(source["path"]).name] + + +@pytest.mark.asyncio +async def test_download_reuses_unchanged_remote_source(monkeypatch, tmp_path): + paths = patch_paths(monkeypatch, tmp_path) + body = json.dumps({"type": "FeatureCollection", "features": [{"type": "Feature"}]}).encode() + seen_headers = [] + + def handler(request): + seen_headers.append(dict(request.headers)) + if request.headers.get("if-none-match") == '"v1"': + return earth_boundaries.httpx.Response(304) + return earth_boundaries.httpx.Response(200, content=body, headers={"etag": '"v1"', "content-type": "application/geo+json"}) + + real_client = earth_boundaries.httpx.AsyncClient + monkeypatch.setattr( + earth_boundaries.httpx, + "AsyncClient", + lambda **kwargs: real_client(transport=earth_boundaries.httpx.MockTransport(handler), **kwargs), + ) + config = {"endpoint": "https://example.org/admin1.geojson", "sourceKind": "admin1-lines"} + + first = await earth_boundaries._download_source("earth_admin1_lines", config) + paths["sources"].joinpath("manifest.json").write_text(json.dumps({"sources": [first]}), encoding="utf-8") + second = await earth_boundaries._download_source("earth_admin1_lines", config) + + assert first["etag"] == '"v1"' + assert second["notModified"] is True + assert second["sha256"] == first["sha256"] + assert seen_headers[1]["if-none-match"] == '"v1"' + assert Path(second["path"]).is_file() def test_earth_boundary_collectors_are_not_registered_as_datasources(): @@ -256,8 +363,7 @@ def test_earth_boundary_collectors_are_not_registered_as_datasources(): def test_static_policy_fallback_contains_reviewed_jeju_polygon(): - repo = Path(__file__).resolve().parents[2] - path = repo / "frontend/public/earth/data/countries-admin0.china-pov-v1.geojson" + path = REPO / "frontend/public/earth/data/countries-admin0.china-pov-v1.geojson" payload = json.loads(path.read_text(encoding="utf-8")) matches = [ feature for feature in payload["features"] diff --git a/backend/tests/test_earth_boundary_geometry.py b/backend/tests/test_earth_boundary_geometry.py new file mode 100644 index 00000000..95a17cad --- /dev/null +++ b/backend/tests/test_earth_boundary_geometry.py @@ -0,0 +1,249 @@ +import sys +from pathlib import Path + +from shapely.geometry import LineString, Polygon, box, mapping + +SCRIPTS = Path(__file__).resolve().parents[2] / "scripts" +if str(SCRIPTS) not in sys.path: + sys.path.insert(0, str(SCRIPTS)) + +import build_earth_boundary_pmtiles as builder # noqa: E402 +import earth_boundary_geometry as geo # noqa: E402 + + +def feature(code, geometry, **props): + return {"type": "Feature", "properties": {"ADM0_A3": code, **props}, "geometry": mapping(geometry)} + + +def test_land_borders_keep_only_shared_edges(): + countries = {"AAA": box(0, 0, 1, 1), "BBB": box(1, 0, 2, 1), "CCC": box(5, 5, 6, 6)} + + borders = geo.derive_land_borders(countries) + + assert len(borders) == 1 + line = borders[0]["geometry"] + assert borders[0]["properties"] == {"ADM0_L": "AAA", "ADM0_R": "BBB"} + assert sorted(line.coords) == [(1.0, 0.0), (1.0, 1.0)] + + +def test_country_geometries_dissolve_internal_policy_edges(): + admin0 = { + "type": "FeatureCollection", + "features": [feature("CHN", box(0, 0, 1, 1)), feature("CHN", box(1, 0, 2, 1))], + } + + countries = geo.country_geometries(admin0) + + assert list(countries) == ["CHN"] + assert countries["CHN"].equals(box(0, 0, 2, 1)) + + +def test_free_endpoints_are_line_ends_touched_once(): + lines = [ + {"geometry": LineString([(0, 0), (1, 0)])}, + {"geometry": LineString([(1, 0), (2, 0)])}, + {"geometry": LineString([(1, 0), (1, 1)])}, + ] + + assert geo.free_endpoints(lines) == {(0.0, 0.0), (2.0, 0.0), (1.0, 1.0)} + + +def test_coastal_end_is_trimmed_at_osm_coast_crossing(): + border = [{"geometry": LineString([(0, 0), (0, 1.03)])}] + coast = [LineString([(-1, 1.0), (1, 1.0)])] + + stats = geo.snap_coastal_ends(border, coast, {(0.0, 1.03)}, max_distance=0.05) + + assert stats["trimmed"] == 1 + assert border[0]["geometry"].coords[-1] == (0.0, 1.0) + + +def test_coastal_end_is_extended_to_nearby_osm_coast(): + border = [{"geometry": LineString([(0, 0), (0, 0.98)])}] + coast = [LineString([(-1, 1.0), (1, 1.0)])] + + stats = geo.snap_coastal_ends(border, coast, {(0.0, 0.98)}, max_distance=0.05) + + assert stats["extended"] == 1 + assert border[0]["geometry"].coords[-1] == (0.0, 1.0) + + +def test_coastal_end_beyond_snap_distance_is_left_alone(): + border = [{"geometry": LineString([(0, 0), (0, 0.9)])}] + coast = [LineString([(-1, 0.96), (1, 0.96)])] + + stats = geo.snap_coastal_ends(border, coast, {(0.0, 0.9)}, max_distance=0.05) + + assert stats["extended"] == 0 and stats["trimmed"] == 0 + assert border[0]["geometry"].coords[-1] == (0.0, 0.9) + + +def test_admin1_lines_follow_china_pov(): + china = box(0, 0, 10, 10) + clip = china.buffer(-geo.CHINA_CLIP_BUFFER_DEGREES) + collection = { + "type": "FeatureCollection", + "features": [ + feature("CHN", LineString([(2, 2), (3, 3)]), MIN_ZOOM=4.6), + feature("TWN", LineString([(20, 20), (21, 21)]), MIN_ZOOM=8.7), + feature("HKG", LineString([(30, 30), (31, 31)]), MIN_ZOOM=10), + feature("IND", LineString([(5, 5), (15, 5)]), MIN_ZOOM=4.6), + feature("USA", LineString([(40, 40), (41, 41)]), MIN_ZOOM=2), + feature("RUS", LineString([(50, 50), (51, 51)]), FCLASS_CN="Unrecognized Admin-1 boundary"), + ], + } + + lines = geo.admin1_lines(collection, clip) + + by_code = {} + for line in lines: + by_code.setdefault(line["properties"]["ADM0_A3"], []).append(line) + assert set(by_code) == {"CHN", "IND", "USA"} + india = by_code["IND"][0]["geometry"] + assert min(x for x, _y in india.coords) >= 10 - geo.CHINA_CLIP_BUFFER_DEGREES - 1e-9 + assert by_code["USA"][0]["properties"]["minzoom"] == 4 + assert by_code["CHN"][0]["properties"]["minzoom"] == 4 + + +def test_disputed_lines_inside_china_are_removed(): + clip = box(0, 0, 10, 10) + collection = { + "type": "FeatureCollection", + "features": [ + feature("X", LineString([(2, 2), (3, 3)]), FEATURECLA="Disputed"), + feature("X", LineString([(20, 2), (21, 3)]), FEATURECLA="Line of control"), + ], + } + + lines = geo.disputed_lines(collection, clip) + + assert len(lines) == 1 + assert lines[0]["properties"]["FEATURECLA"] == "Line of control" + + +def test_claim_features_accept_only_china_pov_nine_dash_line(): + dash = mapping(LineString([(110, 10), (110.1, 10.1)])) + collection = { + "type": "FeatureCollection", + "features": [ + {"type": "Feature", "properties": {"COMMENT": "Chinese 9 dash line", "FCLASS_CN": "International boundary (verify)"}, "geometry": dash}, + {"type": "Feature", "properties": {"COMMENT": "Chinese 9 dash line", "FCLASS_CN": None}, "geometry": dash}, + {"type": "Feature", "properties": {"COMMENT": "Median", "FCLASS_CN": "International boundary (verify)"}, "geometry": dash}, + ], + } + + claims = builder.claim_features(collection) + + assert len(claims) == 1 + assert claims[0]["properties"] == {"name": "九段线", "name_en": "Nine-dash line"} + + +def test_claim_coverage_marks_rule_applied_only_with_all_dashes(): + coverage = { + "appliedRuleIds": ["kosovo"], + "unresolvedRuleIds": [builder.CLAIM_RULE_ID, "china-south-china-sea-islands"], + "unresolvedReasons": {builder.CLAIM_RULE_ID: "missing", "china-south-china-sea-islands": "partial"}, + } + + builder.apply_claim_coverage(coverage, [{}] * builder.MIN_CLAIM_DASHES) + + assert builder.CLAIM_RULE_ID in coverage["appliedRuleIds"] + assert coverage["unresolvedRuleIds"] == ["china-south-china-sea-islands"] + assert coverage["coverage"] == "partial" + assert coverage["claimLine"]["featureCount"] == builder.MIN_CLAIM_DASHES + + +def test_hover_index_is_one_simplified_polygon_per_country(): + admin0 = { + "type": "FeatureCollection", + "features": [ + feature("CHN", box(1, 0, 2, 1), ISO_A3="CHN", NAME_ZH="中国", PLANET_POLICY_RULE="china-hong-kong"), + feature("CHN", box(0, 0, 1, 1), ISO_A3="CHN", NAME_ZH="中国", EXTRA="dropped"), + ], + } + countries = geo.country_geometries(admin0) + + hover = geo.hover_index(admin0, countries, tolerance=0.01) + + assert len(hover["features"]) == 1 + props = hover["features"][0]["properties"] + assert props == { + "ISO_A3": "CHN", "ADM0_A3": "CHN", "NAME_ZH": "中国", + "PLANET_POLICY_RULES": ["china-hong-kong"], + } + assert Polygon(hover["features"][0]["geometry"]["coordinates"][0]).equals(box(0, 0, 2, 1)) + + +def test_geojson_feature_sets_tippecanoe_layer_and_zoom(): + out = geo.geojson_feature( + {"geometry": LineString([(0, 0), (1, 1)]), "properties": {"ADM0_A3": "USA", "minzoom": 4, "NAME": None}}, + "boundary_admin1", + 4, + 6, + ) + + assert out["tippecanoe"] == {"layer": "boundary_admin1", "minzoom": 4, "maxzoom": 6} + assert out["properties"] == {"ADM0_A3": "USA"} + assert out["geometry"]["type"] == "LineString" + + +def test_coastline_country_assigner_tags_single_and_cross_border_lines(): + countries = { + "CHN": box(0, 0, 10, 10), + "VNM": box(10, 0, 20, 10), + "JPN": box(30, 0, 35, 5), + } + assigner = geo.CoastlineCountryAssigner(countries) + + # Pure inland/coastal Taiwan/Japan single-country segment. + jpn_tags = assigner.assign(LineString([(30.0, 0.0), (35.0, 0.0)])) + assert jpn_tags == [(LineString([(30.0, 0.0), (35.0, 0.0)]), "JPN")] + + # Multi-country coastline crossing CHN|VNM at x=10 splits cleanly. + cross_tags = assigner.assign(LineString([(8.0, 0.0), (12.0, 0.0)])) + codes = [code for _seg, code in cross_tags] + assert "CHN" in codes and "VNM" in codes + assert all(seg.length > 0 for seg, _code in cross_tags) + + +def test_build_geo_labels_applies_china_pov_and_tiers(): + def place(name, zh, lon, lat, adm0, fclass, sr, pop, wc=0): + return { + "type": "Feature", + "geometry": {"type": "Point", "coordinates": [lon, lat]}, + "properties": { + "NAME": name, "NAME_EN": name, "NAME_ZH": zh, + "ADM0_A3": adm0, "FEATURECLA": fclass, + "SCALERANK": sr, "POP_MAX": pop, "WORLDCITY": wc, + }, + } + + places = { + "type": "FeatureCollection", + "features": [ + place("Beijing", "北京", 116.4, 39.9, "CHN", "Admin-0 capital", 0, 11106000, 1), + place("Shanghai", "上海", 121.4, 31.2, "CHN", "Admin-1 capital", 0, 14987000, 1), + place("Taipei", "台北", 121.56, 25.03, "TWN", "Admin-0 capital", 1, 6900000, 1), + place("Pristina", "普里什蒂纳", 21.16, 42.66, "KOS", "Admin-0 capital", 4, 465000, 0), + place("Itanagar", "伊塔那噶", 93.61, 27.10, "IND", "Admin-1 capital", 7, 45000, 0), + place("Hangzhou", "杭州", 120.15, 30.27, "CHN", "Admin-1 capital", 3, 5000000, 0), + place("SmallTown", "小镇", 110.0, 30.0, "CHN", "Populated place", 8, 5000, 0), + place("ResearchBase", "科考站", 0.0, -70.0, "ATA", "Scientific station", 3, 50, 0), + ], + } + china_clip = box(91.5, 26.8, 97.5, 29.5) + payload = geo.build_geo_labels(places, policy={"profile": "china-pov-v1"}, china_clip=china_clip) + + assert payload["schema"] == "planet-earth-geo-labels/v1" + by_en = {item["en"]: item for item in payload["places"]} + assert by_en["Beijing"]["t"] == 1 and by_en["Beijing"]["k"] == "capital" and by_en["Beijing"]["iso"] == "CHN" + assert by_en["Shanghai"]["t"] == 1 and by_en["Shanghai"]["k"] == "megacity" + assert by_en["Taipei"]["t"] == 1 and by_en["Taipei"]["k"] == "admin1" and by_en["Taipei"]["iso"] == "CHN" + assert by_en["Pristina"]["t"] == 2 and by_en["Pristina"]["k"] == "admin1" and by_en["Pristina"]["iso"] == "SRB" + assert by_en["Hangzhou"]["t"] == 2 + assert "Itanagar" not in by_en + assert "SmallTown" not in by_en + assert "ResearchBase" not in by_en + # Capitals appear before megacities/admin1 inside Tier 1 + tier1_kinds = [item["k"] for item in payload["places"] if item["t"] == 1] + assert tier1_kinds[0] == "capital" diff --git a/backend/tests/test_earth_clouds.py b/backend/tests/test_earth_clouds.py new file mode 100644 index 00000000..4062b907 --- /dev/null +++ b/backend/tests/test_earth_clouds.py @@ -0,0 +1,436 @@ +"""Tests for real-time satellite IR cloud map engine, collector, APIs, and AI tools.""" + +from __future__ import annotations + +import io +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import httpx +import numpy as np +from httpx import ASGITransport, AsyncClient +from PIL import Image +import pytest + +from app.core.datasource_defaults import DEFAULT_DATASOURCES +from app.core.enums import UserRole +from app.core.security import create_access_token, get_current_user +from app.db.session import get_db +from app.main import app +from app.models.system_setting import SystemSetting +from app.models.user import User +from app.services import earth_clouds +from app.services.ai.tool_registry import query_cloud_posture_tool +from app.services.collectors.cloud_map import EarthCloudMapCollector +from app.services.collectors.registry import collector_registry + + +def _make_png_bytes(rgba_arr: np.ndarray) -> bytes: + buf = io.BytesIO() + Image.fromarray(rgba_arr, mode="RGBA").save(buf, format="PNG") + return buf.getvalue() + + +class _ScalarResult: + def __init__(self, value=None, rows=None): + self._value = value + self._rows = rows or [] + + def scalar_one_or_none(self): + return self._value + + def scalar_one(self): + return self._value + + def scalar(self): + return 0 + + def all(self): + return self._rows + + def first(self): + return self._rows[0] if self._rows else None + + def scalars(self): + return SimpleNamespace(all=lambda: self._rows) + + +class _InMemoryCloudDb: + def __init__(self): + self.setting: SystemSetting | None = None + self.audits = [] + self.committed = False + self.rolled_back = False + + def get_bind(self): + return SimpleNamespace(dialect=SimpleNamespace(name="sqlite")) + + async def get(self, *_args, **_kwargs): + return None + + async def execute(self, statement): + name = statement.__class__.__name__ + if name == "Select": + return _ScalarResult(value=self.setting, rows=[]) + return _ScalarResult() + + def add(self, obj): + if isinstance(obj, SystemSetting): + obj.id = 1 + self.setting = obj + else: + self.audits.append(obj) + + async def delete(self, obj): + if isinstance(obj, SystemSetting): + self.setting = None + + async def commit(self): + self.committed = True + + async def rollback(self): + self.rolled_back = True + + +@pytest.fixture(autouse=True) +def isolated_cloud_dir(tmp_path, monkeypatch): + cloud_dir = tmp_path / "earth-clouds" + monkeypatch.setattr(earth_clouds, "CLOUD_DATA_DIR", cloud_dir) + monkeypatch.setattr("app.core.security.redis_client", SimpleNamespace(sismember=lambda *a, **k: False)) + return cloud_dir + + +def test_gibs_band13_colormap_inversion_and_dvorak_core_recovery(): + """Severe convective ring enclosing a Dvorak gray hole must decode cold, never as a clear hole.""" + h, w = 64, 128 + arr = np.zeros((h, w, 4), dtype=np.uint8) + arr[:, :, :3] = 20 # warm clear surface ~ +50°C + arr[:, :, 3] = 255 + + # Outer convective ring: dark red (255, 0, 0) -> -60.6°C + arr[20:44, 48:80, :3] = [255, 0, 0] + # Inner Dvorak gray wrap core: (102, 102, 102) surrounded by <= -52°C ring -> -74.5°C + arr[28:36, 56:72, :3] = [102, 102, 102] + # Ultra-cold purple peak: (127, 0, 127) -> -90.6°C + arr[30:33, 62:66, :3] = [127, 0, 127] + + temp_c, valid = earth_clouds.decode_gibs_band13_to_temp_and_valid(arr) + assert valid.all() + assert temp_c[5, 5] > 30.0 + assert temp_c[22, 50] < -55.0 + assert temp_c[32, 60] < -70.0 # Dvorak gray hole recovered as ultra-cold! + assert temp_c[31, 64] < -85.0 # Purple peak decoded accurately! + + # Pure white GOES scan-band artifact outside convective rings must be masked invalid (no fake -91.5°C cluster) + stripe_arr = np.zeros((h, w, 4), dtype=np.uint8) + stripe_arr[:, :, :3] = 20 + stripe_arr[:, :, 3] = 255 + stripe_arr[10:18, 20:100, :3] = [254, 254, 254] + stripe_temp, stripe_valid = earth_clouds.decode_gibs_band13_to_temp_and_valid(stripe_arr) + assert not np.any(stripe_valid[10:18, 20:100]) + assert np.all(np.isnan(stripe_temp[10:18, 20:100])) + + density = earth_clouds.temperature_to_density(temp_c, ir_threshold=22, contrast_gamma=0.88) + assert density[5, 5] == 0 + assert density[22, 50] >= 240 + assert density[32, 60] == 255 + + +def test_multi_sat_synthesis_analytics_and_artifact_pruning(isolated_cloud_dir): + cfg = earth_clouds.CloudMapConfig(resolution="2048x1024", max_history_frames=4) + + # Create two synthetic geostationary IR frames (Himawari + Meteosat) + gibs_arr = np.zeros((128, 256, 4), dtype=np.uint8) + gibs_arr[:, :, :3] = 18 + gibs_arr[:, :, 3] = 255 + # Deep convective cyclone over South China Sea / Western Pacific (~15N, 125E) + # 15N -> y = (90-15)/180*128 = 53; 125E -> x = (125+180)/360*256 = 217 + gibs_arr[48:58, 210:224, :3] = [255, 0, 0] + + eumet_arr = np.zeros((128, 256, 4), dtype=np.uint8) + eumet_arr[:, :, :3] = 10 + eumet_arr[:, :, 3] = 255 + eumet_arr[30:38, 120:136, :3] = 210 + + payloads = [ + (earth_clouds.SATELLITE_SOURCES[0], _make_png_bytes(gibs_arr)), + (earth_clouds.SATELLITE_SOURCES[3], _make_png_bytes(eumet_arr)), + ] + density, temp_c, sats = earth_clouds.synthesize_multi_sat_ir(payloads, config=cfg) + assert density.shape == (1024, 2048) + assert set(sats) == {"himawari", "msg_fes"} + + analysis = earth_clouds.analyze_cloud_density_grid(density, temp_c, config=cfg) + assert analysis["global_summary"]["global_cloud_cover_pct"] > 0 + assert len(analysis["regions"]) == len(earth_clouds.FOCUS_REGIONS) + assert analysis["global_summary"]["convective_cluster_count"] >= 1 + top_cluster = analysis["convective_clusters"][0] + assert top_cluster["min_brightness_temp_c"] < -45.0 + + # Save 5 versions and verify retention prunes to max_history_frames=4 + webp_bytes = earth_clouds._encode_cloud_webp(density) + for ver in ( + "20261203T010000Z", + "20261203T020000Z", + "20261203T030000Z", + "20261203T040000Z", + "20261203T050000Z", + ): + earth_clouds._save_frame_artifacts_sync( + version=ver, + captured_at=f"2026-12-03T{ver[9:11]}:00:00Z", + source_used="multi_sat_ir", + satellites=sats, + degraded=False, + config=cfg, + webp_bytes=webp_bytes, + grid_density=analysis["grid_density"], + grid_temp_i8=analysis["grid_temp_i8"], + global_summary=analysis["global_summary"], + regions=analysis["regions"], + clusters=analysis["convective_clusters"], + ) + + assert earth_clouds.read_cloud_frame_bytes("20261203T050000Z") is not None + assert earth_clouds.read_cloud_frame_bytes("20261203T010000Z") is None + assert earth_clouds.read_cloud_frame_bytes("../etc/passwd") is None + + +@pytest.mark.asyncio +async def test_collector_registration_fallback_and_transform(monkeypatch): + assert "global_cloud_map" in DEFAULT_DATASOURCES + assert DEFAULT_DATASOURCES["global_cloud_map"]["id"] == 34 + assert collector_registry.get("global_cloud_map") is not None + + # Simulate multi-sat WMS failure -> automatic fallback to matteason_live + fallback_arr = np.zeros((128, 256, 4), dtype=np.uint8) + fallback_arr[50:65, 180:200, :] = [245, 245, 245, 245] + fallback_png = _make_png_bytes(fallback_arr) + + monkeypatch.setattr(earth_clouds, "_fetch_multi_sat_payloads", AsyncMock(return_value=[])) + monkeypatch.setattr(earth_clouds, "_fetch_matteason_bytes", AsyncMock(return_value=fallback_png)) + + collector = EarthCloudMapCollector() + raw = await collector.fetch() + transformed = collector.transform(raw) + assert len(transformed) >= 1 + len(earth_clouds.FOCUS_REGIONS) + assert transformed[0]["source_id"] == "cloud_snapshot:latest" + assert transformed[0]["metadata"]["cloud_source"] == "matteason_live" + assert transformed[0]["metadata"]["degraded"] is True + + +@pytest.mark.asyncio +async def test_cloud_apis_rbac_optimistic_lock_and_analytics(monkeypatch): + fake_db = _InMemoryCloudDb() + viewer_user = User(id=3, username="viewer", role=UserRole.VIEWER, is_active=True) + admin_user = User(id=1, username="admin", role=UserRole.ADMIN, is_active=True) + active_user = {"user": admin_user} + + async def override_get_db(): + yield fake_db + + async def override_get_user(): + return active_user["user"] + + app.dependency_overrides[get_db] = override_get_db + app.dependency_overrides[get_current_user] = override_get_user + app.dependency_overrides[earth_clouds.get_cloud_datasource_summary] = None # no-op check + monkeypatch.setattr(earth_clouds, "get_cloud_datasource_summary", AsyncMock(return_value={"id": 34, "source": "global_cloud_map"})) + + # Populate one frame + cfg = earth_clouds.CloudMapConfig() + grid_d = np.full((360, 720), 200, dtype=np.uint8) + grid_t = np.full((360, 720), -42, dtype=np.int8) + webp = earth_clouds._encode_cloud_webp(np.full((64, 128), 200, dtype=np.uint8)) + earth_clouds._save_frame_artifacts_sync( + version="20261203T040000Z", + captured_at="2026-12-03T04:00:00Z", + source_used="multi_sat_ir", + satellites=["himawari"], + degraded=False, + config=cfg, + webp_bytes=webp, + grid_density=grid_d, + grid_temp_i8=grid_t, + global_summary={"global_cloud_cover_pct": 78.4, "convective_cluster_count": 1, "min_brightness_temp_c": -42.0}, + regions=[], + clusters=[], + ) + + try: + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + # 1. Runtime meta + frame + point query + r_meta = await client.get("/api/v1/earth/clouds/meta") + assert r_meta.status_code == 200 + assert r_meta.json()["mode"] == "realtime" + assert r_meta.json()["version"] == "20261203T040000Z" + + r_frame = await client.get("/api/v1/earth/clouds/frames/20261203T040000Z") + assert r_frame.status_code == 200 + assert r_frame.headers["content-type"] == "image/webp" + + r_bad_frame = await client.get("/api/v1/earth/clouds/frames/..%2Fsecret") + assert r_bad_frame.status_code == 404 + + r_point = await client.get("/api/v1/data-products/clouds/point", params={"lat": 30.2, "lon": 120.1}) + assert r_point.status_code == 200 + assert r_point.json()["available"] is True + assert r_point.json()["cloud_cover_pct"] > 70.0 + assert r_point.json()["brightness_temp_c"] == -42 + + # 2. RBAC: viewer cannot modify configuration + active_user["user"] = viewer_user + r_cfg_read = await client.get("/api/v1/earth/clouds/configuration") + assert r_cfg_read.status_code == 200 + rev = r_cfg_read.json()["revision"] + + r_viewer_put = await client.put( + "/api/v1/earth/clouds/configuration", + json={"revision": rev, "config": r_cfg_read.json()["config"]}, + ) + assert r_viewer_put.status_code == 403 + + # 3. Admin save & optimistic lock 409 check + active_user["user"] = admin_user + next_cfg = dict(r_cfg_read.json()["config"], ir_threshold=30) + r_admin_put = await client.put( + "/api/v1/earth/clouds/configuration", + json={"revision": rev, "config": next_cfg}, + ) + assert r_admin_put.status_code == 200 + assert r_admin_put.json()["config"]["ir_threshold"] == 30 + assert r_admin_put.json()["revision"] != rev + + r_stale_put = await client.put( + "/api/v1/earth/clouds/configuration", + json={"revision": rev, "config": next_cfg}, + ) + assert r_stale_put.status_code == 409 + + # 4. AI tool posture read + tool_out = await query_cloud_posture_tool(fake_db, latitude=30.2, longitude=120.1) + assert tool_out["available"] is True + assert tool_out["point_query"]["brightness_temp_c"] == -42 + + # 5. RBAC & execution for /clouds/test (formerly crashed with UserRole.OPERATOR AttributeError) + active_user["user"] = viewer_user + r_test_viewer = await client.post("/api/v1/earth/clouds/test", json={"source_id": "multi_sat_ir"}) + assert r_test_viewer.status_code == 403 + + active_user["user"] = admin_user + monkeypatch.setattr( + earth_clouds, + "test_cloud_map_source", + AsyncMock( + return_value={ + "source_id": "multi_sat_ir", + "ok": True, + "reachable_count": 5, + "total_count": 5, + "latency_ms": 42.0, + "satellites": [{"id": "himawari", "ok": True, "latency_ms": 42.0}], + } + ), + ) + r_test_admin = await client.post("/api/v1/earth/clouds/test", json={"source_id": "multi_sat_ir"}) + assert r_test_admin.status_code == 200 + assert r_test_admin.json()["ok"] is True + + # 6. Product domain classification & unified data-products status + from app.api.v1.datasources import infer_datasource_product_key + + assert infer_datasource_product_key("global_cloud_map", "Global Satellite Cloud Map") == "weather" + r_weather_status = await client.get("/api/v1/data-products/weather/status") + assert r_weather_status.status_code == 200 + weather_payload = r_weather_status.json() + assert weather_payload["product_id"] == "weather" + assert weather_payload["has_data"] is True + assert weather_payload["datasources_url"] == "/datasources?product=weather" + assert weather_payload["total_collector_count"] == 3 + + # 6b. GeoColor visual compositing + daytime low-cloud fusion + DIS optical flow helpers + from datetime import UTC, datetime + from app.services.earth_clouds_fx import ( + compute_dis_optical_flow_webp, + decode_visual_payloads, + fuse_daytime_visible_into_density, + synthesize_geocolor_visual_webp, + ) + + vis_arr_clean = np.full((32, 64, 4), (240, 240, 245, 255), dtype=np.uint8) + vis_arr_clean[24:30, 50:58, :3] = [255, 255, 255] # Clipped white fill artifact where thin cloud < 180 + vis_png = _make_png_bytes(vis_arr_clean) + d_prev = np.zeros((32, 64), dtype=np.uint8) + d_prev[10:22, 46:56] = 210 + d_curr = np.zeros((32, 64), dtype=np.uint8) + d_curr[10:22, 50:60] = 210 + d_curr[24:30, 50:58] = 80 + + decoded_clean = decode_visual_payloads([({"id": "himawari", "sub_lon": 140.7}, vis_png)], width=64, height=32) + assert len(decoded_clean) == 1 + vis_webp = synthesize_geocolor_visual_webp( + decoded_clean, + d_curr, + width=64, + height=32, + ) + assert vis_webp is not None and len(vis_webp) > 20 + vis_decoded = np.array(Image.open(io.BytesIO(vis_webp)).convert("RGBA")) + assert int(vis_decoded[16, 55, 3]) >= 180 + assert int(vis_decoded[27, 54, 3]) <= 35 # clipped [255,255,255] outside dense cloud suppressed + + # Warm daytime low cloud (+8C) over East China (~30N, 120E) recovered while night & orange desert stay dark + ir_zero = np.zeros((32, 64), dtype=np.uint8) + temp_grid = np.full((32, 64), 16.0, dtype=np.float32) + # East China row ~ (90-30)/180*32=10, col ~ (120+180)/360*64=53 + temp_grid[9:13, 50:56] = 8.0 + # Sahara daytime / hot sand (+34C) col ~ (15+180)/360*64=34 + temp_grid[10:14, 32:37] = 34.0 + # Winter Tibetan plateau snow (-30C at 32N, 90E -> row ~ 10, col ~ 48) + temp_grid[9:12, 47:50] = -30.0 + vis_arr = np.zeros((32, 64, 4), dtype=np.uint8) + vis_arr[:, :, 3] = 255 + vis_arr[9:13, 50:56, :3] = [215, 215, 215] # monochrome Himawari Band3 bright cloud + vis_arr[10:14, 32:37, :3] = [210, 145, 85] # orange Sahara desert in RGB + vis_arr[9:12, 47:50, :3] = [235, 235, 235] # cold Tibetan surface snow + # Pure-white clipped EUMETView artifact over warm Bay of Bengal (+18C at 12N, 85E -> row ~ 14, col ~ 47) + temp_grid[13:16, 46:49] = 18.0 + vis_arr[13:16, 46:49, :3] = [255, 255, 255] + # Night hemisphere over Americas (col 12, ~-112W at 05:00 UTC) + vis_arr[10:14, 10:16, :3] = [220, 220, 220] + decoded_fused = decode_visual_payloads( + [ + ({"id": "himawari", "sub_lon": 140.7}, _make_png_bytes(vis_arr)), + ({"id": "msg_fes", "sub_lon": 0.0}, _make_png_bytes(vis_arr)), + ({"id": "msg_iodc", "sub_lon": 45.5}, _make_png_bytes(vis_arr)), + ], + width=64, + height=32, + ) + fused = fuse_daytime_visible_into_density( + ir_zero, + temp_grid, + decoded_fused, + width=64, + height=32, + now_utc=datetime(2026, 12, 3, 5, 0, 0, tzinfo=UTC), + ) + assert int(fused[11, 53]) >= 120 + assert int(fused[12, 34]) < 30 + assert int(fused[10, 48]) < 35 # snow at -30C suppressed + assert int(fused[14, 47]) < 35 # pure-white 255 clipped EUMETView artifact suppressed + assert int(fused[12, 13]) == 0 + + flow_res = compute_dis_optical_flow_webp(d_prev, d_curr, flow_width=64, flow_height=32) + assert flow_res is not None + flow_bytes, max_uv = flow_res + assert len(flow_bytes) > 20 and max_uv > 0.0 + + # 7. Cache clear resets runtime mode to fallback_static + r_clear = await client.delete("/api/v1/earth/clouds/cache") + assert r_clear.status_code == 200 + assert r_clear.json()["meta"]["mode"] == "fallback_static" + finally: + app.dependency_overrides.clear() diff --git a/backend/tests/test_earth_tiles_and_wind.py b/backend/tests/test_earth_tiles_and_wind.py new file mode 100644 index 00000000..6e9b1526 --- /dev/null +++ b/backend/tests/test_earth_tiles_and_wind.py @@ -0,0 +1,369 @@ +"""Tests for Phase 2 managed tile pyramid and Phase 3 NOAA GFS wind field pipelines.""" + +from __future__ import annotations + +import io +from unittest.mock import AsyncMock + +import httpx +import numpy as np +from PIL import Image +import pytest + +from app.core.datasource_defaults import DEFAULT_DATASOURCES +from app.main import app +from app.models.user import User, UserRole +from app.services import earth_tiles, earth_wind +from app.services.ai.tool_registry import query_wind_posture_tool +from app.services.collectors.earth_tiles import ( + CloudHDTilesCollector, + Sentinel2ImageryCollector, + VIIRSDailyImageryCollector, +) +from app.services.collectors.wind_gfs import EarthWindGFSCollector + + +def _sample_jpg_bytes() -> bytes: + arr = np.full((32, 32, 3), (38, 122, 198), dtype=np.uint8) + img = Image.fromarray(arr, mode="RGB") + buf = io.BytesIO() + img.save(buf, format="JPEG", quality=85) + return buf.getvalue() + + +class _FakeScalarResult: + def __init__(self, rows=None, scalar=None): + self._rows = list(rows or []) + self._scalar = scalar + + def all(self): + return self._rows + + def first(self): + return self._rows[0] if self._rows else None + + def scalar(self): + return 0 + + def scalar_one_or_none(self): + return self._scalar + + def scalar_one(self): + return self._scalar + + +class _DummyAsyncDB: + def __init__(self, *, active_sources: dict[str, bool] | None = None): + self.active_sources = dict(active_sources or {}) + self.settings: dict[str, dict] = {} + self.added = [] + + async def execute(self, stmt): + sql = str(stmt) + if "FROM data_sources" in sql: + rows = [ + (DEFAULT_DATASOURCES[src]["id"], src, is_active) + for src, is_active in self.active_sources.items() + if src in DEFAULT_DATASOURCES + ] + single_src = next( + (src for src in self.active_sources if src in sql), + None, + ) + scalar_val = self.active_sources.get(single_src) if single_src else None + return _FakeScalarResult(rows=rows, scalar=scalar_val) + if "FROM system_settings" in sql: + for key in ("earth_basemap", "earth_cloud_map"): + if key in self.settings: + return _FakeScalarResult(scalar=self.settings[key]) + return _FakeScalarResult(scalar=None) + return _FakeScalarResult() + + def add(self, obj): + self.added.append(obj) + cat = getattr(obj, "category", None) + if cat: + self.settings[cat] = obj + + async def delete(self, obj): + cat = getattr(obj, "category", None) + if cat and cat in self.settings: + del self.settings[cat] + + async def commit(self): + return None + + async def rollback(self): + return None + + def get_bind(self): + return None + + async def get(self, *_args, **_kwargs): + return None + + +def test_cloud_hd_tile_routes_across_five_satellites(): + # Nighttime / pure IR routes across 5 geostationary satellites (z=7 GIBS clamps to Level6) + url_west_ir, params_west_ir, prov_west_ir = earth_tiles._resolve_cloud_hd_request( + earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 4, 2, 7, daytime=False + ) + assert prov_west_ir == "gibs" and params_west_ir is None and "GOES-West_ABI_Band13_Clean_Infrared" in url_west_ir + + url_east_ir, params_east_ir, prov_east_ir = earth_tiles._resolve_cloud_hd_request( + earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 4, 4, 7, daytime=False + ) + assert prov_east_ir == "gibs" and params_east_ir is None and "GOES-East_ABI_Band13_Clean_Infrared" in url_east_ir + + url_fes_ir, params_fes_ir, prov_fes_ir = earth_tiles._resolve_cloud_hd_request( + earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 4, 8, 7, daytime=False + ) + assert prov_fes_ir == "eumetview" and params_fes_ir is not None and params_fes_ir["LAYERS"] == "msg_fes:ir108" + assert params_fes_ir["SRS"] == "EPSG:3857" + + url_iodc_ir, params_iodc_ir, prov_iodc_ir = earth_tiles._resolve_cloud_hd_request( + earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 4, 10, 7, daytime=False + ) + assert prov_iodc_ir == "eumetview" and params_iodc_ir is not None and params_iodc_ir["LAYERS"] == "msg_iodc:ir108" + + url_hima_ir, params_hima_ir, prov_hima_ir = earth_tiles._resolve_cloud_hd_request( + earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 7, 112, 52, daytime=False + ) + assert ( + prov_hima_ir == "gibs" + and params_hima_ir is None + and "Himawari_AHI_Band13_Clean_Infrared" in url_hima_ir + and "/GoogleMapsCompatible_Level6/6/26/56.png" in url_hima_ir + ) + + # Daytime 1km/2km visible & GeoColor routes across 5 satellites up to Level 7 + url_west_vis, _, prov_west_vis = earth_tiles._resolve_cloud_hd_request( + earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 6, 10, 24, daytime=True + ) + assert prov_west_vis == "gibs_geocolor" and "GOES-West_ABI_GeoColor/default/default/GoogleMapsCompatible_Level7" in url_west_vis + + url_east_vis, _, prov_east_vis = earth_tiles._resolve_cloud_hd_request( + earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 6, 18, 24, daytime=True + ) + assert prov_east_vis == "gibs_geocolor" and "GOES-East_ABI_GeoColor/default/default/GoogleMapsCompatible_Level7" in url_east_vis + + _, params_fes_vis, prov_fes_vis = earth_tiles._resolve_cloud_hd_request( + earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 6, 33, 24, daytime=True + ) + assert prov_fes_vis == "eumetview_visible" and params_fes_vis["LAYERS"] == "msg_fes:rgb_naturalenhncd" + + _, params_iodc_vis, prov_iodc_vis = earth_tiles._resolve_cloud_hd_request( + earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 6, 40, 24, daytime=True + ) + assert prov_iodc_vis == "eumetview_visible" and params_iodc_vis["LAYERS"] == "msg_iodc:rgb_naturalenhncd" + + url_hima_vis, _, prov_hima_vis = earth_tiles._resolve_cloud_hd_request( + earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 7, 108, 52, daytime=True + ) + assert ( + prov_hima_vis == "gibs_visible" + and "Himawari_AHI_Band3_Red_Visible_1km/default/default/GoogleMapsCompatible_Level7/7/52/108.png" in url_hima_vis + ) + + +def test_alpha5_tle_encoding_and_stale_70char_rebuild(): + from types import SimpleNamespace + from app.core.satellite_tle import build_tle_lines_from_elements, format_tle_norad_id + from app.api.v1.visualization import _extract_satellite_record + + assert format_tle_norad_id(25544) == "25544" + assert format_tle_norad_id(100001) == "A0001" + assert format_tle_norad_id(100504) == "A0504" + assert format_tle_norad_id(339999) == "Z9999" + + l1, l2 = build_tle_lines_from_elements( + norad_cat_id=100504, + epoch="2026-12-03T06:00:00Z", + inclination=70.0, + raan=120.0, + eccentricity=0.00015, + arg_of_perigee=90.0, + mean_anomaly=270.0, + mean_motion=15.3, + ) + assert l1 is not None and l2 is not None + assert len(l1) == 69 and len(l2) == 69 + assert l1[2:7] == "A0504" and l2[2:7] == "A0504" + + # Malformed 70-char stored lines from prior 6-digit NORAD padding must rebuild cleanly + fake_record = SimpleNamespace( + name="STARLINK-38356", + extra_data={ + "norad_cat_id": 100504, + "epoch": "2026-12-03T06:00:00Z", + "inclination": 70.0, + "raan": 120.0, + "eccentricity": 0.00015, + "arg_of_perigee": 90.0, + "mean_anomaly": 270.0, + "mean_motion": 15.3, + "tle_line1": "1 100504U 00001A 26337.25000000 .00000000 00000-0 00000-0 0 9990", + "tle_line2": "2 100504 70.0000 120.0000 0001500 90.0000 270.0000 15.30000000000000", + }, + ) + _, _, fixed_l1, fixed_l2, _, _ = _extract_satellite_record(fake_record) + assert fixed_l1 is not None and fixed_l2 is not None + assert len(fixed_l1) == 69 and len(fixed_l2) == 69 + assert fixed_l1[2:7] == "A0504" and fixed_l2[2:7] == "A0504" + assert earth_tiles.BasemapConfig().cloud_hd_tiles_enabled is False + + +def test_erddap_csv0_wind_parser_and_analytics(tmp_path, monkeypatch): + monkeypatch.setattr(earth_wind, "WIND_DATA_DIR", tmp_path / "wind") + + csv_lines = [] + # 0..360 lon grid (every 60 deg) x (-30..30 lat) + for lat in (-30.0, 0.0, 30.0): + for lon in (0.0, 60.0, 120.0, 180.0, 240.0, 300.0): + # Strong westerly jet near lon=120E, lat=30N and moderate elsewhere + u_val = 22.0 if (lat == 30.0 and lon in (120.0, 180.0)) else 6.0 + v_val = 4.0 if (lat == 30.0 and lon in (120.0, 180.0)) else 1.5 + csv_lines.append(f"2026-12-03T12:00:00Z,{lat},{lon},{u_val},{v_val}") + + parsed = earth_wind.parse_erddap_csv0_wind("\n".join(csv_lines)) + assert float(parsed["lons"][0]) < 0.0 # rolled from 0..360 to -180..180 + assert parsed["u"].shape == (3, 6) + + analysis = earth_wind.analyze_wind_grid(parsed, config=earth_wind.WindFieldConfig()) + assert analysis["global_summary"]["max_speed_ms"] > 22.0 + assert analysis["global_summary"]["mean_speed_ms"] > 6.0 + + # Verify save + point query + grid payload + entry = earth_wind._save_wind_run_sync( + version="20261203T120000Z", + captured_at="2026-12-03T12:00:00Z", + parsed=parsed, + analysis=analysis, + max_history_runs=4, + ) + assert entry["grid_url"] == "/api/v1/earth/wind/grid/20261203T120000Z" + payload = earth_wind.read_wind_grid_payload("20261203T120000Z") + assert payload is not None + assert payload["width"] == 6 and payload["height"] == 3 + + +@pytest.mark.asyncio +async def test_tile_proxy_gating_cache_lru_and_basemap_api(tmp_path, monkeypatch): + monkeypatch.setattr(earth_tiles, "TILES_DATA_DIR", tmp_path / "tiles") + monkeypatch.setattr(earth_wind, "WIND_DATA_DIR", tmp_path / "wind") + + from app.api.v1.datasources import infer_datasource_product_key + + assert infer_datasource_product_key("earth_imagery_sentinel2", "Sentinel-2") == "geo" + assert infer_datasource_product_key("earth_imagery_viirs_daily", "NASA VIIRS") == "geo" + assert infer_datasource_product_key("global_wind_gfs", "NOAA GFS Wind") == "weather" + + # Pre-seed Sentinel-2 cached tile and inactive flag test + cached_path = earth_tiles._tile_path("earth_imagery_sentinel2", 0, 0, 0) + earth_tiles._atomic_write_bytes(cached_path, b"RIFFdemoWEBP") + + # Test DataSource.is_active=False enforcement directly + class _DisabledTileDB(_DummyAsyncDB): + async def execute(self, stmt): + sql = str(stmt) + if "FROM data_sources" in sql: + return _FakeScalarResult( + rows=[(36, "earth_imagery_sentinel2", False)], + scalar=type("_DS", (), {"source": "earth_imagery_sentinel2", "is_active": False})(), + ) + return await super().execute(stmt) + + _raw, allowed = await earth_tiles.get_or_fetch_tile( + "earth_imagery_sentinel2", 0, 0, 0, db=_DisabledTileDB() + ) + assert allowed is False + + # Test active source serves cached bytes without upstream call + class _EnabledTileDB(_DummyAsyncDB): + async def execute(self, stmt): + sql = str(stmt) + if "FROM data_sources" in sql: + return _FakeScalarResult( + rows=[(36, "earth_imagery_sentinel2", True)], + scalar=type("_DS", (), {"source": "earth_imagery_sentinel2", "is_active": True})(), + ) + return await super().execute(stmt) + + served, allowed_ok = await earth_tiles.get_or_fetch_tile( + "earth_imagery_sentinel2", 0, 0, 0, db=_EnabledTileDB() + ) + assert allowed_ok is True + assert served == b"RIFFdemoWEBP" + + # Collector instantiation checks (catches missing abstract methods!) + c_hd = CloudHDTilesCollector() + c_s2 = Sentinel2ImageryCollector() + c_viirs = VIIRSDailyImageryCollector() + c_wind = EarthWindGFSCollector() + assert c_hd.name == "cloud_hd_tiles" + assert c_s2.name == "earth_imagery_sentinel2" + assert c_viirs.name == "earth_imagery_viirs_daily" + assert c_wind.name == "global_wind_gfs" + + monkeypatch.setattr( + earth_tiles, + "get_or_fetch_tile", + AsyncMock(return_value=(b"RIFFdemoWEBP", True)), + ) + + from app.core.security import get_current_user + from app.db.session import get_db + + fake_db = _DummyAsyncDB( + active_sources={ + "earth_imagery_sentinel2": True, + "earth_imagery_viirs_daily": False, + "global_cloud_map": True, + "cloud_hd_tiles": True, + "global_wind_gfs": True, + } + ) + admin_user = User(id=1, username="admin", role=UserRole.ADMIN) + + async def _override_db(): + yield fake_db + + app.dependency_overrides[get_db] = _override_db + app.dependency_overrides[get_current_user] = lambda: admin_user + + try: + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: + r_tile = await client.get("/api/v1/earth/tiles/earth_imagery_sentinel2/0/0/0.webp") + assert r_tile.status_code == 200 + assert r_tile.headers["content-type"].startswith("image/webp") + + r_cfg = await client.get("/api/v1/earth/basemap/configuration") + assert r_cfg.status_code == 200 + rev = r_cfg.json()["revision"] + + r_put = await client.put( + "/api/v1/earth/basemap/configuration", + json={ + "revision": rev, + "config": {**r_cfg.json()["config"], "active_source": "earth_imagery_viirs_daily"}, + }, + ) + assert r_put.status_code == 200 + assert r_put.json()["config"]["active_source"] == "earth_imagery_viirs_daily" + + r_stale = await client.put( + "/api/v1/earth/basemap/configuration", + json={"revision": rev, "config": r_cfg.json()["config"]}, + ) + assert r_stale.status_code == 409 + + r_geo = await client.get("/api/v1/data-products/geo/status") + assert r_geo.status_code == 200 + assert r_geo.json()["product_id"] == "geo" + assert r_geo.json()["total_collector_count"] == 2 + + wind_tool = await query_wind_posture_tool(fake_db, latitude=30.0, longitude=120.0) + assert wind_tool["domain"] == "wind" + finally: + app.dependency_overrides.clear() diff --git a/backend/tests/test_location_agent_workflow.py b/backend/tests/test_location_agent_workflow.py index 595ef667..4695f7a7 100644 --- a/backend/tests/test_location_agent_workflow.py +++ b/backend/tests/test_location_agent_workflow.py @@ -1,4 +1,4 @@ -"""Tests for Wikidata/PeeringDB L1 resolvers and Tool-Calling Location Agent.""" +"""Tests for the true-DAG `location.resolve_unknown` workflow, atomic tools, and guardrails.""" from __future__ import annotations @@ -11,12 +11,16 @@ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from app.db.session import Base +from app.models.ai_workflow import AIWorkflow, AIWorkflowRevision from app.models.compute_center_location import ComputeCenterLocationRecord from app.models.situational_assessment import WorkflowRun -from app.services.location.agent_resolver import run_controlled_location_agent -from app.services.location.models import LocationQuery +from app.models.system_setting import SystemSetting +from app.services.compute_center_locations import COMPUTE_CENTER_LOCATION_CACHE, _cache_key +from app.services.location import workflow_tools +from app.services.location.models import LocationCandidate, LocationQuery from app.services.location.resolvers.peeringdb_facility import lookup_peeringdb_facility from app.services.location.resolvers.wikidata import lookup_wikidata_facility +from app.services.location.workflow_tools import run_location_workflow class _SyncAsAsyncSession: @@ -52,7 +56,13 @@ def _make_sync_db(): engine = create_engine("sqlite:///:memory:") Base.metadata.create_all( engine, - tables=[ComputeCenterLocationRecord.__table__, WorkflowRun.__table__], + tables=[ + AIWorkflow.__table__, + AIWorkflowRevision.__table__, + ComputeCenterLocationRecord.__table__, + SystemSetting.__table__, + WorkflowRun.__table__, + ], ) sync_factory = sessionmaker(engine, expire_on_commit=False) @@ -61,304 +71,425 @@ def _make_sync_db(): return self async def __aenter__(self): - self._sess = _SyncAsAsyncSession(sync_factory()) - return self._sess + self._s = sync_factory() + return _SyncAsAsyncSession(self._s) - async def __aexit__(self, *_args): - await self._sess.close() + async def __aexit__(self, exc_type, exc, tb): + self._s.close() + return False return engine, _Ctx() -@pytest.mark.asyncio -async def test_wikidata_and_peeringdb_resolvers_parse_coordinates(monkeypatch): - class _FakeResponse: - def __init__(self, payload): - self._payload = payload +async def _async_val(val): + return val - def raise_for_status(self): - return None - def json(self): - return self._payload - - class _FakeAsyncClient: - def __init__(self, **_kwargs): - pass - - async def __aenter__(self): - return self - - async def __aexit__(self, *_args): - return False - - async def get(self, url, params=None): - if "wikidata.org" in url and (params or {}).get("action") == "wbsearchentities": - return _FakeResponse({"search": [{"id": "Q123456"}]}) - if "wikidata.org" in url and (params or {}).get("action") == "wbgetentities": - return _FakeResponse( - { - "entities": { - "Q123456": { - "labels": {"en": {"value": "Memphis Supercluster Facility"}}, - "descriptions": {"en": {"value": "data center campus in Memphis, Tennessee"}}, - "claims": { - "P625": [ - { - "mainsnak": { - "datavalue": { - "value": {"latitude": 35.0612, "longitude": -90.1511} - } - } - } - ] - }, - } - } - } - ) - if "peeringdb.com" in url: - return _FakeResponse( - { - "data": [ - { - "id": 9901, - "name": "Equinix NY5 Secaucus", - "city": "Secaucus", - "state": "NJ", - "country": "US", - "address1": "800 Secaucus Rd", - "latitude": 40.7831, - "longitude": -74.0725, - } - ] - } - ) - return _FakeResponse({}) - - from app.services.location.resolvers import peeringdb_facility, wikidata - - monkeypatch.setattr(wikidata.httpx, "AsyncClient", _FakeAsyncClient) - monkeypatch.setattr(peeringdb_facility.httpx, "AsyncClient", _FakeAsyncClient) - - wd_out = await lookup_wikidata_facility( - LocationQuery(name="Memphis Supercluster Facility", country="United States") +def _stub_empty_l1(monkeypatch): + monkeypatch.setattr( + workflow_tools, + "lookup_wikidata_facility", + lambda _q: _async_val(SimpleNamespace(candidates=(), attempted_queries=())), ) - assert len(wd_out.candidates) == 1 - assert wd_out.candidates[0].source == "wikidata_facility" - assert wd_out.candidates[0].latitude == pytest.approx(35.0612, abs=1e-4) - - pdb_out = await lookup_peeringdb_facility( - LocationQuery(name="Equinix NY5 Secaucus", country="United States") + monkeypatch.setattr( + workflow_tools, + "lookup_peeringdb_facility", + lambda _q: _async_val(SimpleNamespace(candidates=(), attempted_queries=())), + ) + monkeypatch.setattr( + "app.services.compute_center_locations._lookup_ror_organization", + lambda _q: None, ) - assert len(pdb_out.candidates) == 1 - assert pdb_out.candidates[0].source == "peeringdb_facility" - assert pdb_out.candidates[0].precision == "precise" - assert pdb_out.candidates[0].city == "Secaucus" @pytest.mark.asyncio -async def test_tool_calling_location_agent_loop_and_guardrails(monkeypatch): - from app.services.location import agent_resolver +async def test_l0_short_circuits_cached_terminal_without_calling_l1_or_llm(monkeypatch): + key = _cache_key("epoch_ai_gpu", "epoch-term-1") + COMPUTE_CENTER_LOCATION_CACHE[key] = { + "source": "epoch_ai_gpu", + "source_id": "epoch-term-1", + "verification_status": "undisclosed", + "source_note": "Confirmed NDA undisclosed", + } - async def _fake_safe_fetch(url, **_kwargs): - return { - "url": url, - "status_code": 200, - "content": "The Colossus supercomputer operates at 5420 Tulane Rd, Memphis, TN, USA.", - } - - def _fake_geocode(place_query, country_hint=""): - return { - "latitude": 35.0612, - "longitude": -90.1511, - "display_name": "5420 Tulane Rd, Memphis, Shelby County, Tennessee, United States", - "city": "Memphis", - "region": "Tennessee", - "country": "美国", - "precision": "precise", - } - - monkeypatch.setattr(agent_resolver, "safe_web_fetch", _fake_safe_fetch) - monkeypatch.setattr(agent_resolver, "_agent_geocoder", _fake_geocode) - - class _StepProvider: - def __init__(self): - self.turn = 0 - - async def analyze(self, req): - self.turn += 1 - if self.turn == 1: - return SimpleNamespace( - content="", - tool_calls=[ - SimpleNamespace( - id="call_1", - name="fetch_source_url", - arguments=json.dumps({"url": "https://epoch.ai/colossus-source"}), - ) - ], - ) - if self.turn == 2: - return SimpleNamespace( - content="", - tool_calls=[ - SimpleNamespace( - id="call_2", - name="geocode_verify", - arguments=json.dumps({"place_query": "5420 Tulane Rd, Memphis, USA", "country": "United States"}), - ) - ], - ) - return SimpleNamespace( - content="", - tool_calls=[ - SimpleNamespace( - id="call_3", - name="submit_location_result", - arguments=json.dumps( - { - "status": "located", - "facility_name": "Colossus Memphis Campus", - "city": "Memphis", - "region": "Tennessee", - "country": "United States", - "precision": "precise", - "geocode_candidate_id": "geo_1", - "citations": ["https://epoch.ai/colossus-source"], - "confidence": 0.91, - "reasoning": "Epoch source confirms 5420 Tulane Rd in Memphis.", - } - ), - ) - ], - ) - - engine, factory = _make_sync_db() + class _ExplodingAI: + async def analyze(self, _req): + raise AssertionError("LLM must not be called on cached L0 terminal") + try: + res = await run_location_workflow( + db=None, + query=LocationQuery( + name="SecretCluster", + extra={"source": "epoch_ai_gpu", "source_id": "epoch-term-1"}, + ), + provider_client=_ExplodingAI(), + record_run=False, + ) + assert res["success"] is False + assert res["terminal_status"] == "undisclosed" + assert "NDA undisclosed" in (res["failure_reason"] or "") + statuses = {t["node_id"]: t["status"] for t in res["node_traces"]} + assert statuses["l0_normalize"] == "completed" + assert statuses["l1_knowledge"] == "skipped" + assert statuses["l2_judge_r1"] == "skipped" + assert statuses["l4_persist_outcome"] == "completed" + finally: + COMPUTE_CENTER_LOCATION_CACHE.pop(key, None) + + +@pytest.mark.asyncio +async def test_l1_hit_skips_l2_and_records_single_workflow_run(monkeypatch): + hit = LocationCandidate( + latitude=35.9297, + longitude=-84.3095, + display_name="Oak Ridge National Laboratory", + precision="site", + confidence=0.9, + query="wikidata:Frontier", + source="wikidata_p625", + source_note="Wikidata P625", + matched_fields=("name",), + needs_confirmation=True, + city="Oak Ridge", + country="美国", + ) + monkeypatch.setattr( + workflow_tools, + "lookup_wikidata_facility", + lambda _q: _async_val(SimpleNamespace(candidates=(hit,), attempted_queries=("wikidata:Frontier",))), + ) + monkeypatch.setattr( + workflow_tools, + "lookup_peeringdb_facility", + lambda _q: _async_val(SimpleNamespace(candidates=(), attempted_queries=())), + ) + monkeypatch.setattr( + "app.services.compute_center_locations._lookup_ror_organization", + lambda _q: None, + ) + + class _ExplodingAI: + async def analyze(self, _req): + raise AssertionError("LLM must skip on L1 hit") + + engine, factory = _make_sync_db() try: async with factory() as session: - result, term = await run_controlled_location_agent( - provider_client=_StepProvider(), - web_search_client=None, - query=LocationQuery( - name="Colossus", - country="United States", - extra={"source": "epoch_ai_gpu", "source_id": "epoch-colossus", "source_url": "https://epoch.ai/colossus-source"}, - ), + res = await run_location_workflow( db=session, + query=LocationQuery(name="Frontier", country="美国"), + provider_client=_ExplodingAI(), + trigger_evolution=False, ) - assert term is None - assert len(result.candidates) == 1 - cand = result.candidates[0] - assert cand.precision == "precise" - assert cand.city == "Memphis" - assert cand.raw_payload["citations"] == ["https://epoch.ai/colossus-source"] + assert res["success"] is True + assert res["candidates"][0].city == "Oak Ridge" + assert res["workflow_run_id"] + statuses = {t["node_id"]: t["status"] for t in res["node_traces"]} + assert statuses["l1_knowledge"] == "completed" + assert statuses["l2_research_r1"] == "skipped" + assert statuses["l4_persist_outcome"] == "completed" + run = await session.get(WorkflowRun, res["workflow_run_id"]) + assert run is not None + assert run.status == "completed" + assert run.budget_used.get("steps") == 0 finally: engine.dispose() @pytest.mark.asyncio -async def test_tool_calling_agent_rejects_unobserved_citations_and_persists_terminal(monkeypatch): - from app.services.location import agent_resolver - - monkeypatch.setattr(agent_resolver, "_agent_geocoder", lambda _q, _c="": { - "latitude": 35.0612, - "longitude": -90.1511, - "display_name": "Memphis, TN, USA", - "city": "Memphis", - "country": "美国", - "precision": "city", - }) - - class _FabricatedCitationProvider: - def __init__(self): - self.turn = 0 - - async def analyze(self, _req): - self.turn += 1 - if self.turn == 1: - return SimpleNamespace( - content="", - tool_calls=[ - SimpleNamespace( - id="g1", - name="geocode_verify", - arguments=json.dumps({"place_query": "Memphis, USA", "country": "United States"}), - ) - ], - ) - return SimpleNamespace( - content="", - tool_calls=[ - SimpleNamespace( - id="s1", - name="submit_location_result", - arguments=json.dumps( - { - "status": "located", - "geocode_candidate_id": "geo_1", - "citations": ["https://madeup.example.com/fake-url"], - "country": "United States", - "reasoning": "Made up citation test", - } - ), - ) - ], +async def test_r1_direct_locate_skips_r2_and_resolves_evidence_ids(monkeypatch): + _stub_empty_l1(monkeypatch) + monkeypatch.setattr( + workflow_tools, + "safe_web_fetch", + lambda url, **_kwargs: _async_val( + SimpleNamespace( + url=url, + final_url=url, + title="Colossus Source", + text="xAI Colossus sits at 5420 Tulane Rd, Memphis, TN, United States.", ) - - res_bad, _ = await run_controlled_location_agent( - provider_client=_FabricatedCitationProvider(), - web_search_client=None, - query=LocationQuery(name="FakeCitedCluster", country="United States"), + ), + ) + monkeypatch.setattr( + workflow_tools, + "_agent_geocoder", + lambda _q: { + "lat": "35.0612", + "lon": "-90.1511", + "display_name": "5420 Tulane Rd, Memphis, TN, USA", + "address": {"house_number": "5420", "road": "Tulane Rd", "city": "Memphis", "country": "United States"}, + }, ) - assert res_bad.candidates == [] - assert "No verified citation URLs" in (res_bad.failure_reason or "") - class _TerminalProvider: + class _FakeSearch: + async def search(self, _q, max_results=5): + return [] + + class _R1AI: + def __init__(self): + self.calls = 0 + + async def analyze(self, req): + self.calls += 1 + items = (req.context or {}).get("evidence_items") or [] + assert len(items) == 1 + assert items[0]["id"] == "E1" + assert "epoch.ai/colossus-source" in items[0]["url"] + return SimpleNamespace( + content=json.dumps( + { + "decision": "located", + "facility_name": "xAI Colossus", + "address": "5420 Tulane Rd", + "city": "Memphis", + "region": "Tennessee", + "country": "United States", + "precision": "precise", + "confidence": 0.93, + "evidence_ids": ["E1"], + "reasoning": "E1 confirms Memphis street address.", + } + ), + model="test-model", + provider="test-provider", + ) + + res = await run_location_workflow( + db=None, + query=LocationQuery( + name="Colossus", + country="美国", + extra={ + "source": "epoch_ai_gpu", + "source_id": "epoch-colossus", + "source_url": "https://epoch.ai/colossus-source?utm_source=x", + "sources": ["https://epoch.ai/data/gpu-clusters.csv"], + }, + ), + provider_client=_R1AI(), + web_search_client=_FakeSearch(), + record_run=False, + ) + assert res["success"] is True + cand = res["candidates"][0] + assert cand.precision == "precise" + assert cand.city == "Memphis" + assert cand.raw_payload["evidence_ids"] == ["E1"] + assert cand.raw_payload["citations"] == ["https://epoch.ai/colossus-source?utm_source=x"] + statuses = {t["node_id"]: t["status"] for t in res["node_traces"]} + assert statuses["l2_research_r1"] == "completed" + assert statuses["l2_judge_r1"] == "completed" + assert statuses["l2_research_r2"] == "skipped" + assert statuses["l2_judge_r2"] == "skipped" + + +@pytest.mark.asyncio +async def test_r1_need_followup_triggers_r2_and_cascade_geocodes_city(monkeypatch): + _stub_empty_l1(monkeypatch) + geo_queries = [] + + def _geocoder(q): + geo_queries.append(q) + if "Mesa Laboratory" in q: + return None + return { + "lat": "39.9784", + "lon": "-105.2749", + "display_name": "Boulder, Colorado, United States", + "address": {"city": "Boulder", "state": "Colorado", "country": "United States"}, + } + + monkeypatch.setattr(workflow_tools, "_agent_geocoder", _geocoder) + monkeypatch.setattr( + workflow_tools, + "safe_web_fetch", + lambda url, **_kwargs: _async_val( + SimpleNamespace( + url=url, + final_url=url, + title="NCAR DYEUS", + text="IBM GRAF / DYEUS GPU cluster operates inside NCAR Mesa Laboratory, Boulder, Colorado.", + ) + ), + ) + + search_queries = [] + + class _Search: + async def search(self, q, max_results=5): + search_queries.append(q) + if "Boulder" in q: + return [ + SimpleNamespace( + title="NCAR Boulder announcement", + url="https://ncar.ucar.edu/dyeus", + snippet="DYEUS is hosted in Boulder, Colorado.", + ) + ] + return [ + SimpleNamespace( + title="IBM Weather Blog", + url="https://blogs.nvidia.com/dyeus-graf", + snippet="IBM weather GPU cluster partnered with NCAR.", + ) + ] + + class _TwoRoundAI: + def __init__(self): + self.calls = 0 + + async def analyze(self, req): + self.calls += 1 + if self.calls == 1: + assert all("美国" not in q for q in search_queries) + return SimpleNamespace( + content=json.dumps( + { + "decision": "need_followup", + "followup_queries": ["IBM DYEUS NCAR Boulder"], + "fetch_urls": ["https://blogs.nvidia.com/dyeus-graf"], + "reasoning": "R1 mentions NCAR, fetch full blog and search Boulder.", + } + ), + model="test", + provider="minimax", + ) + items = (req.context or {}).get("evidence_items") or [] + assert len(items) >= 2 + return SimpleNamespace( + content=json.dumps( + { + "decision": "located", + "facility_name": "NCAR Mesa Laboratory", + "city": "Boulder", + "region": "Colorado", + "country": "United States", + "precision": "site", + "confidence": 0.89, + "evidence_ids": ["E2"], + "reasoning": "R2 confirms NCAR Mesa Laboratory in Boulder, CO.", + } + ), + model="test", + provider="minimax", + ) + + ai = _TwoRoundAI() + res = await run_location_workflow( + db=None, + query=LocationQuery( + name="IBM DYEUS", + country="美国", + extra={"operator": "IBM", "source": "epoch_ai_gpu", "source_id": "epoch_ibm_dyeus"}, + ), + provider_client=ai, + web_search_client=_Search(), + record_run=False, + ) + assert ai.calls == 2 + assert any("IBM DYEUS NCAR Boulder" == q for q in search_queries) + assert any("Mesa Laboratory" in q for q in geo_queries) + assert "Boulder, Colorado, United States" in geo_queries + assert res["success"] is True + assert res["candidates"][0].city == "Boulder" + assert res["candidates"][0].precision == "city" # downgraded because geocoder returned city level + statuses = {t["node_id"]: t["status"] for t in res["node_traces"]} + assert statuses["l2_research_r2"] == "completed" + assert statuses["l2_judge_r2"] == "completed" + + +@pytest.mark.asyncio +async def test_r2_coerces_need_followup_to_unresolved(monkeypatch): + _stub_empty_l1(monkeypatch) + + class _Search: + async def search(self, _q, max_results=5): + return [SimpleNamespace(title="Partial", url="https://example.com/partial", snippet="Vague mention")] + + class _StubbornAI: async def analyze(self, _req): return SimpleNamespace( - content="", - tool_calls=[ - SimpleNamespace( - id="t1", - name="submit_location_result", - arguments=json.dumps( - { - "status": "undisclosed", - "reasoning": "Customer confidential cluster location is undisclosed.", - } - ), - ) - ], + content=json.dumps( + { + "decision": "need_followup", + "followup_queries": ["more searches"], + "reasoning": "Still unsure.", + } + ), + model="test", + provider="test", ) + res = await run_location_workflow( + db=None, + query=LocationQuery(name="VagueCluster", country="France"), + provider_client=_StubbornAI(), + web_search_client=_Search(), + record_run=False, + ) + assert res["success"] is False + assert "Still unsure." in (res["failure_reason"] or "") + + +@pytest.mark.asyncio +async def test_terminal_status_rejected_without_evidence_and_persisted_with_evidence(monkeypatch): + _stub_empty_l1(monkeypatch) + monkeypatch.setattr( + "app.services.compute_center_locations.refresh_compute_center_location_cache", + lambda _db: _async_val(None), + ) + + class _UndisclosedAI: + async def analyze(self, _req): + return SimpleNamespace( + content=json.dumps( + { + "decision": "undisclosed", + "evidence_ids": ["E1"], + "reasoning": "Confirmed customer confidential NDA.", + } + ), + model="test", + provider="test", + ) + + class _EmptySearch: + async def search(self, _q, max_results=5): + return [] + + class _HitSearch: + async def search(self, _q, max_results=5): + return [SimpleNamespace(title="NDA", url="https://example.com/nda", snippet="Undisclosed customer facility")] + engine, factory = _make_sync_db() - - from app.services import compute_center_locations - - monkeypatch.setattr( - compute_center_locations, - "refresh_compute_center_location_cache", - lambda _db: _noop(), - ) - - async def _noop(): - return None - try: async with factory() as session: - res_term, term = await run_controlled_location_agent( - provider_client=_TerminalProvider(), - web_search_client=None, - query=LocationQuery( - name="Undisclosed Customer", - extra={"source": "epoch_ai_gpu", "source_id": "epoch-undisclosed"}, - ), + bad = await run_location_workflow( db=session, + query=LocationQuery( + name="SecretA", + extra={"source": "epoch_ai_gpu", "source_id": "epoch-secret-a"}, + ), + provider_client=_UndisclosedAI(), + web_search_client=_EmptySearch(), + trigger_evolution=False, ) - assert term == "undisclosed" - assert res_term.candidates == [] + assert bad["terminal_status"] is None + assert "without tool evidence" in (bad["failure_reason"] or "") + + good = await run_location_workflow( + db=session, + query=LocationQuery( + name="SecretB", + extra={"source": "epoch_ai_gpu", "source_id": "epoch-secret-b"}, + ), + provider_client=_UndisclosedAI(), + web_search_client=_HitSearch(), + trigger_evolution=False, + ) + assert good["terminal_status"] == "undisclosed" saved = await session.get(ComputeCenterLocationRecord, 1) assert saved is not None assert saved.verification_status == "undisclosed" @@ -366,6 +497,209 @@ async def test_tool_calling_agent_rejects_unobserved_citations_and_persists_term engine.dispose() +@pytest.mark.asyncio +async def test_guardrail_rejects_state_level_below_min_confidence_and_unobserved_urls(monkeypatch): + _stub_empty_l1(monkeypatch) + + class _Search: + async def search(self, _q, max_results=5): + return [SimpleNamespace(title="Iowa DC", url="https://example.com/iowa", snippet="Iowa")] + + monkeypatch.setattr( + workflow_tools, + "_agent_geocoder", + lambda _q: { + "lat": "41.878", + "lon": "-93.0977", + "display_name": "Iowa, United States", + "address": {"state": "Iowa", "country": "United States"}, + }, + ) + + class _StateAI: + async def analyze(self, _req): + return SimpleNamespace( + content=json.dumps( + { + "decision": "located", + "city": "Iowa", + "country": "United States", + "precision": "city", + "confidence": 0.85, + "evidence_ids": ["E1"], + "reasoning": "Only state level found.", + } + ) + ) + + res_state = await run_location_workflow( + db=None, + query=LocationQuery(name="StateCluster", country="United States"), + provider_client=_StateAI(), + web_search_client=_Search(), + record_run=False, + ) + assert res_state["success"] is False + assert "only country or region/state level" in (res_state["failure_reason"] or "") + + monkeypatch.setattr( + workflow_tools, + "_agent_geocoder", + lambda _q: { + "lat": "41.5868", + "lon": "-93.625", + "display_name": "Des Moines, IA, USA", + "address": {"city": "Des Moines", "country": "United States"}, + }, + ) + + class _FakeCiteAI: + async def analyze(self, _req): + return SimpleNamespace( + content=json.dumps( + { + "decision": "located", + "city": "Des Moines", + "country": "United States", + "precision": "city", + "confidence": 0.9, + "evidence_ids": ["E99"], + "citations": ["https://fake.example.invalid/madeup"], + "reasoning": "Fabricated URL.", + } + ) + ) + + res_fake = await run_location_workflow( + db=None, + query=LocationQuery(name="FakeCite", country="United States"), + provider_client=_FakeCiteAI(), + web_search_client=_Search(), + record_run=False, + ) + assert res_fake["success"] is False + assert "No verified citation URLs" in (res_fake["failure_reason"] or "") + + class _LowConfAI: + async def analyze(self, _req): + return SimpleNamespace( + content=json.dumps( + { + "decision": "located", + "city": "Des Moines", + "country": "United States", + "precision": "city", + "confidence": 0.42, + "evidence_ids": ["E1"], + "reasoning": "Weak guess.", + } + ) + ) + + res_low = await run_location_workflow( + db=None, + query=LocationQuery(name="LowConf", country="United States"), + provider_client=_LowConfAI(), + web_search_client=_Search(), + record_run=False, + ) + assert res_low["success"] is False + assert "below minimum 0.55" in (res_low["failure_reason"] or "") + + +@pytest.mark.asyncio +async def test_guardrail_cross_country_override_iseg2_pattern_and_evolution_hook(monkeypatch): + _stub_empty_l1(monkeypatch) + monkeypatch.setattr( + workflow_tools, + "_agent_geocoder", + lambda _q: { + "lat": "64.0025", + "lon": "-22.5594", + "display_name": "Keflavik, Iceland", + "address": {"city": "Keflavik", "country": "Iceland"}, + }, + ) + evo_calls = [] + monkeypatch.setattr( + "app.services.ai.workflow_evolver.schedule_post_run_evolution", + lambda wf_id, run_id: evo_calls.append((wf_id, run_id)), + ) + + class _Search: + async def search(self, _q, max_results=5): + return [SimpleNamespace(title="ISEG2", url="https://verneglobal.com/iseg2", snippet="Keflavik, Iceland")] + + class _NoReasonAI: + async def analyze(self, _req): + return SimpleNamespace( + content=json.dumps( + { + "decision": "located", + "city": "Keflavik", + "country": "Iceland", + "precision": "city", + "confidence": 0.9, + "evidence_ids": ["E1"], + "reasoning": "Found in Keflavik.", + } + ) + ) + + res_blocked = await run_location_workflow( + db=None, + query=LocationQuery(name="ISEG2", country="荷兰"), + provider_client=_NoReasonAI(), + web_search_client=_Search(), + record_run=False, + ) + assert res_blocked["success"] is False + assert "Country mismatch" in (res_blocked["failure_reason"] or "") + + class _OverrideAI: + async def analyze(self, _req): + return SimpleNamespace( + content=json.dumps( + { + "decision": "located", + "facility_name": "Verne Global Campus", + "city": "Keflavik", + "country": "Iceland", + "precision": "city", + "confidence": 0.92, + "evidence_ids": ["E1"], + "country_override_reason": "TOP500 lists Nebius HQ NL; facility operates in Iceland.", + "reasoning": "Confirmed Verne Global colocation in Keflavik.", + } + ), + model="MiniMax-M3.1-Flash", + provider="minimax", + ) + + engine, factory = _make_sync_db() + try: + async with factory() as session: + res_ok = await run_location_workflow( + db=session, + query=LocationQuery(name="ISEG2", country="荷兰", extra={"source_id": "top500_13"}), + provider_client=_OverrideAI(), + web_search_client=_Search(), + trigger_evolution=True, + ) + assert res_ok["success"] is True + cand = res_ok["candidates"][0] + assert cand.country == "冰岛" + assert cand.raw_payload["country_mismatch_override"]["resolved_country"] == "冰岛" + assert evo_calls == [("location.resolve_unknown", res_ok["workflow_run_id"])] + run = await session.get(WorkflowRun, res_ok["workflow_run_id"]) + assert run is not None + assert run.status == "completed" + assert run.budget_used.get("steps") == 1 + assert isinstance(run.budget_used.get("node_traces"), list) + finally: + engine.dispose() + + def test_nominatim_geocoder_retries_transient_ssl_eof(monkeypatch): from app.services.location.resolvers import nominatim @@ -397,111 +731,206 @@ def test_nominatim_geocoder_retries_transient_ssl_eof(monkeypatch): @pytest.mark.asyncio -async def test_location_agent_recovers_from_geocode_verify_exception(monkeypatch): - from app.services.location import agent_resolver +async def test_wikidata_skips_p17_country_mismatch(monkeypatch): + from app.services.location.resolvers import wikidata - geo_calls = {"count": 0} + class _Resp: + def __init__(self, payload): + self._payload = payload - def _flaky_geocoder(place_query: str): - geo_calls["count"] += 1 - if geo_calls["count"] == 1: - raise ssl.SSLError("[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1081)") - return { - "lat": "35.1495", - "lon": "-90.0490", - "display_name": place_query, - "city": "Memphis", - "region": "Tennessee", - "country": "United States", - } + def raise_for_status(self): + return None - monkeypatch.setattr(agent_resolver, "_agent_geocoder", _flaky_geocoder) - monkeypatch.setattr( - agent_resolver, - "safe_web_fetch", - lambda url, **_kwargs: _async_val( - SimpleNamespace(url=url, final_url=url, title="Colossus", text="3231 Paul R Lowry Road, Memphis, Tennessee") - ), - ) + def json(self): + return self._payload - class _RecoveringProvider: - def __init__(self): - self.turn = 0 - self.saw_retryable_error = False + class _Client: + def __init__(self, **_kwargs): + pass - async def analyze(self, req): - self.turn += 1 - if self.turn == 1: - return SimpleNamespace( - content="", - tool_calls=[ - SimpleNamespace( - id="c1", - name="fetch_source_url", - arguments=json.dumps({"url": "https://example.com/colossus"}), - ) - ], - ) - if self.turn == 2: - return SimpleNamespace( - content="", - tool_calls=[ - SimpleNamespace( - id="c2", - name="geocode_verify", - arguments=json.dumps({"place_query": "3231 Paul R Lowry Road, Memphis", "country": "United States"}), - ) - ], - ) - if self.turn == 3: - last_msg = req.messages[-1].content if req.messages else "" - if "geocoder request failed" in str(last_msg): - self.saw_retryable_error = True - return SimpleNamespace( - content="", - tool_calls=[ - SimpleNamespace( - id="c3", - name="geocode_verify", - arguments=json.dumps({"place_query": "Memphis, Tennessee", "country": "United States"}), - ) - ], - ) - return SimpleNamespace( - content="", - tool_calls=[ - SimpleNamespace( - id="c4", - name="submit_location_result", - arguments=json.dumps( - { - "status": "located", - "facility_name": "Colossus Memphis", - "city": "Memphis", - "region": "Tennessee", - "country": "United States", - "precision": "city", - "geocode_candidate_id": "geo_1", - "citations": ["https://example.com/colossus"], - "confidence": 0.9, - "reasoning": "Recovered after geocode retry", + async def __aenter__(self): + return self + + async def __aexit__(self, *_args): + return False + + async def get(self, _url, params=None): + action = (params or {}).get("action") + if action == "wbsearchentities": + return _Resp({"search": [{"id": "Q111"}]}) + ids = str((params or {}).get("ids") or "") + if ids == "Q111": + return _Resp( + { + "entities": { + "Q111": { + "labels": {"en": {"value": "Fugaku supercomputer"}}, + "descriptions": {"en": {"value": "Japanese supercomputer"}}, + "claims": { + "P17": [{"mainsnak": {"datavalue": {"value": {"id": "Q17"}}}}], + "P625": [{"mainsnak": {"datavalue": {"value": {"latitude": 34.653, "longitude": 135.220}}}}], + }, } - ), - ) - ], - ) + } + } + ) + return _Resp({"entities": {"Q17": {"labels": {"en": {"value": "Japan"}, "zh": {"value": "日本"}}}}}) - provider = _RecoveringProvider() - res, term = await run_controlled_location_agent( - provider_client=provider, - web_search_client=None, - query=LocationQuery(name="Colossus Memphis", country="United States"), + monkeypatch.setattr(wikidata.httpx, "AsyncClient", _Client) + out = await lookup_wikidata_facility(LocationQuery(name="Fugaku", country="United States")) + assert not out.candidates + + +@pytest.mark.asyncio +async def test_peeringdb_skips_generic_operator_only(monkeypatch): + from app.services.location.resolvers import peeringdb_facility + + class _ExplodingClient: + def __init__(self, **_kwargs): + raise AssertionError("PeeringDB HTTP client must not run for generic operator only") + + monkeypatch.setattr(peeringdb_facility.httpx, "AsyncClient", _ExplodingClient) + out = await lookup_peeringdb_facility( + LocationQuery(name="Nebius", country="Netherlands", extra={"operator": "Nebius"}) ) - assert provider.saw_retryable_error is True - assert term is None - assert len(res.candidates) == 1 - assert res.candidates[0].city == "Memphis" + assert not out.candidates + assert not out.attempted_queries -async def _async_val(val): - return val +def test_nominatim_geocoder_requests_english_locale(monkeypatch): + from app.services.location.resolvers import nominatim + + captured: dict[str, Any] = {} + + class _FakeResp: + def raise_for_status(self): + return None + + def json(self): + return [{"lat": "64.0005", "lon": "-22.5583", "display_name": "Keflavik, Iceland", "address": {"city": "Keflavik", "country": "Iceland", "country_code": "is"}}] + + def _fake_get(url, *, params=None, headers=None, timeout=None): + captured["url"] = url + captured["params"] = dict(params or {}) + captured["headers"] = dict(headers or {}) + captured["timeout"] = timeout + return _FakeResp() + + monkeypatch.setattr(nominatim.httpx, "get", _fake_get) + geocoder = nominatim.build_default_nominatim_geocoder(min_interval_seconds=0.0, max_retries=0) + res = geocoder("Keflavik, Iceland") + assert res is not None + assert captured["params"].get("accept-language") == "en" + assert captured["headers"].get("Accept-Language") == "en" + + +@pytest.mark.asyncio +async def test_geocode_verify_accepts_native_country_name_and_country_code(monkeypatch): + from app.services.location import workflow_tools + + cases = [ + ( + "Keflavik, Iceland", + "冰岛", + {"lat": "64.0005", "lon": "-22.5583", "address": {"town": "Keflavik", "country": "Ísland", "country_code": "is"}}, + "冰岛", + ), + ( + "Zurich, Switzerland", + "瑞士", + {"lat": "47.3769", "lon": "8.5417", "address": {"city": "Zürich", "country": "Schweiz/Suisse/Svizzera/Svizra", "country_code": "ch"}}, + "瑞士", + ), + ( + "Abu Dhabi, UAE", + "阿联酋", + {"lat": "24.4539", "lon": "54.3773", "address": {"city": "Abu Dhabi", "country": "الإمارات العربية المتحدة", "country_code": "ae"}}, + "阿联酋", + ), + ( + "Hong Kong", + "中国(香港)", + {"lat": "22.3193", "lon": "114.1694", "address": {"city": "Hong Kong", "country": "Hong Kong", "country_code": "cn"}}, + "中国(香港)", + ), + ] + + for place_query, expected_country, fake_payload, expected_canonical in cases: + monkeypatch.setattr(workflow_tools, "_agent_geocoder", lambda _q, p=fake_payload: p) + res, entry = await workflow_tools._geocode_verify_single(place_query, expected_country) + assert entry is not None, f"expected match for {place_query}, got {res}" + assert entry["country"] == expected_canonical + + monkeypatch.setattr( + workflow_tools, + "_agent_geocoder", + lambda _q: {"lat": "52.5200", "lon": "13.4050", "address": {"city": "Berlin", "country": "Germany", "country_code": "de"}}, + ) + res, entry = await workflow_tools._geocode_verify_single("Berlin, Germany", "冰岛") + assert entry is None + assert "Country mismatch" in str(res.get("reason")) + + +def test_interpret_geocode_result_uses_country_code_for_native_names(): + from app.services.location.resolvers.nominatim import interpret_geocode_result + + interpreted = interpret_geocode_result( + { + "lat": "64.0005", + "lon": "-22.5583", + "address": {"town": "Keflavik", "country": "Ísland", "country_code": "is"}, + }, + matched_fields=("city",), + context_country="冰岛", + ) + assert interpreted is not None + lat, lon, _addr, classification = interpreted + assert lat == pytest.approx(64.0005) + assert lon == pytest.approx(-22.5583) + assert classification == "city" + + +def test_sanitize_user_facing_reasoning_strips_evidence_ids_and_preserves_clean_text(): + from app.services.location.workflow_tools import sanitize_user_facing_reasoning + + assert ( + sanitize_user_facing_reasoning( + "E6 confirms DYEUS is IBM's system, while E1-E5 and E11–E14 list other sites (E3)." + ) + == "confirms DYEUS is IBM's system, while and list other sites." + ) + assert ( + sanitize_user_facing_reasoning("官方披露该集群采用多地分布式部署(E1、E2),无法单点落位。") + == "官方披露该集群采用多地分布式部署,无法单点落位。" + ) + assert ( + sanitize_user_facing_reasoning("NVIDIA H100 EC2 集群部署于美国俄亥俄州都柏林。") + == "NVIDIA H100 EC2 集群部署于美国俄亥俄州都柏林。" + ) + + +def test_upgrade_untouched_location_judge_prompts_preserves_custom_edits(): + import copy + from app.models.ai_workflow import AIWorkflow + from app.services.ai.workflow_registry import ( + BUILTIN_WORKFLOWS, + _PREV_LOC_JUDGE_PROMPTS, + _upgrade_untouched_location_judge_prompts, + ) + + spec = next(w for w in BUILTIN_WORKFLOWS if w["workflow_id"] == "location.resolve_unknown") + stock_graph = copy.deepcopy(spec["graph"]) + for node in stock_graph["nodes"]: + nid = node["id"] + if nid == "l2_judge_r1": + node["system_prompt"] = _PREV_LOC_JUDGE_PROMPTS["l2_judge_r1"] + elif nid == "l2_judge_r2": + node["system_prompt"] = "CUSTOM USER PROMPT MUST STAY" + + row = AIWorkflow(workflow_id="location.resolve_unknown", name="loc", published_graph=stock_graph) + changed = _upgrade_untouched_location_judge_prompts(row, spec) + assert changed is True + + nodes_by_id = {n["id"]: n for n in row.published_graph["nodes"]} + assert "严禁出现 E1" in nodes_by_id["l2_judge_r1"]["system_prompt"] + assert nodes_by_id["l2_judge_r2"]["system_prompt"] == "CUSTOM USER PROMPT MUST STAY" diff --git a/backend/tests/test_location_pipeline.py b/backend/tests/test_location_pipeline.py index 15d4e724..93c415a2 100644 --- a/backend/tests/test_location_pipeline.py +++ b/backend/tests/test_location_pipeline.py @@ -22,9 +22,6 @@ from app.services.location import ( ResolverOutput, SourceCoordinatesResolver, ) -from app.schemas.ai import SituationalAnalysisResponse -import app.services.location.llm_fallback as llm_fallback -from app.services.location.llm_fallback import collect_llm_location_fallback_candidate # ── Test fixtures ──────────────────────────────────────────────────── @@ -430,567 +427,3 @@ def test_pluggability_custom_resolver_works_without_changing_pipeline(): ) assert len(candidates) == 1 assert candidates[0].source == "peeringdb_stub" - - -# ── LLM fallback helper ───────────────────────────────────────────── - - -class _FakeAIProviderClient: - def __init__(self, content: str | list[str]): - self.contents = content if isinstance(content, list) else [content] - self.calls = 0 - - async def analyze(self, payload, request_id=None): - self.calls += 1 - content = self.contents[min(self.calls - 1, len(self.contents) - 1)] - return SituationalAnalysisResponse( - provider="test", - model="test-model", - content=content, - raw_response={}, - ) - - -@pytest.mark.asyncio -async def test_llm_location_fallback_returns_candidate_from_strict_json(): - client = _FakeAIProviderClient( - json.dumps( - { - "latitude": 45.764, - "longitude": 4.8357, - "precision": "city", - "confidence": 0.74, - "city": "Lyon", - "region": "Auvergne-Rhone-Alpes", - "country": "France", - "matched_location_name": "Lyon, France", - "evidence": ["operator and city point to Lyon"], - "reasoning_summary": "Best supported city-level match.", - } - ) - ) - - result = await collect_llm_location_fallback_candidate( - provider_client=client, - query=LocationQuery( - name="Mystery GPU Cluster", - city="Lyon", - country="France", - extra={"operator": "Mystery Operator"}, - ), - entity_type="compute_center", - attempted_queries=("Mystery Operator, Lyon, France",), - ) - - assert client.calls == 1 - assert result.failure_reason is None - assert result.attempted_queries == ["llm_factcheck:compute_center:Mystery GPU Cluster"] - candidate = result.candidates[0] - assert candidate.source == "llm_location_factcheck" - assert candidate.needs_confirmation is True - assert candidate.precision == "city" - assert candidate.city == "Lyon" - - -@pytest.mark.asyncio -async def test_llm_location_fallback_accepts_common_precision_aliases(): - client = _FakeAIProviderClient( - json.dumps( - { - "candidate": { - "latitude": 43.2389, - "longitude": 76.8897, - "precision": "city-level", - "confidence": "0.68", - "city": "Almaty", - "country": "Kazakhstan", - "matched_location_name": "Almaty, Kazakhstan", - "evidence": ["NITEC context points to Almaty"], - "reasoning_summary": "City-level fallback.", - } - } - ) - ) - - result = await collect_llm_location_fallback_candidate( - provider_client=client, - query=LocationQuery(name="Alem.Cloud", country="Kazakhstan"), - entity_type="compute_center", - ) - - assert result.failure_reason is None - assert result.candidates[0].precision == "city" - assert result.candidates[0].confidence >= 0.55 - - -@pytest.mark.asyncio -async def test_llm_location_fallback_accepts_lat_lng_aliases(): - client = _FakeAIProviderClient( - json.dumps( - { - "lat": 51.1694, - "lng": 71.4491, - "precision": "city", - "confidence": 0.62, - "city": "Astana", - "country": "Kazakhstan", - "matched_location_name": "Astana, Kazakhstan", - "evidence": [ - { - "source": "Official source", - "source_type": "official", - "entity_match": True, - "text": "Alem.Cloud is in Astana.", - } - ], - } - ) - ) - - result = await collect_llm_location_fallback_candidate( - provider_client=client, - query=LocationQuery(name="Alem.Cloud", country="Kazakhstan"), - entity_type="compute_center", - ) - - assert result.failure_reason is None - assert result.candidates[0].latitude == pytest.approx(51.1694) - assert result.candidates[0].longitude == pytest.approx(71.4491) - - -@pytest.mark.asyncio -async def test_llm_location_fallback_geocodes_city_when_coordinates_missing(monkeypatch): - monkeypatch.setattr( - llm_fallback, - "_geocode_llm_city", - lambda query: { - "lat": "51.1694", - "lon": "71.4491", - "display_name": "Astana, Kazakhstan", - "address": {"city": "Astana", "country": "Kazakhstan"}, - }, - ) - client = _FakeAIProviderClient( - json.dumps( - { - "precision": "city", - "confidence": 0.62, - "city": "Astana", - "country": "Kazakhstan", - "matched_location_name": "Astana, Kazakhstan", - "evidence": [ - { - "source": "Official source", - "source_type": "official", - "entity_match": True, - "text": "Alem.Cloud is in Astana.", - } - ], - } - ) - ) - - result = await collect_llm_location_fallback_candidate( - provider_client=client, - query=LocationQuery(name="Alem.Cloud", country="Kazakhstan"), - entity_type="compute_center", - ) - - assert result.failure_reason is None - candidate = result.candidates[0] - assert candidate.latitude == pytest.approx(51.1694) - assert candidate.longitude == pytest.approx(71.4491) - assert "Nominatim city fallback" in candidate.source_note - - -@pytest.mark.asyncio -async def test_llm_location_fallback_geocodes_matched_location_without_city(monkeypatch): - def _fake_geocode(query): - if "Falun" not in query: - return None - return { - "lat": "60.6065", - "lon": "15.6355", - "display_name": "Falun, Dalarna County, Sweden", - "address": {"city": "Falun", "state": "Dalarna County", "country": "Sweden"}, - } - - monkeypatch.setattr(llm_fallback, "_geocode_llm_city", _fake_geocode) - client = _FakeAIProviderClient( - json.dumps( - { - "precision": "city", - "confidence": 0.64, - "country": "Sweden", - "matched_location_name": "Falun, Sweden", - "evidence": [ - { - "source": "Credible public source", - "source_type": "news", - "entity_match": True, - "text": "DeepL Mercury supercomputer is located in Falun.", - } - ], - } - ) - ) - - result = await collect_llm_location_fallback_candidate( - provider_client=client, - query=LocationQuery(name="DeepL Mercury", country="Sweden"), - entity_type="compute_center", - ) - - assert result.failure_reason is None - candidate = result.candidates[0] - assert candidate.city == "Falun" - assert candidate.country == "瑞典" - assert candidate.latitude == pytest.approx(60.6065) - assert candidate.longitude == pytest.approx(15.6355) - - -@pytest.mark.asyncio -async def test_llm_location_fallback_repairs_non_json_answer(monkeypatch): - monkeypatch.setattr( - llm_fallback, - "_geocode_llm_city", - lambda query: { - "lat": "25.033", - "lon": "121.5654", - "display_name": "Taipei, Taiwan", - "address": {"city": "Taipei", "country": "Taiwan"}, - }, - ) - client = _FakeAIProviderClient( - [ - "TAIPEI-1 appears to be located in Taipei, Taiwan, based on NVIDIA context.", - json.dumps( - { - "latitude": None, - "longitude": None, - "precision": "city", - "confidence": 0.62, - "city": "Taipei", - "country": "Taiwan", - "matched_location_name": "Taipei, Taiwan", - "evidence": [ - { - "source": "NVIDIA context", - "source_type": "generic", - "entity_match": True, - "text": "TAIPEI-1 appears to be located in Taipei.", - } - ], - "reasoning_summary": "City-level location extracted from prose.", - } - ), - ] - ) - - result = await collect_llm_location_fallback_candidate( - provider_client=client, - query=LocationQuery(name="TAIPEI-1", country="Taiwan"), - entity_type="compute_center", - ) - - assert client.calls == 2 - assert result.failure_reason is None - assert result.candidates[0].city == "Taipei" - assert result.candidates[0].source == "llm_location_factcheck" - - -@pytest.mark.asyncio -async def test_llm_location_fallback_rejects_city_from_name_without_location_evidence(monkeypatch): - monkeypatch.setattr( - llm_fallback, - "_geocode_llm_city", - lambda query: { - "lat": "25.033", - "lon": "121.5654", - "display_name": "Taipei, Taiwan", - "address": {"city": "Taipei", "country": "Taiwan"}, - }, - ) - client = _FakeAIProviderClient( - json.dumps( - { - "latitude": None, - "longitude": None, - "precision": "city", - "confidence": 0.43, - "city": "Taipei", - "country": "Taiwan", - "matched_location_name": "Taipei, Taiwan", - "evidence": [ - { - "source": "NVIDIA context", - "source_type": "generic", - "entity_match": True, - "text": "TAIPEI-1 points to Taipei city-level placement.", - } - ], - "reasoning_summary": "Weak city-level evidence, but the entity name and geography align.", - } - ) - ) - - result = await collect_llm_location_fallback_candidate( - provider_client=client, - query=LocationQuery(name="TAIPEI-1", country="Taiwan"), - entity_type="compute_center", - ) - - assert result.candidates == [] - assert result.failure_reason is not None - assert "below minimum" in result.failure_reason - - -@pytest.mark.asyncio -async def test_llm_location_fallback_accepts_explicit_facility_location_for_name_city_conflict(monkeypatch): - monkeypatch.setattr( - llm_fallback, - "_geocode_llm_city", - lambda query: { - "lat": "22.6048", - "lon": "120.3000", - "display_name": "Kaohsiung, Taiwan", - "address": {"city": "Kaohsiung", "country": "Taiwan"}, - }, - ) - client = _FakeAIProviderClient( - json.dumps( - { - "latitude": None, - "longitude": None, - "precision": "city", - "confidence": 0.72, - "city": "Kaohsiung", - "country": "Taiwan", - "matched_location_name": "Kaohsiung, Taiwan", - "evidence": [ - { - "source": "Taiwan News", - "source_type": "news", - "entity_match": True, - "text": "Nvidia's first AI supercomputer center, Taipei-1, is located in Kaohsiung.", - } - ], - "reasoning_summary": "Explicit facility location evidence overrides the city-like system name.", - } - ) - ) - - result = await collect_llm_location_fallback_candidate( - provider_client=client, - query=LocationQuery(name="TAIPEI-1", country="Taiwan"), - entity_type="compute_center", - ) - - assert result.failure_reason is None - candidate = result.candidates[0] - assert candidate.city == "Kaohsiung" - assert candidate.confidence >= 0.55 - - -@pytest.mark.asyncio -async def test_llm_location_fallback_rejects_compute_center_city_from_entity_name_when_llm_unparseable(monkeypatch): - def _fake_geocode(query): - if query != "Taipei, 中国(台湾)": - return None - return { - "lat": "25.033", - "lon": "121.5654", - "display_name": "Taipei, Taiwan", - "address": {"city": "Taipei", "country": "Taiwan"}, - } - - monkeypatch.setattr(llm_fallback, "_geocode_llm_city", _fake_geocode) - client = _FakeAIProviderClient(["not a location answer", "still not json"]) - - result = await collect_llm_location_fallback_candidate( - provider_client=client, - query=LocationQuery(name="TAIPEI-1", country="中国(台湾)"), - entity_type="compute_center", - ) - - assert client.calls == 2 - assert result.candidates == [] - assert result.failure_reason is not None - assert "parseable city-level location fact" in result.failure_reason - - -@pytest.mark.asyncio -async def test_llm_location_fallback_extracts_city_from_non_json_when_repair_fails(monkeypatch): - monkeypatch.setattr( - llm_fallback, - "_geocode_llm_city", - lambda query: { - "lat": "60.6065", - "lon": "15.6355", - "display_name": "Falun, Sweden", - "address": {"city": "Falun", "country": "Sweden"}, - }, - ) - client = _FakeAIProviderClient( - [ - "DeepL Mercury 超級電腦位於瑞典的 法倫 (Falun)。", - "still not json", - ] - ) - - result = await collect_llm_location_fallback_candidate( - provider_client=client, - query=LocationQuery(name="DeepL Mercury", country="Sweden"), - entity_type="compute_center", - ) - - assert client.calls == 2 - assert result.failure_reason is None - assert result.candidates[0].city == "Falun" - assert result.candidates[0].needs_confirmation is True - - -@pytest.mark.asyncio -async def test_llm_location_fallback_combines_model_score_with_evidence_score(): - client = _FakeAIProviderClient( - json.dumps( - { - "latitude": 51.1694, - "longitude": 71.4491, - "precision": "city", - "confidence": 0.38, - "city": "Astana", - "country": "Kazakhstan", - "matched_location_name": "Astana, Kazakhstan", - "evidence": [ - { - "source": "Kazakhstan National Supercomputing Center", - "url": "https://example.test/alem-cloud", - "source_type": "official", - "entity_match": True, - "text": "Alem.Cloud is located in Astana.", - } - ], - "reasoning_summary": "Evidence supports city-level location but not exact facility coordinates.", - } - ) - ) - - result = await collect_llm_location_fallback_candidate( - provider_client=client, - query=LocationQuery(name="Alem.Cloud", country="Kazakhstan"), - entity_type="compute_center", - ) - - assert result.failure_reason is None - candidate = result.candidates[0] - assert candidate.city == "Astana" - assert candidate.confidence >= 0.55 - assert candidate.suggested_registry_entry["llm_model_confidence"] == pytest.approx(0.38) - assert candidate.suggested_registry_entry["llm_combined_confidence"] == pytest.approx( - candidate.confidence - ) - - -@pytest.mark.asyncio -async def test_llm_location_fallback_rejects_low_combined_score(): - result = await collect_llm_location_fallback_candidate( - provider_client=_FakeAIProviderClient( - json.dumps( - { - "latitude": 51.1694, - "longitude": 71.4491, - "precision": "city", - "confidence": 0.38, - "city": "Astana", - "country": "Kazakhstan", - "matched_location_name": "Astana, Kazakhstan", - "evidence": ["some page mentions Kazakhstan"], - "reasoning_summary": "Weak and ambiguous city evidence.", - "ambiguity": "weak city evidence", - } - ) - ), - query=LocationQuery(name="Alem.Cloud", country="Kazakhstan"), - entity_type="compute_center", - ) - - assert result.candidates == [] - assert "combined evidence score" in result.failure_reason - assert "below minimum 0.55" in result.failure_reason - - -@pytest.mark.asyncio -async def test_llm_location_fallback_rejects_explicit_conflicts(): - result = await collect_llm_location_fallback_candidate( - provider_client=_FakeAIProviderClient( - json.dumps( - { - "latitude": 25.033, - "longitude": 121.5654, - "precision": "city", - "confidence": 0.70, - "city": "Taipei", - "country": "Taiwan", - "matched_location_name": "Taipei, Taiwan", - "evidence": [ - { - "source": "Conflicting source", - "source_type": "generic", - "entity_match": True, - "has_conflict": True, - "text": "One source says Taipei, another contradicts it.", - } - ], - "reasoning_summary": "Conflicting evidence prevents confirmation.", - } - ) - ), - query=LocationQuery(name="TAIPEI-1", country="Taiwan"), - entity_type="compute_center", - ) - - assert result.candidates == [] - assert "conflict=" in result.failure_reason - - -@pytest.mark.asyncio -@pytest.mark.parametrize( - "content", - [ - "not json", - json.dumps({"latitude": 0, "longitude": 0, "precision": "city", "confidence": 0.9}), - json.dumps({"latitude": 45, "longitude": 4, "precision": "country", "confidence": 0.9}), - json.dumps({"latitude": 45, "longitude": 4, "precision": "city", "confidence": 0.2}), - ], -) -async def test_llm_location_fallback_rejects_unsafe_outputs(content): - result = await collect_llm_location_fallback_candidate( - provider_client=_FakeAIProviderClient(content), - query=LocationQuery(name="Unsafe", country="France"), - entity_type="compute_center", - ) - - assert result.candidates == [] - assert result.failure_reason - assert result.attempted_queries == ["llm_factcheck:compute_center:Unsafe"] - - -@pytest.mark.asyncio -async def test_llm_location_fallback_failure_explains_rejection_reason(): - result = await collect_llm_location_fallback_candidate( - provider_client=_FakeAIProviderClient( - json.dumps({ - "latitude": 45, - "longitude": 4, - "precision": "region", - "confidence": 0.9, - }) - ), - query=LocationQuery(name="Unsafe", country="France"), - entity_type="compute_center", - ) - - assert result.candidates == [] - assert "precision" in result.failure_reason - assert "region" in result.failure_reason diff --git a/backend/tests/test_provider_protocols.py b/backend/tests/test_provider_protocols.py index 23ed5a91..1374876e 100644 --- a/backend/tests/test_provider_protocols.py +++ b/backend/tests/test_provider_protocols.py @@ -442,3 +442,120 @@ async def test_protocol_tools_structured_output_and_json_context(monkeypatch): assert captured_anth[0]["messages"][2]["content"][0]["type"] == "tool_result" assert anth_resp.tool_calls[0].id == "tu_1" assert anth_resp.tool_calls[0].arguments == {"query": "Oak Ridge"} + + +@pytest.mark.asyncio +async def test_anthropic_thinking_tool_choice_downgrade_dedupe_and_citations(monkeypatch): + service = ProviderService( + { + "provider": "minimax", + "provider_api": "anthropic-messages", + "base_url": "https://api.minimaxi.com/anthropic", + "api_key": "test-key", + "model": "MiniMax-M3.1-Flash", + } + ) + captured = [] + + async def fake_post(**kwargs): + captured.append(kwargs["request_body"]) + return { + "stop_reason": "tool_use", + "content": [ + {"type": "thinking", "thinking": "check host", "signature": "sig_abc"}, + { + "type": "web_search_tool_result", + "content": [{"type": "web_search_result", "url": "https://example.com/search-hit"}], + }, + { + "type": "text", + "text": "Found evidence", + "citations": [{"type": "web_search_result_location", "url": "https://example.com/cited"}], + }, + {"type": "tool_use", "id": "tu_2", "name": "submit_location_result", "input": {"status": "located"}}, + ], + } + + monkeypatch.setattr(service, "_post", fake_post) + tools_spec = [ + {"name": "web_search", "description": "custom search", "parameters": {"type": "object", "properties": {}}}, + {"name": "submit_location_result", "description": "submit", "parameters": {"type": "object", "properties": {}}}, + ] + req = SituationalAnalysisRequest( + title="Location agent step 1", + objective="locate", + tools=tools_spec, + tool_choice={"type": "function", "name": "submit_location_result"}, + native_web_search=True, + messages=[ + {"role": "user", "content": "Target context JSON"}, + { + "role": "assistant", + "content": "", + "thinking_blocks": [{"type": "thinking", "thinking": "prior thought", "signature": "sig_0"}], + "tool_calls": [{"id": "tu_0", "name": "web_search", "arguments": {"query": "ISEG2"}}], + }, + {"role": "tool", "tool_call_id": "tu_0", "content": "{}"}, + ], + ) + resp = await service.analyze(req) + body = captured[0] + # Adaptive thinking active -> forced tool_choice downgraded to auto + assert body["tool_choice"] == {"type": "auto"} + # Duplicate custom web_search deduplicated when native_web_search=True + web_search_tools = [t for t in body["tools"] if t.get("name") == "web_search"] + assert len(web_search_tools) == 1 + assert web_search_tools[0]["type"] == "web_search_20250305" + # Assistant thinking_blocks preserved ahead of tool_use + assert body["messages"][1]["content"][0] == {"type": "thinking", "thinking": "prior thought", "signature": "sig_0"} + assert body["messages"][1]["content"][1]["type"] == "tool_use" + # Citations extracted + assert resp.citation_urls == ["https://example.com/search-hit", "https://example.com/cited"] + + +@pytest.mark.asyncio +async def test_responses_tool_loop_turn1_consistency_and_citations(monkeypatch): + service = ProviderService( + { + "provider": "openai", + "provider_api": "openai-responses", + "base_url": "https://api.openai.test/v1", + "api_key": "test-key", + "model": "gpt-5.6-luna", + } + ) + captured = [] + + async def fake_post(**kwargs): + captured.append(kwargs["request_body"]) + return { + "status": "completed", + "output": [ + { + "type": "web_search_call", + "action": {"sources": [{"url": "https://example.com/resp-src"}]}, + }, + { + "type": "message", + "content": [ + { + "type": "output_text", + "text": "Located", + "annotations": [{"type": "url_citation", "url": "https://example.com/resp-ann"}], + } + ], + }, + ], + } + + monkeypatch.setattr(service, "_post", fake_post) + tools_spec = [{"name": "geocode_verify", "description": "geo", "parameters": {"type": "object", "properties": {}}}] + req_turn1 = SituationalAnalysisRequest( + title="step 1", + objective="locate", + tools=tools_spec, + messages=[{"role": "user", "content": "RAW_USER_PROMPT"}], + ) + resp = await service.analyze(req_turn1) + assert captured[0]["input"] == [{"role": "user", "content": "RAW_USER_PROMPT"}] + assert resp.citation_urls == ["https://example.com/resp-src", "https://example.com/resp-ann"] diff --git a/backend/tests/test_situational_awareness.py b/backend/tests/test_situational_awareness.py index 807e803e..cfe7cc4e 100644 --- a/backend/tests/test_situational_awareness.py +++ b/backend/tests/test_situational_awareness.py @@ -377,10 +377,15 @@ async def test_sqlite_ledger_caching_presentations_copilot_and_report_export(): rev_res = await client.post( f"/situational-awareness/candidates/{cand_id}/review", - json={"decision": "approved"}, + json={ + "decision": "approved", + "reason_code": "newer_authoritative_report", + "reason": "Verified against official CAICT 2025 blue book figures.", + }, ) assert rev_res.status_code == 200 assert rev_res.json()["status"] == "approved" + assert rev_res.json()["review_reason_code"] == "newer_authoritative_report" raw_session.close() engine.dispose() diff --git a/backend/tests/test_visualization_compute_centers.py b/backend/tests/test_visualization_compute_centers.py index 52361db8..33b32b38 100644 --- a/backend/tests/test_visualization_compute_centers.py +++ b/backend/tests/test_visualization_compute_centers.py @@ -767,16 +767,17 @@ async def test_collect_compute_center_location_skips_llm_when_candidates_exist(m country="France", ) monkeypatch.setattr(visualization_api, "_load_compute_center_record", AsyncMock(return_value=None)) - monkeypatch.setattr( - visualization_api, - "collect_location_candidates", - lambda **_kwargs: ([candidate], ["Lyon, France"]), - ) - async def _explode(**_kwargs): - raise AssertionError("LLM fallback should not run when a normal candidate exists") + async def _run_wf(**_kwargs): + return { + "candidates": [candidate], + "attempted_queries": ["Lyon, France"], + "workflow_run_id": "run_local_hit", + "terminal_status": None, + "failure_reason": None, + } - monkeypatch.setattr(visualization_api, "collect_llm_location_fallback_candidate", _explode) + monkeypatch.setattr(visualization_api, "run_location_workflow", _run_wf) response = await visualization_api.collect_compute_center_location( "epoch_ai_gpu-test", @@ -791,56 +792,43 @@ async def test_collect_compute_center_location_skips_llm_when_candidates_exist(m assert response["success"] is True assert response["best_candidate"]["source"] == "nominatim_online_geocode" + assert response["workflow_run_id"] == "run_local_hit" @pytest.mark.asyncio async def test_collect_compute_center_location_uses_llm_when_candidates_empty(monkeypatch): - monkeypatch.setattr(visualization_api, "_compute_center_location_web_search_capability", AsyncMock(return_value={"enabled": True})) llm_candidate = compute_center_locations.LocationCandidate( latitude=45.764, longitude=4.8357, display_name="Lyon, France", precision="city", confidence=0.74, - query="llm_factcheck:compute_center:Mystery Cluster", + query="location_workflow:compute_center:Mystery Cluster", source="llm_location_factcheck", - source_note="LLM location factcheck fallback", + source_note="Controlled workflow factcheck", matched_fields=("name",), needs_confirmation=True, city="Lyon", country="France", ) monkeypatch.setattr(visualization_api, "_load_compute_center_record", AsyncMock(return_value=None)) - monkeypatch.setattr( - visualization_api, - "collect_location_candidates", - lambda **_kwargs: ([], ["Mystery Cluster, France"]), - ) - from app.services.location.llm_fallback import LocationLLMFallbackResult, LocationSearchEvidenceResult - - async def _search_evidence(**_kwargs): - return LocationSearchEvidenceResult( - evidence=[ - { - "title": "Mystery Cluster source", - "url": "https://example.test/mystery", - "snippet": "Mystery Cluster is in Lyon.", - } + async def _run_wf(**kwargs): + ctx = kwargs.get("earth_context") or {} + assert ctx["name"] == "Mystery Cluster" + assert ctx["country"] == "France" + return { + "candidates": [llm_candidate], + "attempted_queries": [ + "Mystery Cluster, France", + "web_search:Mystery Cluster France physical location", ], - attempted_queries=["web_search:compute_center:Mystery Cluster France physical location"], - ) + "workflow_run_id": "run_mystery_1", + "terminal_status": None, + "failure_reason": None, + } - async def _fallback(**_kwargs): - return LocationLLMFallbackResult( - candidates=[llm_candidate], - attempted_queries=["llm_factcheck:compute_center:Mystery Cluster"], - ) - - monkeypatch.setattr(visualization_api, "get_ai_provider_client", AsyncMock(return_value=object())) - monkeypatch.setattr(visualization_api, "get_web_search_client", AsyncMock(return_value=object())) - monkeypatch.setattr(visualization_api, "collect_location_search_evidence", _search_evidence) - monkeypatch.setattr(visualization_api, "collect_llm_location_fallback_candidate", _fallback) + monkeypatch.setattr(visualization_api, "run_location_workflow", _run_wf) response = await visualization_api.collect_compute_center_location( "epoch_ai_gpu-test", @@ -855,10 +843,10 @@ async def test_collect_compute_center_location_uses_llm_when_candidates_empty(mo assert response["success"] is True assert response["best_candidate"]["source"] == "llm_location_factcheck" assert response["best_candidate"]["needs_confirmation"] is True + assert response["workflow_run_id"] == "run_mystery_1" assert response["attempted_queries"] == [ "Mystery Cluster, France", - "web_search:compute_center:Mystery Cluster France physical location", - "llm_factcheck:compute_center:Mystery Cluster", + "web_search:Mystery Cluster France physical location", ] @@ -1195,10 +1183,23 @@ async def test_collect_location_endpoint_returns_candidates_for_known_record(mon @pytest.mark.asyncio async def test_collect_location_endpoint_returns_failure_reason(monkeypatch): - monkeypatch.setattr(visualization_api, "_compute_center_location_web_search_capability", AsyncMock(return_value={"enabled": True})) + from types import SimpleNamespace + from app.services.location import workflow_tools + monkeypatch.setattr(compute_center_locations, "_lookup_ror_organization", lambda _query: None) monkeypatch.setattr(compute_center_locations, "_geocode_online", lambda _query: None) + async def _empty_l1(_query): + return SimpleNamespace(candidates=(), attempted_queries=()) + + monkeypatch.setattr(workflow_tools, "lookup_wikidata_facility", _empty_l1) + monkeypatch.setattr(workflow_tools, "lookup_peeringdb_facility", _empty_l1) + monkeypatch.setattr("app.api.v1.settings.get_ai_provider_client", AsyncMock(return_value=None)) + monkeypatch.setattr( + "app.api.v1.settings.get_runtime_web_search_config", + AsyncMock(side_effect=RuntimeError("no db settings")), + ) + class _ScalarResult: def __init__(self, rows): self._rows = rows @@ -1472,3 +1473,261 @@ async def test_compute_center_location_write_endpoints_require_admin(): assert r4.status_code == 403 finally: app.dependency_overrides.clear() + + +@pytest.mark.asyncio +async def test_web_search_capability_allows_searxng_without_api_key(monkeypatch): + from app.services.ai_tools.schemas import WebSearchConfig, WebSearchProviderConfig + + monkeypatch.setattr( + visualization_api, + "get_runtime_web_search_config", + AsyncMock( + return_value=WebSearchConfig( + enabled=True, + default_provider="searxng", + provider="searxng", + providers={ + "searxng": WebSearchProviderConfig( + provider="searxng", + base_url="http://localhost:8080", + api_key="", + ) + }, + ) + ), + ) + cap = await visualization_api._compute_center_location_web_search_capability(AsyncMock()) + assert cap["enabled"] is True + assert cap["provider"] == "searxng" + + +@pytest.mark.asyncio +async def test_save_location_records_workflow_run_feedback(monkeypatch): + from app.services.ai import workflow_evolver + + target_record = _build_record( + record_id=88, + source="top500", + data_type="supercomputer", + name="ISEG2", + country="荷兰", + city="", + latitude=0.0, + longitude=0.0, + metadata={}, + ) + feedback_calls = [] + + async def _fake_feedback(_db, run_id, *, rating, note=None, actor=None): + feedback_calls.append((run_id, rating, note, actor)) + return {"run_id": run_id, "rating": rating} + + monkeypatch.setattr(workflow_evolver, "record_run_feedback", _fake_feedback) + + class _ScalarResult: + def __init__(self, rows): + self._rows = rows + + def scalars(self): + class _Scalars: + def __init__(self, rows): + self._rows = rows + + def first(self): + return self._rows[0] if self._rows else None + + def all(self): + return self._rows + + return _Scalars(self._rows) + + class _FakeSession: + def __init__(self): + self.saved = [] + + async def execute(self, _query): + if self.saved: + return _ScalarResult(self.saved) + return _ScalarResult([target_record]) + + async def scalar(self, _query): + return None + + def add(self, record): + self.saved.append(record) + + async def commit(self): + return None + + async def refresh(self, _record): + return None + + fake_session = _FakeSession() + + async def override_get_db(): + yield fake_session + + app.dependency_overrides[get_db] = override_get_db + app.dependency_overrides[get_current_user] = _override_admin_user + transport = ASGITransport(app=app) + try: + async with AsyncClient(transport=transport, base_url="http://test") as client: + resp = await client.post( + "/api/v1/visualization/compute-centers/top500-88/location", + json={ + "source": "top500", + "name": "ISEG2", + "latitude": 64.0025, + "longitude": -22.5594, + "precision": "city", + "confidence": 0.92, + "location_source": "llm_location_factcheck", + "country": "冰岛", + "workflow_run_id": "run_iseg2_test", + "feedback_rating": 1, + }, + ) + assert resp.status_code == 200 + assert feedback_calls == [ + ("run_iseg2_test", 1, "Adopted compute-center location for top500-88", "admin:test-admin") + ] + finally: + app.dependency_overrides.clear() + + +def test_terminal_compute_center_excluded_from_unresolved_and_counted_in_withheld(): + compute_center_locations.set_compute_center_location_cache({ + "epoch_ai_gpu:epoch_ibm_dyeus": { + "source": "epoch_ai_gpu", + "source_id": "epoch_ibm_dyeus", + "name": "IBM DYEUS", + "country": "United States", + "latitude": None, + "longitude": None, + "precision": "unknown", + "confidence": 0.0, + "location_source": "agent_terminal_undisclosed", + "source_note": "官方未披露物理部署城市", + "needs_confirmation": False, + "verification_status": "undisclosed", + }, + "epoch_ai_gpu:epoch_planned_site": { + "source": "epoch_ai_gpu", + "source_id": "epoch_planned_site", + "name": "Future AI Fab", + "country": "United States", + "latitude": None, + "longitude": None, + "precision": "unknown", + "confidence": 0.0, + "location_source": "agent_terminal_planned", + "source_note": "项目尚在规划中", + "needs_confirmation": False, + "verification_status": "planned", + }, + }) + rec_undisclosed = _build_record( + record_id=201, + source="epoch_ai_gpu", + data_type="gpu_cluster", + name="IBM DYEUS", + country="United States", + city="", + latitude=0.0, + longitude=0.0, + metadata={"value": "100", "unit": "TFlop/s"}, + ) + rec_undisclosed.source_id = "epoch_ibm_dyeus" + rec_planned = _build_record( + record_id=202, + source="epoch_ai_gpu", + data_type="gpu_cluster", + name="Future AI Fab", + country="United States", + city="", + latitude=0.0, + longitude=0.0, + metadata={"value": "200", "unit": "TFlop/s"}, + ) + rec_planned.source_id = "epoch_planned_site" + rec_unknown = _build_record( + record_id=203, + source="epoch_ai_gpu", + data_type="gpu_cluster", + name="Still Unresolved Site", + country="United States", + city="", + latitude=0.0, + longitude=0.0, + metadata={"value": "300", "unit": "TFlop/s"}, + ) + rec_unknown.source_id = "epoch_still_unknown" + + payload = convert_compute_centers_to_geojson([rec_undisclosed, rec_planned, rec_unknown]) + + assert [item["source_id"] for item in payload["unresolved"]] == ["epoch_still_unknown"] + assert payload["withheld_count"] == 2 + assert payload["withheld_by_status"] == {"undisclosed": 1, "planned": 1} + + +@pytest.mark.asyncio +async def test_collect_compute_center_location_handles_planned_and_cloud_only_as_terminal(monkeypatch): + from httpx import ASGITransport, AsyncClient + from app.api.v1 import visualization as vis_api + from app.core.security import get_current_user + from app.db.session import get_db + from app.main import app + + rec = _build_record( + record_id=210, + source="epoch_ai_gpu", + data_type="gpu_cluster", + name="Planned Cloud Cluster", + country="United States", + city="", + latitude=0.0, + longitude=0.0, + metadata={}, + ) + rec.source_id = "epoch_planned_cloud" + + async def _fake_load_record(_db, _source_id): + return rec + + monkeypatch.setattr(vis_api, "_load_compute_center_record", _fake_load_record) + + async def override_get_db(): + yield object() + + app.dependency_overrides[get_db] = override_get_db + app.dependency_overrides[get_current_user] = _override_admin_user + transport = ASGITransport(app=app) + try: + for status_val, reason in ( + ("planned", "项目仍在规划中,暂无具体机房地址"), + ("cloud_only", "纯云端服务形态,无单一物理部署园区"), + ): + async def _fake_run(**_kwargs): + return { + "candidates": [], + "terminal_status": status_val, + "failure_reason": reason, + "attempted_queries": [], + "workflow_run_id": f"run_{status_val}", + } + + monkeypatch.setattr(vis_api, "run_location_workflow", _fake_run) + async with AsyncClient(transport=transport, base_url="http://test") as client: + resp = await client.post( + "/api/v1/visualization/compute-centers/epoch_planned_cloud/collect-location", + json={"force": True}, + ) + assert resp.status_code == 200 + body = resp.json() + assert body["success"] is False + assert body["terminal_status"] == status_val + assert body["failure_reason"] == reason + assert body["workflow_run_id"] == f"run_{status_val}" + finally: + app.dependency_overrides.clear() diff --git a/backend/tests/test_web_search_tools.py b/backend/tests/test_web_search_tools.py index 37bdfd44..74a2a711 100644 --- a/backend/tests/test_web_search_tools.py +++ b/backend/tests/test_web_search_tools.py @@ -13,11 +13,6 @@ from app.api.v1.settings import ( from app.services.ai_tools.schemas import WebSearchConfig, WebSearchProviderConfig from app.services.ai_tools.web_search import WebSearchClient from app.services.credential_guides import generate_credential_guide -from app.services.location.llm_fallback import ( - collect_llm_location_fallback_candidate, - collect_location_search_evidence, -) -from app.services.location.models import LocationQuery @pytest.fixture(autouse=True) @@ -190,39 +185,6 @@ async def test_searxng_adapter_allows_empty_api_key(monkeypatch): assert results[0].metadata["engine"] == "duckduckgo" -@pytest.mark.asyncio -async def test_location_search_evidence_returns_failure_on_empty_results(monkeypatch): - class EmptySearchClient: - async def search(self, *args, **kwargs): - return [] - - result = await collect_location_search_evidence( - web_search_client=EmptySearchClient(), - query=LocationQuery(name="TAIPEI-1", country="Taiwan"), - entity_type="compute_center", - ) - - assert result.evidence == [] - assert "no usable" in result.failure_reason - - -@pytest.mark.asyncio -async def test_llm_location_fallback_skips_when_search_evidence_empty(): - class ExplodingAIClient: - async def analyze(self, *_args, **_kwargs): - raise AssertionError("LLM should not be called without evidence") - - result = await collect_llm_location_fallback_candidate( - provider_client=ExplodingAIClient(), - query=LocationQuery(name="TAIPEI-1", country="Taiwan"), - entity_type="compute_center", - search_evidence=[], - ) - - assert result.candidates == [] - assert "no WebSearch evidence" in result.failure_reason - - @pytest.mark.asyncio async def test_credential_guide_keeps_default_without_search_evidence(): class EmptySearchClient: diff --git a/client/package.json b/client/package.json index ca8c5624..f72e6d9e 100644 --- a/client/package.json +++ b/client/package.json @@ -1,6 +1,6 @@ { "name": "planet-client", - "version": "0.83.0", + "version": "0.84.0", "description": "Intelligent Planet Program - Native Electron Earth Viewer", "private": true, "packageManager": "bun@1", diff --git a/client/scripts/build-earth-bundle.mjs b/client/scripts/build-earth-bundle.mjs index 78ea7204..6f2eeec5 100644 --- a/client/scripts/build-earth-bundle.mjs +++ b/client/scripts/build-earth-bundle.mjs @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { createRequire } from 'node:module' -import { dirname, join } from 'node:path' +import { dirname, join, sep } from 'node:path' import { fileURLToPath } from 'node:url' import { compileEarthRuntime } from '../../frontend/scripts/compile-earth-runtime.mjs' @@ -60,6 +60,7 @@ for (const [name, asset] of assets) { const workerEntrypoints = [ join(earthSourceDir, 'js/satellite-position-worker.js'), join(earthSourceDir, 'js/surface-line-lod-worker.js'), + join(earthSourceDir, 'js/boundary-tile-worker.js'), ] const workerBuild = await Bun.build({ entrypoints: workerEntrypoints, @@ -73,10 +74,17 @@ if (!workerBuild.success) { throw new AggregateError(workerBuild.logs, 'Failed to bundle Earth Web Workers') } +// Earth boundary PMTiles artifacts are served by the backend API +// (/api/v1/earth/boundaries/...); legacy local builds must never ship in the +// desktop installer. +const legacyBoundaryArtifacts = join(earthSourceDir, 'data', 'boundaries') for (const folder of ['css', 'assets', 'data']) { const srcFolder = join(earthSourceDir, folder) if (existsSync(srcFolder)) { - cpSync(srcFolder, join(bundleEarthDir, folder), { recursive: true }) + cpSync(srcFolder, join(bundleEarthDir, folder), { + recursive: true, + filter: (src) => src !== legacyBoundaryArtifacts && !src.startsWith(`${legacyBoundaryArtifacts}${sep}`), + }) } } diff --git a/client/src/main/index.ts b/client/src/main/index.ts index 2eadec2a..97abc072 100644 --- a/client/src/main/index.ts +++ b/client/src/main/index.ts @@ -315,6 +315,7 @@ if (!singleInstanceLock) { installEarthSessionHandlers(session.defaultSession, { earthBundleRoot, getEarthOverlayRoot: () => hotUpdater.getOverlayRoot(), + boundaryCacheDir: path.join(app.getPath('userData'), 'earth-cache', 'boundaries'), getBackendUrl: () => configStore.get().backendUrl, getEarthAuthToken: (opts) => earthAuth.getToken(opts), }) @@ -494,12 +495,12 @@ if (!singleInstanceLock) { if (isHeadlessSmoke) { const smokeTimeout = setTimeout(() => { app.exit(1) - }, 22000) + }, 25000) mainWindow.webContents.once('did-finish-load', async () => { try { const earthStartup = await mainWindow!.webContents.executeJavaScript(`new Promise((resolve) => { - const deadline = performance.now() + 8000; + const deadline = performance.now() + 14000; const poll = () => { const ready = document.documentElement.dataset.earthStartupReady === '1'; const progress = document.documentElement.dataset.earthStartupProgress || ''; @@ -561,7 +562,7 @@ if (!singleInstanceLock) { window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); resolve({ mounted: Boolean(host && sr), - hasPresentedBy: copy.includes('PRESENTED BY'), + hasPresentedBy: copy.includes('PRESENTED BY') || copy.includes('联合研制'), hasPresenterZh: copy.includes('临空智能媒体研究院'), hasPresenterEn: copy.includes('Intelligent Media Institute'), emblemLoaded: Boolean(img && img.complete && img.naturalWidth > 0), diff --git a/client/src/main/protocol-core.ts b/client/src/main/protocol-core.ts index 297b6b65..3cdd2cba 100644 --- a/client/src/main/protocol-core.ts +++ b/client/src/main/protocol-core.ts @@ -101,7 +101,11 @@ export function parseByteRange(rangeHeader: string | null, totalSize: number): B return { kind: 'range', start, end } } -export function createStaticFileResponse(filePath: string, requestHeaders: Headers): Response { +export function createStaticFileResponse( + filePath: string, + requestHeaders: Headers, + options?: { method?: string; cacheControl?: string }, +): Response { let stat: fs.Stats try { stat = fs.statSync(filePath) @@ -112,6 +116,9 @@ export function createStaticFileResponse(filePath: string, requestHeaders: Heade return new Response('Not Found', { status: 404 }) } + const method = (options?.method || 'GET').toUpperCase() + const isHead = method === 'HEAD' + const cacheControl = options?.cacheControl || 'no-cache' const totalSize = stat.size const contentType = getMimeType(filePath) const rangeResult = parseByteRange(requestHeaders.get('range'), totalSize) @@ -129,39 +136,192 @@ export function createStaticFileResponse(filePath: string, requestHeaders: Heade if (rangeResult.kind === 'range') { const { start, end } = rangeResult const chunkSize = end - start + 1 - const stream = Readable.toWeb(fs.createReadStream(filePath, { start, end })) as ReadableStream - return new Response(stream, { + const body = isHead + ? null + : (Readable.toWeb(fs.createReadStream(filePath, { start, end })) as ReadableStream) + return new Response(body, { status: 206, headers: { 'Content-Type': contentType, 'Content-Length': String(chunkSize), 'Content-Range': `bytes ${start}-${end}/${totalSize}`, 'Accept-Ranges': 'bytes', - 'Cache-Control': 'no-cache', + 'Cache-Control': cacheControl, }, }) } - const stream = Readable.toWeb(fs.createReadStream(filePath)) as ReadableStream - return new Response(stream, { + const body = isHead ? null : (Readable.toWeb(fs.createReadStream(filePath)) as ReadableStream) + return new Response(body, { status: 200, headers: { 'Content-Type': contentType, 'Content-Length': String(totalSize), 'Accept-Ranges': 'bytes', - 'Cache-Control': 'no-cache', + 'Cache-Control': cacheControl, }, }) } +const BOUNDARY_FILES_PREFIX = '/api/v1/earth/boundaries/files/' +const BOUNDARY_ARTIFACT_NAME_RE = /^[A-Za-z0-9._-]+\.(pmtiles|json)$/ +const BOUNDARY_PREFIX_GROUPS = ['earth-boundaries.', 'hover-index.', 'hover-borders.', 'geo-labels.'] + +function resolveBoundaryCacheName(pathname: string): string | null { + if (!pathname.startsWith(BOUNDARY_FILES_PREFIX)) return null + const rawName = pathname.slice(BOUNDARY_FILES_PREFIX.length) + if (!rawName || rawName.includes('/')) return null + let decoded: string + try { + decoded = decodeURIComponent(rawName) + } catch { + return null + } + if (!BOUNDARY_ARTIFACT_NAME_RE.test(decoded) || decoded.includes('..')) { + return null + } + return decoded +} + +function cleanupOldBoundaryArtifacts(cacheDir: string, keepFileName: string): void { + const prefix = BOUNDARY_PREFIX_GROUPS.find((item) => keepFileName.startsWith(item)) + if (!prefix) return + try { + for (const entry of fs.readdirSync(cacheDir)) { + if (entry === keepFileName || entry === `${keepFileName}.tmp`) continue + if (entry.startsWith(prefix)) { + fs.rmSync(path.join(cacheDir, entry), { force: true }) + } + } + } catch { + // Cleanup failures never break serving the cached artifact. + } +} + export function createEarthProtocolHandler(options: { earthBundleRoot: string getEarthOverlayRoot?: () => string | null + boundaryCacheDir?: string getBackendUrl: () => string getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise fetchImpl?: typeof fetch }): (request: Request) => Promise { const fetchImpl = options.fetchImpl ?? fetch + const boundaryCacheDir = options.boundaryCacheDir + const inFlightBoundaryDownloads = new Map>() + + const scheduleBoundaryDownload = ( + fileName: string, + targetUrl: URL, + buildAuthHeaders: (forceRefresh?: boolean) => Promise, + ): void => { + if (!boundaryCacheDir || inFlightBoundaryDownloads.has(fileName)) return + + const job = (async () => { + try { + fs.mkdirSync(boundaryCacheDir, { recursive: true }) + const finalPath = path.join(boundaryCacheDir, fileName) + if (fs.existsSync(finalPath)) return + const tmpPath = `${finalPath}.tmp` + + let existingBytes = 0 + try { + const tmpStat = fs.statSync(tmpPath) + if (tmpStat.isFile() && tmpStat.size > 0) existingBytes = tmpStat.size + } catch { + existingBytes = 0 + } + + const makeReqHeaders = async (forceRefresh = false): Promise => { + const headers = await buildAuthHeaders(forceRefresh) + headers.delete('range') + headers.delete('accept-encoding') + if (existingBytes > 0) { + headers.set('range', `bytes=${existingBytes}-`) + } + return headers + } + + let resp = await fetchImpl(targetUrl.toString(), { method: 'GET', headers: await makeReqHeaders(false) }) + if (resp.status === 401 && options.getEarthAuthToken) { + try { + await resp.body?.cancel() + } catch { + // Ignore cancel error before retry. + } + resp = await fetchImpl(targetUrl.toString(), { method: 'GET', headers: await makeReqHeaders(true) }) + } + + if (resp.status === 416 && existingBytes > 0) { + try { + await resp.body?.cancel() + } catch { + // Ignore cancel error before restart. + } + fs.rmSync(tmpPath, { force: true }) + existingBytes = 0 + resp = await fetchImpl(targetUrl.toString(), { method: 'GET', headers: await makeReqHeaders(false) }) + } + + if ((resp.status !== 200 && resp.status !== 206) || !resp.body) { + try { + await resp.body?.cancel() + } catch { + // Ignore stream cleanup failure. + } + return + } + + const append = resp.status === 206 && existingBytes > 0 + let expectedTotalBytes: number | null = null + if (resp.status === 206) { + const contentRange = resp.headers.get('content-range') || '' + const match = /^bytes\s+\d+-\d+\/(\d+)$/i.exec(contentRange.trim()) + if (match) expectedTotalBytes = Number(match[1]) + } else { + const lenHeader = Number(resp.headers.get('content-length') || 0) + if (Number.isFinite(lenHeader) && lenHeader > 0) expectedTotalBytes = lenHeader + } + + const writer = fs.createWriteStream(tmpPath, { flags: append ? 'a' : 'w' }) + let writtenBytes = append ? existingBytes : 0 + const reader = resp.body.getReader() + try { + while (true) { + const { done, value } = await reader.read() + if (done) break + if (!value || value.byteLength === 0) continue + writtenBytes += value.byteLength + if (!writer.write(value)) { + await new Promise((resolve, reject) => { + writer.once('drain', resolve) + writer.once('error', reject) + }) + } + } + await new Promise((resolve, reject) => { + writer.end(() => resolve()) + writer.once('error', reject) + }) + } catch (err) { + writer.destroy() + throw err + } + + if (expectedTotalBytes !== null && writtenBytes !== expectedTotalBytes) { + return + } + fs.renameSync(tmpPath, finalPath) + cleanupOldBoundaryArtifacts(boundaryCacheDir, fileName) + } catch { + // Background cache write errors are non-fatal; next attempt resumes or refetches. + } + })().finally(() => { + inFlightBoundaryDownloads.delete(fileName) + }) + + inFlightBoundaryDownloads.set(fileName, job) + } return async (request: Request): Promise => { const parsedUrl = new URL(request.url) @@ -192,6 +352,26 @@ export function createEarthProtocolHandler(options: { } const method = request.method.toUpperCase() + const boundaryFileName = + boundaryCacheDir && (method === 'GET' || method === 'HEAD') + ? resolveBoundaryCacheName(parsedUrl.pathname) + : null + if (boundaryFileName && boundaryCacheDir) { + const cachedFilePath = path.join(boundaryCacheDir, boundaryFileName) + try { + if (fs.statSync(cachedFilePath).isFile()) { + return createStaticFileResponse(cachedFilePath, request.headers, { + method, + cacheControl: 'public, max-age=31536000, immutable', + }) + } + } catch { + // Cache miss: proxy upstream immediately while populating disk cache in background. + } + if (method === 'GET') { + scheduleBoundaryDownload(boundaryFileName, targetUrl, buildForwardHeaders) + } + } const hasBody = method !== 'GET' && method !== 'HEAD' try { const makeInit = (headers: Headers): RequestInit & { duplex?: 'half' } => { diff --git a/client/src/main/protocol.ts b/client/src/main/protocol.ts index da5e9d2c..bd21be0b 100644 --- a/client/src/main/protocol.ts +++ b/client/src/main/protocol.ts @@ -30,6 +30,7 @@ export function installEarthSessionHandlers( options: { earthBundleRoot: string getEarthOverlayRoot?: () => string | null + boundaryCacheDir?: string getBackendUrl: () => string getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise }, @@ -37,6 +38,7 @@ export function installEarthSessionHandlers( const handler = createEarthProtocolHandler({ earthBundleRoot: options.earthBundleRoot, getEarthOverlayRoot: options.getEarthOverlayRoot, + boundaryCacheDir: options.boundaryCacheDir, getBackendUrl: options.getBackendUrl, getEarthAuthToken: options.getEarthAuthToken, fetchImpl: (input, init) => net.fetch(input as string, init), diff --git a/client/tests/protocol.test.ts b/client/tests/protocol.test.ts index 635315af..9ee173e4 100644 --- a/client/tests/protocol.test.ts +++ b/client/tests/protocol.test.ts @@ -146,6 +146,79 @@ describe('protocol-core static and range handling', () => { ), ).rejects.toThrow() }) + + test('caches boundary artifacts to disk, cleans stale versions, and serves local 206/HEAD', async () => { + const fs = require('node:fs') + const boundaryCacheDir = path.join(tempRoot, 'boundary-cache') + fs.mkdirSync(boundaryCacheDir, { recursive: true }) + const staleFile = path.join(boundaryCacheDir, 'earth-boundaries.oldver.pmtiles') + writeFileSync(staleFile, 'stale-data', 'utf8') + + const payload = 'PMTiles-Mock-Archive-Payload-0123456789' + const upstreamCalls: Array<{ url: string; range: string | null }> = [] + const handler = createEarthProtocolHandler({ + earthBundleRoot: bundleRoot, + boundaryCacheDir, + getBackendUrl: () => 'http://127.0.0.1:8000', + fetchImpl: (async (input: RequestInfo | URL, init?: RequestInit) => { + const headers = new Headers(init?.headers) + const range = headers.get('range') + upstreamCalls.push({ url: String(input), range }) + if (range && /^bytes=(\d+)-(\d*)$/.test(range)) { + const match = /^bytes=(\d+)-(\d*)$/.exec(range)! + const start = Number(match[1]) + const end = match[2] ? Math.min(Number(match[2]), payload.length - 1) : payload.length - 1 + const slice = payload.slice(start, end + 1) + return new Response(slice, { + status: 206, + headers: { + 'Content-Range': `bytes ${start}-${end}/${payload.length}`, + 'Content-Length': String(slice.length), + Accept: 'bytes', + }, + }) + } + return new Response(payload, { + status: 200, + headers: { 'Content-Length': String(payload.length) }, + }) + }) as typeof fetch, + }) + + // First Range request misses local disk cache -> proxies upstream AND caches full file in background. + const url = 'planet://earth/api/v1/earth/boundaries/files/earth-boundaries.newver.pmtiles' + const first = await handler(new Request(url, { headers: { Range: 'bytes=0-6' } })) + expect(first.status).toBe(206) + expect(await first.text()).toBe('PMTiles') + + const targetPath = path.join(boundaryCacheDir, 'earth-boundaries.newver.pmtiles') + for (let i = 0; i < 40 && !fs.existsSync(targetPath); i += 1) { + await new Promise((r) => setTimeout(r, 15)) + } + expect(fs.existsSync(targetPath)).toBe(true) + expect(fs.existsSync(staleFile)).toBe(false) + + // Subsequent Range and HEAD requests hit local disk cache with zero upstream calls. + const callsBeforeHit = upstreamCalls.length + const hitRange = await handler(new Request(url, { headers: { Range: 'bytes=8-11' } })) + expect(hitRange.status).toBe(206) + expect(hitRange.headers.get('Content-Range')).toBe(`bytes 8-11/${payload.length}`) + expect(hitRange.headers.get('Cache-Control')).toContain('immutable') + expect(await hitRange.text()).toBe('Mock') + + const hitHead = await handler(new Request(url, { method: 'HEAD' })) + expect(hitHead.status).toBe(200) + expect(hitHead.headers.get('Content-Length')).toBe(String(payload.length)) + expect(await hitHead.text()).toBe('') + expect(upstreamCalls.length).toBe(callsBeforeHit) + + // Path traversal or unexpected extensions are never read/written from local boundary cache. + const traversal = await handler( + new Request('planet://earth/api/v1/earth/boundaries/files/..%2Fsecret.pmtiles'), + ) + expect(traversal.status).toBe(200) + expect(upstreamCalls.length).toBe(callsBeforeHit + 1) + }) }) describe('external links and runtime config', () => { diff --git a/config/earth-boundary-sources.example.json b/config/earth-boundary-sources.example.json index cb27f603..92d24407 100644 --- a/config/earth-boundary-sources.example.json +++ b/config/earth-boundary-sources.example.json @@ -41,9 +41,19 @@ } }, "earth_coastline": { - "displayName": "Earth 海岸线源", + "displayName": "Earth 海岸线源(OSM)", "sourceKind": "coastline", - "endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_coastline.geojson", + "endpoint": "https://osmdata.openstreetmap.de/download/coastlines-split-4326.zip", + "method": "GET", + "headers": {}, + "auth_type": "none", + "license": "ODbL 1.0 © OpenStreetMap contributors", + "timeout": 1800 + }, + "earth_disputed_lines": { + "displayName": "Earth 争议线源", + "sourceKind": "disputed-lines", + "endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_admin_0_boundary_lines_disputed_areas.geojson", "method": "GET", "headers": {}, "auth_type": "none", @@ -73,9 +83,9 @@ } }, "earth_claim_lines": { - "displayName": "Earth 主张线源", + "displayName": "Earth 九段线源(Natural Earth 中国视角)", "sourceKind": "claim-lines", - "endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_admin_0_boundary_lines_disputed_areas.geojson", + "endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_admin_0_boundary_lines_maritime_indicator_chn.geojson", "method": "GET", "headers": {}, "auth_type": "none", @@ -103,10 +113,51 @@ } } } + }, + "earth_admin1_lines": { + "displayName": "Earth 省界/州界源", + "sourceKind": "admin1-lines", + "endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_admin_1_states_provinces_lines.geojson", + "method": "GET", + "headers": {}, + "auth_type": "none", + "license": "Natural Earth public domain", + "mapping_json": { + "source": { + "items_path": "$.features[*]" + }, + "fields": { + "source_id": { + "path": "$.properties.id", + "type": "string" + }, + "name": { + "path": "$.properties.name", + "type": "string" + }, + "geometry": { + "path": "$.geometry", + "type": "object" + }, + "properties": { + "path": "$.properties", + "type": "object" + } + } + } + }, + "earth_populated_places": { + "displayName": "Earth 城市标注源(Natural Earth)", + "sourceKind": "populated-places", + "endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_populated_places.geojson", + "method": "GET", + "headers": {}, + "auth_type": "none", + "license": "Natural Earth public domain" } }, "notes": [ "Earth can download these sources directly from the toolbar settings when no local source override exists.", - "If tippecanoe/pmtiles are unavailable, the backend generates a GeoJSON high-precision package so the feature remains usable." + "PMTiles builds require tippecanoe in PATH (bundled in the backend image; run scripts/harness/install-earth-boundary-tools.sh locally). Builds fail loudly when it is missing." ] } diff --git a/deploy/helm/planet/templates/backend.yaml b/deploy/helm/planet/templates/backend.yaml index 32ccec6c..6e2e2afb 100644 --- a/deploy/helm/planet/templates/backend.yaml +++ b/deploy/helm/planet/templates/backend.yaml @@ -59,6 +59,8 @@ spec: volumeMounts: - name: earth-brand-data mountPath: /app/backend/data/earth-brand + - name: earth-boundary-data + mountPath: /app/backend/data/earth-boundaries {{- if not .Values.worker.enabled }} - name: collector-cache mountPath: /root/.cache/planet/downloads @@ -73,6 +75,13 @@ spec: {{- else }} emptyDir: {} {{- end }} + - name: earth-boundary-data + {{- if .Values.backend.persistence.earthBoundaries.existingClaim }} + persistentVolumeClaim: + claimName: {{ .Values.backend.persistence.earthBoundaries.existingClaim | quote }} + {{- else }} + emptyDir: {} + {{- end }} {{- if not .Values.worker.enabled }} - name: collector-cache {{- if .Values.backend.persistence.collectorCache.existingClaim }} diff --git a/deploy/helm/planet/values.yaml b/deploy/helm/planet/values.yaml index 057c0992..89ef1ac1 100644 --- a/deploy/helm/planet/values.yaml +++ b/deploy/helm/planet/values.yaml @@ -57,6 +57,9 @@ backend: persistence: earthBrand: existingClaim: "" + # Earth boundary sources + PMTiles artifacts (built by the Earth "高精" rebuild). + earthBoundaries: + existingClaim: "" collectorCache: existingClaim: "" resources: diff --git a/docker-compose.deploy.yml b/docker-compose.deploy.yml index 7b4b228e..2baf3c65 100644 --- a/docker-compose.deploy.yml +++ b/docker-compose.deploy.yml @@ -139,6 +139,7 @@ services: - "8000" volumes: - earth_brand_data:/app/backend/data/earth-brand + - earth_boundary_data:/app/backend/data/earth-boundaries - client_updates_data:/app/backend/data/client-updates - collector_cache:/root/.cache/planet/downloads mem_limit: ${PLANET_BACKEND_MEM_LIMIT:-2g} @@ -213,6 +214,7 @@ volumes: postgres_data: redis_data: earth_brand_data: + earth_boundary_data: client_updates_data: collector_cache: diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 055da48a..194a2d81 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,27 @@ This project follows the repository versioning rule: - `improvement` -> `+0.0.1`(bugfix + 小功能混合) - `bugfix` -> `+0.0.1` +## [0.84.0] — 2026-12-04 + +Released: 2026-12-04 + +### Highlights + +- **算力台账修订、双时间轴回溯与只读血缘推导(Phase 1 M0–M4)**: 新增不可变版本台账 `compute_configuration_revisions`(迁移 `0007`)与 `publish_id` 乐观锁(消除 ABA 冲突)、系统发布时间轴 `as_of` / `publish_id` 与报告发表时间轴 `cutoff_at` 双轴叠加回放、逐国来源 `value_sources` 保护、候选提取去重与强制复核理由护栏、与 BGP 解耦的 `publish_id` 驱动算力修订演播及失败自动补播,以及地球算力卡片版本切换、参谋同版本绑定与公共脱敏血缘抽屉。 +- **全球实时云图、10m 全球风场与高清球面底图瓦片(`weather` / `geo` 双域)**: 上线多星红外/日间 GeoColor 合成云图与 DIS 光流插值(`earth_clouds.py`、`cloud-map.js`)、NOAA GFS 10m 全球风场动画流线(`earth_wind.py`、`wind-layer.js`)及 Sentinel-2 / VIIRS 视口 LOD 高清底图瓦片代理(`earth_tiles.py`、`spherical-tile-layer.js`),并在管理台新增 `/earth-content?section=cloud_map`、`basemap` 工作台与仪表盘/弹性表格增强。 +- **地球高精度中国 POV 边界 PMTiles 与 3D 城市分级标注**: 升级 `/api/v1/earth/boundaries/*` 分发版本化 `pmtiles`、`hover-index`、`hover-borders` 与 `geo-labels`,支持 Web Worker 离线解码(`z2`/`z4`/`z6`/`z8`)、IndexedDB 与 Electron 磁盘 `Range` 缓存、全周界无遮罩高亮,以及中英文自适应避让的 3D 分级城市标注(`geo-labels.js`)。 +- **数据台账与位置解析 DAG 统一**: 上线以地球图层为一级导航的数据台账 `/data`(`/api/v1/data-ledger/*`),并将未知算力/设施位置解析统一为 9 节点 `location.resolve_unknown` DAG 工作流(`workflow_tools.py` + `dag_executor.py`),移除旧 `agent_resolver.py` 与 `llm_fallback.py`。 +- **修复线上独立 Admin 镜像默认品牌与云图预览裂图**: 通过 Vite `@earth-builtin-asset/*` 插件在构建期将 5 张内置预览图打包至 `/assets/*.png` 并在预览渲染层做映射(`earthBuiltinAssets.ts`),保持 `/earth/assets/...` 持久化配置与桌面端离线契约及 `dist/earth` 隔离校验完全不变;同步完成近期文档/计划归档与代码清理。 + +### Added / Changed + +- Backend: `0007_add_compute_configuration_revisions.py`、`compute_configuration_revision.py`、`compute_lineage.py`、`compute_revision_diff.py`、`data_ledger.py`、`earth_clouds.py`、`earth_clouds_fx.py`、`earth_tiles.py`、`earth_wind.py`、`workflow_tools.py`、`earth_boundaries.py` +- Admin & Frontend: `earthBuiltinAssets.ts`、`EarthCloudMapSettings.tsx`、`EarthBasemapSettings.tsx`、`pages/data-ledger/*`、`ComputeComparisonSettings.tsx`、`vite.config.mts` +- Earth & Desktop Client: `boundary-tile-worker.js`、`boundary-tile-cache.js`、`geo-labels.js`、`cloud-map.js`、`wind-layer.js`、`spherical-tile-layer.js`、`client/src/main/protocol-core.ts`、`client/scripts/build-earth-bundle.mjs` +- Docs & Plans: 归档 `phase1-compute-revision-plan.md` 与 `earth-high-resolution-basemap-tiles-plan.md`,同步中英文技术文档与运维手册 + +--- + ## [0.83.0] — 2026-12-02 Released: 2026-12-02 diff --git a/docs/plans/README.md b/docs/plans/README.md index e9124455..837eb449 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -27,11 +27,13 @@ - [AI 参谋工作流可视化编排、客户端上下文与受控位置 Agent 方案](ai-advisor-workflow-and-location-agent-plan.md) - [Earth 地理资源、空间浮动卡片与性能实施计划](earth-spatial-presentation-and-geographic-assets-plan.md) - [算力与资源态势:展示、采集与 AI 迭代实施计划](compute-resource-intelligence-plan.md) +- [Planet 一期执行计划:一条算力数据修订如何走到地球上(已落地)](phase1-compute-revision-plan.md) - [控制台 i18n 接入计划](/home/ray/dev/linkong/planet/docs/plans/admin-console-i18n-plan.md) - [Earth Mobile Drawer UI Plan](/home/ray/dev/linkong/planet/docs/plans/earth-mobile-drawer-ui-plan.md) - [Earth Compute Center BGP Style Plan](/home/ray/dev/linkong/planet/docs/plans/earth-compute-center-bgp-style-plan.md) - [Earth Renderer Architecture Separation Plan](/home/ray/dev/linkong/planet/docs/plans/earth-renderer-architecture-separation-plan.md) -- [Earth 高精度国界静态瓦片计划](/home/ray/dev/linkong/planet/docs/plans/earth-high-precision-boundary-tiles-plan.md) +- [Earth 高精度国界静态瓦片计划(已落地)](/home/ray/dev/linkong/planet/docs/plans/earth-high-precision-boundary-tiles-plan.md) +- [Earth 高分辨率卫星底图瓦片计划(已落地)](earth-high-resolution-basemap-tiles-plan.md) - [Earth WebGL Instancing Satellites Plan](/home/ray/dev/linkong/planet/docs/plans/earth-webgl-instancing-satellites-plan.md) - [Earth Real Terrain Plan](/home/ray/dev/linkong/planet/docs/plans/earth-real-terrain-plan.md) - [Earth News Source Configuration And Collector Plan](/home/ray/dev/linkong/planet/docs/plans/earth-news-source-configuration-and-collector-plan.md) diff --git a/docs/plans/earth-high-precision-boundary-tiles-plan.md b/docs/plans/earth-high-precision-boundary-tiles-plan.md index 1de80317..ecb3361a 100644 --- a/docs/plans/earth-high-precision-boundary-tiles-plan.md +++ b/docs/plans/earth-high-precision-boundary-tiles-plan.md @@ -2,7 +2,9 @@ ## Status -Superseded status: +**Implemented & Verified (`pmtiles-mvt` Batch 1 + 3D Tiered City Labels Batch 2):** High-precision boundaries (`earth-boundaries..pmtiles`, `hover-index..json`, `hover-borders..json`) and China-POV 3D city labels (`geo-labels..json`, `planet-earth-geo-labels/v1`) are served through `/api/v1/earth/boundaries/*` (`manifest`, `GET`/`HEAD` `Range` immutable `/files/{name}` isolated on `rate_limit_tier="tile"`, `config`, `build`), decoded off-thread in `boundary-tile-worker.js` + `boundary-tile-decode.js` across 4 zoom tiers (`z2`/`z4`/`z6`/`z8`), cached via `earth-preload.js` + IndexedDB + Electron disk cache, rendered with parent-tile persistence, full-perimeter hover (zero fill mask), and collision-free `geo-labels.js` tier progression. + +Superseded historical note: This plan originally treated boundaries as collector-managed source records. The current implementation has moved country boundaries out of the datasource / collector lifecycle. Boundaries are now Earth static rendering assets managed by `Operations and Configuration -> Earth Content -> Boundary Precision` and `/api/v1/earth/boundaries/*`. The bundled low-precision GeoJSON is the default fallback, and high precision is an opt-in local PMTiles build. diff --git a/docs/plans/earth-high-resolution-basemap-tiles-plan.md b/docs/plans/earth-high-resolution-basemap-tiles-plan.md index f3a1350c..d552e1eb 100644 --- a/docs/plans/earth-high-resolution-basemap-tiles-plan.md +++ b/docs/plans/earth-high-resolution-basemap-tiles-plan.md @@ -1,5 +1,9 @@ # Earth High Resolution Basemap Tiles Plan +## Status + +**Implemented & Verified:** High-resolution spherical Earth basemap and HD regional cloud tiles are implemented across backend (`backend/app/services/earth_tiles.py`, `backend/app/services/collectors/earth_tiles.py`, `/api/v1/earth/basemap/*`, `/api/v1/earth/tiles/*` for `earth_imagery_sentinel2`, `earth_imagery_viirs_daily`, and `cloud_hd_tiles` under the `geo` / `weather` datasource domains), Admin (`frontend/src/admin/pages/EarthBasemapSettings.tsx` at `/earth-content?section=basemap`), and Earth (`frontend/public/earth/js/spherical-tile-layer.js`). The original planning notes below are preserved as design context. + ## Summary High-precision borders now expose a separate visual problem: the vector coastline and border data are more accurate than the current raster Earth texture. The next step is a high-resolution basemap tile layer that aligns visually with the high-precision coastline instead of replacing the globe with one huge static image. diff --git a/docs/plans/phase1-compute-revision-plan.md b/docs/plans/phase1-compute-revision-plan.md new file mode 100644 index 00000000..eb0489f0 --- /dev/null +++ b/docs/plans/phase1-compute-revision-plan.md @@ -0,0 +1,476 @@ +# Planet 一期执行计划:一条算力数据修订如何走到地球上 + +## 状态 + +**已落地实现并验收(M0–M4 全部完成,待随新版本归档发布):** +- **M0**:已采集真实 CAICT 算力数据修订样例并固化至 `backend/tests/fixtures/compute_revision_case.json`。 +- **M1**:新增不可变版本台账表 `compute_configuration_revisions`(迁移 `0007_add_compute_configuration_revisions.py`)、启动基线封存 `ensure_compute_revision_baseline`、`publish_id` 乐观锁(消除 ABA 冲突)、恢复默认新增 `action="reset"` 版本记录,以及 `as_of` / `publish_id` 系统发布时间轴回溯。 +- **M2**:实现候选提取去重(`dedupe_fingerprint`)、逐国旧值→新值→差值对比与统计期冲突识别、采纳/驳回强制理由代码与说明、逐国来源 `value_sources` 保护及导入草稿冲突二次确认。 +- **M3**:实现与 BGP 解耦的 `publish_id` 驱动算力修订演播(`compute-revision-notice`)及失败状态持久化、启动/定时/手动补播闭环。 +- **M4**:实现地球算力卡片与参谋工作台同一 `publish_id` 绑定、历史发布版本切换、只读血缘推导抽屉(`/api/v1/data-products/compute/lineage` 公共访问自动脱敏),以及中英文技术文档与回归单测(`test_compute_revisions.py`、`test_compute_m2_candidates_and_sources.py`、`test_compute_m3_presentations.py`、`test_compute_m4_lineage_and_copilot.py`)。 + +以下为原始执行设计文档,保留作为历史设计上下文。 + +> 本文件写给执行代理(Gemini Neon)。照本文件执行,遇到与代码现状不符的地方,以代码为准并在里程碑报告中说明。 +> 仓库路径:`/home/ray/dev/linkong/planet`(Windows 侧为 `\\wsl.localhost\Ubuntu\home\ray\dev\linkong\planet`)。 + +--- + +## 0. 执行前必读 + +### 0.1 先读这些文件(仓库规则要求) +1. `rules.md`(必载 `core` / `security` / `workflow`,涉及 Admin/Earth UI 时加载 `uiux`) +2. `AGENTS.md` +3. `CODEMAP.md`、`docs/HARNESS.md` +4. 文档改动前读 `docs/documentation-coverage-rules.md` + +开工前运行: +```bash +git status --short +scripts/harness/doctor.sh +``` +保留工作区里已有的用户改动,不要覆盖或回退。 + +### 0.2 硬性规则 +- 前端只用 Bun,禁止 npm / pnpm / yarn。 +- 本地前端开发用 Vite(`./planet.sh start` / `./planet.sh restart -f`),不要构建或运行静态 Nginx `planet_admin` 容器。 +- 后端用结构化日志(`get_logger` + `info_event` / `warning_event`),禁止 `print()`,禁止 `except Exception: pass` 吞异常。 +- 不要修改已存在的迁移文件(迁移运行器会校验文件 checksum,见 `backend/app/db/migrations.py`)。新迁移用下一个空闲编号(当前最新应为 `0006`,先 `ls backend/app/db/migration_steps/` 确认)。 +- 不要 `git commit` / `git push`,除非用户明确要求。 +- 不要新增外部数据源、不要占用数据源 ID(39 以后留给二期)。 +- 不要编造报告数据。M0 找不到真实修订案例时,停下来报告,不要自造数字。 + +### 0.3 一期目标(用户能看到的结果) +领导从地球上一个刚被修订的算力数字出发,能当场查到: +1. **哪一年、哪个口径变了**,旧值 → 新值,差多少个百分点,并明确标注是“历史数据修订”,不是“今天算力跃升”; +2. **依据**:哪份报告、哪一页、报告发表日期; +3. **谁确认的**:复核人、理由、发布时间(公开页面脱敏); +4. **切回发布前**:看到当时系统里的数字和结论。 + +### 0.4 本期明确不做(Non-goals) +- 不接飞机、GPS 干扰、灾害等任何新数据源。 +- 不建通用本体表 / `lineage_links` 关系表(关系一律读取时从现有数据推导,遵守 `backend/app/services/ai/entity_resolver.py` 第一行的“zero duplicate mirror tables”原则)。 +- 不做通用的 `/ai/workflows/{id}/evaluate` 接口。 +- 不做双人复核开关,不新增角色。现有角色只有 `viewer` / `admin` / `super_admin`(`backend/app/core/enums.py`)。 +- 不放开同一 `(metric, year)` 多条观测并存(`ComputeConfiguration.consistent_evidence` 的唯一性约束保持不变)。 +- 不改 `classify_snapshot_delta` 和 BGP 主动研判逻辑。 +- 不拆除 `compute-topic.js`,不改 Copilot 打开时关闭算力卡片的现有互斥(`main.js` 约 L4659)。 +- 不重构 Earth 渲染层。 + +### 0.5 两根时间轴(全期必须区分,命名不可混用) +| 名称 | 参数 | 含义 | 已有/新增 | +| --- | --- | --- | --- | +| 报告发表时间轴 | `time_basis="as_known_then"` + `cutoff_at` | 按报告 `published_at` / `report_year` 过滤事后报告 | 已有(`tool_registry.filter_compute_config_by_cutoff`) | +| 系统发布时间轴 | `as_of`(ISO 时间)或 `publish_id` | 取 `published_at <= as_of` 的那一版已发布台账 | **本期新增** | + +两者可以叠加:先按 `as_of` 取当时的台账版本,再按 `cutoff_at` 过滤报告。UI 文案:前者叫“报告发表截至”,后者叫“系统发布版本”。 + +--- + +## 1. 现状关键事实(已核对,执行时再确认一遍) + +| 位置 | 现状 | 本期要解决的问题 | +| --- | --- | --- | +| `backend/app/services/compute_configuration.py` | 配置存在 `SystemSetting(category="compute_comparison")`;`revision` 既是版本号又是乐观锁 token;恢复默认复用 `DEFAULT_REVISION`(默认文件哈希)并 `db.delete(record)` | A→B→A 后旧 token 重新生效(ABA),旧页面能静默覆盖;恢复默认后丢失历史 | +| `read_configuration()` | 唯一读入口,调用方:`compute_intelligence.py` 的 `/series` 与 `/configuration`、`tool_registry.query_compute_posture_tool` | 加 `as_of` / `publish_id` 支持只改这一处 | +| `backend/app/api/v1/compute_intelligence.py` L107–117 | 发布后调用 `process_compute_config_proactive_delta`,异常被 `except Exception: pass` 吞掉 | 演播失败无痕迹、不补播 | +| `backend/app/services/ai/proactive_pipeline.py` L290–356 | 算力演播只比较 3 个标量(`cn_total_share` 等),经 `classify_snapshot_delta` 判定;该函数与 BGP(L211)共用 | 2.0pp 阈值漏判小幅修订;`seen_fingerprints` 会把 B→A 恢复当成重复吞掉;改它会影响 BGP | +| `backend/app/schemas/compute_configuration.py` `ComputeObservation` | 一行一个 `source_id`,`values` 是多国字典 | 只修订中国时无法让美国保留原来源 | +| `frontend/src/admin/pages/compute-comparison-model.ts` L290–302 `applyApprovedCandidateToDraft` | 合并 `values` 并把整行 `source_id` 改成新报告 | 美国的值被错误地挂到新报告上 | +| `backend/app/models/situational_assessment.py` `ComputeEvidenceCandidate` | 只有 `status / proposed_payload / source_payload / reviewed_by / reviewed_at` | 没有逐国对比、理由、去重、发布关联 | +| `backend/app/api/v1/situational_awareness.py` `CandidateReviewRequest`(约 L192) | 只有 `decision` | 采纳/驳回没有理由 | +| `backend/app/services/ai/semantic_delta.py` `extract_compute_candidates_deterministic` | 正则只认 美国/中国/日本 + “份额 xx%”;每个指标出一条多国候选 | 真实报告可能需要扩展(由 M0 决定) | +| `backend/app/services/ai/workflow_runtime.py` 约 L2233 | 无 `frozen_series` 的旧记录返回 `incomplete_snapshot` | 复用该提示处理“基线之前”的回溯 | +| `stage_presentations` 表 | 已接入 `earth_data_change_events` outbox(`earth_layer_adapters.py`);前端 `stage-narrative-player.js` 有按 `(presentation_key, time_basis, revision)` 去重的队列和相机主权状态机 | 演播推送和去重复用它,不另建队列 | + +--- + +## 2. 里程碑总览 + +| 里程碑 | 内容 | 完成标志 | 是否需要用户确认后继续 | +| --- | --- | --- | --- | +| **M0** | 找到真实修订案例,做成测试数据 | 有带页码出处的真实“旧值→新值”案例 fixture | **是**(找不到就停) | +| **M1** | 版本表成为唯一来源;修 ABA;恢复默认改为插入新版本;`as_of` 回溯 | A→B→A 三个时点读到 A、B、A;旧 token 返回 409 | 否,报告后继续 | +| **M2** | 候选逐国对比、必填理由、去重;`value_sources` 逐国来源;导入逻辑修复 | 只修订中国时美国仍引用原报告 | 否 | +| **M3** | 演播由 `publish_id` 驱动、失败可补播、与 BGP 解耦 | 中断后补播一次;重复事件不重播;B→A 恢复会播 | 否 | +| **M4** | 卡片/参谋带同一 `publish_id`;版本切换;血缘抽屉;文档 | 端到端演示 9 条验收全部通过 | 交付 | + +每个里程碑结束输出一份简短报告(格式见第 8 节)。 + +--- + +## 3. M0:找到真实修订案例 + +### 3.1 任务 +1. 读 `backend/app/services/compute_history_defaults.json` 的 `sources` 与 `observations`,列出每份报告覆盖的年份与指标。 +2. 查找同一 `(metric, year)` 被后一份报告给出不同数值的真实案例。优先检查: + - CAICT《先进计算暨算力发展指数蓝皮书(2025年)》是否重新给出 2023 年全球份额、全球总规模或中国总规模,与 2024 年版(2023 年美 41% / 中 31%,全球 1397 EFlops,中国 435 EFlops)不同; + - CAICT 各年白皮书对前一年中国算力总规模(EFlops)的修订; + - Epoch AI 数据集对既有集群样本份额的修订。 + 可以使用网页搜索和抓取公开 PDF;记录 URL、页码 / 图表号、原文摘录。 +3. 判断该案例属于哪个 `metric`:`global_share` / `intelligent_share` / `absolute` / `frontier_cluster_share` / `chip_inflow_share`,以及是否涉及 `period_label` 或 `global_total` 变化。 +4. 用真实摘录测试 `extract_compute_candidates_deterministic` 能否提取。不能提取时,记录需要扩展的规则(例如 `absolute` 的“总规模 XXX EFlops”、全球总量),在 M2 实现,范围只限这个案例需要的写法。 + +### 3.2 产出 +- `backend/tests/fixtures/compute_revision_case.json`: + ```json + { + "case_id": "caict-2025-restates-2023-...", + "metric": "absolute", + "year": 2023, + "period_label": null, + "old": {"source_id": "caict-2024", "values": {"CN": 435}, "locator": "..."}, + "new": { + "source_id": "...", "title": "...", "url": "https://...", "publisher": "...", + "report_year": 2025, "published_at": "2026-03-06", + "locator": "正文 xx 页 图 x", + "excerpt": "原文摘录(不超过 5000 字)", + "values": {"CN": 0} + }, + "unchanged_codes": ["US"], + "notes": "说明为何判定为修订而非口径不同" + } + ``` +- M0 报告:案例出处、判断依据、抽取器是否需要扩展。 + +### 3.3 停止条件 +找不到真实修订案例时**停止**,向用户报告并给出选项: +- (a) 使用明确标注为“演练数据”的案例(演示时全程显示“演练”标签,不能当真实数据展示); +- (b) 换用其他指标或其他机构的报告; +- (c) 调整一期演示方式。 + +不要自行选择 (a)。 + +--- + +## 4. M1:版本表与时间回溯 + +### 4.1 数据模型 +新增模型 `ComputeConfigurationRevision`,放在 `backend/app/models/compute_configuration_revision.py`,并在 `backend/app/db/session.py`(或项目注册模型的位置)引入。 + +表 `compute_configuration_revisions`: + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `id` | Integer PK autoincrement | 单调递增,用于排序和演播 revision | +| `publish_id` | String(64) unique not null | 每次发布 / 恢复唯一;同时是乐观锁 token | +| `parent_publish_id` | String(64) nullable | 上一版 | +| `action` | String(16) | `baseline` / `publish` / `reset` | +| `content_fingerprint` | String(64) index | 配置内容的规范 JSON SHA-256,仅用于判断内容是否变化 | +| `is_default_content` | Boolean | 内容是否等于内置默认台账 | +| `config_payload` | JSON | 完整台账快照 | +| `diff_summary` | JSON list | 相对上一版的变化(格式见 4.3) | +| `source_candidate_ids` | JSON list[int] | 本次发布包含的已采纳候选 | +| `publish_note` | Text default "" | 发布说明 | +| `published_by_id` / `published_by_name` / `published_by_role` | int / String / String,nullable | 发布人 | +| `published_at` | DateTime(tz) index not null | 发布时间 | +| `presentation_status` | String(16) | `pending` / `delivered` / `failed` / `skipped` | +| `presentation_attempts` | Integer default 0 | | +| `presentation_error` | Text default "" | | +| `presentation_delivered_at` | DateTime(tz) nullable | | + +迁移 `backend/app/db/migration_steps/00NN_add_compute_configuration_revisions.py`: +- 幂等建表与索引,兼容 PostgreSQL 与 SQLite(参照 `0006_add_ai_workflow_bindings.py` 的方言分支写法); +- 同一迁移里给 `compute_evidence_candidates` 加 M2 需要的列(见 5.1),避免两次迁移; +- 迁移只建结构,不在迁移里写基线数据。 + +基线封存:新增 `ensure_compute_revision_baseline(db)`(放在 `compute_configuration.py`),幂等: +- 表里已有记录 → 直接返回; +- 否则读取当前 `SystemSetting` 行(没有则用默认台账),插入一条 `action="baseline"` 的记录;`publish_id` 沿用当前 `envelope["revision"]`,这样已打开的后台页面不会因为升级而报冲突; +- 在应用启动初始化处调用(用 `rg -n "ensure_builtin_workflows" backend/app` 找到现有启动初始化位置,放在一起)。 + +### 4.2 读写改造(`backend/app/services/compute_configuration.py`) +**唯一事实来源规则**:版本表是历史和当前版本的来源;`SystemSetting` 保留为“当前版本缓存”,和版本表在**同一事务**内写入,内容必须一致,`envelope["revision"] == 当前 publish_id`。 + +1. `publish_configuration(...)` 改为: + - 按现有方式加行锁,比较 `payload.revision` 与当前 `publish_id`,不一致 → 409; + - 计算新内容 `content_fingerprint`;与当前版本相同 → 不建新版本,返回当前 envelope,并在响应中带 `no_changes: true`; + - 计算 `diff_summary`; + - 插入新版本行:`publish_id = uuid4().hex`(恢复默认也生成新的 uuid,**不再复用 `DEFAULT_REVISION`**),`presentation_status` 初始为 `pending`(`diff_summary` 中没有观测值变化时为 `skipped`); + - 恢复默认:`action="reset"`,内容为默认台账,**更新** `SystemSetting`(`is_default=True`),不再 `db.delete(record)`; + - 写 `AuditLog`(保留现有字段,`details` 增加 `publish_id`、`parent_publish_id`、`diff_summary` 摘要),一次 `commit`。 +2. `read_configuration(db, *, as_of: datetime | None = None, publish_id: str | None = None) -> dict`: + - 两者都没有 → 保持现有行为(读 `SystemSetting`,没有则默认); + - 有 `publish_id` → 读该版本,不存在 → 404; + - 有 `as_of` → 读 `published_at <= as_of` 的最新版本;没有(早于基线)→ 返回 `{"snapshot_unavailable": True, ...}`,调用方据此返回“历史快照不完整”提示(复用 `workflow_runtime.py` 中 `_INCOMPLETE_COMPUTE_REPLAY_NOTICE` 的文案风格); + - 返回的 envelope 增加:`publish_id`、`published_at`、`action`、`is_default`。 +3. 新增 `list_configuration_revisions(db, limit=20)`,返回 `id / publish_id / action / published_at / is_default_content / 变化摘要(条数 + 首条描述)/ presentation_status`。 + +### 4.3 `diff_summary` 格式 +新增纯函数 `diff_compute_configurations(old: ComputeConfiguration, new: ComputeConfiguration) -> list[dict]`(放在 `backend/app/services/compute_revision_diff.py`),只比较 `observations`,其他部分只记数量变化: + +```json +[ + { + "kind": "observation_value", + "metric": "global_share", + "year": 2024, + "period_label": null, + "code": "CN", + "old_value": 23.0, + "new_value": 24.5, + "delta": 1.5, + "change_kind": "historical_revision", + "old_source_id": "caict-2025", + "new_source_id": "report-b" + }, + {"kind": "observation_row_added", "metric": "...", "year": 2025, "period_label": null}, + {"kind": "observation_row_removed", "metric": "...", "year": 2019, "period_label": null}, + {"kind": "period_label_changed", "metric": "...", "year": 2025, "old": "2025H1", "new": "2025"}, + {"kind": "section_changed", "section": "milestones", "added": 1, "removed": 0, "modified": 0} +] +``` +- `change_kind`:旧值存在且不同 → `historical_revision`;旧值不存在 → `new_observation`;值相同只换来源 → `source_reattributed`。 +- 任何非零差值都要记录,**不设 2.0pp 阈值**。 +- 来源按 M2 的 `value_sources` 规则取逐国来源(M1 阶段还没有 `value_sources` 时取行级 `source_id`,M2 再补)。 + +### 4.4 接口 +- `PUT /api/v1/data-products/compute/configuration`:`ComputeConfigurationWrite` 增加 `publish_note: str = ""`(max 1000)、`source_candidate_ids: list[int] = []`(max 50)。响应增加 `publish_id`、`no_changes`、`presentation_status`。 +- `POST /api/v1/data-products/compute/configuration/reset`:响应同上。 +- 新增 `GET /api/v1/data-products/compute/revisions?limit=20`:权限同 `/configuration`(`configuration_admin`),返回 `list_configuration_revisions`。 +- `GET /api/v1/data-products/compute/series` 与 `GET /api/v1/situational-awareness/posture/compute`:新增可选参数 `as_of`、`publish_id`,响应增加 `publish_id`、`published_at`、`as_of`、`snapshot_unavailable`。 +- `query_compute_posture_tool(...)` 增加 `as_of` / `publish_id` 参数并透传给 `read_configuration`;`result["version"]` 改为 `publish_id`。 +- `posture_agent.compute_posture_fingerprint` 已包含 `series_payload["version"]`,改成 `publish_id` 后,不同版本自然生成不同研判缓存;确认 `generate_or_get_compute_posture` 的 `audit_meta` 写入 `publish_id`。 + +### 4.5 前端(Admin) +`frontend/src/admin/pages/ComputeComparisonSettings.tsx` 与 `compute-comparison-model.ts`: +- 保存时继续传 `revision`(值即当前 `publish_id`);收到 409 时保持现有“配置已变化,请重新加载”提示; +- 新增“发布说明”输入框(可选;M2 中在混源份额行存在时变为必填); +- 新增“修订历史”区块:调用 `/revisions`,按时间列出版本(动作、时间、发布人、变化摘要、演播状态)。遵守 `rules.md` 的 `uiux` 与 Admin 控件规范,运行 `scripts/harness/frontend-rules-check.sh`。 + +### 4.6 M1 测试(`backend/tests/test_compute_configuration.py` 或新文件 `test_compute_revisions.py`) +1. **A→B→A 历史还原**:基线 A → 发布 B → 恢复 A,生成 3 条版本,`publish_id` 各不相同;`as_of` 分别取三个时点之后,读到 A、B、A。 +2. **ABA 并发冲突**:拿基线 token `T0` 的客户端,在 B 发布、恢复 A 之后用 `T0` 提交 → 409。 +3. **无变化发布**:内容与当前相同 → `no_changes: true`,不新增版本。 +4. **基线幂等**:多次调用 `ensure_compute_revision_baseline` 只有一条基线;基线 `publish_id` 等于升级前的 `revision`。 +5. **早于基线的 `as_of`**:返回 `snapshot_unavailable: true`。 +6. **diff**:1.5pp 修订被记录为 `historical_revision`;新增年份为 `new_observation`。 +7. 迁移在 SQLite 与 PostgreSQL 路径下都能重复执行(参考 `test_ha_and_migrations.py`)。 + +--- + +## 5. M2:候选复核与逐国来源 + +### 5.1 候选表新增列(在 M1 的迁移里一并加) +`compute_evidence_candidates`: + +| 列 | 类型 | 说明 | +| --- | --- | --- | +| `comparison` | JSON default `{}` | 提取时与当前版本的逐国对比,格式见 5.2 | +| `dedupe_fingerprint` | String(64) index nullable | `sha256(source_id | metric | year | period_label | 排序后的 values)` | +| `review_reason_code` | String(40) nullable | 理由代码 | +| `review_reason` | Text default "" | 理由说明 | +| `published_publish_id` | String(64) nullable index | 发布后回填 | + +同步更新 `ComputeEvidenceCandidate` 模型和 `to_dict()`。 + +### 5.2 提取改造(`POST /situational-awareness/candidates/extract`) +1. `CandidateExtractRequest` 增加可选 `period_label`(max 40)。 +2. 按 M0 结论扩展 `extract_compute_candidates_deterministic`,只加真实案例需要的规则,并为新规则写单元测试。现有正则行为保持不变。 +3. 每条候选生成后: + - 计算 `dedupe_fingerprint`;已存在相同指纹的候选(任意状态)→ 不新建,响应中返回已有候选并标 `duplicate: true`; + - 读取当前版本台账,按 `(metric, year)` 找到现有观测行,生成 `comparison`: + ```json + { + "publish_id": "当前版本", + "metric": "global_share", "year": 2024, + "period_label": null, "existing_period_label": null, + "period_conflict": false, + "denominator": "global", + "codes": { + "CN": {"old_value": 23.0, "new_value": 24.5, "delta": 1.5, "change_kind": "historical_revision", "old_source_id": "caict-2025"}, + "US": {"old_value": 44.0, "new_value": 44.0, "delta": 0.0, "change_kind": "unchanged", "old_source_id": "caict-2025"} + }, + "has_historical_revision": true + } + ``` + - `denominator` 取 `compute_history.MODE_DENOMINATOR` 对应口径; + - 候选与现有行 `period_label` 不同 → `period_conflict: true`。 +4. 抽取时把报告写入 `EvidenceRecord`(`id = source_id`,`excerpt`、`locator`、`content_sha256`),已存在则不覆盖。 + +### 5.3 复核改造(`POST /situational-awareness/candidates/{id}/review`) +`CandidateReviewRequest`: +```python +decision: Literal["approved", "rejected"] +reason_code: Literal[ + "newer_authoritative_report", "corrects_prior_error", "adds_missing_observation", "methodology_update", + "unverifiable_source", "denominator_mismatch", "extraction_error", "superseded", "duplicate", +] +reason: str = Field(min_length=2, max_length=1000) +``` +- 采纳只能用前 4 个代码,驳回只能用后 5 个,不匹配 → 422; +- 已发布(`published_publish_id` 非空)的候选不能再改 → 409; +- 写入 `review_reason_code`、`review_reason`、`reviewed_by`、`reviewed_at`;`AuditLog.details` 包含理由。 + +### 5.4 逐国来源 `value_sources` +`backend/app/schemas/compute_configuration.py` 的 `ComputeObservation` 增加: +```python +value_sources: dict[str, Identifier] | None = None +``` +校验(加在 `comparable_values` 或 `ComputeConfiguration.consistent_evidence` 中): +- `value_sources` 的键必须是 `values` 的子集; +- 引用的每个来源必须存在于 `sources`,且 `year <= report_year`; +- 某国未出现在 `value_sources` 中 → 使用行级 `source_id`。 + +新增辅助函数 `source_for(row, code) -> str`,所有读取来源的地方都改用它。必须同步修改: +- `compute_history.compute_history`:每行输出 `evidence_by_code: {participant_code: [source_id, ...]}`(区域取成员来源去重)和 `mixed_sources: bool`;保留现有 `evidence_id`(行级)以兼容前端; +- `_latest_bilateral_pair` / `_build_bilateral_rpi`:增加 `cn_evidence_id`、`us_evidence_id`; +- `_build_denominator_attribution`:`evidence_ids` 用逐国来源; +- `tool_registry.filter_compute_config_by_cutoff`:某国来源被截断时只去掉该国的值;一行所有国家都被去掉时去掉整行; +- `diff_compute_configurations`:`old_source_id` / `new_source_id` 用逐国来源。 + +### 5.5 导入草稿修复(`compute-comparison-model.ts` `applyApprovedCandidateToDraft`) +规则: +1. 找不到 `(metric, year)` 行 → 按候选新建一行(含 `period_label`),行级 `source_id` 为候选来源。 +2. 找到行且 `period_label` 冲突 → **不合并**,返回需要确认的状态。UI 弹确认框:“替换本年主观测”会用候选整行替换(值、`period_label`、来源),列出会被丢弃的国家代码;取消则不导入。 +3. 找到行且无冲突: + - 只更新候选中出现的国家的值; + - **不修改行级 `source_id`**;候选来源与该国现来源不同时,写入 `value_sources[code] = 候选来源`; + - 合并后若所有国家来源相同 → 把行级 `source_id` 设为该来源并删除 `value_sources`。 +4. 若 `metric` 属于份额类(`global_share` / `intelligent_share` / `frontier_cluster_share` / `chip_inflow_share`)且合并后一行有多个来源:在草稿上标记该行,提示“跨报告局部修订:请在发布说明中写明同分母依据”。 +5. 导入时把候选 id 记入草稿的待发布候选列表,保存时作为 `source_candidate_ids` 提交。 + +后端发布校验(`publish_configuration`): +- 份额类混源行存在且 `publish_note` 为空 → 422,提示写明同分母依据; +- `source_candidate_ids` 中每个候选必须为 `approved` 且未发布,否则 422;发布事务内回填 `published_publish_id`。 + +为 `applyApprovedCandidateToDraft` 写单元测试(项目已有前端测试时放在相同位置,用 `bun test` 运行;没有则在后端用等价 Python 逻辑测试不适用,必须用 Bun 测试前端模型)。 + +### 5.6 Admin 界面 +候选卡片显示: +- 修订类型徽章:历史修订 / 新增观测 / 统计期冲突 / 重复; +- 逐国表格:国家、旧值、新值、差值(百分点或 EFlops)、旧来源; +- 指标口径、分母、年份、报告页码; +- 采纳 / 驳回时必须选择理由代码并填写说明(表单校验,不能空提交)。 + +### 5.7 M2 测试 +1. **只修订中国**(核心):报告 A 同时给中美份额,报告 B 只给中国新值 → 采纳 B 导入发布后,`/series` 中 `evidence_by_code` 显示 CN→B、US→A;`/lineage`(M4)中美国仍引用 A。 +2. 同一报告重复提取 → 不新增候选,返回 `duplicate: true`。 +3. 采纳理由缺失或代码与决定不匹配 → 422。 +4. `period_label` 冲突时导入被拦截;确认替换后整行替换。 +5. 份额混源行无发布说明 → 422。 +6. 截断:`as_known_then` 截断报告 B 后,中国值消失、美国值保留。 +7. M0 的真实案例摘录能被提取,`comparison` 中修订国家为 `historical_revision`。 + +--- + +## 6. M3:演播由版本驱动、可补播、与 BGP 解耦 + +### 6.1 新流程(`backend/app/services/ai/proactive_pipeline.py`) +新增 `process_compute_revision_presentation(db, revision_id) -> dict`: +1. 读取版本行;`presentation_status` 为 `delivered` 或 `skipped` → 直接返回(幂等)。 +2. 从 `diff_summary` 取 `kind == "observation_value"` 且 `delta != 0` 的条目;没有 → 标记 `skipped`。 +3. 用该版本的台账(`query_compute_posture_tool(..., publish_id=...)`)生成研判(`generate_or_get_compute_posture(..., persist=True)`),并编译演播契约: + - `presentation_key = "compute-revision-notice"`; + - `StagePresentation.revision = 版本行 id`(单调递增,前端按 `(key, time_basis, revision)` 去重); + - 契约中写入 `publish_id`; + - 有 `historical_revision` 时:标题“{year} 年{指标中文名}数据获修订”,正文列出“{国家} {旧值} → {新值}({差值})”,并包含固定提示“这是对历史数据的修订,不代表当期算力跃升”; + - 第一幕镜头对准第一个变化国家,`compute_mode` = 该指标对应模式,`focus_year` = 该年份,`spotlight_codes` = 变化国家; + - 恢复默认等回退也按同样规则生成(B→A 是相对上一版的真实变化,必须演播)。 +4. 写入前检查:已存在 `presentation_key` 相同且契约中 `publish_id` 相同的 `StagePresentation` → 不重复写入(确认 `publish_stage_contract` 的去重方式,必要时在调用前查询)。 +5. 成功 → `delivered`,记录 `presentation_delivered_at`;继续调用现有 `_evaluate_topic_watches`。 + +`process_compute_config_proactive_delta` 保留函数名以兼容调用方,内部改为对当前版本调用 `process_compute_revision_presentation`。算力路径**不再调用** `classify_snapshot_delta`,`_COMPUTE_STATE_KEY` 检查点不再使用。`classify_snapshot_delta` 与 BGP 代码不改。 + +### 6.2 失败处理与补播 +- `compute_intelligence.py` 的 PUT 与 reset:删除 `except Exception: pass`。发布提交后调用演播;异常时记录 `warning_event`(`event="compute.revision.presentation_failed"`),版本行置 `failed`、`presentation_attempts += 1`、写 `presentation_error`,提交;接口仍返回 200(发布已成功),响应带 `presentation_status`。 +- 新增 `retry_pending_compute_presentations(db, max_attempts=3)`:处理 `pending` / `failed` 且未超过次数的版本,按 `id` 升序。 +- 调用时机:应用启动初始化一次;按 `backend/app/services/scheduler.py` 现有的定时任务写法加一个每 5 分钟的任务;`POST /situational-awareness/proactive/evaluate` 的 `domain == "compute"` 分支改为调用它。 + +### 6.3 前端演播行为 +确认 `stage-narrative-player.js` 现有逻辑满足以下行为;只在缺失时修改: +- 地球空闲时收到新契约 → 自动播放; +- 用户正在拖拽、查看或使用参谋时 → 不抢镜头,只显示“待播新态势”提示; +- 同一 `(key, time_basis, revision)` 重复到达 → 不重复入队。 +在 `domainLabels` 中为修订提示显示“算力数据修订”。 + +### 6.4 M3 测试 +1. **中断补播**:发布时让演播函数抛异常 → 版本行 `failed`;调用 `retry_pending_compute_presentations` → `delivered`,生成恰好一条 `StagePresentation`。 +2. **重复不重播**:对同一版本再次调用 → 不新增 `StagePresentation`。 +3. **B→A 恢复会播**:A→B→A,第三次生成新的演播契约。 +4. **1.5pp 小修订会播**。 +5. **只改里程碑等非观测内容** → `skipped`,无演播。 +6. BGP 主动研判现有测试全部通过,未改动。 + +--- + +## 7. M4:卡片与参谋同源、版本切换、血缘抽屉 + +### 7.1 血缘接口(读取时推导,不建关系表) +新增 `GET /api/v1/data-products/compute/lineage?code=CN&metric=global_share&year=2024&publish_id=...`(`publish_id` 省略为当前版本),权限 `require_earth_or_api_access("data_products:read")`。 + +实现: +1. 读取指定版本台账,取该国当前值和来源(`source_for`),附报告详情(标题、发布机构、URL、页码、`published_at`、`EvidenceRecord.content_sha256`)。 +2. 从该版本向前遍历版本表(最多 50 条),收集 `diff_summary` 中匹配 `(metric, year, code)` 的条目,每条输出:`publish_id`、`published_at`、`action`、`old_value`、`new_value`、`delta`、`change_kind`、`old_source_id`、`new_source_id`、关联候选(通过 `source_candidate_ids`)的理由代码与理由、复核人、发布说明、发布人。 +3. 输出对象级时间:观测期(`year` / `period_label`)、报告发表日、入库时间(候选 `created_at`,基线数据为空)、生效发布时间。 + +**脱敏**:调用者不是已登录的 `admin` / `super_admin` 时(查找项目现有的可选当前用户依赖;没有则新增一个不报错的可选版本),返回中: +- 复核人、发布人姓名替换为“已人工复核”; +- 不返回 `review_reason` 和 `publish_note` 原文,只返回理由代码对应的中文类别。 + +### 7.2 Earth 算力卡片(`frontend/public/earth/js/compute-topic.js`) +- 状态增加 `publishId`(取自 `/series` 响应)和 `asOf`;`/series`、`/posture/compute` 请求都带上 `as_of`(设置时)。 +- 配置面板增加“系统发布版本”选择:选项来自公开的轻量接口。`/revisions` 是管理员接口,为 Earth 新增 `GET /api/v1/data-products/compute/revisions/public?limit=20`,只返回 `publish_id`、`published_at`、`action`、变化摘要(脱敏),权限 `require_earth_or_api_access("data_products:read")`。 +- 查看历史版本时,卡片顶部显示提示条:“正在查看 {时间} 发布的版本(非当前)”,带“回到当前”按钮。早于基线时显示“历史快照不完整”。 +- 数值旁的溯源按钮打开现有证据面板,扩展为血缘视图:当前值与来源、修订时间线、复核信息(按 7.1 脱敏)。 +- `open-copilot` 和 `open-compute-workbench` 传给参谋的上下文增加 `publishId`、`asOf`(现有 `mode`、`focusYear`、`selectedCodes` 保留)。 + +### 7.3 参谋同源(`situational-copilot.js` 与后端工作流) +- 前端把 `publishId`、`asOf` 放入会话上下文,后端 `workflow_runtime` / `dag_executor` 调用 `query_compute_posture_tool` 时透传。 +- 后端生成的 `view_spec` 增加 `publish_id`、`mode`、`focus_year`(`_compile_compute_workbench` 与 `compile_compute_view_spec`)。 +- 前端渲染参谋的算力结果时,比较 `view_spec` 的 `publish_id` / `mode` / `focus_year` 与当前卡片状态: + - 一致 → 正常显示; + - 不一致 → 图表区与文字区都显示“本结果基于 {版本/口径},与当前地球视图不同”,并提供“按当前视图重新研判”按钮。**不得**出现图表与文字基于不同口径而无提示。 +- 追问“这次为什么变了”时,后端把当前版本的 `diff_summary` 和关联候选理由加入工作流上下文,参谋回答必须引用同一 `publish_id` 下的证据。 + +### 7.4 文档 +- 更新 `docs/technical/zh/platform-data-flows.md` 与 `docs/technical/en/platform-data-flows.md` 的算力部分:版本表、两根时间轴、演播补播、血缘推导、脱敏规则。 +- 若 Admin / Earth 交互有用户可见变化,按 `docs/documentation-coverage-rules.md` 更新对应前端技术文档。 +- 运行 `scripts/harness/docs-consistency-check.sh`。 + +### 7.5 M4 验收(端到端,全部通过才算一期完成) +用 M0 的真实案例走完以下 9 条,每条保留证据(测试输出或截图): + +1. **修订识别**:提取真实报告摘录 → 候选显示“历史修订”、逐国旧值/新值/差值、口径、分母、报告页码。 +2. **人工决策留痕**:`admin` 选理由采纳并发布;另做一次驳回,理由被记录;`viewer` 调用复核和发布接口返回 403。 +3. **主动演播与礼让**:发布后空闲地球自动播放“{year} 年数据获修订”,文案包含“历史数据修订,非当期跃升”;用户操作中只显示提示;重复提交同一报告不产生新候选、不重播。 +4. **卡片与参谋同源**:从卡片打开参谋,参谋结果的 `publish_id` / 口径 / 年份与卡片一致;在卡片切换口径后,参谋旧结果显示“与当前视图不同”提示,点击后按新口径重新生成。 +5. **血缘一追到底**:点击地球上修订后的数字,能看到报告原文出处、页码、哈希、观测期、入库时间、复核理由类别、发布时间、修订前旧值。登录管理员能看到复核人姓名和理由原文,公开访问看不到。 +6. **切回发布前**:选择发布前的版本,卡片与参谋显示旧值和当时的结论。 +7. **只修订中国**:美国未变的值继续引用原报告。 +8. **A→B→A**:三个时点分别显示 A、B、A,两次变更各有理由;旧页面 token 提交返回 409。 +9. **中断补播**:模拟演播失败,补播后地球播放一次;同一事件再次到达时地球不动。 + +--- + +## 8. 每个里程碑的检查与报告 + +### 8.1 检查命令(按改动范围选择,里程碑结束时全部跑) +```bash +cd backend && uv run --frozen --group dev --project .. python -m pytest -q +scripts/harness/backend-rules-check.sh +cd frontend && bun install --frozen-lockfile && bun run build && bun run build:admin +scripts/harness/frontend-rules-check.sh +scripts/harness/docs-consistency-check.sh +scripts/harness/quick-check.sh +``` +M4 结束再跑 `scripts/harness/validate.sh`。涉及 Admin / Earth 界面的改动,需要在浏览器中实测渲染(桌面、移动端、125% / 150% 缩放),并检查 Admin 一屏高度链没有被破坏。 + +测试失败时先判断它保护的行为:实现回归就修实现;断言绑定的是已被本计划明确改变的旧细节(例如恢复默认复用 `DEFAULT_REVISION`),才更新测试,并在报告中说明。 + +### 8.2 里程碑报告格式 +``` +## M{n} 完成报告 +- 完成内容:(对应本计划的小节编号) +- 改动文件:(路径列表) +- 新增/修改测试:(测试名 + 结果) +- 检查命令结果:(通过/失败 + 失败原因) +- 与计划不一致之处:(代码现状与计划描述不同的地方,以及处理方式) +- 遗留问题与风险: +``` + +### 8.3 需要停下来问用户的情况 +- M0 找不到真实修订案例; +- 发现计划中的约定会破坏现有功能且没有安全的保守做法; +- 需要新增数据源、新增角色、修改既有迁移文件、或改动 BGP 逻辑; +- 需要大范围重构 `compute-topic.js` 或 Earth 渲染层。 diff --git a/docs/technical/en/backend-collectors.md b/docs/technical/en/backend-collectors.md index 886e09c0..e3b97a44 100644 --- a/docs/technical/en/backend-collectors.md +++ b/docs/technical/en/backend-collectors.md @@ -97,7 +97,7 @@ AIS vessel collectors use a different persistence path from regular `CollectedDa `vessel_current_state` only lets newer observations overwrite dynamic position fields; static fields such as name and vessel type are merged by non-empty value and source priority. Earth snapshots return only vessels inside the freshness window, keeping high-frequency AIS history out of the display path. -Earth boundaries are no longer data collectors. They are Earth static rendering assets: the Earth Assets settings panel owns source configuration, and `/api/v1/earth/boundaries/*` builds `frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles`. When no high-precision PMTiles artifact is available locally, the frontend uses the bundled low-precision GeoJSON fallback and does not write boundary records to `CollectedData`. +Earth boundaries and populated-place label catalogs are not data collectors. They are Earth static rendering assets: the Earth Content -> Boundary Precision panel (`PUT /api/v1/earth/boundaries/config`) owns source configuration, and `/api/v1/earth/boundaries/*` (`/status`, `/manifest`, `/build`, `/build/status`, plus `GET`/`HEAD` HTTP `Range` immutable `/files/{name}` isolated on `rate_limit_tier="tile"`) builds and serves `earth-boundaries..pmtiles`, `hover-index..json`, `hover-borders..json`, and `geo-labels..json` (`planet-earth-geo-labels/v1`, built from `earth_populated_places` under China POV rules). When no high-precision PMTiles artifact is built locally, the frontend uses the bundled `countries-admin0.china-pov-v1.geojson` fallback and does not write boundary records to `CollectedData`. TOP500 and Epoch AI compute sources do not always provide usable coordinates. Epoch's official CSV `Location` may contain only a country or be empty even when a row has latitude/longitude; it is never treated as a precise site without the required source semantics. The unified Earth compute-center endpoint uses valid source-provided coordinates or `compute_center_locations` dimension-table coordinates during the main map startup path; records without renderable coordinates remain in the complete `unresolved` list instead of being rendered from a local registry, country centroid, or guessed headquarters. `precise`/`site` keep source coordinates; city-level and confirmation-required points may receive only a deterministic display offset keyed by `source` + `source_id`, with the original coordinate untouched. When users manually collect candidates, the backend queries ROR and Nominatim/OpenStreetMap from source fields; accepted candidates are saved into `compute_center_locations` and rendered from that table on the next layer refresh. diff --git a/docs/technical/en/earth-frontend-context.md b/docs/technical/en/earth-frontend-context.md index 0fed4f5c..76bba467 100644 --- a/docs/technical/en/earth-frontend-context.md +++ b/docs/technical/en/earth-frontend-context.md @@ -295,7 +295,7 @@ The real satellite altitude preference is persisted by `controls.js`, while the SGP4 propagation returns an inertial-frame position, so it must not be drawn directly as Earth-fixed longitude / latitude. `satellites.js` uses `gstime` to convert ECI/TEME positions to ECF, then maps that result into the same Three.js axes as `latLonToVector3()`. Satellite dots and short trails use Earth-fixed coordinates for each sample time, representing the object's current position relative to the globe surface. The locked predicted orbit uses the `gstime` from the lock moment for an open full-period prediction curve, projecting the inertial orbit plane onto the current globe pose. No first vertex or closing chord is appended; arc-length highlights travel toward increasing prediction time, and visual inclination stays aligned with the details card. Fallback predicted orbits must also use a real RAAN + inclination orbital-plane formula, not treat inclination as a constant latitude. -Boundary precision is stored separately by `country-boundaries.js` under `planet.earth.boundaries.highPrecisionEnabled`. When high precision is off, Earth keeps using the bundled low-precision `countries-admin0.min.geojson` fallback even if high-precision manifest/PMTiles files exist locally. When high precision is on but the artifact is missing, the Earth toolbar settings call `/api/v1/earth/boundaries/build` and poll progress. After success, `reloadCountryBoundaries()` hot-swaps the boundary layer without refreshing the page. Boundary hover is independent from interactable hover: a country polygon remains highlighted whenever the surface coordinate is inside it, while the tooltip can still prioritize a satellite, vessel, BGP marker, or other interactable. +Boundary precision is stored separately by `country-boundaries.js` under `planet.earth.boundaries.highPrecisionEnabled`. When high precision is off, Earth keeps using the bundled low-precision `countries-admin0.china-pov-v1.geojson` fallback even if high-precision manifest/PMTiles files exist locally. When high precision is on but the artifact is missing, the Earth toolbar settings call `/api/v1/earth/boundaries/build` and poll progress. After success, `reloadCountryBoundaries()` hot-swaps the boundary layer without refreshing the page. Boundary hover is independent from interactable hover: a country polygon remains highlighted whenever the surface coordinate is inside it, while the tooltip can still prioritize a satellite, vessel, BGP marker, or other interactable. ## Current Terrain Pipeline @@ -620,3 +620,31 @@ When compute image configuration has no model/group rules, resolution uses a bou - **Surface Influence Zones & Stage Directives** (`influence-zones.js` + `scene_directives.py`): renders geopolitical country/region presets and great-circle radius zones emitted by AI/stage directives via single-pass offscreen `scratchCanvas` soft-blur compositing and explicit `tier` / `z_index` stacking (`renderOrderBase = 0.965`, strictly between HD imagery `0.96` and borders `0.97`). - **Rayleigh Scattering, Ribbons & GPU Iridium Projection**: `earth-surface-material.js` and `earth.js` pair with `earth_clouds_2048.png` for Rayleigh terminator shading, soft surface cloud shadows, and grazing water highlights; `surface-ribbon.js` unifies screen-space anti-aliased glowing ribbons for borders, BGP radar/stage arcs, cable pulses, vessel tracks, and selected satellite orbits; `iridium-footprint-adapter.js` moves Iridium footprint vertices onto GPU projection. - **Prefer-One-Bend Callout Routing & Write Auth**: `callout-connector.js` (`applyPreferredOneBendAnchor`) shifts aligned perimeter anchors toward the card body/header when sufficient major-axis distance and edge span exist so connectors prefer one clean bend (never exceeding one bend, gracefully falling back to a 2-point line on compact capsules or short spans); `admin-write-auth.js` gates Earth-side compute location collection and saving behind admin token refresh and `/login` prompts. + +### Real-Time Global IR Cloud Map Pipeline & Dual-Frame Shader + +- **Data-First Multi-Satellite Clouds, Managed Tile Pyramids & NOAA GFS Wind Grid** (`earth_clouds.py` + `earth_clouds_fx.py` + `earth_tiles.py` + `earth_wind.py`): + - `global_cloud_map` (`id=34`, `product=weather`): defaults to **`4096x2048`** (`request_timeout_seconds = 45`), extending the 5-satellite Band13/10.8μm IR feathered composite (limb cutoff `delta > 74°`) with a band-pass warm-low-cloud daytime visible fusion gate (`fuse_daytime_visible_into_density`, recovering `-2°C..+16°C` stratocumulus while rejecting sub-`-8°C` winter plateau snow, hot deserts, and clipped `[255,255,255]` EUMETView artifacts), GeoColor RGB overlays (`frames/_vis.webp`), and `cv2.DISOpticalFlow_create` displacement fields (`flows/.webp`), exposed via `/api/v1/earth/clouds/{meta,frames/{ver},frames/{ver}/visual,flows/{ver}}`; local 8K basemaps and `earth_clouds_2048.png` remain as fallbacks. + - Managed Tile Pyramid (`cloud_hd_tiles` `id=35` in `weather`; `earth_imagery_sentinel2` `id=36` and `earth_imagery_viirs_daily` `id=37` in `geo`): `BaseCollector` warmup jobs pre-seed `z=0..warmup_max_zoom` while `/api/v1/earth/tiles/{source}/{z}/{x}/{y}.webp` enforces `DataSource.is_active` gating and per-source disk LRU eviction; defaults set `cloud_hd_tiles_enabled = false` and `lod_switch_altitude = 1.85` so the single seamlessly feathered 4K global map drives clouds across all zoom levels (when `cloud_hd_tiles` is manually enabled, HTTP responses cap browser `max-age=300` and apply the same warm-low-cloud band-pass filter). + - `global_wind_gfs` (`id=38`, `product=weather`): fetches NOAA NCEP GFS 10m `ugrd10m`/`vgrd10m` vectors from PacIOOS ERDDAP onto normalized `-180..180` grids under `data/earth-wind/`, backing `/api/v1/earth/wind/{meta,grid/{ver}}`, `/api/v1/data-products/wind/{summary,point}`, and AI Advisor `query_wind_posture_tool`. +- **Selectable Surface Color Grades, RGB Frequency-Separated Detail Transfer, Windy Streamlines & Linear Cloud Space** (`constants.js` + `cloud-map.js` + `earth-surface-material.js` + `spherical-tile-layer.js` + `wind-layer.js` + `controls.js` + `satellites.js` + `earth_clouds_fx.py`): + - **Three Selectable Surface Color Grades (`SURFACE_COLOR_GRADES`, default `classic-083`)**: Explicitly parameterizes `uLandGradeGain`, `uLandCoolBias`, `uDiffuseFloor`, `uToneMapMode`, and `iceFactor` to deliver `classic-083` (clean, cool, crisp `v0.83.0` filmic tone with indigo ocean, pure white snow peaks, and `opacity: 0.38` cloud veil without pre/post-load brightness jumps), `fresh-natural` (vibrant greens via chroma-preserving C1 curve), and `balanced-satellite`, selectable via Settings → Display → `Surface Tone` (`EARTH_SETTINGS_VERSION = 21`) alongside `uSurfaceBrightness` (`0.65..1.6`, default `1.0`). + - **RGB 3-Channel Frequency-Separated Detail Transfer** (`createEarthSurfaceTileMaterial`, cache key `earth-surface-tile-v5`): Uses `tileLowRgb` / `rgbRatio` / `transferRatio` to strip Sentinel-2's diagonal swath stripes while injecting full-color 10m terrain micro-features matched across all zoom levels (`50%..500%`) and color grades; both tile and wind groups use plain `THREE.Object3D` (`groupOrder = 0`), and `uLandMask` decodes uniformly via `#ifndef LEGACY_TEXTURE_ENCODING surfaceSRGB(mask)`. + - **Windy-Style Curved Global Wind Streamlines** (`wind-layer.js`): 3,600 advected particles with 8-segment curved history ribbons (`CONFIG.earthRadius + 1.6`, `renderOrder = 1.04`, `THREE.AdditiveBlending`) rendered in a cool frost-white/sky-cyan/aurora-ice palette below clouds and distinct from satellite markers/trails. + - **Linear Cloud Maps & Parallel 4K Decoding** (`cloud-map.js` + `earth_clouds.py` + `earth_clouds_fx.py`): Keeps `uCloudMap` and `uCloudVisualMap` in `THREE.NoColorSpace` to avoid linear-density darkening into gray smog, deduplicates visible image decoding via `decode_visual_payloads`, parallelizes IR+VIS WMS fetches, and filters EUMETView clipped `[255,255,255]` blocks; 6-digit NORAD IDs map to USSF Alpha-5 TLE identifiers and locked `predictedOrbitLine` ribbons rotate via `anchorSiderealTime - gstime(liveTime)`. + - **Unified Weather Layer Toggle, Display Weather Section & v22 Defaults** (`constants.js` + `index.html` + `controls.js` + `layer-startup-tasks.js`): Consolidates cloud and wind rows in the layer panel into one default-on `Weather` (`#toggle-weather`) switch and adds a dedicated `Weather` subsection in Settings → Display (`WEATHER_LAYER_DEFINITIONS` multi-select chips for `Clouds` and `Wind`, both on by default alongside live/timelapse cloud toggles, with bidirectional master-chip synchronization), while renaming the news subsection heading to `News`. `EARTH_SETTINGS_VERSION = 22` sets default sky brightness to `200%`, terrain opacity to `68%`, satellite close-up label zoom threshold to `330%`, default label limit to `16` (preserving the `5..36` slider range), and default altitude compression to `0%`. + +### High-Precision PMTiles Vector Boundaries & 3D Tiered City Labels + +- **High-Precision Boundary Pipeline & Multi-Layer Caching** (`country-boundaries.js` + `boundary-tile-worker.js` + `boundary-tile-decode.js` + `boundary-tile-cache.js` + `earth-preload.js` + Electron `protocol-core.ts`): + - **4 Zoom Tiers & Coastal Endpoint Alignment**: `tileZoomThresholds` divides `1x–5x` into `z2` (`0x`), `z4` (`1.3x`), `z6` (`2.3x`), and `z8` (`3.8x`); Natural Earth administrative borders (`boundary_admin0` / `boundary_disputed_internal` / `boundary_admin1`) saturate at `z6` and persist smoothly above `z6` while `z8` refines OSM `coastline` geometry. Build-time geometry prep (`earth_boundary_geometry.py`) extends/trims coastal border endpoints onto coastlines and bakes a `2px` antimeridian-wrapping `THREE.NoColorSpace` (`flipY=true`) land mask. + - **Flicker-Free Scheduling, Poison-Free Negative Caching & Batched Rendering**: Uses trailing-edge debouncing, monotonic `generation` cancellation, center-first queue ordering, and parent-tile persistence (`resolveDisplayTiles`) feeding `<= 3` GPU draw calls (`country-boundary-batch`, `country-admin1-batch`, `country-boundary-claim-batch`). `_emptyTileKeys` caches only verified zero-feature responses (never HTTP 429 or aborted requests), `ResilientPmtilesCache` evicts rejected directory/header promises, and layered persistence spans `earth-preload.js` + IndexedDB (`force-cache` Range fetches + `prewarmBoundaryTiles`) plus Electron `userData` disk caching for zero remote file requests on reload. Country hover merges `hover-borders..json` land borders with PMTiles coastlines for full-perimeter glowing strokes with no country fill mask. +- **3D Tiered City Labels** (`geo-labels.js` + `constants.js` + `hud.css` + `layer-startup-tasks.js` + `controls.js`): + - Loads `manifest.geoLabels` (`geo-labels..json`) via preload + IndexedDB after boundary startup, anchors dot markers at `earthSurfacePoint(..., CONFIG.earthRadius + 0.48)` (`translate(-3px,-50%)`), and culls far-side cities with `isSurfaceAnchorVisible` (`occlusionRadiusFactor = 0.999`). + - Smoothly fades three zoom tiers — Tier 1 (`1.7x..2.05x`, capitals / megacities), Tier 2 (`2.75x..3.15x`, major cities), Tier 3 (`3.75x..4.2x`, provincial/state admin-1 capitals) — capped at `28` desktop / `14` mobile labels per frame while avoiding HUD panels, `#earth-region-callouts`, `.map-cluster-badge` / `.map-cluster-child`, and `.satellite-map-label`, following `zh`/`en` locale changes and the `City Labels` (`[data-geo-labels-toggle]`, default on) switch in Settings → Display. + +### Compute Ledger Version Replay, Lineage Drawer & Copilot View-Sync Guard + +- **Published-revision selector and historical banner** (`compute-topic.js` + `compute-topic.css`): adds a `Published revision` selector backed by the redacted public endpoint `/api/v1/data-products/compute/revisions/public` alongside Period and Measure, forwarding `publish_id` / `as_of` on both `/series` and `/posture/compute`. Viewing a historical revision renders a top banner (`Viewing revision published {ts} (not current)`) with a one-click `Return to current` button, while pre-baseline timestamps surface an `Incomplete historical snapshot` notice. +- **Per-country provenance and Lineage Drawer** (`compute-topic.js` + `compute-topic-model.js`): adds an inline provenance button beside each hero metric using per-country `evidence_by_code` and fetches `/api/v1/data-products/compute/lineage` (attaching Bearer auth only when the stored session role is `admin` or `super_admin` so public/viewer traffic remains redacted without triggering 403), rendering current value, source title/locator/excerpt/SHA-256, object-level timestamps, and revision timeline inside `#compute-evidence`. +- **Copilot same-source binding and mismatch guard** (`situational-copilot.js` + `workbench-blocks.js` + `main.js`): forwards `publishId`, `asOf`, `mode`, and `focusYear` from Compute Cards into Copilot sessions/turns and listens to `earth:compute-view-changed` to compare each turn's `view_spec` `(publish_id, mode, focus_year)` against live card state. Any divergence displays a mismatch banner with a `Re-evaluate for current view` button in **both** the narrative text area and the chart/workbench area so charts and prose never silently disagree. `stage-narrative-player.js` labels `compute-revision-notice` as `Compute Data Revision` and syncs the updated `publishId`. diff --git a/docs/technical/en/earth-layer-style-reference.md b/docs/technical/en/earth-layer-style-reference.md index 97d55604..4fffedbe 100644 --- a/docs/technical/en/earth-layer-style-reference.md +++ b/docs/technical/en/earth-layer-style-reference.md @@ -71,38 +71,49 @@ The land/ocean base is an Earth base-map asset and preloads at startup; the "Bor | Name | Variable | Current Value | Location / Notes | | --- | --- | --- | --- | -| Boundary tile manifest | `COUNTRY_BOUNDARY_CONFIG.tileManifestPath` | `"/earth/data/boundaries/v1/manifest.json"` | High-precision PMTiles manifest; missing manifest uses the low-precision fallback | -| Boundary tile provider | `COUNTRY_BOUNDARY_CONFIG.tileProvider` | `"auto"` | Prefer high-precision PMTiles/MVT, then fall back to legacy GeoJSON | -| PMTiles artifact path | `COUNTRY_BOUNDARY_CONFIG.pmtilesPath` | `"/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles"` | Production single-file PMTiles/MVT artifact | -| Low-precision fallback | `COUNTRY_BOUNDARY_CONFIG.legacyFallbackPath` | `"/earth/data/countries-admin0.min.geojson"` | Default land/ocean base and hover data when no high-precision boundary asset has been built locally | -| MVT layer names | `COUNTRY_BOUNDARY_CONFIG.mvtLayerNames` | `boundary_admin0 / boundary_disputed_internal / coastline / claim_line` | Fixed layer names decoded by the PMTiles provider | -| Boundary tile base path | `COUNTRY_BOUNDARY_CONFIG.tileBasePath` | `"/earth/data/boundaries/v1/"` | PMTiles manifest base path | -| Boundary tile zoom thresholds | `COUNTRY_BOUNDARY_CONFIG.tileZoomThresholds` | `1.6 -> z5`, `2.8 -> z6`, `3.4 -> z7`, `4.0 -> z8`, `4.6 -> z9`, `5.2 -> z10` | Production PMTiles zoom selection | -| Boundary tile cache limit | `COUNTRY_BOUNDARY_CONFIG.tileCacheLimit` | `150` | Frontend LRU cache entries for loaded tile geometries | -| Boundary tile debounce | `COUNTRY_BOUNDARY_CONFIG.tileDebounceMs` | `180` | View-change debounce before requesting visible tiles | +| Boundary tile manifest | `COUNTRY_BOUNDARY_CONFIG.tileManifestPath` | `"/api/v1/earth/boundaries/manifest"` | High-precision PMTiles manifest; missing or disabled uses the bundled fallback | +| Boundary files endpoint | `COUNTRY_BOUNDARY_CONFIG.tileFilesPath` | `"/api/v1/earth/boundaries/files/"` | Serves PMTiles (`Range`), `hover-index`, `hover-borders`, and `geo-labels` JSON | +| Boundary tile provider | `COUNTRY_BOUNDARY_CONFIG.tileProvider` | `"auto"` | Prefer high-precision PMTiles/MVT, then fall back to policy GeoJSON | +| Low-precision fallback | `POLICY_FALLBACK_URL` (`country-boundaries.js`) | `countries-admin0.china-pov-v1.geojson` | Default land/ocean base and hover data when high-precision assets are disabled or unbuilt | +| MVT layer names | `COUNTRY_BOUNDARY_CONFIG.mvtLayerNames` | `boundary_admin0` / `boundary_disputed_internal` / `coastline` (boundary), `boundary_admin1` (admin1), `claim_line` (claim) | Fixed layer groups decoded by the PMTiles provider | +| Boundary tile zoom thresholds | `COUNTRY_BOUNDARY_CONFIG.tileZoomThresholds` | `0 -> z2`, `1.3 -> z4`, `2.3 -> z6`, `3.8 -> z8` | 4-tier PMTiles zoom schedule (`borderMaxZoom = 6`; `z8` refines OSM coastlines only) | +| Boundary tile cache limit | `COUNTRY_BOUNDARY_CONFIG.tileCacheLimit` | `640` | Frontend LRU cache entries for loaded tile geometries | +| Boundary tile debounce | `COUNTRY_BOUNDARY_CONFIG.tileDebounceMs` | `180` | Trailing-edge view-change debounce before queuing visible tiles | +| Admin-1 fade & style | `admin1MinViewZoom / FullViewZoom / Color / Opacity` | `2.0 / 2.8 / 0x9fd0ff / 0.26` | `country-admin1-batch` smoothly fades in as zoom increases | | Ocean fill color | local `OCEAN_HEX` | `0x010609` | Land/ocean base canvas background | | Land fill color | `COUNTRY_BOUNDARY_CONFIG.landColor` | `0x080f1b` | Land/ocean base canvas land | | Land/ocean base opacity | `COUNTRY_BOUNDARY_CONFIG.landOpacity` | `1.0` | `MeshBasicMaterial.opacity` | | Land/ocean base radius offset | `COUNTRY_BOUNDARY_CONFIG.landAltitudeOffset` | `0.32` | `country-land-ocean` radius; separated from the Earth base sphere to avoid snow / black block flicker at 50% zoom | | Land/ocean base renderOrder | `COUNTRY_BOUNDARY_CONFIG.landRenderOrder` | `0.86` | `country-land-ocean.renderOrder` | -| Land/ocean mask size | `landMaskWidth / landMaskHeight` | `2048 / 1024` | Canvas / DataTexture size | +| Land/ocean mask size | `landMaskWidth / landMaskHeight` | `2048 / 1024` | `2px` antimeridian-wrapping `NoColorSpace` (`flipY=true`) DataTexture | | Country tint color | `COUNTRY_BOUNDARY_CONFIG.tintColor` | `0x0b1830` | Tint when HD texture is off | | Country tint radius offset | `COUNTRY_BOUNDARY_CONFIG.tintAltitudeOffset` | `0.32` | `country-tint` radius | | Country tint renderOrder | `COUNTRY_BOUNDARY_CONFIG.tintRenderOrder` | `0.2` | `country-tint.renderOrder` | | Border line color | `COUNTRY_BOUNDARY_CONFIG.lineColor` | `0x7fc7ff` | Normal border line | | Border line opacity | `COUNTRY_BOUNDARY_CONFIG.lineOpacity` | `0.58` | Normal border line opacity | -| Border dimmed opacity on hover | `COUNTRY_BOUNDARY_CONFIG.dimmedLineOpacity` | `0.18` | Normal border opacity during hover | -| Border line radius offset | `COUNTRY_BOUNDARY_CONFIG.lineAltitudeOffset` | `0.115` | Normal border line radius; line layers rely on renderOrder and independent geometry, not whole-globe shell depth spacing | -| Border line renderOrder | `COUNTRY_BOUNDARY_CONFIG.lineRenderOrder` | `2.2` | Normal border line level | -| Border hover color | `COUNTRY_BOUNDARY_CONFIG.hoverLineColor` | `0xff3b1f` | Neon red-orange | +| Border dimmed opacity on hover | `COUNTRY_BOUNDARY_CONFIG.dimmedLineOpacity` | `0.18` | Normal border opacity during hover (applied to base batch only) | +| Border line radius offset | `COUNTRY_BOUNDARY_CONFIG.lineAltitudeOffset` | `0.48` (`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`) | Shares exact HD surface shell radius to eliminate rotation parallax | +| Border line renderOrder | `COUNTRY_BOUNDARY_CONFIG.lineRenderOrder` | `0.97` | Normal border line level | +| Border hover color | `COUNTRY_BOUNDARY_CONFIG.hoverLineColor` | `0xff3b1f` | Neon red-orange full-perimeter highlight (land borders + OSM coastlines, no fill mask) | | Border hover opacity | `COUNTRY_BOUNDARY_CONFIG.hoverLineOpacity` | `1.0` | Hover line opacity | -| Border hover radius offset | `COUNTRY_BOUNDARY_CONFIG.hoverAltitudeOffset` | `0.115` | Hover line radius; matches the normal border geometry to avoid double-edge ghosting during highlight changes | -| Border hover renderOrder | `COUNTRY_BOUNDARY_CONFIG.hoverLineRenderOrder` | `2.3` | Hover line level | +| Border hover radius offset | `COUNTRY_BOUNDARY_CONFIG.hoverAltitudeOffset` | `0.48` (`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`) | Hover line radius; matches normal border and HD texture geometry | +| Border hover renderOrder | `COUNTRY_BOUNDARY_CONFIG.hoverLineRenderOrder` | `0.99` | Hover line level | | Border hover glow opacity | `COUNTRY_BOUNDARY_CONFIG.hoverGlowOpacity` | `0.38` | Glow line opacity | -| Border hover glow line width | `COUNTRY_BOUNDARY_CONFIG.hoverGlowLineWidth` | `3` | Glow `LineBasicMaterial.linewidth` | -| Border hover glow level offset | `COUNTRY_BOUNDARY_CONFIG.hoverGlowRenderOrderOffset` | `0.01` | Glow renderOrder = `2.29` | +| Border hover glow line width | `COUNTRY_BOUNDARY_CONFIG.hoverGlowLineWidth` | `3` | Glow line width | +| Border hover glow level offset | `COUNTRY_BOUNDARY_CONFIG.hoverGlowRenderOrderOffset` | `0.01` | Glow order offset relative to hover line | | Border hover glow radius offset | `COUNTRY_BOUNDARY_CONFIG.hoverGlowRadiusOffset` | `0` | Glow uses the same radius as the hover line to avoid coastline detail misalignment | +## 3D Tiered City Labels + +Rendered in `.geo-labels` (`geo-labels.js` + `hud.css`, `z-index: 4`) using `earthSurfacePoint(..., R + 0.48)` dot anchoring and `isSurfaceAnchorVisible` back-hemisphere culling: + +| Name | Variable | Current Value | Location / Notes | +| --- | --- | --- | --- | +| Default & screen cap | `defaultEnabled / maxVisibleDesktop / maxVisibleMobile` | `true / 28 / 14` | Controlled by Display → `City Labels`; capped per frame by viewport class | +| Scan interval & occlusion | `scanIntervalMs / occlusionRadiusFactor` | `160 / 0.999` | Collision/obstacle scan every 160ms; active labels update every frame | +| Tier zoom thresholds | `GEO_LABEL_CONFIG.tierFade` | `1: 1.7..2.05`, `2: 2.75..3.15`, `3: 3.75..4.2` | Smooth fade across Tier 1 (capitals/megacities), Tier 2 (major), and Tier 3 (admin-1) | +| Visual hierarchy | `data-kind` (`capital` / `megacity` / `major` / `admin1`) | Gold `11.5px` / White `11px` / Slate `10.5px` / Muted `10px` | Capitals show a `6px` warm-gold dot; demoted regional seats use `admin1` muted styling | + ## Real Terrain | Name | Variable | Current Value | Location / Notes | diff --git a/docs/technical/en/earth-render-layer-order.md b/docs/technical/en/earth-render-layer-order.md index eb32184a..952a85d4 100644 --- a/docs/technical/en/earth-render-layer-order.md +++ b/docs/technical/en/earth-render-layer-order.md @@ -27,9 +27,9 @@ Note: the layer control panel order and the registration / startup load order ar | 1 | Submarine cables / landing points | `cables.js`, `cable-batches.js` | All cable segments share one `LineSegments`; all landing points use instanced billboards; render order remains `1`; cables and landing-point anchors share the HD surface offset `0.48` and the same triangle-surface coordinates | Original `Line` / `Sprite` objects retain per-item picking and selection state but no longer draw individually; landing-point sphere occlusion remains, with `depthTest: false` on the batch | Style textures and instance attributes preserve color, pulse, size, visibility, and click behavior. | | 1.2 | Real terrain | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` plus terrain displacement | Raycast disabled | Terrain overlays HD texture; temporarily hidden when HD texture is off, restores to prior state when re-enabled. | | 2.05 | Grid lines | `earth.js` | `CONFIG.earthRadius + 0.14` | Raycast disabled | Low-opacity lines over HD texture. | -| 0.97–0.99 | Country borders | `country-boundaries.js` | `lineAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48`; claim lines have no extra lift | Raycast disabled | Line geometry still has its own `renderOrder`, but it shares the exact same radius as the HD texture shell to avoid parallax while the globe rotates. | -| 0.98 | Country border hover glow | `country-boundaries.js` | Same surface mapping, no extra lift | `depthTest: true`, transparent render queue, raycast disabled | Additive glow to reinforce border edge and terrain hover visibility. | -| 0.99 | Country border hover line | `country-boundaries.js` | `hoverAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | `depthTest: true`, transparent render queue, raycast disabled | Neon red-orange hover line; aligned with the normal borders and HD texture shell to avoid ghosting or floating; China and Taiwan share the same highlight group. | +| 0.97–0.99 | Country borders | `country-boundaries.js` | `lineAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48`; PMTiles tiles share at most 3 batched draw calls (`country-boundary-batch`, `country-admin1-batch`, `country-boundary-claim-batch`); claim lines have no extra lift | Raycast disabled | Line geometry has its own `renderOrder` and parent-tile persistence to prevent LOD blank gaps, while sharing the exact HD texture shell radius to avoid parallax during globe rotation. | +| 0.98 | Country border hover glow | `country-boundaries.js` | Same surface mapping, no extra lift | `depthTest: true`, transparent render queue, raycast disabled | Additive glow reinforcing full-perimeter border edge and coastline visibility. | +| 0.99 | Country border hover line | `country-boundaries.js` | `hoverAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | `depthTest: true`, transparent render queue, raycast disabled | Neon red-orange full-perimeter hover line (combining land borders and OSM coastlines with no country fill mask); aligned with normal borders and the HD shell; China and Taiwan share the same highlight group. | | 3 | Satellite footprint fill / Iridium coverage ring | `satellites.js`, `iridium-footprint-adapter.js` | `GROUND_FOOTPRINT_RENDER_ORDER` | depth-tested; Iridium adapter fill / ring use the same renderOrder | Footprint above land / texture / terrain and country borders, below compute centers and satellites. | | 3-4.5 | BGP collectors, event rings, and event markers | `bgp.js`, `interactable.js` | Collector markers use `BGP_COLLECTOR_RENDER_ORDER = 4.4`; event markers use `BGP_EVENT_RENDER_ORDER = 4.5`; overlays remain in BGP-owned groups | Screen-space Interactable picking; BGP collectors/events may use collision avoidance where appropriate | BGP collectors share the surface-facility band with vessels; BGP events share the compute-center band. | | 4.3 | AIS vessel track lines | `vessels.js` | `VESSEL_RENDER_ORDER - 0.1`; `CONFIG.earthRadius + VESSEL_CONFIG.track.altitudeOffset` | Follows vessel selection, not independently picked | Recent track for the selected vessel, below vessel markers. | @@ -111,3 +111,5 @@ Co-located markers share a compact projection stack across categories; screen co Regional news and compute retain the `#earth-region-callouts` root (z-index 20) and share flank/corridor assignment with object details through `callout-stage-arbitrator.js`, which assigns symmetric left and right flanks to bilateral `CN` and `US` spotlight peers via `bilateralPeerKey`. Expanded cards inside the regional root use 50, drag foreground 55, hover expansion 60–65, ordinary capsules 30, and dimmed/shrunk rear capsules 8, whereas spotlight and hover-expanded cards stay 100% opaque on the rear hemisphere while switching their connector to a dashed `.is-rear` rim guide and exposing a header rotate-to-front button. Compute hub drill-down overlays and stage logical AS route arcs follow strict shell separation and batching rules: China's eight National Compute Hubs render through a single GPU-instanced `createInteractableLayer` at `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` (`renderOrder = 4.58`); western green-hub `AdditiveBlending` pulse rings use `renderOrder = 4.42` (`depthWrite: false`); East-West synergy arcs, stage logical AS routes, country hover highlights, selected cable pulses, vessel tracks, and selected satellite orbits share the screen-space anti-aliased `surface-ribbon.js` pipeline (avoiding the Windows ANGLE 1px `THREE.Line` cap); and Iridium footprints run through GPU vertex projection in `iridium-footprint-adapter.js`, disposing geometry and materials immediately on hide or tour exit. + +The projected 3D city-label DOM layer `.geo-labels` (`geo-labels.js` + `hud.css`) sits at `z-index: 4` (above the WebGL canvas and below `.map-clusters` at `5` and `.satellite-labels` at `6`). Labels anchor their left dot via `earthSurfacePoint(lat, lon, R + 0.48)` (`translate(-3px,-50%)`), cull back-hemisphere points via `isSurfaceAnchorVisible`, and run priority collision/obstacle avoidance against HUD panels, cluster badges, regional cards, and satellite close-up labels. diff --git a/docs/technical/en/frontend-admin-frontend-context.md b/docs/technical/en/frontend-admin-frontend-context.md index e1cdd0bf..5be912c8 100644 --- a/docs/technical/en/frontend-admin-frontend-context.md +++ b/docs/technical/en/frontend-admin-frontend-context.md @@ -92,6 +92,14 @@ The Admin datasource page routes single-source trigger, table-selected trigger, This queue is a user-perception layer. Backend task status remains the only source of truth for running, completion, failure, and skipped decisions. +## Collected Data Layer Ledger + +`/data` ([DataList.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/DataList.tsx) and `pages/data-ledger/`) organizes review around Earth layer categories (synced with `?layer=`, defaulting to `compute`) backed by `/api/v1/data-ledger/*`: + +- Left-pane [LayerNav.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/data-ledger/LayerNav.tsx) reuses backend `PRODUCT_DEFINITIONS` counts across Earth layers while preserving `Raw Collected Records` (`?layer=raw`) for legacy `/api/v1/collected` filtering, dimension toggle, and export. +- `layer=compute` mounts [ComputeLedger.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/data-ledger/ComputeLedger.tsx) with 5 facility-type filters, 4 location status buckets (`located`, `needs_confirmation`, `terminal`, `pending`), country/keyword search, 28px `TableActionButton` actions (`Relocate` with `force: true` and `Edit coordinates` dialog reusing `/api/v1/visualization/compute-centers/{source_id}/collect-location` and coordinate save endpoints), plus row details with sanitized reasoning and `/advisor/runs` links. +- Other layers (`satellites`, `cables`, `vessels`, `bgp`, `news`, `weather`, `geo`) render read-only paginated views via [LayerItemsLedger.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/data-ledger/LayerItemsLedger.tsx) inside the single-screen internal-scroll layout. + ## Admin Theme Slider The Admin sidebar theme switcher still reuses shared [SegmentedControl.tsx](/home/ray/dev/linkong/planet/frontend/src/components/SegmentedControl/SegmentedControl.tsx), while [styles.css](/home/ray/dev/linkong/planet/frontend/src/admin/styles.css) overrides the segment variables by `data-theme`: @@ -465,6 +473,14 @@ The image library supports upload/URL entry, attribution, licensing, enabled sta Under `/earth/card-images`, configuration GET/PUT, upload POST, targets GET and preview POST require administrators. Resolve and content-addressed files are public read-only routes. Configuration writes use revision checks and audit transactions. -## Multi-metric compute ledger and candidate review queue +## Multi-metric compute ledger, candidate review queue, and revision history -`ComputeComparisonSettings.tsx` powers `/earth-content?section=compute_comparison` within the Admin single-screen height chain (`height: 100%` + `min-height: 0`), keeping the header and six workspace tabs (Observations, AI structure, Innovation gap, Milestones & 8 Hubs, Sources, and Candidate queue) pinned while only the inner `Scrollbar` scrolls. Saves use optimistic revision locking and round-trip `structures`, `milestones`, and `national_hubs` intact; the Candidate queue connects to `/api/v1/situational-awareness/candidates` for excerpt extraction, manual approval/rejection, and one-click import into the draft. +`ComputeComparisonSettings.tsx` powers `/earth-content?section=compute_comparison` within the Admin single-screen height chain (`height: 100%` + `min-height: 0`), keeping the header, publish-note bar, and seven workspace tabs (Observations, AI structure, Innovation gap, Milestones & 8 Hubs, Sources, Candidate queue, and Revision history) pinned while only the inner `Scrollbar` scrolls. Saves use optimistic `publish_id` locking, preserve `structures`, `milestones`, `national_hubs`, and per-country `value_sources` (requiring a `publish_note` explaining same-denominator comparability whenever a share row mixes multiple sources), and append to the immutable revision ledger. The Candidate queue connects to `/api/v1/situational-awareness/candidates` with revision/new/period-conflict/duplicate badges, per-country old→new→delta comparison tables, mandatory matched reason codes and rationale on approve/reject, non-destructive per-country draft imports, and explicit confirmation dialogs on `period_label` conflicts; Revision history lists `/api/v1/data-products/compute/revisions` entries with diff summaries, actor metadata, publish notes, and presentation delivery status. + +## Global Real-Time Cloud & High-Res Basemap Workbenches (`weather` / `geo`) + +`EarthCloudMapSettings.tsx` mounts at `/earth-content?section=cloud_map` under the shared Admin single-screen (`height: 100%` + `min-height: 0`) shell and focuses strictly on live preview and Earth presentation controls: a 2:1 starry preview with SVG graticule and convective-cluster overlay, history frame scrubbing, global/regional KPIs, display toggles (live IR enablement, daytime GeoColor compositing, DIS optical-flow advection, cloud-top relief strength, timelapse playback, convective markers, opacity, reset), plus a read-only weather collector summary linking to `/datasources?product=weather` (`global_cloud_map`, `cloud_hd_tiles`, `global_wind_gfs`) and `/collection-management` (`采集器配置`). `EarthBasemapSettings.tsx` mounts at `/earth-content?section=basemap` to preview and configure the managed tile pyramid sources (`earth_imagery_sentinel2`, `earth_imagery_viirs_daily` under the new `geo` / `地理/底图` product domain, plus `cloud_hd_tiles`), disk LRU cache caps, per-source cache clearing, and viewport LOD switch altitude thresholds. + +## Bundled Built-in Preview Assets for Admin-Only Builds + +Production `planet_admin` images are built with `PLANET_FRONTEND_TARGET=admin` (`publicDir: false` in `frontend/vite.config.mts`, keeping `dist/earth/` strictly excluded), while backend default brand and static cloud configurations retain `/earth/assets/...` paths for the desktop offline Earth contract. To prevent Admin preview `` tags from falling through Nginx SPA `index.html` fallback as broken images, `earthBuiltinAssetsPlugin` in `frontend/vite.config.mts` maps `@earth-builtin-asset/*` imports directly to hashed files under `/assets/*.png` (`brand/earth-logo.png`, `brand/title-zh.png`, `brand/title-en.png`, `brand/lim-logo.png`, `earth_clouds_2048.png`). `resolveEarthPreviewAssetUrl()` in `frontend/src/admin/lib/earthBuiltinAssets.ts` resolves those built-in paths only at preview render time in `EarthBrandPreview` and `EarthCloudMapSettings`, leaving persisted `/earth/assets/...` config values, form inputs, and user-uploaded `/earth-brand-assets/...` URLs untouched. diff --git a/docs/technical/en/location-pipeline-development.md b/docs/technical/en/location-pipeline-development.md index b4ede8fd..1d7755b5 100644 --- a/docs/technical/en/location-pipeline-development.md +++ b/docs/technical/en/location-pipeline-development.md @@ -68,8 +68,7 @@ class LocationResolver(Protocol): | `BuildsUponComputeCenterResolver` | `services/compute_center_locations.py` | Epoch `builds_upon` parent-cluster campus inheritance from verified coordinates | | `lookup_wikidata_facility` | `resolvers/wikidata.py` | Async L1 Wikidata P625/P276 facility coordinate lookup | | `lookup_peeringdb_facility` | `resolvers/peeringdb_facility.py` | Async L1 PeeringDB `/api/fac` commercial colocation street/lat-lon lookup | -| `run_controlled_location_agent` | `location/agent_resolver.py` | Controlled L2–L4 4-step Tool-Calling agent (`fetch_source_url`, `web_search`, `geocode_verify`, `submit_location_result`) with terminal status persistence | -| `LocationLLMFallback` | `location/llm_fallback.py` | Structured fact-check fallback for non-tool-calling models with lat/lon range, country verification, and city downgrade guardrails | +| `run_location_workflow` | `location/workflow_tools.py` | Unified 9-node `location.resolve_unknown` DAG workflow via `dag_executor.py` (context normalization, cross-source/knowledge lookup, web research, cascade `geocode_verify`, L3 `evaluate_location_geo_guardrail`, and L4 terminal persistence; replaces retired `agent_resolver.py` and `llm_fallback.py`) | Nominatim is the geocoding service in the OpenStreetMap ecosystem. Given a place name, city, country, organization, or facility query, it returns possible coordinates, a display name, and structured address fields. It is useful for turning city/facility text into candidate coordinates, but it is not an authoritative fact registry and can match same-name places or broad administrative areas. Planet therefore treats Nominatim output as confirmation-required candidates and uses it with caching and rate limiting. @@ -92,7 +91,7 @@ StoredComputeCenterLocationResolver() The main map startup path is source coordinates first, then the database-backed current-location table. The table is `compute_center_locations`, keyed by `(source, source_id)`, and stores manually accepted locations or true coordinates migrated from source records. `init_db()` only migrates source records that already contain real coordinates; it does not import old hard-coded hints and does not run ROR, Nominatim, or LLM geocoding during startup. -Candidate collection is intentionally separate from rendering. `collect_location_candidates()` builds ROR and Nominatim/OpenStreetMap queries from source fields, but it does not emit the current `compute_center_locations` row as a candidate. If those regular candidates are empty, the API layer calls `LocationLLMFallback` through the current default AI Provider and only returns `source="llm_location_factcheck"` candidates with `needs_confirmation=true`. LLM candidates use a combined threshold made from the model self-score plus backend evidence scoring; when the LLM provides a credible city/country but no coordinates, the backend may fill city-level coordinates through Nominatim without increasing the evidence score. After a user accepts a candidate, the save endpoint upserts it into the dimension table; the next map refresh renders it through `StoredComputeCenterLocationResolver`. +Candidate collection is intentionally separate from rendering. `collect_location_candidates()` builds ROR and Nominatim/OpenStreetMap queries from source fields, but it does not emit the current `compute_center_locations` row as a candidate. When regular candidates are insufficient or deeper verification is requested, the API invokes `run_location_workflow()` (the unified 9-node `location.resolve_unknown` DAG) to combine cross-source hints, Wikidata/PeeringDB lookup, source/web evidence gathering, cascade Nominatim verification, and `evaluate_location_geo_guardrail` checks, returning evidence-backed confirmation-required candidates or terminal statuses (`undisclosed` / `multi_site` / `anonymous`). After a user accepts a candidate, the save endpoint upserts it into the dimension table; the next map refresh renders it through `StoredComputeCenterLocationResolver`. `resolve_compute_center_location()`, `resolve_compute_center_location_full()`, and `collect_location_candidates()` remain the domain API. `visualization.py` consumes that API and no longer owns coordinate hints, country-centroid fallbacks, or Nominatim details. diff --git a/docs/technical/en/manual.md b/docs/technical/en/manual.md index 9d97b6c5..b90b9fec 100644 --- a/docs/technical/en/manual.md +++ b/docs/technical/en/manual.md @@ -433,15 +433,15 @@ Docs supports: category navigation, Markdown rendering, tables and code blocks, ## Compute intelligence -Administrators maintain the multi-metric compute ledger in **Earth content → Compute comparison**, organized into six workspaces: **Observations**, **AI structure**, **Innovation gap**, **Milestones & 8 Hubs**, **Sources**, and **Candidate queue**. In addition to manual entry, administrators can extract candidate figures from report excerpts in the Candidate queue, review them manually, and import approved items into the draft; unreviewed candidates never go live. Global shares use the world denominator, absolute scale uses FP32 EFlop/s, and the China-US Relative Parity Index (`RPI = CN / US × 100`) plus bilateral shares are derived deterministically on the server. +Administrators maintain the multi-metric compute ledger in **Earth content → Compute comparison**, organized into seven workspaces: **Observations**, **AI structure**, **Innovation gap**, **Milestones & 8 Hubs**, **Sources**, **Candidate queue**, and **Revision history**. When extracting candidate figures from report excerpts, the queue compares each candidate against the live ledger to display old/new/delta values, change badges (Historical revision, New observation, Period conflict, or Duplicate), and denominator basis; approving or rejecting requires a matching reason category and rationale. Importing into a draft updates only revised countries while preserving original per-country sources for unchanged peers, and any share row mixing multiple sources requires a publish note documenting same-denominator comparability. Global shares use the world denominator, absolute scale uses FP32 EFlop/s, and the China-US Relative Parity Index (`RPI = CN / US × 100`) plus bilateral shares are derived deterministically on the server. -Innovation gap observations track the ISTIC Global AI Innovation Index score gap (US minus China, narrowing `22.02 → 19.96 → 17.95` across 2023–2025) alongside compute share divergence. Sources referenced by observations, structure rows, milestones, or national hubs cannot be deleted until dereferenced. Duplicate metric/year entries, structure shares not totaling 100%, or global shares exceeding 100% are rejected. Concurrent saves return `409 Conflict` while preserving the local draft; restoring bundled defaults requires confirmation and is audited. +Innovation gap observations track the ISTIC Global AI Innovation Index score gap (US minus China, narrowing `22.02 → 19.96 → 17.95` across 2023–2025) alongside compute share divergence. Sources referenced by observations, structure rows, milestones, or national hubs cannot be deleted until dereferenced. Duplicate metric/year entries, structure shares not totaling 100%, or global shares exceeding 100% are rejected. Concurrent saves return `409 Conflict` while preserving the local draft; restoring bundled defaults creates a fresh audited revision visible in **Revision history**. -Open the analysis panel beside Compute Centers to choose among five strategic lenses (CN-US Relative Parity RPI, Global total share, Global AI compute share, Frontier cluster power share, and Absolute FP32 scale) or launch the **4-Act Compute Posture Tour** and **5-Act BGP Route Incident Playback**. When region cards are enabled on desktop, China and the United States occupy symmetric left and right spotlight corridors. When an anchor rotates behind the globe, card typography stays 100% opaque while the connector switches to a dashed rim guide and the header exposes a **Rotate to front view** icon button instead of raw "Far side" text. +Open the analysis panel beside Compute Centers to choose among five strategic lenses (CN-US Relative Parity RPI, Global total share, Global AI compute share, Frontier cluster power share, and Absolute FP32 scale), switch the **Published revision**, or launch the **4-Act Compute Posture Tour** and **5-Act BGP Route Incident Playback**. Selecting a historical revision displays a top banner with a **Return to current** button while synchronizing both cards and Copilot to that revision's figures and conclusions. Clicking the provenance button beside any hero metric opens the **Lineage Drawer** showing source excerpts, page/locator, SHA-256 digest, observation/report/ingestion/publish timestamps, and revision history (public views redact reviewer names and raw internal notes, while signed-in administrators see full attribution). When region cards are enabled on desktop, China and the United States occupy symmetric left and right spotlight corridors. When an anchor rotates behind the globe, card typography stays 100% opaque while the connector switches to a dashed rim guide and the header exposes a **Rotate to front view** icon button instead of raw "Far side" text. Each strategic compute card presents five narrative layers: hero metric with global denominator dilution attribution, the CN-US RPI duel bar, 5-mode pills plus domestic AI compute structure bar (e.g., China `81%` AI vs Global `85%`), side-by-side Divergence Corridor and Innovation Gap Convergence SVG charts with milestone flags, a sanitized posture brief (zero chain-of-thought leakage), and action controls. Clicking **8 National Hubs** overlays China's eight East-Data-West-Compute hubs, western green-power pulse rings, and East-West synergy arcs on the 3D globe. -Open the **Posture Workbench** directly from the Layer panel header, the **BGP Incident Forensics** button on the BGP layer row, or **Forensic Investigation** inside any BGP anomaly card. The workbench maintains multi-turn context across natural-language follow-ups, switches instantaneously among **Workbench**, **Chart**, **Table**, **Trend**, **Attribution**, and **One-Pager** presets, and enforces **Retrospective**, **As Known Then**, or **Live** knowledge boundaries. Pinning a result opens a side-by-side comparison slot on wide screens or docks into top Pinned Tabs on compact/mobile viewports; **Subscribe Watch** monitors future posture deltas, and **Export** downloads a Markdown brief locked to the exact frozen revision. Dragging or zooming the globe during a stage tour halts camera flight immediately, and new background posture updates wait in a queued badge while you explore manually. +Open the **Posture Workbench** directly from the Layer panel header, the **BGP Incident Forensics** button on the BGP layer row, or **Forensic Investigation** inside any BGP anomaly card. Launching Copilot from a compute card binds the session to the card's active published revision, metric mode, and focus year; if you later switch mode or revision on the card, Copilot surfaces a mismatch banner in both the narrative and chart areas with a **Re-evaluate for current view** action. The workbench maintains multi-turn context across natural-language follow-ups (including asking why a figure changed to inspect revision rationale under the same revision), switches instantaneously among **Workbench**, **Chart**, **Table**, **Trend**, **Attribution**, and **One-Pager** presets, and enforces **Retrospective**, **As Known Then**, or **Live** knowledge boundaries. Pinning a result opens a side-by-side comparison slot on wide screens or docks into top Pinned Tabs on compact/mobile viewports; **Subscribe Watch** monitors future posture deltas, and **Export** downloads a Markdown brief locked to the exact frozen revision. Dragging or zooming the globe during a stage tour halts camera flight immediately, and new compute revision notices or posture updates wait in a queued badge while you explore manually—auto-playing when idle with an explicit note that historical restatements do not represent current-period capacity jumps. The bundled authoritative ledger covers verified 2020–2024 and 2025-H1 observations (e.g., 2024 global compute share US `44%` vs CN `23%` on a `~2210 EFlop/s` global denominator; AI compute share US `48%` vs CN `25%`). Selecting an unreleased year such as `2026` explicitly displays pending-release status alongside the latest verified period without fabricating backfilled numbers. National report metrics remain strictly separate from public facility counts. @@ -460,7 +460,7 @@ Selecting a satellite shows an open predicted arc with highlights moving in the Retriggering a datasource creates a new task while older failures remain in the failed group. Task Status uses a checklist icon, distinct from Refresh. CelesTrak can reuse valid recent download cache; each new collection attempt still gets its own task and updates collected data. -Display → Satellites → Close-up labels defaults on; turning it off hides satellite map names while retaining detail cards. The zoom-threshold slider below the switch ranges from 250% to 500% (default 400%); labels appear at or above the selected zoom and hide below it. The count slider sets a saved limit of 5–36 labels (default 36); occlusion or limited space may result in fewer visible labels. Sky brightness ranges from 0–200%, defaulting to 100%. Both choices persist. Expanded regional cards follow smoothly within assigned vertical space without decorative floating. Hover and a short interval after leaving pause automatic region-focus changes. Capsules temporarily expose complete content and actions while existing cards continue following geographic anchors. Compute legend category counts describe currently located markers. +Display → Satellites → Close-up labels defaults on; turning it off hides satellite map names while retaining detail cards. The zoom-threshold slider below the switch ranges from 250% to 500% (default 400%); labels appear at or above the selected zoom and hide below it. The count slider sets a saved limit of 5–36 labels (default 36); occlusion or limited space may result in fewer visible labels. Display → City Labels also defaults on: as you zoom into the globe, country capitals, major cities, and provincial/state seats fade in progressively in the current interface language while avoiding HUD panels and facility markers. Sky brightness ranges from 0–200%, defaulting to 100%. Both choices persist. Expanded regional cards follow smoothly within assigned vertical space without decorative floating. Hover and a short interval after leaving pause automatic region-focus changes. Capsules temporarily expose complete content and actions while existing cards continue following geographic anchors. Compute legend category counts describe currently located markers. Surface aggregates appear as solid numbered circles. Click to expand members; only co-located or extremely close geographic markers form compact stacks at their location, with exposed clickable edges. Ordinary markers stay at their real projected positions. Selecting a rear icon brings it forward and opens its details; clearing focus restores its original position. Ordinary groups split above 250%; no aggregate badge remains at 500%, and co-located markers expand directly. diff --git a/docs/technical/en/ops-runbook.md b/docs/technical/en/ops-runbook.md index 5a9065de..c912398d 100644 --- a/docs/technical/en/ops-runbook.md +++ b/docs/technical/en/ops-runbook.md @@ -469,9 +469,9 @@ uv run pytest backend/tests/test_otp_service.py 1. In the console, open `Operations and Configuration -> Earth Content -> Boundary Precision` to save boundary source configuration. The local config is written to `config/earth-boundary-sources.local.json`; do not commit it. 2. Click "Build high precision boundaries", or switch the Earth toolbar settings gear to High Precision for the first build. The backend downloads the three source packages to `data/earth-boundary-sources/`, writes the source manifest, and invokes the PMTiles build script. 3. The builder requires `tippecanoe` and `pmtiles` on PATH. Missing tools return a clear API error and do not write data-source collection records. -4. A successful production build outputs `frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles` and its manifest. -5. After deployment, open Earth, enable "Border Lines", and inspect China's southeast coast, Taiwan, Hainan, the South China Sea, Zangnan, Kosovo, and Gaza for hover behavior and boundary policy. -6. If no high-precision manifest/PMTiles exists locally, Earth uses the bundled `frontend/public/earth/data/countries-admin0.min.geojson` fallback. If high-precision assets exist but tile requests fail, troubleshoot PMTiles range requests, manifest provider, Nginx `.pmtiles` static serving, and sha256 consistency. +4. A successful build writes versioned artifacts into the backend boundary data volume (`backend/data/earth-boundaries/` by default) and serves `earth-boundaries..pmtiles`, `hover-index..json`, `hover-borders..json`, and `geo-labels..json` via `/api/v1/earth/boundaries/manifest` and `/api/v1/earth/boundaries/files/{name}` (`GET`/`HEAD`, HTTP `Range`, immutable caching). +5. After deployment, open Earth, enable "Border Lines", and inspect China's southeast coast, Taiwan, Hainan, the South China Sea, Zangnan, Kosovo, and Gaza for hover behavior, boundary policy, and tiered city labels. +6. If no high-precision manifest/PMTiles exists locally, Earth uses the bundled `frontend/public/earth/data/countries-admin0.china-pov-v1.geojson` fallback. If high-precision assets exist but tile requests fail, troubleshoot `/api/v1/earth/boundaries/files/{name}` `Range` requests, manifest provider, reverse-proxy forwarding, and `sha256` consistency. ## Publish locally and deploy production releases automatically diff --git a/docs/technical/en/platform-data-flows.md b/docs/technical/en/platform-data-flows.md index 3ab2570d..3c9c3e00 100644 --- a/docs/technical/en/platform-data-flows.md +++ b/docs/technical/en/platform-data-flows.md @@ -85,6 +85,17 @@ Compute centers represent supercomputers, AI GPU sites, model-platform facilitie - **Delete semantics**: deleting TOP500 or similar sources refreshes `computeCenters`; changing the location table also refreshes the layer. The default is `reload`, because location updates do not always need an immediate clear. - **Common failure**: collection finished but Earth count did not change. Check visualization cache, location rows, and adapter coverage. +### Compute Ledger Revisions, Dual Timelines, and Read-Time Lineage + +Curated national/regional compute observations operate independently from facility samples on top of the immutable `compute_configuration_revisions` ledger (`system_settings` category `compute_comparison` acts only as a synchronized current-revision cache; resets insert a new UUID revision without deleting rows): + +- **Dual-timeline semantics**: + - `cutoff_at` (`time_basis=as_known_then`) filters observations by report publication date; per-country `value_sources` drop only the post-cutoff country while retaining earlier-reported peers in the same year. + - `as_of` / `publish_id` replay the system publish timeline across `GET /data-products/compute/series`, `GET /situational-awareness/posture/compute`, and Copilot sessions/turns; timestamps earlier than the initial baseline return `snapshot_unavailable: true` instead of falling back to live configuration. +- **Candidate extraction, deduplication, and gated review**: `POST /situational-awareness/candidates/extract` deduplicates by `dedupe_fingerprint`, inserts immutable `EvidenceRecord` entries (`content_sha256`, `locator`, `excerpt`) without overwriting existing rows, and computes per-country `comparison` metadata (`historical_revision`, `period_conflict`, denominator); `POST /candidates/{id}/review` enforces decision-matched `reason_code` and rationale text, returning 409 once `published_publish_id` is recorded. +- **Revision-driven presentations and retry**: `PUT /data-products/compute/configuration` and `POST /configuration/reset` invoke `process_compute_revision_presentation` directly from the committed revision's `diff_summary` (decoupled from BGP's `classify_snapshot_delta`), emitting `compute-revision-notice` contracts for any non-zero observation delta (including small historical restatements and B→A resets) with monotonic `revision = revision_row.id` and `publish_id` deduplication; delivery errors mark `presentation_status=failed` for startup, 5-minute scheduled, and `POST /proactive/evaluate` retries. +- **Read-time lineage derivation and redaction**: `GET /data-products/compute/lineage` derives provenance at read time (no mirror/relation table) by walking up to 50 prior `compute_configuration_revisions` rows and joining `compute_evidence_candidates` and `evidence_records` for current value, source details/SHA-256, object-level timestamps (observation period, report publication date, candidate ingestion time, effective publish time), and revision history. Public and non-admin callers on `/lineage` and `/revisions/public` receive redacted responses (reviewer/publisher names replaced with `"已人工复核"`, raw `review_reason`/`publish_note` omitted, only localized reason categories retained). + ## BGP BGP data shows route collectors, anomalies, incidents, diffusion rings, and situation summaries. Earth does not render raw BGP rows directly; it renders projected observations, anomalies, and incidents. This is the most common path where deleting raw data can leave old objects visible. diff --git a/docs/technical/zh/backend-collectors.md b/docs/technical/zh/backend-collectors.md index 4ae7e06a..bb969ec2 100644 --- a/docs/technical/zh/backend-collectors.md +++ b/docs/technical/zh/backend-collectors.md @@ -98,7 +98,7 @@ AIS 船只类采集器和其它 `CollectedData` 采集器的落库路径不同 `vessel_current_state` 的动态位置只允许被更新观测时间更晚的数据覆盖;名称、船型等静态字段按非空和来源优先策略合并。Earth snapshot 默认只返回有效窗口内的当前船只,避免高频 AIS 历史数据影响地球渲染性能。 -智能星球国界不再属于采集器体系。它是智能星球静态渲染资产,由控制台 `运维与配置 -> 智能星球内容 -> 国界精度` 维护源配置,并由 `/api/v1/earth/boundaries/*` 构建 `frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles`。本地没有高精 PMTiles 时,前端会使用仓库内置的低精度 GeoJSON 作为 fallback,不会向 `CollectedData` 写入国界记录。 +智能星球国界与城市地名清单不再属于采集器体系,而是作为智能星球静态渲染资产,由控制台 `运维与配置 -> 智能星球内容 -> 国界精度`(`PUT /api/v1/earth/boundaries/config`)维护源配置,并由 `/api/v1/earth/boundaries/*`(含 `/status`、`/manifest`、`/build`、`/build/status` 及支持 `GET`/`HEAD`、HTTP `Range` 与不可变缓存、隔离为 `rate_limit_tier="tile"` 的 `/files/{name}`)构建并分发 `earth-boundaries..pmtiles`、`hover-index..json`、`hover-borders..json` 与 `geo-labels..json`(`planet-earth-geo-labels/v1`,基于 `earth_populated_places` 与中国 POV 规则生成)。本地未构建高精产物时,前端继续使用内置低精度 `countries-admin0.china-pov-v1.geojson` fallback,不会向 `CollectedData` 写入国界记录。 TOP500 和 Epoch AI 算力数据的公开源不总是提供可用经纬度。Epoch 官方 CSV 的 `Location` 可能只有国家或为空,即使行中存在经纬度,也不能仅凭它当作精确 site。Earth 统一算力中心接口在主地图启动链路中只使用有效源坐标或 `compute_center_locations` 维表坐标;不可渲染记录保留在完整 `unresolved` 列表,不通过本地注册表、国家中心或猜测总部自动渲染。`precise`/`site` 保持源坐标;城市级和待确认点只可按 `source` + `source_id` 生成确定性的展示偏移,原坐标不改写。用户手动采集候选时,后端会用源字段调用 ROR 组织注册 API 和 Nominatim/OpenStreetMap 在线搜索;候选经前端保存后写入 `compute_center_locations`,后续地图刷新再从维表渲染。 diff --git a/docs/technical/zh/earth-frontend-context.md b/docs/technical/zh/earth-frontend-context.md index 0c952a75..8a39ebdd 100644 --- a/docs/technical/zh/earth-frontend-context.md +++ b/docs/technical/zh/earth-frontend-context.md @@ -504,7 +504,7 @@ Earth 设置面板当前由 [controls.js](/home/ray/dev/linkong/planet/frontend/ SGP4 传播输出是惯性系位置,不能直接当成 Earth 的经纬度固定坐标使用。`satellites.js` 会用当前时间的 `gstime` 把 ECI/TEME 位置转换到 ECF,再映射到 `latLonToVector3()` 使用的 Three.js 坐标轴。卫星点和短尾迹使用随采样时间变化的地固坐标,表示相对当前地球表面的实际位置;锁定后的预测轨道线使用锁定时刻固定的 `gstime`,把未来一个完整周期的惯性轨道投到当前地球姿态上显示为开放弧线;不追加首点或用直线强制封口,轨道面倾角与详情卡一致。流光按累计弧长和未来采样方向移动。fallback 预测轨道也必须使用真正的 RAAN + inclination 轨道平面公式,不能把 inclination 当成恒定纬度。 -国界精度偏好独立存储在 `country-boundaries.js` 的 `planet.earth.boundaries.highPrecisionEnabled`。未开启高精时,即使本机已经有高精 manifest/PMTiles,也继续加载低精 `countries-admin0.min.geojson` fallback;开启高精但高精产物缺失时,智能星球工具栏设置会调用 `/api/v1/earth/boundaries/build` 启动后台构建并轮询进度。构建成功后调用 `reloadCountryBoundaries()` 热切换,不再刷新整个页面。国界 hover 与 tooltip 解耦:只要地表坐标落在国界 polygon 内就保持高亮;如果鼠标同时命中卫星、船只、BGP 等 interactable,tooltip 显示 interactable 信息,但国界高亮不应闪烁。 +国界精度偏好独立存储在 `country-boundaries.js` 的 `planet.earth.boundaries.highPrecisionEnabled`。未开启高精时,即使本机已经有高精 manifest/PMTiles,也继续加载内置低精 `countries-admin0.china-pov-v1.geojson` fallback;开启高精但高精产物缺失时,智能星球工具栏设置会调用 `/api/v1/earth/boundaries/build` 启动后台构建并轮询进度。构建成功后调用 `reloadCountryBoundaries()` 热切换,不再刷新整个页面。国界 hover 与 tooltip 解耦:只要地表坐标落在国界 polygon 内就保持高亮;如果鼠标同时命中卫星、船只、BGP 等 interactable,tooltip 显示 interactable 信息,但国界高亮不应闪烁。 ## 当前地形链路 @@ -759,3 +759,31 @@ BGP 观测站以 collector 编号建立标记索引。共享索引不登记空 I - **贴地影响范围与阶段导演指令**(`influence-zones.js` + `scene_directives.py`):支持 AI / 场景指令下发 `influence_zones`(国家/区域预设多边形及大圆辐射区),通过单次离屏 `scratchCanvas` 模糊合成与层级排序(`tier` / `z_index`)渲染可配置颜色、透明度、`edge_mode`(`sharp` / `soft`)及入场扫光;保持 `renderOrderBase = 0.965`,位于高清地表之上、国界与交互图标之下。 - **行星本体光影与丝带管线**:`earth-surface-material.js` 与 `earth.js` 结合本地 `earth_clouds_2048.png` 实现三阶瑞利散射晨昏过渡、海面掠射高光与地表云影投影;`surface-ribbon.js` 为国界 hover、BGP 雷达/高空路由、选中海缆流光、船舶尾迹及选中卫星轨道提供统一屏幕空间抗锯齿发光丝带;`iridium-footprint-adapter.js` 将 Iridium 足迹迁入 GPU 顶点投影。 - **卡片连线优先一折与管理写鉴权**:`callout-connector.js`(`applyPreferredOneBendAnchor`)在主轴跨度与卡片可用边长充足时优先偏出单一折点(严格保持 `<= 1` 折,短距或紧凑胶囊平滑退化为 2 点直线);`admin-write-auth.js` 统一管控 Earth 侧算力中心位置采集与保存的管理员会话鉴权及 `/login` 引导。 + +### 全球实时红外云图数据管线与双帧平滑着色器 + +- **数据优先的多星云图、高分瓦片金字塔与 GFS 全球风场**(`backend/app/services/earth_clouds.py` + `earth_clouds_fx.py` + `earth_tiles.py` + `earth_wind.py`): + - `global_cloud_map`(`id=34`,`product=weather`):默认输出 **`4096x2048`**(采集超时默认 45s),在五星 Band13/10.8μm IR 连续高斯羽化合成基础上,增加带通暖低云门控的日间可见光融合(`fuse_daytime_visible_into_density`,收紧至 74° 边缘羽化、剔除 `-8°C` 以下高原积雪与 EUMETView `255` 裁切纯白误判)、日间 GeoColor/可见光合成(`frames/_vis.webp`)与 `cv2.DISOpticalFlow_create` 光流位移场(`flows/.webp`),输出 `/api/v1/earth/clouds/{meta,frames/{ver},frames/{ver}/visual,flows/{ver}}`;静态 `./assets/earth_clouds_2048.png` 与 8K 静态底图继续作为兜底。 + - 受控瓦片金字塔代理(`cloud_hd_tiles` `id=35` 归属 `weather`;`earth_imagery_sentinel2` `id=36` 与 `earth_imagery_viirs_daily` `id=37` 归属 `geo`):经 `BaseCollector` 定期预热 `z=0..warmup_max_zoom` 并提供 `/api/v1/earth/tiles/{source}/{z}/{x}/{y}.webp` 门控代理(严格校验 `DataSource.is_active` 与磁盘 LRU 上限);默认 `lod_switch_altitude = 1.85`、`cloud_hd_tiles_enabled = false`(由单一无缝 4K 全局云图提供全尺度连续云层;若管理员显式开启 `cloud_hd_tiles`,浏览器缓存头限制为 `max-age=300` 并同步应用暖低云带通门控)。 + - `global_wind_gfs`(`id=38`,`product=weather`):从 PacIOOS ERDDAP 拉取 NOAA NCEP GFS 全球 10m 风矢量(`ugrd10m`, `vgrd10m`)并归算到 `-180..180` 网格,持久化于 `data/earth-wind/`,提供 `/api/v1/earth/wind/{meta,grid/{ver}}`、`/api/v1/data-products/wind/{summary,point}` 与 AI `query_wind_posture_tool`。 +- **三维升级着色器、三档可选色调、RGB 频域融合、Windy 风场流线与线性云图采样**(`constants.js` + `cloud-map.js` + `earth-surface-material.js` + `spherical-tile-layer.js` + `wind-layer.js` + `controls.js` + `satellites.js` + `earth_clouds_fx.py`): + - **三档可选地表色调(`SURFACE_COLOR_GRADES`,默认 `classic-083`)**:通过 `uLandGradeGain`、`uLandCoolBias`、`uDiffuseFloor`、`uToneMapMode` 与冰雪保留因子 `iceFactor` 显式参数化 `classic-083`(经典通透,默认:无偏黄、深靛蓝海洋、雪峰纯白、`opacity=0.38` 轻薄云层)、`fresh-natural`(鲜嫩自然:保色度 C1 高光肩部)、`balanced-satellite`(均衡遥感),经设置面板「显示 -> 地表色调」(`EARTH_SETTINGS_VERSION = 21`)切换且加载前后零色彩跳变;「地表亮度」(`0.65..1.6`,默认 `1.0`)联动调节 `uSurfaceBrightness`。 + - **RGB 三通道频域高低频细节融合**(`createEarthSurfaceTileMaterial`,缓存键 `earth-surface-tile-v5`):以 `tileLowRgb` / `rgbRatio` / `transferRatio` 将 Sentinel-2 10m 真彩高频肌理注入所选 8K 底图与色调方案,抹平卫星扫描斜条带并保证 50%→500% 缩放色彩严格一致;瓦片容器与风场容器均使用普通 `THREE.Object3D` 保持 `groupOrder = 0`;`uLandMask` 分支统一采用 `#ifndef LEGACY_TEXTURE_ENCODING surfaceSRGB(mask)`。 + - **Windy 风格弧形风场丝带**(`wind-layer.js`):3,600 粒子 × 8 段历史弧形微轨迹(`CONFIG.earthRadius + 1.6`,`renderOrder = 1.04`,`THREE.AdditiveBlending` 霜白/冰青冷色调,尾迹渐隐至 0),与橙/紫/绿高轨卫星点彻底区隔。 + - **线性云图空间与 4K 并行解码**(`cloud-map.js` + `earth_clouds.py` + `earth_clouds_fx.py`):`uCloudMap` 与 `uCloudVisualMap` 统一标为 `THREE.NoColorSpace` 消除线性密度二次 sRGB 变暗发灰,后端通过 `decode_visual_payloads` 复用解码数组、并发拉取 IR+VIS WMS 并剔除 EUMETView `[255,255,255]` 裁切纯白方块;6 位数 NORAD 编码为 USSF Alpha-5,`predictedOrbitLine` 每帧同步地球自转。 + - **气象图层收拢、显示设置板块化与 v22 默认值**(`constants.js` + `index.html` + `controls.js` + `layer-startup-tasks.js`):左侧图层列表将云图与风场收拢为单一默认开启的「气象」总开关(`#toggle-weather`),并在设置 → 显示新增「气象」板块(以可扩展 `WEATHER_LAYER_DEFINITIONS` 多选胶囊分别开关「大气云图」与「全球风场」,默认均开启,并收纳实时卫星云图与云图历史演变开关),同步将新闻二级小标题更名为「新闻」;`EARTH_SETTINGS_VERSION = 22` 默认星空亮度 `200%`、地形透明度 `68%`、卫星近景标签阈值 `330%` / 默认数量上限 `16`(滑块范围仍为 `5..36`)、默认轨道高度压缩 `0%`。 + +### 高精 PMTiles 矢量边界与 3D 城市分级标注 + +- **高精矢量边界管线与多层缓存**(`country-boundaries.js` + `boundary-tile-worker.js` + `boundary-tile-decode.js` + `boundary-tile-cache.js` + `earth-preload.js` + Electron `protocol-core.ts`): + - **4 档视口缩放层级与海岸线闭合**:`tileZoomThresholds` 划分为 `z2`(0x)/ `z4`(1.3x)/ `z6`(2.3x)/ `z8`(3.8x),Natural Earth 国界与省界(`boundary_admin0` / `boundary_disputed_internal` / `boundary_admin1`)在 `z6` 饱和并用父瓦片跨至 `z8`,`z8` 专注细化 OSM 海岸线(`coastline`);后端构图通过 `earth_boundary_geometry.py` 按海岸线自动吸合/延伸/裁切临海端点并在 `2px` `THREE.NoColorSpace` (`flipY=true`) 跨日界线海陆掩膜纹理上消缺。 + - **无闪烁调度、防投毒与 GPU 合批**:使用尾缘防抖调度 + 单调 `generation` 取消过期并发队列 + 屏幕中心优先加载,通过 `resolveDisplayTiles` 保留已就绪父瓦片直至可视子瓦片全部就绪,合并为 `country-boundary-batch` / `country-admin1-batch` / `country-boundary-claim-batch` 最多 `<= 3` 个 GPU draw call;仅在 `getZxy()` 正常返回空瓦片时记录空缓存(HTTP 429/网络异常绝不写入负缓存),`ResilientPmtilesCache` 自动驱逐失败 Promise 并在浏览器(IndexedDB + `force-cache` + `earth-preload.js` + `prewarmBoundaryTiles`)与 Electron(`userData` 磁盘 Range 缓存)实现重启/刷新零远端重复请求;国家 hover(`hover-borders..json` + PMTiles 海岸线抽取)渲染完整陆地国界与海岸线霓虹描边,不叠盖整国暗红蒙版。 +- **3D 城市分级标注**(`geo-labels.js` + `constants.js` + `hud.css` + `layer-startup-tasks.js` + `controls.js`): + - 在高精边界启动任务结束后读取 manifest 中的 `geoLabels`(`geo-labels..json`,经 `earth-preload.js` 与 IndexedDB `boundary-tile-cache.js` 持久化缓存),基于 `earthSurfacePoint(..., CONFIG.earthRadius + 0.48)` 锚定左对齐圆点(`translate(-3px,-50%)`)并通过 `isSurfaceAnchorVisible`(`occlusionRadiusFactor = 0.999`)裁除背面半球城市。 + - 按当前视口缩放平滑渐显 3 级层级:Tier 1(`1.7x..2.05x` 首都 / 直辖 / 特区 / 重点人口枢纽)、Tier 2(`2.75x..3.15x` 区域与主要城市)、Tier 3(`3.75x..4.2x` 省级/州府等行政中心);桌面最多同时展示 `28` 个、移动端最多 `14` 个标签,严格按层级优先级与碰撞盒避让 `#earth-region-callouts`、`.hud-panel`、`.map-cluster-badge` / `.map-cluster-child` 及 `.satellite-map-label`(零 DOM 重叠),随 `onEarthLocaleChange` 在 `zh`/`en` 间实时切换,并在桌面/移动端设置 → 显示提供「城市地名标注」(`[data-geo-labels-toggle]`,默认开启)。 + +### 算力台账版本切换、血缘抽屉与参谋同源校对 + +- **系统发布版本回放与顶部警示条**(`compute-topic.js` + `compute-topic.css`):算力配置面板与移动端设置新增「系统发布版本」下拉选项(读取脱敏公共接口 `/api/v1/data-products/compute/revisions/public`),支持与「参考期 / 口径」正交切换并同步向 `/series` 与 `/posture/compute` 透传 `publish_id` / `as_of`;查看历史版本时卡片与配置区顶部展示「正在查看 {时间} 发布的版本(非当前)」及「回到当前」按钮,早于基线时展示「历史快照不完整」。 +- **逐国溯源与血缘抽屉**(`compute-topic.js` + `compute-topic-model.js`):主指标旁新增血缘触发按钮,优先按逐国 `evidence_by_code` 定位出处并请求 `/api/v1/data-products/compute/lineage`(仅在本地会话角色为 `admin`/`super_admin` 时附带 Bearer 凭证以展示复核人姓名与理由原文,公共访问与普通用户保持脱敏视图),在 `#compute-evidence` 内展示当前值、报告原文摘录、页码与 SHA-256、对象级四项时间线及修订历史。 +- **参谋同源绑定与视图失配提示**(`situational-copilot.js` + `workbench-blocks.js` + `main.js`):算力卡片打开参谋时同步透传 `publishId` / `asOf` / `mode` / `focusYear`,并监听 `earth:compute-view-changed` 将后端 `view_spec` 中的 `(publish_id, mode, focus_year)` 与卡片实时状态比对;若卡片切换口径、年份或发布版本,参谋在文字区与图表工作台区**同步**显示「本结果基于 {版本/口径},与当前地球视图不同」及「按当前视图重新研判」按钮,确保图文永不静默跨口径混排。`stage-narrative-player.js` 为 `compute-revision-notice` 显示「算力数据修订」标签并在演播完成后联动刷新最新 `publishId`。 diff --git a/docs/technical/zh/earth-layer-style-reference.md b/docs/technical/zh/earth-layer-style-reference.md index 469dbaf8..a548f400 100644 --- a/docs/technical/zh/earth-layer-style-reference.md +++ b/docs/technical/zh/earth-layer-style-reference.md @@ -75,38 +75,49 @@ | 正式名称 | 变量名 | 当前值 | 使用位置 / 说明 | | --- | --- | --- | --- | -| 国界瓦片 manifest | `COUNTRY_BOUNDARY_CONFIG.tileManifestPath` | `"/earth/data/boundaries/v1/manifest.json"` | 高精 PMTiles manifest;缺失时使用低精度 fallback | -| 国界瓦片 provider | `COUNTRY_BOUNDARY_CONFIG.tileProvider` | `"auto"` | 优先高精 PMTiles/MVT,缺失时降级到 legacy GeoJSON | -| PMTiles 产物路径 | `COUNTRY_BOUNDARY_CONFIG.pmtilesPath` | `"/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles"` | 生产单文件 PMTiles/MVT artifact | -| 低精度 fallback | `COUNTRY_BOUNDARY_CONFIG.legacyFallbackPath` | `"/earth/data/countries-admin0.min.geojson"` | 本地未构建高精国界时的缺省海陆基座和 hover 数据 | -| MVT 图层名 | `COUNTRY_BOUNDARY_CONFIG.mvtLayerNames` | `boundary_admin0 / boundary_disputed_internal / coastline / claim_line` | PMTiles provider 解码时读取的固定 layer 名 | -| 国界瓦片基础路径 | `COUNTRY_BOUNDARY_CONFIG.tileBasePath` | `"/earth/data/boundaries/v1/"` | PMTiles manifest 基础路径 | -| 国界瓦片缩放阈值 | `COUNTRY_BOUNDARY_CONFIG.tileZoomThresholds` | `1.6 -> z5`, `2.8 -> z6`, `3.4 -> z7`, `4.0 -> z8`, `4.6 -> z9`, `5.2 -> z10` | 生产 PMTiles zoom 选择 | -| 国界瓦片缓存上限 | `COUNTRY_BOUNDARY_CONFIG.tileCacheLimit` | `150` | 前端已加载瓦片几何的 LRU 缓存条目数 | -| 国界瓦片 debounce | `COUNTRY_BOUNDARY_CONFIG.tileDebounceMs` | `180` | 视野变化后请求可见瓦片前的防抖时间 | +| 国界瓦片 manifest | `COUNTRY_BOUNDARY_CONFIG.tileManifestPath` | `"/api/v1/earth/boundaries/manifest"` | 高精 PMTiles manifest;缺失或关闭高精时使用内置 fallback | +| 国界瓦片文件基址 | `COUNTRY_BOUNDARY_CONFIG.tileFilesPath` | `"/api/v1/earth/boundaries/files/"` | PMTiles、`hover-index`、`hover-borders` 与 `geo-labels` 分发端点(支持 HTTP Range) | +| 国界瓦片 provider | `COUNTRY_BOUNDARY_CONFIG.tileProvider` | `"auto"` | 优先高精 PMTiles/MVT,缺失时降级到 policy fallback GeoJSON | +| 低精度 fallback | `POLICY_FALLBACK_URL` (`country-boundaries.js`) | `countries-admin0.china-pov-v1.geojson` | 本地未开启或未构建高精国界时的缺省海陆基座和 hover 数据 | +| MVT 图层名 | `COUNTRY_BOUNDARY_CONFIG.mvtLayerNames` | `boundary_admin0` / `boundary_disputed_internal` / `coastline`(boundary),`boundary_admin1`(admin1),`claim_line`(claim) | PMTiles provider 解码时读取的固定 layer 组 | +| 国界瓦片缩放阈值 | `COUNTRY_BOUNDARY_CONFIG.tileZoomThresholds` | `0 -> z2`, `1.3 -> z4`, `2.3 -> z6`, `3.8 -> z8` | 4 档瓦片切换阈值(`borderMaxZoom = 6`;`z8` 专用于细化 OSM 海岸线) | +| 国界瓦片缓存上限 | `COUNTRY_BOUNDARY_CONFIG.tileCacheLimit` | `640` | 前端已加载瓦片几何的 LRU 缓存条目数 | +| 国界瓦片 debounce | `COUNTRY_BOUNDARY_CONFIG.tileDebounceMs` | `180` | 视野变化后请求可见瓦片前的尾缘防抖时间 | +| 省界/州界缩放与外观 | `admin1MinViewZoom / FullViewZoom / Color / Opacity` | `2.0 / 2.8 / 0x9fd0ff / 0.26` | `country-admin1-batch` 随放大平滑淡入 | | 海洋填充色 | local `OCEAN_HEX` | `0x010609` | 海陆基座 canvas 背景 | | 陆地填充色 | `COUNTRY_BOUNDARY_CONFIG.landColor` | `0x080f1b` | 海陆基座 canvas 陆地 | | 海陆基座透明度 | `COUNTRY_BOUNDARY_CONFIG.landOpacity` | `1.0` | `MeshBasicMaterial.opacity` | | 海陆基座半径偏移 | `COUNTRY_BOUNDARY_CONFIG.landAltitudeOffset` | `0.32` | `country-land-ocean` 半径;与地球基座拉开以避免 50% 缩放时雪花/黑块闪烁 | | 海陆基座 renderOrder | `COUNTRY_BOUNDARY_CONFIG.landRenderOrder` | `0.86` | `country-land-ocean.renderOrder` | -| 海陆 mask 尺寸 | `landMaskWidth / landMaskHeight` | `2048 / 1024` | canvas / DataTexture 尺寸 | +| 海陆 mask 尺寸 | `landMaskWidth / landMaskHeight` | `2048 / 1024` | 2px 跨日界线 `NoColorSpace` (`flipY=true`) canvas / DataTexture | | 国界 tint 颜色 | `COUNTRY_BOUNDARY_CONFIG.tintColor` | `0x0b1830` | 高清材质关闭时 tint | | 国界 tint 半径偏移 | `COUNTRY_BOUNDARY_CONFIG.tintAltitudeOffset` | `0.32` | `country-tint` 半径 | | 国界 tint renderOrder | `COUNTRY_BOUNDARY_CONFIG.tintRenderOrder` | `0.2` | `country-tint.renderOrder` | | 国界线颜色 | `COUNTRY_BOUNDARY_CONFIG.lineColor` | `0x7fc7ff` | 普通国界线 | | 国界线透明度 | `COUNTRY_BOUNDARY_CONFIG.lineOpacity` | `0.58` | 普通国界线 opacity | -| 国界线 hover 时压暗透明度 | `COUNTRY_BOUNDARY_CONFIG.dimmedLineOpacity` | `0.18` | hover 时普通国界线 opacity | -| 国界线半径偏移 | `COUNTRY_BOUNDARY_CONFIG.lineAltitudeOffset` | `0.115` | 普通国界线半径;线层靠 renderOrder 和独立 geometry 叠加,不作为整球基座深度间距参考 | -| 国界线 renderOrder | `COUNTRY_BOUNDARY_CONFIG.lineRenderOrder` | `2.2` | 普通国界线层级 | -| 国界 hover 颜色 | `COUNTRY_BOUNDARY_CONFIG.hoverLineColor` | `0xff3b1f` | 霓虹红橘 | +| 国界线 hover 时压暗透明度 | `COUNTRY_BOUNDARY_CONFIG.dimmedLineOpacity` | `0.18` | hover 时普通国界线 opacity(仅作用于基底线,不污染 hover 高亮线) | +| 国界线半径偏移 | `COUNTRY_BOUNDARY_CONFIG.lineAltitudeOffset` | `0.48` (`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`) | 与高清地表完全同壳,消除旋转视差 | +| 国界线 renderOrder | `COUNTRY_BOUNDARY_CONFIG.lineRenderOrder` | `0.97` | 普通国界线层级 | +| 国界 hover 颜色 | `COUNTRY_BOUNDARY_CONFIG.hoverLineColor` | `0xff3b1f` | 霓虹红橘(无整国蒙版,融合陆界与 OSM 海岸线全周界高亮) | | 国界 hover 透明度 | `COUNTRY_BOUNDARY_CONFIG.hoverLineOpacity` | `1.0` | hover 实线 opacity | -| 国界 hover 半径偏移 | `COUNTRY_BOUNDARY_CONFIG.hoverAltitudeOffset` | `0.115` | hover 实线半径;与普通国界线同源几何对齐,避免高亮切换时出现重影 | -| 国界 hover renderOrder | `COUNTRY_BOUNDARY_CONFIG.hoverLineRenderOrder` | `2.3` | hover 实线层级 | +| 国界 hover 半径偏移 | `COUNTRY_BOUNDARY_CONFIG.hoverAltitudeOffset` | `0.48` (`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`) | hover 实线半径;与普通国界线及高清材质同壳对齐 | +| 国界 hover renderOrder | `COUNTRY_BOUNDARY_CONFIG.hoverLineRenderOrder` | `0.99` | hover 实线层级 | | 国界 hover glow 透明度 | `COUNTRY_BOUNDARY_CONFIG.hoverGlowOpacity` | `0.38` | glow 线 opacity | -| 国界 hover glow 线宽 | `COUNTRY_BOUNDARY_CONFIG.hoverGlowLineWidth` | `3` | glow `LineBasicMaterial.linewidth` | -| 国界 hover glow 层级偏移 | `COUNTRY_BOUNDARY_CONFIG.hoverGlowRenderOrderOffset` | `0.01` | glow renderOrder = `2.29` | +| 国界 hover glow 线宽 | `COUNTRY_BOUNDARY_CONFIG.hoverGlowLineWidth` | `3` | glow 线宽 | +| 国界 hover glow 层级偏移 | `COUNTRY_BOUNDARY_CONFIG.hoverGlowRenderOrderOffset` | `0.01` | hover glow 相对实线递增 `0.01` 偏移 | | 国界 hover glow 半径偏移 | `COUNTRY_BOUNDARY_CONFIG.hoverGlowRadiusOffset` | `0` | glow 与 hover 实线共用半径,避免海岸细节处双线错位 | +## 3D 城市地名标注 + +由 `geo-labels.js` 与 `.geo-labels`(`hud.css`,`z-index: 4`)负责渲染,基于 `earthSurfacePoint(..., R + 0.48)` 锚定左对齐圆点,并由 `isSurfaceAnchorVisible` 裁除背面城市: + +| 正式名称 | 变量名 | 当前值 | 使用位置 / 说明 | +| --- | --- | --- | --- | +| 默认显隐与同屏上限 | `defaultEnabled / maxVisibleDesktop / maxVisibleMobile` | `true / 28 / 14` | 受「显示 -> 城市地名标注」开关控制,桌面与移动端分档限流 | +| 扫描周期与背面遮挡 | `scanIntervalMs / occlusionRadiusFactor` | `160 / 0.999` | 160ms 冲突与障碍物重算,已选标签逐帧跟随并裁除背面半球 | +| 分级渐显阈值 | `GEO_LABEL_CONFIG.tierFade` | `1: 1.7..2.05`, `2: 2.75..3.15`, `3: 3.75..4.2` | Tier 1(首都/直辖/特区)→ Tier 2(主要城市)→ Tier 3(省会/州府)平滑淡入 | +| 分类视觉语义 | `data-kind` (`capital` / `megacity` / `major` / `admin1`) | 琥珀金 `11.5px` / 亮白 `11px` / 柔白 `10.5px` / 浅灰 `10px` | 首都配备 `6px` 柔光金色圆点;降级行政中心统一使用 `admin1` 弱化灰点样式 | + ## 真实地形 | 正式名称 | 变量名 | 当前值 | 使用位置 / 说明 | diff --git a/docs/technical/zh/earth-render-layer-order.md b/docs/technical/zh/earth-render-layer-order.md index 400bfbb6..a8e5ebb9 100644 --- a/docs/technical/zh/earth-render-layer-order.md +++ b/docs/technical/zh/earth-render-layer-order.md @@ -7,12 +7,12 @@ | 顺序类型 | 当前顺序 | 说明 | | --- | --- | --- | -| 控制面板顺序 | 海缆 → 卫星 → 算力中心 → 船只 → BGP → 地形 → 高清材质 → 大气云图 → 国界线 → 经纬线 | 由 `displayOrder` 控制,按操作关注度排列;卫星轨迹已迁到设置面板,不再作为图层列表项。 | -| 注册 / 启动加载顺序 | 经纬线 → 国界线 / 海陆基座 → 高清材质 → 大气云图 → 海缆 → 算力中心 → 船只 → BGP → 卫星 | 由注册顺序和 `startupPriority` 控制,按地表到天空排列;启动队列会先读取保存的图层可见状态,明确关闭的普通图层不预加载,高清材质关闭时不下载贴图;国界线图层例外,海陆基座始终预加载,保存状态只控制可交互国界线和 hover;轨迹和地形是依赖/可选显示层,不参与常规启动数据加载。 | +| 控制面板顺序 | 海缆 → 卫星 → 算力中心 → 船只 → BGP → 地形 → 高清材质 → 大气云图 → 10m 全球风场 → 国界线 → 经纬线 | 由 `displayOrder` 控制,按操作关注度排列;卫星轨迹已迁到设置面板,不再作为图层列表项。 | +| 注册 / 启动加载顺序 | 经纬线 → 国界线 / 海陆基座 → 高清材质 → 大气云图 → 10m 全球风场 → 海缆 → 算力中心 → 船只 → BGP → 卫星 | 由注册顺序和 `startupPriority` 控制,按地表到天空排列;启动队列会先读取保存的图层可见状态,明确关闭的普通图层不预加载,高清材质关闭时不下载贴图;国界线图层例外,海陆基座始终预加载,保存状态只控制可交互国界线和 hover;轨迹和地形是依赖/可选显示层,不参与常规启动数据加载。 | ## 地表图层栈 -算力专题沿用原算力中心 Interactable 图标、深度与层次顺序;国家/年份切换会替换该层数据并清除旧选中状态。专题 HUD 属于屏幕 UI,在 `main.js` 的指针排除列表中,不参与地球 picking;区域数据卡在屏幕空间由地理锚点牵引,背面不画穿球连线,设施详情复用原详情卡和移动端详情抽屉。高清地表由 `earth-surface-material.js` 的单次绘制 `ShaderMaterial` 负责,保持原有 R+0.48 网格、深度策略和地表拾取对象。四张 8K 底图仍由原控制器切换,成功后更新采样 uniform 并释放旧纹理,失败保留原图。法线、视线和真实太阳方向统一到世界坐标;土地哑光,海洋只有掠射角冷色反射,没有白色镜面高光。海洋区分优先复用现有海陆地理纹理,未加载时使用保守色差估计,冰雪抑制反射;关闭国界线不移除光学遮罩。原始 JPEG 不重绘、不降采样。 颜色纹理标记 sRGB 并启用 mipmaps。r128 在地表 Shader 中解码 sRGB,r160 由纹理硬件格式解码;二者在线性空间合成光照后只编码一次。局部 filmic 曲线只作用于地表,不打开全局 ACES 曝光,避免改变星空和业务图层。晨昏范围为法线点积 [-0.12, 0.28],夜面在线性色调映射后保留 0.12–0.32 光照,避免暗部被曲线再次压黑。大气收敛为 R×1.025 的一个 BackSide/Additive 壳,depthWrite=false、depthTest=true,内沿散射并入地表;云图独立开关,使用哑光昼夜材质并在 1.1 顺序绘制。星图使用已有 `starmap_deep_8k.jpg`,不加染色遮罩。 +算力专题沿用原算力中心 Interactable 图标、深度与层次顺序;国家/年份切换会替换该层数据并清除旧选中状态。专题 HUD 属于屏幕 UI,在 `main.js` 的指针排除列表中,不参与地球 picking;区域数据卡在屏幕空间由地理锚点牵引,背面不画穿球连线,设施详情复用原详情卡和移动端详情抽屉。高清地表由 `earth-surface-material.js` 的单次绘制 `ShaderMaterial` 负责,保持原有 R+0.48 网格、深度策略和地表拾取对象。四张 8K 底图仍由原控制器切换,成功后更新采样 uniform 并释放旧纹理,失败保留原图。法线、视线和真实太阳方向统一到世界坐标;土地哑光,海洋只有掠射角冷色反射,没有白色镜面高光。海洋区分优先复用现有海陆地理纹理,未加载时使用保守色差估计,冰雪抑制反射;关闭国界线不移除光学遮罩。原始 JPEG 不重绘、不降采样。 颜色纹理标记 sRGB 并启用 mipmaps。r128 在地表 Shader 中解码 sRGB,r160 由纹理硬件格式解码;二者在线性空间合成光照后只编码一次。局部 filmic 曲线只作用于地表,不打开全局 ACES 曝光,避免改变星空和业务图层。晨昏范围为法线点积 [-0.12, 0.28],夜面在线性色调映射后保留 0.12–0.32 光照,避免暗部被曲线再次压黑。大气收敛为 R×1.025 的一个 BackSide/Additive 壳,depthWrite=false、depthTest=true,内沿散射并入地表;云图独立开关,使用哑光昼夜材质并在 1.1 顺序绘制,支持日间 GeoColor 真彩合成、云顶浮雕法线光影与 DIS 光流插值。星图使用已有 `starmap_deep_8k.jpg`,不加染色遮罩。 | 顺序 | 图层 | 来源 | 渲染 / 半径策略 | 深度 / 交互策略 | 备注 | | --- | --- | --- | --- | --- | --- | @@ -22,15 +22,18 @@ | 0.2 | 国界暗色 tint | `country-boundaries.js` | `tintAltitudeOffset = 0.32`,与海陆填色共用网格及半径 | depthTest=true、depthWrite=false,禁用 raycast | 加载占位及高清材质关闭时使用;填色就绪后按 renderOrder 覆盖。 | | 0.86 | 海陆基座填充 | `country-boundaries.js` | `landAltitudeOffset = 0.32`; 海洋 `#010609`,陆地 `#080f1b` | 禁用 raycast | 即使国界线关闭,基座地图仍保持可用;半径与基座球拉开以避免远距 z-fighting。 | | 0.96 | 高清 Earth 材质 | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | 可见时作为地表拾取目标 | 高清材质始终压过海陆基座填充;半径必须高于海陆基座并与基座球保持足够间距;支持三阶瑞利散射晨昏过渡与海面掠射光。 | -| 0.962 | 云影投影球壳 | `earth.js` | 与高清材质共用球半径、微角偏移 | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 随大气云图开关联动,基于 `earth_clouds_2048.png` 投射柔和地表云影,严格位于 `0.96` 之上、`0.965` 之下。 | +| 0.961 | 分块高清底图瓦片 (LOD) | `earth.js`, `spherical-tile-layer.js` | `R+0.48`(与 8K 地表共用 `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET` 且 `polygonOffset` 优先排序;容器为普通 `Object3D` 保持 `groupOrder = 0`;相机距离比 `<= 1.85` 时从 `z=5` 按视口切分,远中景保留 8K 静态底图兜底,前端 `512` 常驻缓存并中止视野外请求) | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 统一走后端 `/api/v1/earth/tiles/{source}/{z}/{x}/{y}.webp` 代理,受 `DataSource.is_active` 门控与磁盘 LRU 限制。 | +| 0.962 | 云影投影球壳 | `earth.js` | 与高清材质共用球半径、微角偏移 | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 随大气云图开关联动,基于实时云图帧投射柔和地表云影,严格位于 `0.96`/`0.961` 之上、`0.965` 之下。 | | 0.965 | 贴地影响范围层 | `influence-zones.js`, `scene_directives.py` | 复用 `r = 100.48`(`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`)`128×128` 球壳;`renderOrderBase = 0.965`,按 `tier` / `z_index` 递增 `0.0003` | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 支持区域预设单次离屏模糊合成与圆形大圆距离片元着色,严格压在 `0.96` 高清地表之上且低于国界线 `0.97` 与全部交互图标。 | -| 1 / 1.1 | 大气辉光 / 云图 | `earth.js` | 单层大气 R×1.025;云图 R+3(`FrontSide` Shader + `earth_clouds_2048.png`) | 大气 BackSide、depthWrite=false、depthTest=true;保留云图开关 | 内沿光照与 Mie 前向散射并入高清地表与大气壳,不新增全屏后处理。 | +| 1 / 1.1 | 大气辉光 / 云图 | `earth.js` | 单层大气 R×1.025;云图 R+3(`FrontSide` Shader + 实时 IR/日间可见光融合云图 + 静态 `earth_clouds_2048.png` 兜底) | 大气 BackSide、depthWrite=false、depthTest=true;保留云图开关 | 内沿光照与 Mie 前向散射并入高清地表与大气壳,支持 GeoColor 昼色、白天低云可见光融合与 DIS 光流形变过渡。 | +| 1.12 | 分块高清红外云图瓦片 (LOD) | `earth.js`, `spherical-tile-layer.js` | `R+3.04`(容器为普通 `Object3D` 保持 `groupOrder = 0`;默认关闭,由全局 IR+Visible 融合云图承担近距显示,可在控制台显式开启) | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 受 `cloud_hd_tiles` 数据源开关控制。 | +| 1.15 | 10m 全球风场流线 | `wind-layer.js` | `R+3.6` 预分配 `THREE.LineSegments` 动画风粒子流线(父容器为 `Object3D` 保持 `groupOrder = 0`) | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 数据来自 `global_wind_gfs`(NOAA GFS `/api/v1/earth/wind/meta`),未采集时点击开关弹确认前往 `/datasources?product=weather`。 | | 1 | 海缆 / 登陆点 | `cables.js`, `cable-batches.js` | 海缆全量线段合并为一个 `LineSegments`;登陆点全量使用实例化 billboard;`renderOrder = 1`、海缆与登陆点统一使用高清地表 `0.48` 偏移和同源三角表面坐标 | 原始 `Line` / `Sprite` 仅作为逐项拾取和选择状态对象,材质不再单独绘制;登陆点仍按球体遮挡判断背面可见性,批量材质 `depthTest: false` | 样式通过线缆样式纹理和登陆点实例属性同步;保留颜色、脉冲、尺寸、显隐与点击语义。 | | 1.2 | 真实地形 | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` 加地形位移 | 禁用 raycast | 地形压过高清材质;高清材质关闭时临时隐藏,重新开启后恢复原状态。 | | 2.05 | 经纬线 | `earth.js` | `CONFIG.earthRadius + 0.14` | 禁用 raycast | 低透明度显示在高清材质上。 | -| 0.97–0.99 | 国界线 | `country-boundaries.js` | `lineAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48`;claim 线不再额外抬高 | `depthTest: true`,禁用 raycast | 线层使用独立 line geometry 与 `renderOrder` 控制,但半径与高清材质壳完全一致,避免转动地球时与高清贴图出现视差。 | +| 0.97–0.99 | 国界线 | `country-boundaries.js` | `lineAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48`;PMTiles 瓦片共享最多 3 个合批网格(`country-boundary-batch`、`country-admin1-batch`、`country-boundary-claim-batch`);claim 线不再额外抬高 | `depthTest: true`,禁用 raycast | 线层使用独立 line geometry 与 `renderOrder` 控制,通过父瓦片兜底消除切换闪烁,半径与高清材质壳完全一致,避免转动地球时与高清贴图出现视差。 | | 0.98 | 国界 hover 光晕 | `country-boundaries.js` | 与地表锚点相同,无额外抬高 | `depthTest: true`,透明绘制队列,禁用 raycast | additive 光晕处于登陆点下方,背面由球体遮挡。 | -| 0.99 | 国界 hover 实线 | `country-boundaries.js` | `hoverAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | `depthTest: true`,透明绘制队列,禁用 raycast | 霓虹红橘 hover 线;与普通国界线和高清材质同源半径对齐,避免重影和漂浮感;中国和中国(台湾)共享高亮组。 | +| 0.99 | 国界 hover 实线 | `country-boundaries.js` | `hoverAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | `depthTest: true`,透明绘制队列,禁用 raycast | 霓虹红橘全周界 hover 线(融合陆地国界与 OSM 海岸线,无整国半透明蒙版);与普通国界线和高清材质同源半径对齐,避免重影和漂浮感;中国与中国(台湾)共享高亮组。 | | 3 | 卫星 footprint 填充 / Iridium coverage ring | `satellites.js`, `iridium-footprint-adapter.js` | `GROUND_FOOTPRINT_RENDER_ORDER` | depth-tested;Iridium adapter 的 fill / ring 也使用同一 renderOrder | Footprint 在 land / texture / terrain 和国界线之上,但在算力中心和卫星之下。 | | 3-4.5 | BGP 观测站、事件扩散圈和事件 marker | `bgp.js`, `interactable.js` | BGP 观测站和事件 marker 均使用 `Interactable` 批量 `THREE.Points`;事件 marker 使用 `BGP_EVENT_RENDER_ORDER = 4.5`;观测站主图标使用 `BGP_COLLECTOR_RENDER_ORDER = 4.4` 和 `BGP_CONFIG.collectorAltitudeOffset = 0.2`;事件 overlay 进入 `bgp-event-overlay-layer`;观测站 halo 和覆盖扇形进入 `bgp-collector-radar-layer` | BGP 事件和观测站都通过 `Interactable` 屏幕空间 picking,并参与同坐标避让 | BGP 观测站主图标与船只同层;BGP 事件与算力中心同层;向外扩散圈、观测站雷达/覆盖动画继续由 BGP 业务逻辑驱动。 | | 4.3 | AIS 船只轨迹线 | `vessels.js` | `VESSEL_RENDER_ORDER - 0.1`;`CONFIG.earthRadius + VESSEL_CONFIG.track.altitudeOffset` | 跟随船只显隐,不单独参与拾取 | 选中船只后显示最近轨迹,低于船只 marker。 | @@ -113,3 +116,5 @@ Earth 的地表不是单一 mesh,而是多层近似同心球:基座球、海 区域新闻与算力保留 `#earth-region-callouts` 根节点(z-index 20),并与物件详情共享 `callout-stage-arbitrator.js` 的左右侧及纵向走廊;中美双主舞台对比卡通过 `bilateralPeerKey` 对称分配左右走廊。区域根内展开卡片为 50、拖拽前景为 55,悬停展开层为 60–65;普通胶囊为 30,背面胶囊为 8 并渐淡缩小,而主舞台及悬停展开卡在背面时保持正文 100% 不透明,仅将连线切换为 `.is-rear` 虚线边缘引导并激活标题栏“转至正面视角”按钮。 算力专题下钻图层与逻辑路由演出弧线严格遵守同心壳深度与合批规则:中国“东数西算”八大国家算力枢纽复用 `createInteractableLayer` 单次实例化合批,贴地偏移为 `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48`、`renderOrder = 4.58`;西部绿电枢纽双环 `AdditiveBlending` 脉冲环 `renderOrder = 4.42`(`depthWrite: false`),东西部协同弧线与高空 BGP 逻辑路由、国界 hover、选中海缆流光、船舶尾迹及选中卫星轨道共用 `surface-ribbon.js` 屏幕空间抗锯齿发光丝带底层(摆脱 Windows ANGLE 下 `THREE.Line` 1px 限制),Iridium 足迹通过 `iridium-footprint-adapter.js` 迁入 GPU 顶点投影;退出或隐藏图层时立即 `dispose()` 几何与材质。 + +3D 城市分级标注投影层 `.geo-labels`(`geo-labels.js` + `hud.css`)使用 `z-index: 4`(位于 WebGL 画布之上、`.map-clusters` 的 `5` 与 `.satellite-labels` 的 `6` 之下);以 `earthSurfacePoint(lat, lon, R + 0.48)` 锚定左端圆点并与球体正面遮挡判定同步裁除背面城市,逐帧更新可见标签同时按层级优先级与碰撞盒自动避让 HUD、聚合徽标、区域卡片和卫星近景标签。 diff --git a/docs/technical/zh/frontend-admin-frontend-context.md b/docs/technical/zh/frontend-admin-frontend-context.md index 1072eaab..f4501e81 100644 --- a/docs/technical/zh/frontend-admin-frontend-context.md +++ b/docs/technical/zh/frontend-admin-frontend-context.md @@ -92,6 +92,14 @@ Admin 的数据源页把单源触发、表格勾选触发和触发全部统一 这个队列是用户感知层,不替代后端调度状态。后端仍然是任务是否运行、完成、失败或跳过的唯一事实来源。 +## 采集数据按图层台账 + +`/data`([DataList.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/DataList.tsx) 及 `pages/data-ledger/` 子模块)以地球图层为一级导航(同步 URL 参数 `?layer=`,默认 `compute`),数据契约由 `/api/v1/data-ledger/*` 提供: + +- 左侧 [LayerNav.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/data-ledger/LayerNav.tsx) 复用后端 `PRODUCT_DEFINITIONS` 展示各地球图层分类与条数,并保留「原始采集记录」(`?layer=raw`)视图作为底层 `/api/v1/collected` 查询、统计切分与导出入口。 +- `layer=compute` 渲染 [ComputeLedger.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/data-ledger/ComputeLedger.tsx):支持 5 类算力设施类型分段筛选与计数、4 类定位状态分桶(已定位 / 待确认 / 暂不可定位 / 待定位)、国家与关键词搜索,并在「操作」列复用 `TableActionButton` 调用强制重新定位与手工编辑坐标(复用 `/api/v1/visualization/compute-centers/{source_id}/collect-location` 与坐标保存接口),点击行可查看核验依据与关联工作流运行链接。 +- 其他地球图层(卫星、海底光缆、船只、BGP、新闻与直播、气象、地理/底图)统一由 [LayerItemsLedger.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/data-ledger/LayerItemsLedger.tsx) 渲染只读分页台账,遵循单屏高度闭合与表格内部滚动约束。 + ## 控制台主题滑块 Admin 侧栏底部主题切换继续复用共享 [SegmentedControl.tsx](/home/ray/dev/linkong/planet/frontend/src/components/SegmentedControl/SegmentedControl.tsx),但主题变量在 [styles.css](/home/ray/dev/linkong/planet/frontend/src/admin/styles.css) 内跟随 `data-theme` 覆盖: @@ -470,6 +478,14 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten 接口前缀 `/earth/card-images`:管理员 `GET/PUT configuration`、`POST upload`、`GET targets`、`POST preview`;公共 `GET resolve`、`GET files/{filename}`。配图配置读写保持版本和审计,文件路径不接受任意目录。 -## 算力多口径证据台账与待审队列 +## 算力多口径证据台账、待审队列与发布历史 -`ComputeComparisonSettings.tsx` 承载 `/earth-content?section=compute_comparison` 的单屏工作区,顶部标题栏与六个分类按钮(多口径观测、算力内部结构、创新指数分差、里程碑与八大枢纽、报告来源、Agent 待审队列)固定在头部,仅下方 `Scrollbar` 承担纵向滚动,严格闭合 `height: 100%` + `min-height: 0` 单屏高度链。发布配置走乐观锁修订号校验并完整保留 `structures`、`milestones` 与 `national_hubs`;待审队列对接 `/api/v1/situational-awareness/candidates`,支持从报告摘录提取候选份额、管理员审核通过/驳回及一键导入草稿。 +`ComputeComparisonSettings.tsx` 承载 `/earth-content?section=compute_comparison` 的单屏工作区,顶部标题栏、发布说明输入与七个分类标签(多口径观测、算力内部结构、创新指数分差、里程碑与八大枢纽、报告来源、Agent 待审队列、发布历史)固定在头部,仅下方 `Scrollbar` 承担纵向滚动,严格闭合 `height: 100%` + `min-height: 0` 单屏高度链。发布配置走乐观锁 `publish_id` 校验、完整保留 `structures` / `milestones` / `national_hubs` 及逐国来源 `value_sources`(份额类跨报告混源行强制填写同分母发布说明),并写入不可变版本台账;待审队列对接 `/api/v1/situational-awareness/candidates`,展示历史修订/新增观测/统计期冲突/重复徽章及逐国旧值→新值→差值对比表,采纳/驳回强制选择匹配理由代码与说明,导入草稿自动保护未修订国家来源并在 `period_label` 冲突时弹窗二次确认;「发布历史」标签拉取 `/api/v1/data-products/compute/revisions` 展示变更摘要、操作人、发布说明与演播投递状态。 + +## 全球实时红外云图与高清底图工作台(`weather` / `geo` 双域分工) + +`EarthCloudMapSettings.tsx` 挂载于 `/earth-content?section=cloud_map`(“大气云图”),遵循职责分离与单屏 `height: 100%` + `min-height: 0` 高度链:聚焦 2:1 星空实时云图预览及经纬网格/强对流核 SVG 叠加、历史帧切换、全球与 8 大区域统计以及 Earth 端展示配置(启用实时云图、日间 GeoColor 真彩合成、DIS 光流形变插值、云顶浮雕强度、允许历史帧演变播放、默认开启对流核标识、默认透明度与恢复默认),同时展示只读气象采集状态摘要并引导至 `/datasources?product=weather` 与 `/collection-management`;连通性探活、采集调度/触发、数据归属与缓存清理归口至数据源管理(`weather` / `气象` 域纳管 `global_cloud_map`、`cloud_hd_tiles`、`global_wind_gfs`,新增 `geo` / `地理/底图` 域纳管 `earth_imagery_sentinel2`、`earth_imagery_viirs_daily`),上游/合成参数与连通性测试归口至采集管理中的 `采集器配置`。`EarthBasemapSettings.tsx` 挂载于 `/earth-content?section=basemap`(“底图资源”),聚焦 Sentinel-2 / NASA VIIRS 与高清云图瓦片金字塔的受控缓存预览、缓存清理、主动底图选择与视口 LOD 阈值策略。 + +## Admin 独立构建内置预览资源映射 + +线上 `planet_admin` 镜像以 `PLANET_FRONTEND_TARGET=admin` 构建(`vite.config.mts` 中 `publicDir: false`,严格排除 `dist/earth/`),但后端默认品牌与静态云图配置仍保留面向桌面端离线协议的 `/earth/assets/...` 路径。为避免线上 Admin 预览请求落入 SPA `index.html` 兜底而裂图,`frontend/vite.config.mts` 通过 `earthBuiltinAssetsPlugin` 暴露 `@earth-builtin-asset/*` 前缀并在构建期将 5 张内置预览资源(`brand/earth-logo.png`、`brand/title-zh.png`、`brand/title-en.png`、`brand/lim-logo.png`、`earth_clouds_2048.png`)按内容哈希直接发射到 `/assets/*.png`;`frontend/src/admin/lib/earthBuiltinAssets.ts` 的 `resolveEarthPreviewAssetUrl()` 仅在 `EarthBrandPreview` 与 `EarthCloudMapSettings` 预览渲染时做 URL 映射,保持表单展示值、后端存储值(`/earth/assets/...`)与用户上传的 `/earth-brand-assets/...` 原样不变。 diff --git a/docs/technical/zh/location-pipeline-development.md b/docs/technical/zh/location-pipeline-development.md index 18b9968d..51a6b272 100644 --- a/docs/technical/zh/location-pipeline-development.md +++ b/docs/technical/zh/location-pipeline-development.md @@ -68,8 +68,7 @@ class LocationResolver(Protocol): | `BuildsUponComputeCenterResolver` | `services/compute_center_locations.py` | Epoch `builds_upon` 同园区父集群继承(继承已核验坐标) | | `lookup_wikidata_facility` | `resolvers/wikidata.py` | 异步 L1 Wikidata P625/P276 设施实体坐标检索 | | `lookup_peeringdb_facility` | `resolvers/peeringdb_facility.py` | 异步 L1 PeeringDB `/api/fac` 商业数据中心门牌与经纬度检索 | -| `run_controlled_location_agent` | `location/agent_resolver.py` | L2–L4 受控 4 步 Tool-Calling 位置取证 Agent(抓取一手源网页 + WebSearch + `geocode_verify` + 终态持久化) | -| `LocationLLMFallback` | `location/llm_fallback.py` | 兼容无 Tool-Calling 模型时的兜底事实核查,带严格经纬度区间、国家校验与市级降级护栏 | +| `run_location_workflow` | `location/workflow_tools.py` | 统一 9 节点 `location.resolve_unknown` DAG 工作流(经 `dag_executor.py` 执行上下文归一化、知识库/跨源检索、Web 取证、级联 `geocode_verify`、L3 地理护栏 `evaluate_location_geo_guardrail` 与 L4 终态持久化,取代旧 `agent_resolver.py` 与 `llm_fallback.py`) | Nominatim 是 OpenStreetMap 生态里的地理编码服务:给它一个地点名称、城市、国家或机构查询文本,它会返回可能匹配的经纬度、展示名称和地址结构。它适合把“城市/机构/园区名称”转成候选坐标,但不是权威事实库,可能命中同名地点或过宽泛的行政区,所以本项目只把它作为待确认候选来源,并带缓存和速率限制使用。 @@ -92,7 +91,7 @@ StoredComputeCenterLocationResolver() 主地图启动链路只做“源坐标优先,其次数据库维表坐标”。数据库表为 `compute_center_locations`,唯一键是 `(source, source_id)`,用于保存人工确认或从源记录真实坐标迁入的位置。`init_db()` 只幂等迁入源记录里已有的真实经纬度,不迁入旧硬编码 hint,不在启动期批量调用 ROR、Nominatim 或 LLM。 -手动候选采集链路和渲染链路分开。`collect_location_candidates()` 使用源字段构造 ROR 和 Nominatim/OpenStreetMap 查询,但不会把 `compute_center_locations` 当前坐标当候选返回。如果这些常规候选为空,API 层会调用 `LocationLLMFallback`,通过当前默认 AI Provider 进行位置 factcheck,并只返回 `source="llm_location_factcheck"`、`needs_confirmation=true` 的候选。LLM 候选使用“模型自评分 + 后端证据评分”的组合阈值;如果 LLM 只给出可信 city/country 而没有坐标,后端会用 Nominatim 补城市级坐标,但不会因此提高证据分。用户在前端确认某个候选后,通过保存接口写入维表;之后地图刷新时由 `StoredComputeCenterLocationResolver` 渲染。 +手动候选采集链路和渲染链路分开。`collect_location_candidates()` 使用源字段构造 ROR 和 Nominatim/OpenStreetMap 查询,但不会把 `compute_center_locations` 当前坐标当候选返回。若常规候选不足或需要深度核验,API 层调用 `run_location_workflow()`(运行 9 节点 `location.resolve_unknown` DAG),结合跨源线索、Wikidata/PeeringDB、一手源网页/WebSearch 取证、Nominatim 级联地理编码与 `evaluate_location_geo_guardrail` 地理护栏产出带证据链的待确认候选或终态(`undisclosed` / `multi_site` / `anonymous`)。用户在前端确认某个候选后,通过保存接口写入维表;之后地图刷新时由 `StoredComputeCenterLocationResolver` 渲染。 `resolve_compute_center_location()`、`resolve_compute_center_location_full()` 和 `collect_location_candidates()` 保留为领域 API。`visualization.py` 只消费领域 API,不再持有坐标提示常量、国家质心兜底或 Nominatim 细节。 diff --git a/docs/technical/zh/manual.md b/docs/technical/zh/manual.md index 9e0f2cb4..889e97d4 100644 --- a/docs/technical/zh/manual.md +++ b/docs/technical/zh/manual.md @@ -433,15 +433,15 @@ AIS 船只图例按船型显示颜色:货轮、油轮、客船、渔船、军 ## 算力与资源态势 -管理员可在控制台“智能星球内容 → 算力对比”维护多口径证据台账:包含“多口径观测”“算力内部结构”“创新指数分差”“里程碑与八大枢纽”“报告来源”及“Agent 待审队列”六个工作分区。除手动录入来源与观测外,可在待审队列粘贴研报摘录提取候选份额,人工审核通过后一键导入草稿,严禁未审候选直接上屏。占比以全球为分母,绝对量统一为 FP32 EFlop/s;中美相对算力指数(RPI = 中国 / 美国 × 100)与双边份额由服务端按同年权威观测确定性派生。 +管理员可在控制台“智能星球内容 → 算力对比”维护多口径证据台账:包含“多口径观测”“算力内部结构”“创新指数分差”“里程碑与八大枢纽”“报告来源”“Agent 待审队列”及“发布历史”七个工作分区。在待审队列中粘贴研报摘录提取候选份额后,系统自动对照当前台账展示旧值、新值、差值、修订类型(历史修订 / 新增观测 / 统计期冲突 / 重复)与分母口径;采纳或驳回时必须选择理由代码并填写说明。导入草稿时仅更新修订国家的数值与逐国来源,未修订国家继续保留原报告出处;若份额类观测行混合了不同报告来源,发布前必须填写同分母说明。占比以全球为分母,绝对量统一为 FP32 EFlop/s;中美相对算力指数(RPI = 中国 / 美国 × 100)与双边份额由服务端按同年权威观测确定性派生。 -“创新指数分差”独立维护中信所《全球人工智能创新指数报告》美国减中国的综合得分差(如 2023—2025 年 22.02 → 19.96 → 17.95),与算力份额分叉形成对照。被任何观测、结构、里程碑或八大枢纽引用的报告来源不能直接移除;重复指标年份、结构占比偏离 100%、占比总和超过 100% 等内容会拒绝发布。多人同时编辑时,后保存者收到 409 冲突提示并保留本地草稿。“恢复默认”需要确认并记录操作审计。 +“创新指数分差”独立维护中信所《全球人工智能创新指数报告》美国减中国的综合得分差(如 2023—2025 年 22.02 → 19.96 → 17.95),与算力份额分叉形成对照。被任何观测、结构、里程碑或八大枢纽引用的报告来源不能直接移除;重复指标年份、结构占比偏离 100%、占比总和超过 100% 等内容会拒绝发布。多人同时编辑时,后保存者收到 409 冲突提示并保留本地草稿。“恢复默认”会生成新的发布版本号与审计记录,历史版本可在“发布历史”标签中完整查阅。 -点击算力中心图层行的“算力态势分析”打开配置窗,可切换五种战略视角(中美相对算力 RPI、全球总算力份额、全球智能算力份额、前沿智算集群与机架功率、绝对规模 EFlop/s),并可一键启动“算力态势 4 幕剧场导览”或“BGP 路由异动 5 幕复盘”。开启区域卡片后,桌面端默认在地球左右走廊对称展开中美双主舞台对比卡;当锚点转至地球背面时,卡片正文保持 100% 清晰可读,改用虚线边缘引导线并在标题栏提供“转至正面视角”图标按钮,不再显示生硬的“球体背面”文字。 +点击算力中心图层行的“算力态势分析”打开配置窗,可切换五种战略视角(中美相对算力 RPI、全球总算力份额、全球智能算力份额、前沿智算集群与机架功率、绝对规模 EFlop/s)及“系统发布版本”,并可一键启动“算力态势 4 幕剧场导览”或“BGP 路由异动 5 幕复盘”。选择任意历史发布版本时,卡片与配置窗顶部显示“正在查看历史版本(非当前)”提示条与“回到当前”按钮,卡片与 AI 参谋同步回放该版本当时的数值与结论。点击卡片主指标旁的溯源按钮可展开血缘抽屉,查看报告原文摘录、页码、内容哈希、观测期/发表日/入库时间/生效时间及修订记录(公开访问对复核人姓名与内部说明自动脱敏,登录管理员可查看完整留痕)。开启区域卡片后,桌面端默认在地球左右走廊对称展开中美双主舞台对比卡;当锚点转至地球背面时,卡片正文保持 100% 清晰可读,改用虚线边缘引导线并在标题栏提供“转至正面视角”图标按钮,不再显示生硬的“球体背面”文字。 战略算力卡片采用五层叙事结构:主指标与全球分母膨胀归因、中美算力天平(RPI)、五维口径胶囊切换与中国内部算力结构条(如智能算力占比 81% 对全球 85%)、带政策/技术里程碑旗标的分叉走廊折线图与创新指数收敛对照图、受控研判摘要(零思考链泄漏)及底部动作栏。点击“八大枢纽”可在三维球面叠加中国“东数西算”八大国家算力枢纽徽标、西部绿电脉冲环与东西部协同弧线。 -图层面板顶栏的“态势工作台”按钮、BGP 观测图层行的“BGP 异动取证”按钮及 BGP 事件详情卡内的“参谋取证调查”入口均可直接打开动态态势工作台。工作台支持多轮自然语言连续追问(自动继承前序国家、口径与事件上下文),可一键零延迟切换“综合工作台 / 对照图 / 数据表 / 趋势走廊 / 归因拆解 / 一页简报”等预设视图,并支持切换“事后复盘 / 当时可知 / 实时观测”时间知识边界。点击“固定对照”可在宽屏并排保留历史研判视图或在窄屏收纳为顶部快速切换标签;点击“订阅异动”可关注后续态势增量;点击导出按钮可下载严格绑定当前冻结修订号(Revision)与证据引用的 Markdown 简报。三维剧场导览播放期间,任意拖拽地球或滚动滚轮都会立即停止自动飞行运镜;当后台产生新态势而用户正在手动浏览时,导览栏仅显示待播提示胶囊,不打断当前操作。 +图层面板顶栏的“态势工作台”按钮、BGP 观测图层行的“BGP 异动取证”按钮及 BGP 事件详情卡内的“参谋取证调查”入口均可直接打开动态态势工作台。从算力卡片打开参谋时,系统自动绑定当前地球视图的发布版本、口径与年份;若在卡片上切换口径或历史版本,参谋在文字综述与图表工作台区均会提示“与当前地球视图不同”,点击“按当前视图重新研判”即可按最新视图重新生成。工作台支持多轮自然语言连续追问(含追问“这次为什么变了”查看修订依据,并自动继承前序国家、口径与事件上下文),可一键零延迟切换“综合工作台 / 对照图 / 数据表 / 趋势走廊 / 归因拆解 / 一页简报”等预设视图,并支持切换“事后复盘 / 当时可知 / 实时观测”时间知识边界。点击“固定对照”可在宽屏并排保留历史研判视图或在窄屏收纳为顶部快速切换标签;点击“订阅异动”可关注后续态势增量;点击导出按钮可下载严格绑定当前冻结修订号(Revision)与证据引用的 Markdown 简报。三维剧场导览播放期间,任意拖拽地球或滚动滚轮都会立即停止自动飞行运镜;当后台发布算力数据修订或产生新态势而用户正在手动浏览时,导览栏仅显示待播提示胶囊,不打断当前操作,空闲时自动播报并明确标注“历史数据修订,不代表当期算力跃升”。 默认权威台账覆盖 2020—2024 年及 2025-H1 核实数据(如信通院总算力份额 2024 年美 44% / 中 23%、全球分母约 2210 EFlop/s,智能算力份额美 48% / 中 25%)。明确选择尚未发布报告的年份(如 2026)时保留待发布提示并回显最新核实期,绝不伪造回填数值。国家宏观报告指标与公开设施样本独立,设施数仅作辅助证据。 @@ -460,7 +460,7 @@ AIS 船只图例按船型显示颜色:货轮、油轮、客船、渔船、军 再次触发同一数据源会创建新任务,旧失败项留在失败分组。“任务状态”使用清单图标,与刷新操作区分。CelesTrak 在短时间内可复用有效下载缓存;重新采集仍会生成独立任务并更新采集数据。 -显示设置中的“卫星 → 近景标签”默认开启,关闭后隐藏地图上的卫星名称,详情卡仍可使用。开关下的“近景标签显示阈值”滑块可设为 250%–500%,默认 400%;达到该缩放比例时显示标签,低于阈值时隐藏。数量滑块可设为 5–36 个,默认 36;这是显示上限,遮挡或空间不足时实际数量可能更少,设置会保存。“星空亮度”滑块范围为 0–200%,默认 100%,两项会记住选择。展开的区域卡片在各自纵向范围内平滑跟随,不再叠加装饰漂浮。悬停期间及离开后短暂停留时不自动切换关注区域;胶囊可临时展开完整内容和操作,已有卡片仍跟随地理锚点。算力图例里的分类数量只统计当前已定位点。 +显示设置中的“卫星 → 近景标签”默认开启,关闭后隐藏地图上的卫星名称,详情卡仍可使用。开关下的“近景标签显示阈值”滑块可设为 250%–500%,默认 400%;达到该缩放比例时显示标签,低于阈值时隐藏。数量滑块可设为 5–36 个,默认 36;这是显示上限,遮挡或空间不足时实际数量可能更少,设置会保存。“城市地名标注”默认开启,在放大地球时随层级依次显示国家首都、重要城市与省/州行政中心名称,并随界面语言自动切换中英文、自动避让界面面板与设施图标。“星空亮度”滑块范围为 0–200%,默认 100%,两项会记住选择。展开的区域卡片在各自纵向范围内平滑跟随,不再叠加装饰漂浮。悬停期间及离开后短暂停留时不自动切换关注区域;胶囊可临时展开完整内容和操作,已有卡片仍跟随地理锚点。算力图例里的分类数量只统计当前已定位点。 地表点位聚合后显示带数量的实心圆,点击可展开成员;只有同坐标或极近坐标点位在原位置附近紧凑堆叠,普通点始终回到各自真实位置;堆叠露出可点击边缘,点击后排图标会将它置前并打开详情,取消焦点后恢复原位。放大超过 250% 后普通聚合自动拆开,500% 不再保留聚合圆标,同坐标点直接展开。 diff --git a/docs/technical/zh/ops-runbook.md b/docs/technical/zh/ops-runbook.md index b3761ecd..e629d457 100644 --- a/docs/technical/zh/ops-runbook.md +++ b/docs/technical/zh/ops-runbook.md @@ -469,9 +469,9 @@ uv run pytest backend/tests/test_otp_service.py 1. 在控制台 `运维与配置 -> 智能星球内容 -> 国界精度` 保存国界源配置;本机配置写入 `config/earth-boundary-sources.local.json`,不要提交。 2. 点击“构建高精国界”,或在 Earth 页面工具栏齿轮中切到“高精”触发首次构建。后端会下载三类源到 `data/earth-boundary-sources/`,生成 source manifest,并调用 PMTiles 构建脚本。 3. 构建器需要本机 PATH 里有 `tippecanoe` 和 `pmtiles`。缺工具时接口返回明确错误,不会写入数据源采集记录。 -4. 构建成功后应输出 `frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles` 和对应 manifest。 -5. 部署后打开智能星球,开启“国界线”,放大中国东南海岸、台湾、海南、南海、藏南、科索沃、加沙等区域验证 hover 和边界口径。 -6. 如果本地没有高精 manifest/PMTiles,Earth 会使用 `frontend/public/earth/data/countries-admin0.min.geojson` 低精度 fallback;如果高精产物存在但瓦片请求失败,按 PMTiles range 请求、manifest provider、Nginx `.pmtiles` 静态返回和 sha256 一致性排查。 +4. 构建成功后产物写入后端边界数据卷(默认 `backend/data/earth-boundaries/`),由 `/api/v1/earth/boundaries/manifest` 与 `/api/v1/earth/boundaries/files/{name}`(支持 `GET`/`HEAD`、`Range` 与不可变缓存)分发 `earth-boundaries..pmtiles`、`hover-index..json`、`hover-borders..json` 与 `geo-labels..json`。 +5. 部署后打开智能星球,开启“国界线”,放大中国东南海岸、台湾、海南、南海、藏南、科索沃、加沙等区域验证 hover、边界口径与城市分级标注。 +6. 如果本地没有高精 manifest/PMTiles,Earth 会使用仓库内置 `frontend/public/earth/data/countries-admin0.china-pov-v1.geojson` 低精度 fallback;如果高精产物存在但瓦片请求失败,按 `/api/v1/earth/boundaries/files/{name}` 的 `Range` 请求、manifest provider、反代透传与 `sha256` 一致性排查。 ## 在本机发版,生产机自动部署 diff --git a/docs/technical/zh/platform-data-flows.md b/docs/technical/zh/platform-data-flows.md index ce086502..3ee308e6 100644 --- a/docs/technical/zh/platform-data-flows.md +++ b/docs/technical/zh/platform-data-flows.md @@ -85,6 +85,17 @@ flowchart TB - **删除语义**:删除 TOP500 等 source 后必须刷新 `computeCenters`;删除位置维表则也要刷新该图层。通常用 `reload`,因为位置更新不一定需要先清空。 - **常见异常**:采集已完成但 Earth 数量不变,通常是接口使用缓存、位置维表未更新,或 source 删除没有触发 adapter。 +### 算力台账修订、双时间轴与血缘推导链路 + +国家/区域算力对比台账独立于设施样本,围绕不可变版本账本 `compute_configuration_revisions` 运行(`system_settings` 中的 `compute_comparison` 仅作为当前发布版本的同步缓存,恢复默认时新增版本记录且不删除行): + +- **双时间轴语义**: + - `cutoff_at`(`time_basis=as_known_then`)按报告发表日过滤来源;行内逐国来源(`value_sources`)被截断时只剔除该国数值,不影响同年份仍早于截点的其他国家。 + - `as_of` / `publish_id` 按系统发布时间轴回放历史发布台账(`GET /data-products/compute/series`、`GET /situational-awareness/posture/compute` 及 Copilot 会话/轮次透传);早于首次基线版本时返回 `snapshot_unavailable: true` 且不回查当前台账。 +- **候选提取、去重与复核**:`POST /situational-awareness/candidates/extract` 按 `(source_id, metric, year, period_label, values)` 计算 `dedupe_fingerprint` 去重,写入只增不覆盖的 `EvidenceRecord`(含 `content_sha256`、`locator`、`excerpt`),并与当前台账生成逐国 `comparison`(标注 `historical_revision`、`period_conflict` 与分母口径);`POST /candidates/{id}/review` 强制要求匹配的 `reason_code` 与说明,且已关联 `published_publish_id` 的候选锁定不可再改(409)。 +- **版本驱动演播与失败补播**:`PUT /data-products/compute/configuration` 与 `POST /configuration/reset` 提交事务后直接按新版本 `diff_summary` 调用 `process_compute_revision_presentation`(与 BGP `classify_snapshot_delta` 完全解耦),为任意非零观测变更(含小幅历史修订与 B→A 回退)编译 `compute-revision-notice` 演播契约(以 `revision = 版本行 id` 单调递增并按 `publish_id` 去重);失败时记录 `presentation_status=failed` 与错误摘要并由启动初始化、5 分钟定时任务及 `POST /proactive/evaluate` 自动补播。 +- **读取时血缘推导与脱敏**:`GET /data-products/compute/lineage` 不建镜像关系表,直接按目标版本与向前最多 50 条 `compute_configuration_revisions` 的 `diff_summary` 关联 `compute_evidence_candidates` 和 `evidence_records`,推导当前值、报告出处/哈希、对象级时间线(观测期、发表日、候选入库时间、生效发布时间)与修订时间线;非管理员(匿名或 `viewer`)访问 `/lineage` 与 `/revisions/public` 时自动脱敏,将复核/发布人替换为「已人工复核」并仅保留理由类别中文标签,隐藏原始 `review_reason` 与 `publish_note`。 + ## BGP 链路 BGP 数据用于展示路由观测站、异常事件、事件扩散圈和态势摘要。Earth 不直接展示原始 BGP 行,而是展示聚合后的观测、异常和事件。因此 BGP 是最容易出现“原始数据删了但 Earth 还在”的链路。 diff --git a/docs/version-history.md b/docs/version-history.md index 67e38388..fa937e78 100644 --- a/docs/version-history.md +++ b/docs/version-history.md @@ -16,12 +16,13 @@ ## Current Version - `main` 当前主线历史推导到:`0.16.5` -- `dev` 当前开发分支历史推导到:`0.83.0` +- `dev` 当前开发分支历史推导到:`0.84.0` ## Timeline | Version | Type | Branch | Commit | Summary | | --- | --- | --- | --- | --- | +| `0.84.0` | feature | `dev` | `v0.84.0` | 算力台账不可变修订/双时间轴/只读血缘、全球实时云图与风场/高清底图瓦片、高精度中国 POV 边界 PMTiles 与 3D 城市分级标注、图层数据台账与 9 节点位置 DAG 统一、修复线上独立 Admin 默认品牌/云图预览裂图及文档清理 | | `0.83.0` | feature | `dev` | `v0.83.0` | Earth Phase 1–4 贴地影响范围与三维视觉升级、聚合分色环与优先一折连线、AI 参谋自进化加固与数据源连通性修复、桌面客户端启动与资源包更新及代码文档清理 | | `0.82.0` | feature | `dev` | `v0.82.0` | AI 参谋 3 层工作流自进化与元进化(Tier-0 安全内核/金丝雀回滚/Fixture A/B 评测/多模态 Playground 与地球绑定)、Electron 无边框录屏与 i18n、AI 模型目录升级及 README Mermaid 架构图 | | `0.81.0` | feature | `dev` | `v0.81.0` | 重构 AI 参谋(纯聊天 Playground/本地上下文抽屉/React Flow 9 工作流编排/AI Diff 调优/运行审计)与告警观测台,升级 L0–L4 Tool-Calling 位置 Agent、防爬鉴权与 X-API-Key、桌面录屏及多模型聚合目录 | diff --git a/frontend/nginx.conf.template b/frontend/nginx.conf.template index e9445373..558bd5e5 100644 --- a/frontend/nginx.conf.template +++ b/frontend/nginx.conf.template @@ -91,23 +91,6 @@ server { try_files $uri =404; } - location = /earth/data/boundaries/v1/manifest.json { - add_header Cache-Control "no-store"; - try_files $uri =404; - } - - location ~ ^/earth/data/boundaries/.*\.pmtiles$ { - types { application/octet-stream pmtiles; } - add_header Accept-Ranges bytes; - add_header Cache-Control "public, max-age=31536000, immutable"; - try_files $uri =404; - } - - location /earth/data/boundaries/ { - add_header Cache-Control "public, max-age=31536000, immutable"; - try_files $uri =404; - } - location /earth/vendor/mediapipe/ { types { text/javascript mjs js; diff --git a/frontend/package.json b/frontend/package.json index 92217d8c..81692e49 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "planet-frontend", - "version": "0.83.0", + "version": "0.84.0", "private": true, "packageManager": "bun@1", "dependencies": { diff --git a/frontend/public/earth/css/compute-topic.css b/frontend/public/earth/css/compute-topic.css index 0dff9a60..03d75533 100644 --- a/frontend/public/earth/css/compute-topic.css +++ b/frontend/public/earth/css/compute-topic.css @@ -32,7 +32,7 @@ top: var(--hud-offset); left: 50%; width: min(calc(380px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset))); - max-height: min(48vh, calc(380px * var(--hud-scale))); + max-height: min(56vh, calc(440px * var(--hud-scale))); transform: translateX(-50%); padding: 0; border-radius: 0; @@ -307,6 +307,7 @@ body:not(.layout-mode-mobile) .compute-card:not(.is-spotlight):not(.is-hover-exp } body:not(.layout-mode-mobile) .compute-card:not(.is-spotlight):not(.is-hover-expanded) .compute-card__period-badge, +body:not(.layout-mode-mobile) .compute-card:not(.is-spotlight):not(.is-hover-expanded) .compute-revision-banner, body:not(.layout-mode-mobile) .compute-card:not(.is-spotlight):not(.is-hover-expanded) .compute-card__summary, body:not(.layout-mode-mobile) .compute-card:not(.is-spotlight):not(.is-hover-expanded) .compute-card__essentials, body:not(.layout-mode-mobile) .compute-card:not(.is-spotlight):not(.is-hover-expanded) .compute-card__body { @@ -1244,9 +1245,9 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging) position: absolute; z-index: 166; left: 50%; - top: min(44vh, 340px); - width: min(calc(384px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset))); - max-height: 44vh; + top: min(36vh, 280px); + width: min(calc(420px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset))); + max-height: 58vh; padding: 0; border-radius: 0; transform: translateX(-50%); @@ -1258,7 +1259,7 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging) display: flex; flex-direction: column; gap: calc(8px * var(--hud-scale)); - max-height: 34vh; + max-height: 48vh; padding: calc(10px * var(--hud-scale)) calc(12px * var(--hud-scale)); overflow: auto; font-size: calc(11.5px * var(--hud-scale)); @@ -4289,3 +4290,333 @@ body:not(.layout-mode-mobile) .stage-narrative-bar.is-compact-coexist { --hud-action-padding: calc(4px * var(--hud-scale)); flex: 0 0 auto; } + +/* M4: Historical revision banner, per-value lineage trigger, lineage drawer & Copilot mismatch guard */ +.compute-picker__revision-field { + width: 100%; + justify-content: space-between; +} + +.compute-picker__revision-field select { + max-width: calc(226px * var(--hud-scale)); + flex: 1 1 auto; +} + +.compute-revision-banner { + display: flex; + align-items: center; + gap: calc(6px * var(--hud-scale)); + width: 100%; + box-sizing: border-box; + padding: calc(5px * var(--hud-scale)) calc(10px * var(--hud-scale)); + border-top: 1px solid rgba(245, 158, 11, 0.24); + border-bottom: 1px solid rgba(245, 158, 11, 0.24); + background: rgba(245, 158, 11, 0.12); + color: #fde68a; + font-size: calc(10.8px * var(--hud-scale)); + line-height: 1.35; +} + +.compute-revision-banner.is-warning { + border-color: rgba(248, 113, 113, 0.3); + background: rgba(239, 68, 68, 0.14); + color: #fecaca; +} + +.compute-revision-banner > .material-symbols-rounded { + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + width: 1em; + height: 1em; + overflow: hidden; + font-size: calc(14px * var(--hud-scale)); + line-height: 1; + font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20; + user-select: none; + pointer-events: none; +} + +.compute-revision-banner__text { + flex: 1 1 auto; + min-width: 0; +} + +.compute-revision-banner__btn { + flex: 0 0 auto; + white-space: nowrap; +} + +.compute-card__lineage-btn { + appearance: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: calc(22px * var(--hud-scale)); + height: calc(22px * var(--hud-scale)); + margin-left: calc(2px * var(--hud-scale)); + padding: 0; + border: 1px solid rgba(147, 202, 255, 0.24); + border-radius: calc(4px * var(--hud-scale)); + background: rgba(120, 180, 255, 0.1); + color: var(--hud-accent-strong); + cursor: pointer; + align-self: center; + transition: background 0.16s ease, border-color 0.16s ease, color 0.16s ease; +} + +.compute-card__lineage-btn:hover { + background: rgba(120, 180, 255, 0.22); + border-color: rgba(147, 202, 255, 0.45); + color: #ffffff; +} + +.compute-card__lineage-btn > .material-symbols-rounded { + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + width: 1em; + height: 1em; + overflow: hidden; + font-size: calc(14px * var(--hud-scale)); + line-height: 1; + font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20; + user-select: none; + pointer-events: none; +} + +.compute-evidence__status, +.compute-evidence__empty { + margin: 0; + color: var(--hud-text-soft); + font-size: calc(11px * var(--hud-scale)); +} + +.compute-evidence__hero { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: calc(8px * var(--hud-scale)); + padding: calc(7px * var(--hud-scale)) calc(9px * var(--hud-scale)); + border: 1px solid var(--hud-line); + border-radius: calc(4px * var(--hud-scale)); + background: rgba(255, 255, 255, 0.03); +} + +.compute-evidence__hero-val { + display: inline-flex; + align-items: baseline; + gap: 4px; + font-variant-numeric: tabular-nums; +} + +.compute-evidence__hero-val strong { + font-size: calc(22px * var(--hud-scale)); + color: var(--hud-title); + line-height: 1; +} + +.compute-evidence__hero-meta { + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 2px; + font-size: calc(10.5px * var(--hud-scale)); + color: var(--hud-text-muted); +} + +.compute-evidence__hero-meta code, +.compute-evidence__hash code { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: calc(10px * var(--hud-scale)); + color: var(--hud-accent-strong); +} + +.compute-evidence__section { + display: flex; + flex-direction: column; + gap: calc(5px * var(--hud-scale)); + padding-top: calc(7px * var(--hud-scale)); + border-top: 1px solid var(--hud-line); +} + +.compute-evidence__section-title { + margin: 0; + color: var(--hud-text-soft); + font-size: calc(10.8px * var(--hud-scale)); + font-weight: 600; +} + +.compute-evidence__source-title { + margin: 0; + color: var(--hud-title); + font-size: calc(11.6px * var(--hud-scale)); + font-weight: 600; + line-height: 1.35; +} + +.compute-evidence__excerpt { + margin: 0; + padding: calc(6px * var(--hud-scale)) calc(8px * var(--hud-scale)); + border-left: 2px solid rgba(147, 202, 255, 0.36); + background: rgba(255, 255, 255, 0.03); + color: var(--hud-text-soft); + font-size: calc(10.8px * var(--hud-scale)); + line-height: 1.45; +} + +.compute-evidence__hash { + display: inline-flex; + align-items: center; + gap: 6px; + margin: 0; + font-size: calc(10.2px * var(--hud-scale)); + color: var(--hud-text-muted); +} + +.compute-evidence__ts-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: calc(5px * var(--hud-scale)); + margin: 0; +} + +.compute-evidence__ts-grid > div { + padding: calc(5px * var(--hud-scale)) calc(7px * var(--hud-scale)); + border: 1px solid var(--hud-line); + border-radius: calc(4px * var(--hud-scale)); + background: rgba(255, 255, 255, 0.025); +} + +.compute-evidence__ts-grid dt { + color: var(--hud-text-muted); + font-size: calc(9.8px * var(--hud-scale)); +} + +.compute-evidence__ts-grid dd { + margin: 2px 0 0; + color: var(--hud-text); + font-size: calc(10.8px * var(--hud-scale)); + font-variant-numeric: tabular-nums; +} + +.compute-evidence__timeline { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: calc(6px * var(--hud-scale)); +} + +.compute-evidence__timeline-item { + display: flex; + flex-direction: column; + gap: 3px; + padding: calc(6px * var(--hud-scale)) calc(8px * var(--hud-scale)); + border: 1px solid var(--hud-line); + border-radius: calc(4px * var(--hud-scale)); + background: rgba(255, 255, 255, 0.03); + font-size: calc(10.8px * var(--hud-scale)); +} + +.compute-evidence__timeline-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; +} + +.compute-evidence__badge { + padding: 1px 6px; + border-radius: 3px; + border: 1px solid rgba(147, 202, 255, 0.28); + background: rgba(120, 180, 255, 0.14); + color: var(--hud-accent-strong); + font-size: calc(9.8px * var(--hud-scale)); + font-weight: 600; +} + +.compute-evidence__badge.is-revision { + border-color: rgba(245, 158, 11, 0.36); + background: rgba(245, 158, 11, 0.16); + color: #fde68a; +} + +.compute-evidence__timeline-ts { + color: var(--hud-text-muted); + font-size: calc(10px * var(--hud-scale)); + font-variant-numeric: tabular-nums; +} + +.compute-evidence__timeline-vals { + color: var(--hud-title); + font-variant-numeric: tabular-nums; +} + +.compute-evidence__timeline-src, +.compute-evidence__timeline-actor { + color: var(--hud-text-muted); + font-size: calc(10px * var(--hud-scale)); + word-break: break-all; +} + +.compute-evidence__timeline-reason { + color: var(--hud-text-soft); +} + +.compute-evidence__timeline-note { + margin: 2px 0 0; + color: var(--hud-text-soft); + line-height: 1.4; +} + +.copilot-view-mismatch { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: calc(6px * var(--hud-scale)); + margin-bottom: calc(6px * var(--hud-scale)); + padding: calc(6px * var(--hud-scale)) calc(8px * var(--hud-scale)); + border: 1px solid rgba(245, 158, 11, 0.34); + border-radius: calc(4px * var(--hud-scale)); + background: rgba(245, 158, 11, 0.12); + color: #fde68a; + font-size: calc(10.8px * var(--hud-scale)); + line-height: 1.35; +} + +.copilot-view-mismatch > .material-symbols-rounded { + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + width: 1em; + height: 1em; + overflow: hidden; + font-size: calc(14px * var(--hud-scale)); + line-height: 1; + font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20; + color: #fbbf24; + user-select: none; + pointer-events: none; +} + +.copilot-view-mismatch__text { + flex: 1 1 160px; + min-width: 0; +} + +.copilot-view-mismatch__btn { + flex: 0 0 auto; + border-color: rgba(245, 158, 11, 0.42); + background: rgba(245, 158, 11, 0.16); + color: #fef3c7; +} + +.copilot-view-mismatch__btn:hover { + background: rgba(245, 158, 11, 0.28); + color: #ffffff; +} diff --git a/frontend/public/earth/css/hud.css b/frontend/public/earth/css/hud.css index 59b02041..dbd5d68e 100644 --- a/frontend/public/earth/css/hud.css +++ b/frontend/public/earth/css/hud.css @@ -376,6 +376,13 @@ display: none !important; } +.hud-preload-hidden-legend #legend, +.hud-preload-hidden-earth-stats #earth-stats, +.hud-preload-hidden-media-panel #media-panel, +.hud-preload-hidden-layer-toggles #layer-toggles { + display: none !important; +} + /* Shared popover select used by HUD settings and source pickers. */ .hud-select-trigger { display: inline-flex; @@ -852,7 +859,8 @@ display: flex; align-items: center; gap: 6px; - padding: 2px; + margin: -3px 0 -4px; + padding: 5px 2px 6px; overflow-x: auto; overflow-y: hidden; scrollbar-width: none; @@ -1824,11 +1832,12 @@ display: flex; align-items: center; gap: 8px; - margin: 4px 0 14px; - padding: 0; + margin: -4px -4px 4px; + padding: 8px 4px 10px; border: none; background: transparent; - width: 100%; + width: calc(100% + 8px); + box-sizing: border-box; overflow-x: auto; scrollbar-width: none; } @@ -2379,6 +2388,126 @@ 50% { transform: scale(1.18); opacity: 1; } } +.earth-layer-confirm { + position: fixed; + inset: 0; + z-index: 12100; + display: grid; + place-items: center; + padding: 20px; + pointer-events: auto; +} + +.earth-layer-confirm__scrim { + position: absolute; + inset: 0; + background: rgba(2, 7, 16, 0.56); + animation: earth-oobe-fade-in 160ms ease-out both; +} + +.earth-layer-confirm__panel { + position: relative; + z-index: 1; + width: min(460px, calc(100vw - 32px)); + padding: 22px 24px; + border-radius: var(--hud-panel-radius, 18px); + color: rgba(235, 245, 255, 0.96); + display: flex; + flex-direction: column; + gap: 12px; +} + +.earth-layer-confirm__head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.earth-layer-confirm__eyebrow { + font-size: 0.72rem; + font-weight: 800; + letter-spacing: 0.14em; + text-transform: uppercase; + color: #6ab4ff; +} + +.earth-layer-confirm__close { + width: 28px; + height: 28px; + border-radius: 999px; + border: 1px solid rgba(151, 190, 238, 0.24); + background: rgba(15, 28, 48, 0.28); + color: rgba(226, 240, 255, 0.88); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + font-size: 16px; + line-height: 1; +} + +.earth-layer-confirm__title { + margin: 0; + font-size: 1.12rem; + font-weight: 700; + line-height: 1.35; + color: #f7fbff; +} + +.earth-layer-confirm__desc { + margin: 0; + font-size: 0.88rem; + line-height: 1.6; + color: rgba(203, 222, 244, 0.88); +} + +.earth-layer-confirm__meta { + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 8px 10px; + border-radius: 10px; + border: 1px solid rgba(132, 176, 236, 0.22); + background: rgba(8, 18, 34, 0.3); + font-size: 0.78rem; + color: rgba(186, 209, 236, 0.88); +} + +.earth-layer-confirm__actions { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 10px; + margin-top: 6px; +} + +.earth-layer-confirm__primary, +.earth-layer-confirm__secondary { + min-height: 36px; + padding: 0 15px; + border-radius: 10px; + font: inherit; + font-size: 0.86rem; + font-weight: 700; + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; +} + +.earth-layer-confirm__primary { + border: 1px solid rgba(88, 164, 255, 0.78); + background: linear-gradient(180deg, rgba(78, 158, 255, 0.92), rgba(31, 103, 232, 0.92)); + color: #ffffff; +} + +.earth-layer-confirm__secondary { + border: 1px solid rgba(151, 190, 238, 0.28); + background: rgba(12, 24, 42, 0.32); + color: rgba(226, 240, 255, 0.92); +} + @media (max-width: 820px) { .earth-oobe { place-items: end center; @@ -3540,6 +3669,7 @@ label.is-disabled.earth-mobile-settings-card { gap: calc(8px * var(--hud-scale)); min-height: 0; overflow-y: auto; + padding-top: calc(2px * var(--hud-scale)); padding-right: calc(4px * var(--hud-scale)); } @@ -5126,6 +5256,74 @@ label.is-disabled.earth-mobile-settings-card { .satellite-map-label span, .satellite-map-label small { display:block; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } .satellite-map-label small { font-size:10px; font-weight:400; color:#cbd5e1; } +.geo-labels { position: absolute; inset: 0; overflow: hidden; pointer-events: none; z-index: 4; contain: layout style paint; } +.geo-labels[hidden], .geo-map-label[hidden] { display: none; } +.geo-map-label { + position: absolute; + top: 0; + left: 0; + display: inline-flex; + align-items: center; + gap: 5px; + max-width: 184px; + white-space: nowrap; + pointer-events: none; + will-change: transform, opacity; + color: rgba(226, 232, 240, 0.92); + font: 500 11px/1.2 system-ui, sans-serif; + letter-spacing: 0.02em; + text-shadow: 0 1px 3px rgba(2, 6, 23, 0.95), 0 0 6px rgba(2, 6, 23, 0.85); +} +.geo-map-label__dot { + flex: none; + width: 4px; + height: 4px; + border-radius: 50%; + background: rgba(148, 163, 184, 0.9); + box-shadow: 0 0 0 1px rgba(2, 6, 23, 0.85); +} +.geo-map-label__name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.geo-map-label[data-kind="capital"] { + color: #fef3c7; + font-size: 11.5px; + font-weight: 600; +} +.geo-map-label[data-kind="capital"] .geo-map-label__dot { + width: 6px; + height: 6px; + background: #fde68a; + box-shadow: 0 0 0 1.5px rgba(254, 243, 199, 0.35), 0 0 6px rgba(253, 230, 138, 0.45); +} +.geo-map-label[data-kind="megacity"] { + color: #f8fafc; + font-size: 11px; + font-weight: 600; +} +.geo-map-label[data-kind="megacity"] .geo-map-label__dot { + width: 4.5px; + height: 4.5px; + background: #e2e8f0; +} +.geo-map-label[data-kind="major"] { + color: rgba(226, 232, 240, 0.88); + font-size: 10.5px; + font-weight: 500; +} +.geo-map-label[data-kind="admin1"] { + color: rgba(203, 213, 225, 0.82); + font-size: 10px; + font-weight: 400; +} +.geo-map-label[data-kind="admin1"] .geo-map-label__dot { + width: 3.5px; + height: 3.5px; + background: rgba(148, 163, 184, 0.72); +} + /* Only aggregate/expanded points use DOM; ordinary markers stay GPU-batched. */ .map-clusters { position:absolute; inset:0; pointer-events:none; z-index:5; } .map-clusters__legs { position:absolute; inset:0; width:100%; height:100%; overflow:visible; pointer-events:none; } diff --git a/frontend/public/earth/data/countries-admin0.min.geojson b/frontend/public/earth/data/countries-admin0.min.geojson deleted file mode 100644 index e8273b89..00000000 --- a/frontend/public/earth/data/countries-admin0.min.geojson +++ /dev/null @@ -1 +0,0 @@ -{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"ADMIN":"Fiji","NAME_EN":"Fiji","CONTINENT":"Oceania","ADM0_A3":"FJI","ISO_A3":"FJI","NAME":"Fiji","ISO_A2":"FJ","NAME_ZH":"斐济"},"geometry":{"type":"MultiPolygon","coordinates":[[[[180,-16.067133],[180,-16.555217],[179.364143,-16.801354],[178.725059,-17.012042],[178.596839,-16.63915],[179.096609,-16.433984],[179.413509,-16.379054],[180,-16.067133]]],[[[178.12557,-17.50481],[178.3736,-17.33992],[178.71806,-17.62846],[178.55271,-18.15059],[177.93266,-18.28799],[177.38146,-18.16432],[177.28504,-17.72465],[177.67087,-17.38114],[178.12557,-17.50481]]],[[[-179.79332,-16.020882],[-179.917369,-16.501783],[-180,-16.555217],[-180,-16.067133],[-179.79332,-16.020882]]]]}},{"type":"Feature","properties":{"ADMIN":"United Republic of Tanzania","NAME_EN":"Tanzania","CONTINENT":"Africa","ADM0_A3":"TZA","ISO_A3":"TZA","NAME":"Tanzania","ISO_A2":"TZ","NAME_ZH":"坦桑尼亚"},"geometry":{"type":"Polygon","coordinates":[[[33.903711,-0.95],[34.07262,-1.05982],[37.69869,-3.09699],[37.7669,-3.67712],[39.20222,-4.67677],[38.74054,-5.90895],[38.79977,-6.47566],[39.44,-6.84],[39.47,-7.1],[39.19469,-7.7039],[39.25203,-8.00781],[39.18652,-8.48551],[39.53574,-9.11237],[39.9496,-10.0984],[40.316586,-10.317098],[40.31659,-10.3171],[39.521,-10.89688],[38.427557,-11.285202],[37.82764,-11.26879],[37.47129,-11.56876],[36.775151,-11.594537],[36.514082,-11.720938],[35.312398,-11.439146],[34.559989,-11.52002],[34.28,-10.16],[33.940838,-9.693674],[33.73972,-9.41715],[32.759375,-9.230599],[32.191865,-8.930359],[31.556348,-8.762049],[31.157751,-8.594579],[30.74001,-8.340006],[30.740015,-8.340007],[30.199997,-7.079981],[29.620032,-6.520015],[29.419993,-5.939999],[29.519987,-5.419979],[29.339998,-4.499983],[29.753512,-4.452389],[30.11632,-4.09012],[30.50554,-3.56858],[30.75224,-3.35931],[30.74301,-3.03431],[30.52766,-2.80762],[30.469674,-2.413855],[30.46967,-2.41383],[30.758309,-2.28725],[30.816135,-1.698914],[30.419105,-1.134659],[30.76986,-1.01455],[31.86617,-1.02736],[33.903711,-0.95]]]}},{"type":"Feature","properties":{"ADMIN":"Western Sahara","NAME_EN":"Western Sahara","CONTINENT":"Africa","ADM0_A3":"SAH","ISO_A3":"ESH","NAME":"W. Sahara","ISO_A2":"EH","NAME_ZH":"西撒哈拉"},"geometry":{"type":"Polygon","coordinates":[[[-8.66559,27.656426],[-8.665124,27.589479],[-8.6844,27.395744],[-8.687294,25.881056],[-11.969419,25.933353],[-11.937224,23.374594],[-12.874222,23.284832],[-13.118754,22.77122],[-12.929102,21.327071],[-16.845194,21.333323],[-17.063423,20.999752],[-17.020428,21.42231],[-17.002962,21.420734],[-14.750955,21.5006],[-14.630833,21.86094],[-14.221168,22.310163],[-13.89111,23.691009],[-12.500963,24.770116],[-12.030759,26.030866],[-11.71822,26.104092],[-11.392555,26.883424],[-10.551263,26.990808],[-10.189424,26.860945],[-9.735343,26.860945],[-9.413037,27.088476],[-8.794884,27.120696],[-8.817828,27.656426],[-8.66559,27.656426]]]}},{"type":"Feature","properties":{"ADMIN":"Canada","NAME_EN":"Canada","CONTINENT":"North America","ADM0_A3":"CAN","ISO_A3":"CAN","NAME":"Canada","ISO_A2":"CA","NAME_ZH":"加拿大"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-122.84,49],[-122.97421,49.002538],[-124.91024,49.98456],[-125.62461,50.41656],[-127.43561,50.83061],[-127.99276,51.71583],[-127.85032,52.32961],[-129.12979,52.75538],[-129.30523,53.56159],[-130.51497,54.28757],[-130.536109,54.802754],[-130.53611,54.80278],[-129.98,55.285],[-130.00778,55.91583],[-131.70781,56.55212],[-132.73042,57.69289],[-133.35556,58.41028],[-134.27111,58.86111],[-134.945,59.27056],[-135.47583,59.78778],[-136.47972,59.46389],[-137.4525,58.905],[-138.34089,59.56211],[-139.039,60],[-140.013,60.27682],[-140.99778,60.30639],[-140.9925,66.00003],[-140.986,69.712],[-140.985988,69.711998],[-139.12052,69.47102],[-137.54636,68.99002],[-136.50358,68.89804],[-135.62576,69.31512],[-134.41464,69.62743],[-132.92925,69.50534],[-131.43136,69.94451],[-129.79471,70.19369],[-129.10773,69.77927],[-128.36156,70.01286],[-128.13817,70.48384],[-127.44712,70.37721],[-125.75632,69.48058],[-124.42483,70.1584],[-124.28968,69.39969],[-123.06108,69.56372],[-122.6835,69.85553],[-121.47226,69.79778],[-119.94288,69.37786],[-117.60268,69.01128],[-116.22643,68.84151],[-115.2469,68.90591],[-113.89794,68.3989],[-115.30489,67.90261],[-113.49727,67.68815],[-110.798,67.80612],[-109.94619,67.98104],[-108.8802,67.38144],[-107.79239,67.88736],[-108.81299,68.31164],[-108.16721,68.65392],[-106.95,68.7],[-106.15,68.8],[-105.34282,68.56122],[-104.33791,68.018],[-103.22115,68.09775],[-101.45433,67.64689],[-99.90195,67.80566],[-98.4432,67.78165],[-98.5586,68.40394],[-97.66948,68.57864],[-96.11991,68.23939],[-96.12588,67.29338],[-95.48943,68.0907],[-94.685,68.06383],[-94.23282,69.06903],[-95.30408,69.68571],[-96.47131,70.08976],[-96.39115,71.19482],[-95.2088,71.92053],[-93.88997,71.76015],[-92.87818,71.31869],[-91.51964,70.19129],[-92.40692,69.69997],[-90.5471,69.49766],[-90.55151,68.47499],[-89.21515,69.25873],[-88.01966,68.61508],[-88.31749,67.87338],[-87.35017,67.19872],[-86.30607,67.92146],[-85.57664,68.78456],[-85.52197,69.88211],[-84.10081,69.80539],[-82.62258,69.65826],[-81.28043,69.16202],[-81.2202,68.66567],[-81.96436,68.13253],[-81.25928,67.59716],[-81.38653,67.11078],[-83.34456,66.41154],[-84.73542,66.2573],[-85.76943,66.55833],[-86.0676,66.05625],[-87.03143,65.21297],[-87.32324,64.77563],[-88.48296,64.09897],[-89.91444,64.03273],[-90.70398,63.61017],[-90.77004,62.96021],[-91.93342,62.83508],[-93.15698,62.02469],[-94.24153,60.89865],[-94.62931,60.11021],[-94.6846,58.94882],[-93.21502,58.78212],[-92.76462,57.84571],[-92.29703,57.08709],[-90.89769,57.28468],[-89.03953,56.85172],[-88.03978,56.47162],[-87.32421,55.99914],[-86.07121,55.72383],[-85.01181,55.3026],[-83.36055,55.24489],[-82.27285,55.14832],[-82.4362,54.28227],[-82.12502,53.27703],[-81.40075,52.15788],[-79.91289,51.20842],[-79.14301,51.53393],[-78.60191,52.56208],[-79.12421,54.14145],[-79.82958,54.66772],[-78.22874,55.13645],[-77.0956,55.83741],[-76.54137,56.53423],[-76.62319,57.20263],[-77.30226,58.05209],[-78.51688,58.80458],[-77.33676,59.85261],[-77.77272,60.75788],[-78.10687,62.31964],[-77.41067,62.55053],[-75.69621,62.2784],[-74.6682,62.18111],[-73.83988,62.4438],[-72.90853,62.10507],[-71.67708,61.52535],[-71.37369,61.13717],[-69.59042,61.06141],[-69.62033,60.22125],[-69.2879,58.95736],[-68.37455,58.80106],[-67.64976,58.21206],[-66.20178,58.76731],[-65.24517,59.87071],[-64.58352,60.33558],[-63.80475,59.4426],[-62.50236,58.16708],[-61.39655,56.96745],[-61.79866,56.33945],[-60.46853,55.77548],[-59.56962,55.20407],[-57.97508,54.94549],[-57.3332,54.6265],[-56.93689,53.78032],[-56.15811,53.64749],[-55.75632,53.27036],[-55.68338,52.14664],[-56.40916,51.7707],[-57.12691,51.41972],[-58.77482,51.0643],[-60.03309,50.24277],[-61.72366,50.08046],[-63.86251,50.29099],[-65.36331,50.2982],[-66.39905,50.22897],[-67.23631,49.51156],[-68.51114,49.06836],[-69.95362,47.74488],[-71.10458,46.82171],[-70.25522,46.98606],[-68.65,48.3],[-66.55243,49.1331],[-65.05626,49.23278],[-64.17099,48.74248],[-65.11545,48.07085],[-64.79854,46.99297],[-64.47219,46.23849],[-63.17329,45.73902],[-61.52072,45.88377],[-60.51815,47.00793],[-60.4486,46.28264],[-59.80287,45.9204],[-61.03988,45.26525],[-63.25471,44.67014],[-64.24656,44.26553],[-65.36406,43.54523],[-66.1234,43.61867],[-66.16173,44.46512],[-64.42549,45.29204],[-66.02605,45.25931],[-67.13741,45.13753],[-67.79134,45.70281],[-67.79046,47.06636],[-68.23444,47.35486],[-68.905,47.185],[-69.237216,47.447781],[-69.99997,46.69307],[-70.305,45.915],[-70.66,45.46],[-71.08482,45.30524],[-71.405,45.255],[-71.50506,45.0082],[-73.34783,45.00738],[-74.867,45.00048],[-75.31821,44.81645],[-76.375,44.09631],[-76.5,44.018459],[-76.820034,43.628784],[-77.737885,43.629056],[-78.72028,43.625089],[-79.171674,43.466339],[-79.01,43.27],[-78.92,42.965],[-78.939362,42.863611],[-80.247448,42.3662],[-81.277747,42.209026],[-82.439278,41.675105],[-82.690089,41.675105],[-83.02981,41.832796],[-83.142,41.975681],[-83.12,42.08],[-82.9,42.43],[-82.43,42.98],[-82.137642,43.571088],[-82.337763,44.44],[-82.550925,45.347517],[-83.592851,45.816894],[-83.469551,45.994686],[-83.616131,46.116927],[-83.890765,46.116927],[-84.091851,46.275419],[-84.14212,46.512226],[-84.3367,46.40877],[-84.6049,46.4396],[-84.543749,46.538684],[-84.779238,46.637102],[-84.87608,46.900083],[-85.652363,47.220219],[-86.461991,47.553338],[-87.439793,47.94],[-88.378114,48.302918],[-89.272917,48.019808],[-89.6,48.01],[-90.83,48.27],[-91.64,48.14],[-92.61,48.45],[-93.63087,48.60926],[-94.32914,48.67074],[-94.64,48.84],[-94.81758,49.38905],[-95.15609,49.38425],[-95.15907,49],[-97.22872,49.0007],[-100.65,49],[-104.04826,48.99986],[-107.05,49],[-110.05,49],[-113,49],[-116.04818,49],[-117.03121,49],[-120,49],[-122.84,49]]],[[[-83.99367,62.4528],[-83.25048,62.91409],[-81.87699,62.90458],[-81.89825,62.7108],[-83.06857,62.15922],[-83.77462,62.18231],[-83.99367,62.4528]]],[[[-79.775833,72.802902],[-80.876099,73.333183],[-80.833885,73.693184],[-80.353058,73.75972],[-78.064438,73.651932],[-76.34,73.102685],[-76.251404,72.826385],[-77.314438,72.855545],[-78.39167,72.876656],[-79.486252,72.742203],[-79.775833,72.802902]]],[[[-80.315395,62.085565],[-79.92939,62.3856],[-79.52002,62.36371],[-79.26582,62.158675],[-79.65752,61.63308],[-80.09956,61.7181],[-80.36215,62.01649],[-80.315395,62.085565]]],[[[-93.612756,74.979997],[-94.156909,74.592347],[-95.608681,74.666864],[-96.820932,74.927623],[-96.288587,75.377828],[-94.85082,75.647218],[-93.977747,75.29649],[-93.612756,74.979997]]],[[[-93.840003,77.519997],[-94.295608,77.491343],[-96.169654,77.555111],[-96.436304,77.834629],[-94.422577,77.820005],[-93.720656,77.634331],[-93.840003,77.519997]]],[[[-96.754399,78.765813],[-95.559278,78.418315],[-95.830295,78.056941],[-97.309843,77.850597],[-98.124289,78.082857],[-98.552868,78.458105],[-98.631984,78.87193],[-97.337231,78.831984],[-96.754399,78.765813]]],[[[-88.15035,74.392307],[-89.764722,74.515555],[-92.422441,74.837758],[-92.768285,75.38682],[-92.889906,75.882655],[-93.893824,76.319244],[-95.962457,76.441381],[-97.121379,76.751078],[-96.745123,77.161389],[-94.684086,77.097878],[-93.573921,76.776296],[-91.605023,76.778518],[-90.741846,76.449597],[-90.969661,76.074013],[-89.822238,75.847774],[-89.187083,75.610166],[-87.838276,75.566189],[-86.379192,75.482421],[-84.789625,75.699204],[-82.753445,75.784315],[-81.128531,75.713983],[-80.057511,75.336849],[-79.833933,74.923127],[-80.457771,74.657304],[-81.948843,74.442459],[-83.228894,74.564028],[-86.097452,74.410032],[-88.15035,74.392307]]],[[[-111.264443,78.152956],[-109.854452,77.996325],[-110.186938,77.697015],[-112.051191,77.409229],[-113.534279,77.732207],[-112.724587,78.05105],[-111.264443,78.152956]]],[[[-110.963661,78.804441],[-109.663146,78.601973],[-110.881314,78.40692],[-112.542091,78.407902],[-112.525891,78.550555],[-111.50001,78.849994],[-110.963661,78.804441]]],[[[-55.600218,51.317075],[-56.134036,50.68701],[-56.795882,49.812309],[-56.143105,50.150117],[-55.471492,49.935815],[-55.822401,49.587129],[-54.935143,49.313011],[-54.473775,49.556691],[-53.476549,49.249139],[-53.786014,48.516781],[-53.086134,48.687804],[-52.958648,48.157164],[-52.648099,47.535548],[-53.069158,46.655499],[-53.521456,46.618292],[-54.178936,46.807066],[-53.961869,47.625207],[-54.240482,47.752279],[-55.400773,46.884994],[-55.997481,46.91972],[-55.291219,47.389562],[-56.250799,47.632545],[-57.325229,47.572807],[-59.266015,47.603348],[-59.419494,47.899454],[-58.796586,48.251525],[-59.231625,48.523188],[-58.391805,49.125581],[-57.35869,50.718274],[-56.73865,51.287438],[-55.870977,51.632094],[-55.406974,51.588273],[-55.600218,51.317075]]],[[[-83.882626,65.109618],[-82.787577,64.766693],[-81.642014,64.455136],[-81.55344,63.979609],[-80.817361,64.057486],[-80.103451,63.725981],[-80.99102,63.411246],[-82.547178,63.651722],[-83.108798,64.101876],[-84.100417,63.569712],[-85.523405,63.052379],[-85.866769,63.637253],[-87.221983,63.541238],[-86.35276,64.035833],[-86.224886,64.822917],[-85.883848,65.738778],[-85.161308,65.657285],[-84.975764,65.217518],[-84.464012,65.371772],[-83.882626,65.109618]]],[[[-78.770639,72.352173],[-77.824624,72.749617],[-75.605845,72.243678],[-74.228616,71.767144],[-74.099141,71.33084],[-72.242226,71.556925],[-71.200015,70.920013],[-68.786054,70.525024],[-67.91497,70.121948],[-66.969033,69.186087],[-68.805123,68.720198],[-66.449866,68.067163],[-64.862314,67.847539],[-63.424934,66.928473],[-61.851981,66.862121],[-62.163177,66.160251],[-63.918444,64.998669],[-65.14886,65.426033],[-66.721219,66.388041],[-68.015016,66.262726],[-68.141287,65.689789],[-67.089646,65.108455],[-65.73208,64.648406],[-65.320168,64.382737],[-64.669406,63.392927],[-65.013804,62.674185],[-66.275045,62.945099],[-68.783186,63.74567],[-67.369681,62.883966],[-66.328297,62.280075],[-66.165568,61.930897],[-68.877367,62.330149],[-71.023437,62.910708],[-72.235379,63.397836],[-71.886278,63.679989],[-73.378306,64.193963],[-74.834419,64.679076],[-74.818503,64.389093],[-77.70998,64.229542],[-78.555949,64.572906],[-77.897281,65.309192],[-76.018274,65.326969],[-73.959795,65.454765],[-74.293883,65.811771],[-73.944912,66.310578],[-72.651167,67.284576],[-72.92606,67.726926],[-73.311618,68.069437],[-74.843307,68.554627],[-76.869101,68.894736],[-76.228649,69.147769],[-77.28737,69.76954],[-78.168634,69.826488],[-78.957242,70.16688],[-79.492455,69.871808],[-81.305471,69.743185],[-84.944706,69.966634],[-87.060003,70.260001],[-88.681713,70.410741],[-89.51342,70.762038],[-88.467721,71.218186],[-89.888151,71.222552],[-90.20516,72.235074],[-89.436577,73.129464],[-88.408242,73.537889],[-85.826151,73.803816],[-86.562179,73.157447],[-85.774371,72.534126],[-84.850112,73.340278],[-82.31559,73.750951],[-80.600088,72.716544],[-80.748942,72.061907],[-78.770639,72.352173]]],[[[-94.503658,74.134907],[-92.420012,74.100025],[-90.509793,73.856732],[-92.003965,72.966244],[-93.196296,72.771992],[-94.269047,72.024596],[-95.409856,72.061881],[-96.033745,72.940277],[-96.018268,73.43743],[-95.495793,73.862417],[-94.503658,74.134907]]],[[[-122.854924,76.116543],[-122.854925,76.116543],[-121.157535,76.864508],[-119.103939,77.51222],[-117.570131,77.498319],[-116.198587,77.645287],[-116.335813,76.876962],[-117.106051,76.530032],[-118.040412,76.481172],[-119.899318,76.053213],[-121.499995,75.900019],[-122.854924,76.116543]]],[[[-132.710008,54.040009],[-131.74999,54.120004],[-132.04948,52.984621],[-131.179043,52.180433],[-131.57783,52.182371],[-132.180428,52.639707],[-132.549992,53.100015],[-133.054611,53.411469],[-133.239664,53.85108],[-133.180004,54.169975],[-132.710008,54.040009]]],[[[-105.492289,79.301594],[-103.529282,79.165349],[-100.825158,78.800462],[-100.060192,78.324754],[-99.670939,77.907545],[-101.30394,78.018985],[-102.949809,78.343229],[-105.176133,78.380332],[-104.210429,78.67742],[-105.41958,78.918336],[-105.492289,79.301594]]],[[[-123.510002,48.510011],[-124.012891,48.370846],[-125.655013,48.825005],[-125.954994,49.179996],[-126.850004,49.53],[-127.029993,49.814996],[-128.059336,49.994959],[-128.444584,50.539138],[-128.358414,50.770648],[-127.308581,50.552574],[-126.695001,50.400903],[-125.755007,50.295018],[-125.415002,49.950001],[-124.920768,49.475275],[-123.922509,49.062484],[-123.510002,48.510011]]],[[[-121.53788,74.44893],[-120.10978,74.24135],[-117.55564,74.18577],[-116.58442,73.89607],[-115.51081,73.47519],[-116.76794,73.22292],[-119.22,72.52],[-120.46,71.82],[-120.46,71.383602],[-123.09219,70.90164],[-123.62,71.34],[-125.928949,71.868688],[-125.5,72.292261],[-124.80729,73.02256],[-123.94,73.68],[-124.91775,74.29275],[-121.53788,74.44893]]],[[[-107.81943,75.84552],[-106.92893,76.01282],[-105.881,75.9694],[-105.70498,75.47951],[-106.31347,75.00527],[-109.7,74.85],[-112.22307,74.41696],[-113.74381,74.39427],[-113.87135,74.72029],[-111.79421,75.1625],[-116.31221,75.04343],[-117.7104,75.2222],[-116.34602,76.19903],[-115.40487,76.47887],[-112.59056,76.14134],[-110.81422,75.54919],[-109.0671,75.47321],[-110.49726,76.42982],[-109.5811,76.79417],[-108.54859,76.67832],[-108.21141,76.20168],[-107.81943,75.84552]]],[[[-106.52259,73.07601],[-105.40246,72.67259],[-104.77484,71.6984],[-104.46476,70.99297],[-102.78537,70.49776],[-100.98078,70.02432],[-101.08929,69.58447],[-102.73116,69.50402],[-102.09329,69.11962],[-102.43024,68.75282],[-104.24,68.91],[-105.96,69.18],[-107.12254,69.11922],[-109,68.78],[-111.534149,68.630059],[-113.3132,68.53554],[-113.85496,69.00744],[-115.22,69.28],[-116.10794,69.16821],[-117.34,69.96],[-116.67473,70.06655],[-115.13112,70.2373],[-113.72141,70.19237],[-112.4161,70.36638],[-114.35,70.6],[-116.48684,70.52045],[-117.9048,70.54056],[-118.43238,70.9092],[-116.11311,71.30918],[-117.65568,71.2952],[-119.40199,71.55859],[-118.56267,72.30785],[-117.86642,72.70594],[-115.18909,73.31459],[-114.16717,73.12145],[-114.66634,72.65277],[-112.44102,72.9554],[-111.05039,72.4504],[-109.92035,72.96113],[-109.00654,72.63335],[-108.18835,71.65089],[-107.68599,72.06548],[-108.39639,73.08953],[-107.51645,73.23598],[-106.52259,73.07601]]],[[[-100.43836,72.70588],[-101.54,73.36],[-100.35642,73.84389],[-99.16387,73.63339],[-97.38,73.76],[-97.12,73.47],[-98.05359,72.99052],[-96.54,72.56],[-96.72,71.66],[-98.35966,71.27285],[-99.32286,71.35639],[-100.01482,71.73827],[-102.5,72.51],[-102.48,72.83],[-100.43836,72.70588]]],[[[-106.6,73.6],[-105.26,73.64],[-104.5,73.42],[-105.38,72.76],[-106.94,73.46],[-106.6,73.6]]],[[[-98.5,76.72],[-97.735585,76.25656],[-97.704415,75.74344],[-98.16,75],[-99.80874,74.89744],[-100.88366,75.05736],[-100.86292,75.64075],[-102.50209,75.5638],[-102.56552,76.3366],[-101.48973,76.30537],[-99.98349,76.64634],[-98.57699,76.58859],[-98.5,76.72]]],[[[-96.01644,80.60233],[-95.32345,80.90729],[-94.29843,80.97727],[-94.73542,81.20646],[-92.40984,81.25739],[-91.13289,80.72345],[-89.45,80.509322],[-87.81,80.32],[-87.02,79.66],[-85.81435,79.3369],[-87.18756,79.0393],[-89.03535,78.28723],[-90.80436,78.21533],[-92.87669,78.34333],[-93.95116,78.75099],[-93.93574,79.11373],[-93.14524,79.3801],[-94.974,79.37248],[-96.07614,79.70502],[-96.70972,80.15777],[-96.01644,80.60233]]],[[[-91.58702,81.89429],[-90.1,82.085],[-88.93227,82.11751],[-86.97024,82.27961],[-85.5,82.652273],[-84.260005,82.6],[-83.18,82.32],[-82.42,82.86],[-81.1,83.02],[-79.30664,83.13056],[-76.25,83.172059],[-75.71878,83.06404],[-72.83153,83.23324],[-70.665765,83.169781],[-68.5,83.106322],[-65.82735,83.02801],[-63.68,82.9],[-61.85,82.6286],[-61.89388,82.36165],[-64.334,81.92775],[-66.75342,81.72527],[-67.65755,81.50141],[-65.48031,81.50657],[-67.84,80.9],[-69.4697,80.61683],[-71.18,79.8],[-73.2428,79.63415],[-73.88,79.430162],[-76.90773,79.32309],[-75.52924,79.19766],[-76.22046,79.01907],[-75.39345,78.52581],[-76.34354,78.18296],[-77.88851,77.89991],[-78.36269,77.50859],[-79.75951,77.20968],[-79.61965,76.98336],[-77.91089,77.022045],[-77.88911,76.777955],[-80.56125,76.17812],[-83.17439,76.45403],[-86.11184,76.29901],[-87.6,76.42],[-89.49068,76.47239],[-89.6161,76.95213],[-87.76739,77.17833],[-88.26,77.9],[-87.65,77.970222],[-84.97634,77.53873],[-86.34,78.18],[-87.96192,78.37181],[-87.15198,78.75867],[-85.37868,78.9969],[-85.09495,79.34543],[-86.50734,79.73624],[-86.93179,80.25145],[-84.19844,80.20836],[-83.408696,80.1],[-81.84823,80.46442],[-84.1,80.58],[-87.59895,80.51627],[-89.36663,80.85569],[-90.2,81.26],[-91.36786,81.5531],[-91.58702,81.89429]]],[[[-75.21597,67.44425],[-75.86588,67.14886],[-76.98687,67.09873],[-77.2364,67.58809],[-76.81166,68.14856],[-75.89521,68.28721],[-75.1145,68.01036],[-75.10333,67.58202],[-75.21597,67.44425]]],[[[-96.257401,69.49003],[-95.647681,69.10769],[-96.269521,68.75704],[-97.617401,69.06003],[-98.431801,68.9507],[-99.797401,69.40003],[-98.917401,69.71003],[-98.218261,70.14354],[-97.157401,69.86003],[-96.557401,69.68003],[-96.257401,69.49003]]],[[[-64.51912,49.87304],[-64.17322,49.95718],[-62.85829,49.70641],[-61.835585,49.28855],[-61.806305,49.10506],[-62.29318,49.08717],[-63.58926,49.40069],[-64.51912,49.87304]]],[[[-64.01486,47.03601],[-63.6645,46.55001],[-62.9393,46.41587],[-62.01208,46.44314],[-62.50391,46.03339],[-62.87433,45.96818],[-64.1428,46.39265],[-64.39261,46.72747],[-64.01486,47.03601]]]]}},{"type":"Feature","properties":{"ADMIN":"United States of America","NAME_EN":"United States of America","CONTINENT":"North America","ADM0_A3":"USA","ISO_A3":"USA","NAME":"United States of America","ISO_A2":"US","NAME_ZH":"美国"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-122.84,49],[-120,49],[-117.03121,49],[-116.04818,49],[-113,49],[-110.05,49],[-107.05,49],[-104.04826,48.99986],[-100.65,49],[-97.22872,49.0007],[-95.15907,49],[-95.15609,49.38425],[-94.81758,49.38905],[-94.64,48.84],[-94.32914,48.67074],[-93.63087,48.60926],[-92.61,48.45],[-91.64,48.14],[-90.83,48.27],[-89.6,48.01],[-89.272917,48.019808],[-88.378114,48.302918],[-87.439793,47.94],[-86.461991,47.553338],[-85.652363,47.220219],[-84.87608,46.900083],[-84.779238,46.637102],[-84.543749,46.538684],[-84.6049,46.4396],[-84.3367,46.40877],[-84.14212,46.512226],[-84.091851,46.275419],[-83.890765,46.116927],[-83.616131,46.116927],[-83.469551,45.994686],[-83.592851,45.816894],[-82.550925,45.347517],[-82.337763,44.44],[-82.137642,43.571088],[-82.43,42.98],[-82.9,42.43],[-83.12,42.08],[-83.142,41.975681],[-83.02981,41.832796],[-82.690089,41.675105],[-82.439278,41.675105],[-81.277747,42.209026],[-80.247448,42.3662],[-78.939362,42.863611],[-78.92,42.965],[-79.01,43.27],[-79.171674,43.466339],[-78.72028,43.625089],[-77.737885,43.629056],[-76.820034,43.628784],[-76.5,44.018459],[-76.375,44.09631],[-75.31821,44.81645],[-74.867,45.00048],[-73.34783,45.00738],[-71.50506,45.0082],[-71.405,45.255],[-71.08482,45.30524],[-70.66,45.46],[-70.305,45.915],[-69.99997,46.69307],[-69.237216,47.447781],[-68.905,47.185],[-68.23444,47.35486],[-67.79046,47.06636],[-67.79134,45.70281],[-67.13741,45.13753],[-66.96466,44.8097],[-68.03252,44.3252],[-69.06,43.98],[-70.11617,43.68405],[-70.645476,43.090238],[-70.81489,42.8653],[-70.825,42.335],[-70.495,41.805],[-70.08,41.78],[-70.185,42.145],[-69.88497,41.92283],[-69.96503,41.63717],[-70.64,41.475],[-71.12039,41.49445],[-71.86,41.32],[-72.295,41.27],[-72.87643,41.22065],[-73.71,40.931102],[-72.24126,41.11948],[-71.945,40.93],[-73.345,40.63],[-73.982,40.628],[-73.952325,40.75075],[-74.25671,40.47351],[-73.96244,40.42763],[-74.17838,39.70926],[-74.90604,38.93954],[-74.98041,39.1964],[-75.20002,39.24845],[-75.52805,39.4985],[-75.32,38.96],[-75.071835,38.782032],[-75.05673,38.40412],[-75.37747,38.01551],[-75.94023,37.21689],[-76.03127,37.2566],[-75.72205,37.93705],[-76.23287,38.319215],[-76.35,39.15],[-76.542725,38.717615],[-76.32933,38.08326],[-76.989998,38.239992],[-76.30162,37.917945],[-76.25874,36.9664],[-75.9718,36.89726],[-75.86804,36.55125],[-75.72749,35.55074],[-76.36318,34.80854],[-77.397635,34.51201],[-78.05496,33.92547],[-78.55435,33.86133],[-79.06067,33.49395],[-79.20357,33.15839],[-80.301325,32.509355],[-80.86498,32.0333],[-81.33629,31.44049],[-81.49042,30.72999],[-81.31371,30.03552],[-80.98,29.18],[-80.535585,28.47213],[-80.53,28.04],[-80.056539,26.88],[-80.088015,26.205765],[-80.13156,25.816775],[-80.38103,25.20616],[-80.68,25.08],[-81.17213,25.20126],[-81.33,25.64],[-81.71,25.87],[-82.24,26.73],[-82.70515,27.49504],[-82.85526,27.88624],[-82.65,28.55],[-82.93,29.1],[-83.70959,29.93656],[-84.1,30.09],[-85.10882,29.63615],[-85.28784,29.68612],[-85.7731,30.15261],[-86.4,30.4],[-87.53036,30.27433],[-88.41782,30.3849],[-89.18049,30.31598],[-89.593831,30.159994],[-89.413735,29.89419],[-89.43,29.48864],[-89.21767,29.29108],[-89.40823,29.15961],[-89.77928,29.30714],[-90.15463,29.11743],[-90.880225,29.148535],[-91.626785,29.677],[-92.49906,29.5523],[-93.22637,29.78375],[-93.84842,29.71363],[-94.69,29.48],[-95.60026,28.73863],[-96.59404,28.30748],[-97.14,27.83],[-97.37,27.38],[-97.38,26.69],[-97.33,26.21],[-97.14,25.87],[-97.53,25.84],[-98.24,26.06],[-99.02,26.37],[-99.3,26.84],[-99.52,27.54],[-100.11,28.11],[-100.45584,28.69612],[-100.9576,29.38071],[-101.6624,29.7793],[-102.48,29.76],[-103.11,28.97],[-103.94,29.27],[-104.45697,29.57196],[-104.70575,30.12173],[-105.03737,30.64402],[-105.63159,31.08383],[-106.1429,31.39995],[-106.50759,31.75452],[-108.24,31.754854],[-108.24194,31.34222],[-109.035,31.34194],[-111.02361,31.33472],[-113.30498,32.03914],[-114.815,32.52528],[-114.72139,32.72083],[-115.99135,32.61239],[-117.12776,32.53534],[-117.295938,33.046225],[-117.944,33.621236],[-118.410602,33.740909],[-118.519895,34.027782],[-119.081,34.078],[-119.438841,34.348477],[-120.36778,34.44711],[-120.62286,34.60855],[-120.74433,35.15686],[-121.71457,36.16153],[-122.54747,37.55176],[-122.51201,37.78339],[-122.95319,38.11371],[-123.7272,38.95166],[-123.86517,39.76699],[-124.39807,40.3132],[-124.17886,41.14202],[-124.2137,41.99964],[-124.53284,42.76599],[-124.14214,43.70838],[-124.020535,44.615895],[-123.89893,45.52341],[-124.079635,46.86475],[-124.39567,47.72017],[-124.68721,48.184433],[-124.566101,48.379715],[-123.12,48.04],[-122.58736,47.096],[-122.34,47.36],[-122.5,48.18],[-122.84,49]]],[[[-155.40214,20.07975],[-155.22452,19.99302],[-155.06226,19.8591],[-154.80741,19.50871],[-154.83147,19.45328],[-155.22217,19.23972],[-155.54211,19.08348],[-155.68817,18.91619],[-155.93665,19.05939],[-155.90806,19.33888],[-156.07347,19.70294],[-156.02368,19.81422],[-155.85008,19.97729],[-155.91907,20.17395],[-155.86108,20.26721],[-155.78505,20.2487],[-155.40214,20.07975]]],[[[-155.99566,20.76404],[-156.07926,20.64397],[-156.41445,20.57241],[-156.58673,20.783],[-156.70167,20.8643],[-156.71055,20.92676],[-156.61258,21.01249],[-156.25711,20.91745],[-155.99566,20.76404]]],[[[-156.75824,21.17684],[-156.78933,21.06873],[-157.32521,21.09777],[-157.25027,21.21958],[-156.75824,21.17684]]],[[[-158.0252,21.71696],[-157.94161,21.65272],[-157.65283,21.32217],[-157.70703,21.26442],[-157.7786,21.27729],[-158.12667,21.31244],[-158.2538,21.53919],[-158.29265,21.57912],[-158.0252,21.71696]]],[[[-159.36569,22.21494],[-159.34512,21.982],[-159.46372,21.88299],[-159.80051,22.06533],[-159.74877,22.1382],[-159.5962,22.23618],[-159.36569,22.21494]]],[[[-166.467792,60.38417],[-165.67443,60.293607],[-165.579164,59.909987],[-166.19277,59.754441],[-166.848337,59.941406],[-167.455277,60.213069],[-166.467792,60.38417]]],[[[-153.228729,57.968968],[-152.564791,57.901427],[-152.141147,57.591059],[-153.006314,57.115842],[-154.00509,56.734677],[-154.516403,56.992749],[-154.670993,57.461196],[-153.76278,57.816575],[-153.228729,57.968968]]],[[[-140.985988,69.711998],[-140.986,69.712],[-140.9925,66.00003],[-140.99778,60.30639],[-140.013,60.27682],[-139.039,60],[-138.34089,59.56211],[-137.4525,58.905],[-136.47972,59.46389],[-135.47583,59.78778],[-134.945,59.27056],[-134.27111,58.86111],[-133.35556,58.41028],[-132.73042,57.69289],[-131.70781,56.55212],[-130.00778,55.91583],[-129.98,55.285],[-130.53611,54.80278],[-130.536109,54.802754],[-130.53611,54.802753],[-131.085818,55.178906],[-131.967211,55.497776],[-132.250011,56.369996],[-133.539181,57.178887],[-134.078063,58.123068],[-135.038211,58.187715],[-136.628062,58.212209],[-137.800006,58.499995],[-139.867787,59.537762],[-140.825274,59.727517],[-142.574444,60.084447],[-143.958881,59.99918],[-145.925557,60.45861],[-147.114374,60.884656],[-148.224306,60.672989],[-148.018066,59.978329],[-148.570823,59.914173],[-149.727858,59.705658],[-150.608243,59.368211],[-151.716393,59.155821],[-151.859433,59.744984],[-151.409719,60.725803],[-150.346941,61.033588],[-150.621111,61.284425],[-151.895839,60.727198],[-152.57833,60.061657],[-154.019172,59.350279],[-153.287511,58.864728],[-154.232492,58.146374],[-155.307491,57.727795],[-156.308335,57.422774],[-156.556097,56.979985],[-158.117217,56.463608],[-158.433321,55.994154],[-159.603327,55.566686],[-160.28972,55.643581],[-161.223048,55.364735],[-162.237766,55.024187],[-163.069447,54.689737],[-164.785569,54.404173],[-164.942226,54.572225],[-163.84834,55.039431],[-162.870001,55.348043],[-161.804175,55.894986],[-160.563605,56.008055],[-160.07056,56.418055],[-158.684443,57.016675],[-158.461097,57.216921],[-157.72277,57.570001],[-157.550274,58.328326],[-157.041675,58.918885],[-158.194731,58.615802],[-158.517218,58.787781],[-159.058606,58.424186],[-159.711667,58.93139],[-159.981289,58.572549],[-160.355271,59.071123],[-161.355003,58.670838],[-161.968894,58.671665],[-162.054987,59.266925],[-161.874171,59.633621],[-162.518059,59.989724],[-163.818341,59.798056],[-164.662218,60.267484],[-165.346388,60.507496],[-165.350832,61.073895],[-166.121379,61.500019],[-165.734452,62.074997],[-164.919179,62.633076],[-164.562508,63.146378],[-163.753332,63.219449],[-163.067224,63.059459],[-162.260555,63.541936],[-161.53445,63.455817],[-160.772507,63.766108],[-160.958335,64.222799],[-161.518068,64.402788],[-160.777778,64.788604],[-161.391926,64.777235],[-162.45305,64.559445],[-162.757786,64.338605],[-163.546394,64.55916],[-164.96083,64.446945],[-166.425288,64.686672],[-166.845004,65.088896],[-168.11056,65.669997],[-166.705271,66.088318],[-164.47471,66.57666],[-163.652512,66.57666],[-163.788602,66.077207],[-161.677774,66.11612],[-162.489715,66.735565],[-163.719717,67.116395],[-164.430991,67.616338],[-165.390287,68.042772],[-166.764441,68.358877],[-166.204707,68.883031],[-164.430811,68.915535],[-163.168614,69.371115],[-162.930566,69.858062],[-161.908897,70.33333],[-160.934797,70.44769],[-159.039176,70.891642],[-158.119723,70.824721],[-156.580825,71.357764],[-155.06779,71.147776],[-154.344165,70.696409],[-153.900006,70.889989],[-152.210006,70.829992],[-152.270002,70.600006],[-150.739992,70.430017],[-149.720003,70.53001],[-147.613362,70.214035],[-145.68999,70.12001],[-144.920011,69.989992],[-143.589446,70.152514],[-142.07251,69.851938],[-140.985988,69.711998],[-140.985988,69.711998]]],[[[-171.731657,63.782515],[-171.114434,63.592191],[-170.491112,63.694975],[-169.682505,63.431116],[-168.689439,63.297506],[-168.771941,63.188598],[-169.52944,62.976931],[-170.290556,63.194438],[-170.671386,63.375822],[-171.553063,63.317789],[-171.791111,63.405846],[-171.731657,63.782515]]]]}},{"type":"Feature","properties":{"ADMIN":"Kazakhstan","NAME_EN":"Kazakhstan","CONTINENT":"Asia","ADM0_A3":"KAZ","ISO_A3":"KAZ","NAME":"Kazakhstan","ISO_A2":"KZ","NAME_ZH":"哈萨克斯坦"},"geometry":{"type":"Polygon","coordinates":[[[87.35997,49.214981],[86.598776,48.549182],[85.768233,48.455751],[85.720484,47.452969],[85.16429,47.000956],[83.180484,47.330031],[82.458926,45.53965],[81.947071,45.317027],[79.966106,44.917517],[80.866206,43.180362],[80.18015,42.920068],[80.25999,42.349999],[79.643645,42.496683],[79.142177,42.856092],[77.658392,42.960686],[76.000354,42.988022],[75.636965,42.8779],[74.212866,43.298339],[73.645304,43.091272],[73.489758,42.500894],[71.844638,42.845395],[71.186281,42.704293],[70.962315,42.266154],[70.388965,42.081308],[69.070027,41.384244],[68.632483,40.668681],[68.259896,40.662325],[67.985856,41.135991],[66.714047,41.168444],[66.510649,41.987644],[66.023392,41.994646],[66.098012,42.99766],[64.900824,43.728081],[63.185787,43.650075],[62.0133,43.504477],[61.05832,44.405817],[60.239972,44.784037],[58.689989,45.500014],[58.503127,45.586804],[55.928917,44.995858],[55.968191,41.308642],[55.455251,41.259859],[54.755345,42.043971],[54.079418,42.324109],[52.944293,42.116034],[52.50246,41.783316],[52.446339,42.027151],[52.692112,42.443895],[52.501426,42.792298],[51.342427,43.132975],[50.891292,44.031034],[50.339129,44.284016],[50.305643,44.609836],[51.278503,44.514854],[51.316899,45.245998],[52.16739,45.408391],[53.040876,45.259047],[53.220866,46.234646],[53.042737,46.853006],[52.042023,46.804637],[51.191945,47.048705],[50.034083,46.60899],[49.10116,46.39933],[48.59325,46.56104],[48.694734,47.075628],[48.05725,47.74377],[47.31524,47.71585],[46.466446,48.394152],[47.043672,49.152039],[46.751596,49.356006],[47.54948,50.454698],[48.577841,49.87476],[48.702382,50.605128],[50.766648,51.692762],[52.328724,51.718652],[54.532878,51.02624],[55.71694,50.62171],[56.77798,51.04355],[58.36332,51.06364],[59.642282,50.545442],[59.932807,50.842194],[61.337424,50.79907],[61.588003,51.272659],[59.967534,51.96042],[60.927269,52.447548],[60.739993,52.719986],[61.699986,52.979996],[60.978066,53.664993],[61.4366,54.00625],[65.178534,54.354228],[65.66687,54.60125],[68.1691,54.970392],[69.068167,55.38525],[70.865267,55.169734],[71.180131,54.133285],[72.22415,54.376655],[73.508516,54.035617],[73.425679,53.48981],[74.38482,53.54685],[76.8911,54.490524],[76.525179,54.177003],[77.800916,53.404415],[80.03556,50.864751],[80.568447,51.388336],[81.945986,50.812196],[83.383004,51.069183],[83.935115,50.889246],[84.416377,50.3114],[85.11556,50.117303],[85.54127,49.692859],[86.829357,49.826675],[87.35997,49.214981]]]}},{"type":"Feature","properties":{"ADMIN":"Uzbekistan","NAME_EN":"Uzbekistan","CONTINENT":"Asia","ADM0_A3":"UZB","ISO_A3":"UZB","NAME":"Uzbekistan","ISO_A2":"UZ","NAME_ZH":"乌兹别克斯坦"},"geometry":{"type":"Polygon","coordinates":[[[55.968191,41.308642],[55.928917,44.995858],[58.503127,45.586804],[58.689989,45.500014],[60.239972,44.784037],[61.05832,44.405817],[62.0133,43.504477],[63.185787,43.650075],[64.900824,43.728081],[66.098012,42.99766],[66.023392,41.994646],[66.510649,41.987644],[66.714047,41.168444],[67.985856,41.135991],[68.259896,40.662325],[68.632483,40.668681],[69.070027,41.384244],[70.388965,42.081308],[70.962315,42.266154],[71.259248,42.167711],[70.420022,41.519998],[71.157859,41.143587],[71.870115,41.3929],[73.055417,40.866033],[71.774875,40.145844],[71.014198,40.244366],[70.601407,40.218527],[70.45816,40.496495],[70.666622,40.960213],[69.329495,40.727824],[69.011633,40.086158],[68.536416,39.533453],[67.701429,39.580478],[67.44222,39.140144],[68.176025,38.901553],[68.392033,38.157025],[67.83,37.144994],[67.075782,37.356144],[66.518607,37.362784],[66.54615,37.974685],[65.215999,38.402695],[64.170223,38.892407],[63.518015,39.363257],[62.37426,40.053886],[61.882714,41.084857],[61.547179,41.26637],[60.465953,41.220327],[60.083341,41.425146],[59.976422,42.223082],[58.629011,42.751551],[57.78653,42.170553],[56.932215,41.826026],[57.096391,41.32231],[55.968191,41.308642]]]}},{"type":"Feature","properties":{"ADMIN":"Papua New Guinea","NAME_EN":"Papua New Guinea","CONTINENT":"Oceania","ADM0_A3":"PNG","ISO_A3":"PNG","NAME":"Papua New Guinea","ISO_A2":"PG","NAME_ZH":"巴布亚新几内亚"},"geometry":{"type":"MultiPolygon","coordinates":[[[[141.00021,-2.600151],[142.735247,-3.289153],[144.583971,-3.861418],[145.27318,-4.373738],[145.829786,-4.876498],[145.981922,-5.465609],[147.648073,-6.083659],[147.891108,-6.614015],[146.970905,-6.721657],[147.191874,-7.388024],[148.084636,-8.044108],[148.734105,-9.104664],[149.306835,-9.071436],[149.266631,-9.514406],[150.038728,-9.684318],[149.738798,-9.872937],[150.801628,-10.293687],[150.690575,-10.582713],[150.028393,-10.652476],[149.78231,-10.393267],[148.923138,-10.280923],[147.913018,-10.130441],[147.135443,-9.492444],[146.567881,-8.942555],[146.048481,-8.067414],[144.744168,-7.630128],[143.897088,-7.91533],[143.286376,-8.245491],[143.413913,-8.983069],[142.628431,-9.326821],[142.068259,-9.159596],[141.033852,-9.117893],[141.017057,-5.859022],[141.00021,-2.600151]]],[[[152.640017,-3.659983],[153.019994,-3.980015],[153.140038,-4.499983],[152.827292,-4.766427],[152.638673,-4.176127],[152.406026,-3.789743],[151.953237,-3.462062],[151.384279,-3.035422],[150.66205,-2.741486],[150.939965,-2.500002],[151.479984,-2.779985],[151.820015,-2.999972],[152.239989,-3.240009],[152.640017,-3.659983]]],[[[151.30139,-5.840728],[150.754447,-6.083763],[150.241197,-6.317754],[149.709963,-6.316513],[148.890065,-6.02604],[148.318937,-5.747142],[148.401826,-5.437756],[149.298412,-5.583742],[149.845562,-5.505503],[149.99625,-5.026101],[150.139756,-5.001348],[150.236908,-5.53222],[150.807467,-5.455842],[151.089672,-5.113693],[151.647881,-4.757074],[151.537862,-4.167807],[152.136792,-4.14879],[152.338743,-4.312966],[152.318693,-4.867661],[151.982796,-5.478063],[151.459107,-5.56028],[151.30139,-5.840728]]],[[[154.759991,-5.339984],[155.062918,-5.566792],[155.547746,-6.200655],[156.019965,-6.540014],[155.880026,-6.819997],[155.599991,-6.919991],[155.166994,-6.535931],[154.729192,-5.900828],[154.514114,-5.139118],[154.652504,-5.042431],[154.759991,-5.339984]]]]}},{"type":"Feature","properties":{"ADMIN":"Indonesia","NAME_EN":"Indonesia","CONTINENT":"Asia","ADM0_A3":"IDN","ISO_A3":"IDN","NAME":"Indonesia","ISO_A2":"ID","NAME_ZH":"印度尼西亚"},"geometry":{"type":"MultiPolygon","coordinates":[[[[141.00021,-2.600151],[141.017057,-5.859022],[141.033852,-9.117893],[140.143415,-8.297168],[139.127767,-8.096043],[138.881477,-8.380935],[137.614474,-8.411683],[138.039099,-7.597882],[138.668621,-7.320225],[138.407914,-6.232849],[137.92784,-5.393366],[135.98925,-4.546544],[135.164598,-4.462931],[133.66288,-3.538853],[133.367705,-4.024819],[132.983956,-4.112979],[132.756941,-3.746283],[132.753789,-3.311787],[131.989804,-2.820551],[133.066845,-2.460418],[133.780031,-2.479848],[133.696212,-2.214542],[132.232373,-2.212526],[131.836222,-1.617162],[130.94284,-1.432522],[130.519558,-0.93772],[131.867538,-0.695461],[132.380116,-0.369538],[133.985548,-0.78021],[134.143368,-1.151867],[134.422627,-2.769185],[135.457603,-3.367753],[136.293314,-2.307042],[137.440738,-1.703513],[138.329727,-1.702686],[139.184921,-2.051296],[139.926684,-2.409052],[141.00021,-2.600151]]],[[[124.968682,-8.89279],[125.07002,-9.089987],[125.08852,-9.393173],[124.43595,-10.140001],[123.579982,-10.359987],[123.459989,-10.239995],[123.550009,-9.900016],[123.980009,-9.290027],[124.968682,-8.89279]]],[[[134.210134,-6.895238],[134.112776,-6.142467],[134.290336,-5.783058],[134.499625,-5.445042],[134.727002,-5.737582],[134.724624,-6.214401],[134.210134,-6.895238]]],[[[117.882035,4.137551],[117.313232,3.234428],[118.04833,2.28769],[117.875627,1.827641],[118.996747,0.902219],[117.811858,0.784242],[117.478339,0.102475],[117.521644,-0.803723],[116.560048,-1.487661],[116.533797,-2.483517],[116.148084,-4.012726],[116.000858,-3.657037],[114.864803,-4.106984],[114.468652,-3.495704],[113.755672,-3.43917],[113.256994,-3.118776],[112.068126,-3.478392],[111.703291,-2.994442],[111.04824,-3.049426],[110.223846,-2.934032],[110.070936,-1.592874],[109.571948,-1.314907],[109.091874,-0.459507],[108.952658,0.415375],[109.069136,1.341934],[109.66326,2.006467],[109.830227,1.338136],[110.514061,0.773131],[111.159138,0.976478],[111.797548,0.904441],[112.380252,1.410121],[112.859809,1.49779],[113.80585,1.217549],[114.621355,1.430688],[115.134037,2.821482],[115.519078,3.169238],[115.865517,4.306559],[117.015214,4.306094],[117.882035,4.137551]]],[[[129.370998,-2.802154],[130.471344,-3.093764],[130.834836,-3.858472],[129.990547,-3.446301],[129.155249,-3.362637],[128.590684,-3.428679],[127.898891,-3.393436],[128.135879,-2.84365],[129.370998,-2.802154]]],[[[126.874923,-3.790983],[126.183802,-3.607376],[125.989034,-3.177273],[127.000651,-3.129318],[127.249215,-3.459065],[126.874923,-3.790983]]],[[[127.932378,2.174596],[128.004156,1.628531],[128.594559,1.540811],[128.688249,1.132386],[128.635952,0.258486],[128.12017,0.356413],[127.968034,-0.252077],[128.379999,-0.780004],[128.100016,-0.899996],[127.696475,-0.266598],[127.39949,1.011722],[127.600512,1.810691],[127.932378,2.174596]]],[[[122.927567,0.875192],[124.077522,0.917102],[125.065989,1.643259],[125.240501,1.419836],[124.437035,0.427881],[123.685505,0.235593],[122.723083,0.431137],[121.056725,0.381217],[120.183083,0.237247],[120.04087,-0.519658],[120.935905,-1.408906],[121.475821,-0.955962],[123.340565,-0.615673],[123.258399,-1.076213],[122.822715,-0.930951],[122.38853,-1.516858],[121.508274,-1.904483],[122.454572,-3.186058],[122.271896,-3.5295],[123.170963,-4.683693],[123.162333,-5.340604],[122.628515,-5.634591],[122.236394,-5.282933],[122.719569,-4.464172],[121.738234,-4.851331],[121.489463,-4.574553],[121.619171,-4.188478],[120.898182,-3.602105],[120.972389,-2.627643],[120.305453,-2.931604],[120.390047,-4.097579],[120.430717,-5.528241],[119.796543,-5.6734],[119.366906,-5.379878],[119.653606,-4.459417],[119.498835,-3.494412],[119.078344,-3.487022],[118.767769,-2.801999],[119.180974,-2.147104],[119.323394,-1.353147],[119.825999,0.154254],[120.035702,0.566477],[120.885779,1.309223],[121.666817,1.013944],[122.927567,0.875192]]],[[[120.295014,-10.25865],[118.967808,-9.557969],[119.90031,-9.36134],[120.425756,-9.665921],[120.775502,-9.969675],[120.715609,-10.239581],[120.295014,-10.25865]]],[[[121.341669,-8.53674],[122.007365,-8.46062],[122.903537,-8.094234],[122.756983,-8.649808],[121.254491,-8.933666],[119.924391,-8.810418],[119.920929,-8.444859],[120.715092,-8.236965],[121.341669,-8.53674]]],[[[118.260616,-8.362383],[118.87846,-8.280683],[119.126507,-8.705825],[117.970402,-8.906639],[117.277731,-9.040895],[116.740141,-9.032937],[117.083737,-8.457158],[117.632024,-8.449303],[117.900018,-8.095681],[118.260616,-8.362383]]],[[[108.486846,-6.421985],[108.623479,-6.777674],[110.539227,-6.877358],[110.759576,-6.465186],[112.614811,-6.946036],[112.978768,-7.594213],[114.478935,-7.776528],[115.705527,-8.370807],[114.564511,-8.751817],[113.464734,-8.348947],[112.559672,-8.376181],[111.522061,-8.302129],[110.58615,-8.122605],[109.427667,-7.740664],[108.693655,-7.6416],[108.277763,-7.766657],[106.454102,-7.3549],[106.280624,-6.9249],[105.365486,-6.851416],[106.051646,-5.895919],[107.265009,-5.954985],[108.072091,-6.345762],[108.486846,-6.421985]]],[[[104.369991,-1.084843],[104.53949,-1.782372],[104.887893,-2.340425],[105.622111,-2.428844],[106.108593,-3.061777],[105.857446,-4.305525],[105.817655,-5.852356],[104.710384,-5.873285],[103.868213,-5.037315],[102.584261,-4.220259],[102.156173,-3.614146],[101.399113,-2.799777],[100.902503,-2.050262],[100.141981,-0.650348],[99.26374,0.183142],[98.970011,1.042882],[98.601351,1.823507],[97.699598,2.453184],[97.176942,3.308791],[96.424017,3.86886],[95.380876,4.970782],[95.293026,5.479821],[95.936863,5.439513],[97.484882,5.246321],[98.369169,4.26837],[99.142559,3.59035],[99.693998,3.174329],[100.641434,2.099381],[101.658012,2.083697],[102.498271,1.3987],[103.07684,0.561361],[103.838396,0.104542],[103.437645,-0.711946],[104.010789,-1.059212],[104.369991,-1.084843]]]]}},{"type":"Feature","properties":{"ADMIN":"Argentina","NAME_EN":"Argentina","CONTINENT":"South America","ADM0_A3":"ARG","ISO_A3":"ARG","NAME":"Argentina","ISO_A2":"AR","NAME_ZH":"阿根廷"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-68.63401,-52.63637],[-68.25,-53.1],[-67.75,-53.85],[-66.45,-54.45],[-65.05,-54.7],[-65.5,-55.2],[-66.45,-55.25],[-66.95992,-54.89681],[-67.56244,-54.87001],[-68.63335,-54.8695],[-68.63401,-52.63637]]],[[[-57.625133,-30.216295],[-57.874937,-31.016556],[-58.14244,-32.044504],[-58.132648,-33.040567],[-58.349611,-33.263189],[-58.427074,-33.909454],[-58.495442,-34.43149],[-57.22583,-35.288027],[-57.362359,-35.97739],[-56.737487,-36.413126],[-56.788285,-36.901572],[-57.749157,-38.183871],[-59.231857,-38.72022],[-61.237445,-38.928425],[-62.335957,-38.827707],[-62.125763,-39.424105],[-62.330531,-40.172586],[-62.145994,-40.676897],[-62.745803,-41.028761],[-63.770495,-41.166789],[-64.73209,-40.802677],[-65.118035,-41.064315],[-64.978561,-42.058001],[-64.303408,-42.359016],[-63.755948,-42.043687],[-63.458059,-42.563138],[-64.378804,-42.873558],[-65.181804,-43.495381],[-65.328823,-44.501366],[-65.565269,-45.036786],[-66.509966,-45.039628],[-67.293794,-45.551896],[-67.580546,-46.301773],[-66.597066,-47.033925],[-65.641027,-47.236135],[-65.985088,-48.133289],[-67.166179,-48.697337],[-67.816088,-49.869669],[-68.728745,-50.264218],[-69.138539,-50.73251],[-68.815561,-51.771104],[-68.149995,-52.349983],[-68.571545,-52.299444],[-69.498362,-52.142761],[-71.914804,-52.009022],[-72.329404,-51.425956],[-72.309974,-50.67701],[-72.975747,-50.74145],[-73.328051,-50.378785],[-73.415436,-49.318436],[-72.648247,-48.878618],[-72.331161,-48.244238],[-72.447355,-47.738533],[-71.917258,-46.884838],[-71.552009,-45.560733],[-71.659316,-44.973689],[-71.222779,-44.784243],[-71.329801,-44.407522],[-71.793623,-44.207172],[-71.464056,-43.787611],[-71.915424,-43.408565],[-72.148898,-42.254888],[-71.746804,-42.051386],[-71.915734,-40.832339],[-71.680761,-39.808164],[-71.413517,-38.916022],[-70.814664,-38.552995],[-71.118625,-37.576827],[-71.121881,-36.658124],[-70.364769,-36.005089],[-70.388049,-35.169688],[-69.817309,-34.193571],[-69.814777,-33.273886],[-70.074399,-33.09121],[-70.535069,-31.36501],[-69.919008,-30.336339],[-70.01355,-29.367923],[-69.65613,-28.459141],[-69.001235,-27.521214],[-68.295542,-26.89934],[-68.5948,-26.506909],[-68.386001,-26.185016],[-68.417653,-24.518555],[-67.328443,-24.025303],[-66.985234,-22.986349],[-67.106674,-22.735925],[-66.273339,-21.83231],[-64.964892,-22.075862],[-64.377021,-22.798091],[-63.986838,-21.993644],[-62.846468,-22.034985],[-62.685057,-22.249029],[-60.846565,-23.880713],[-60.028966,-24.032796],[-58.807128,-24.771459],[-57.777217,-25.16234],[-57.63366,-25.603657],[-58.618174,-27.123719],[-57.60976,-27.395899],[-56.486702,-27.548499],[-55.695846,-27.387837],[-54.788795,-26.621786],[-54.625291,-25.739255],[-54.13005,-25.547639],[-53.628349,-26.124865],[-53.648735,-26.923473],[-54.490725,-27.474757],[-55.162286,-27.881915],[-56.2909,-28.852761],[-57.625133,-30.216295]]]]}},{"type":"Feature","properties":{"ADMIN":"Chile","NAME_EN":"Chile","CONTINENT":"South America","ADM0_A3":"CHL","ISO_A3":"CHL","NAME":"Chile","ISO_A2":"CL","NAME_ZH":"智利"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-68.63401,-52.63637],[-68.63335,-54.8695],[-67.56244,-54.87001],[-66.95992,-54.89681],[-67.29103,-55.30124],[-68.14863,-55.61183],[-68.639991,-55.580018],[-69.2321,-55.49906],[-69.95809,-55.19843],[-71.00568,-55.05383],[-72.2639,-54.49514],[-73.2852,-53.95752],[-74.66253,-52.83749],[-73.8381,-53.04743],[-72.43418,-53.7154],[-71.10773,-54.07433],[-70.59178,-53.61583],[-70.26748,-52.93123],[-69.34565,-52.5183],[-68.63401,-52.63637]]],[[[-69.590424,-17.580012],[-69.100247,-18.260125],[-68.966818,-18.981683],[-68.442225,-19.405068],[-68.757167,-20.372658],[-68.219913,-21.494347],[-67.82818,-22.872919],[-67.106674,-22.735925],[-66.985234,-22.986349],[-67.328443,-24.025303],[-68.417653,-24.518555],[-68.386001,-26.185016],[-68.5948,-26.506909],[-68.295542,-26.89934],[-69.001235,-27.521214],[-69.65613,-28.459141],[-70.01355,-29.367923],[-69.919008,-30.336339],[-70.535069,-31.36501],[-70.074399,-33.09121],[-69.814777,-33.273886],[-69.817309,-34.193571],[-70.388049,-35.169688],[-70.364769,-36.005089],[-71.121881,-36.658124],[-71.118625,-37.576827],[-70.814664,-38.552995],[-71.413517,-38.916022],[-71.680761,-39.808164],[-71.915734,-40.832339],[-71.746804,-42.051386],[-72.148898,-42.254888],[-71.915424,-43.408565],[-71.464056,-43.787611],[-71.793623,-44.207172],[-71.329801,-44.407522],[-71.222779,-44.784243],[-71.659316,-44.973689],[-71.552009,-45.560733],[-71.917258,-46.884838],[-72.447355,-47.738533],[-72.331161,-48.244238],[-72.648247,-48.878618],[-73.415436,-49.318436],[-73.328051,-50.378785],[-72.975747,-50.74145],[-72.309974,-50.67701],[-72.329404,-51.425956],[-71.914804,-52.009022],[-69.498362,-52.142761],[-68.571545,-52.299444],[-69.461284,-52.291951],[-69.94278,-52.537931],[-70.845102,-52.899201],[-71.006332,-53.833252],[-71.429795,-53.856455],[-72.557943,-53.53141],[-73.702757,-52.835069],[-73.702757,-52.83507],[-74.946763,-52.262754],[-75.260026,-51.629355],[-74.976632,-51.043396],[-75.479754,-50.378372],[-75.608015,-48.673773],[-75.18277,-47.711919],[-74.126581,-46.939253],[-75.644395,-46.647643],[-74.692154,-45.763976],[-74.351709,-44.103044],[-73.240356,-44.454961],[-72.717804,-42.383356],[-73.3889,-42.117532],[-73.701336,-43.365776],[-74.331943,-43.224958],[-74.017957,-41.794813],[-73.677099,-39.942213],[-73.217593,-39.258689],[-73.505559,-38.282883],[-73.588061,-37.156285],[-73.166717,-37.12378],[-72.553137,-35.50884],[-71.861732,-33.909093],[-71.43845,-32.418899],[-71.668721,-30.920645],[-71.370083,-30.095682],[-71.489894,-28.861442],[-70.905124,-27.64038],[-70.724954,-25.705924],[-70.403966,-23.628997],[-70.091246,-21.393319],[-70.16442,-19.756468],[-70.372572,-18.347975],[-69.858444,-18.092694],[-69.590424,-17.580012]]]]}},{"type":"Feature","properties":{"ADMIN":"Democratic Republic of the Congo","NAME_EN":"Democratic Republic of the Congo","CONTINENT":"Africa","ADM0_A3":"COD","ISO_A3":"COD","NAME":"Dem. Rep. Congo","ISO_A2":"CD","NAME_ZH":"刚果民主共和国"},"geometry":{"type":"Polygon","coordinates":[[[29.339998,-4.499983],[29.519987,-5.419979],[29.419993,-5.939999],[29.620032,-6.520015],[30.199997,-7.079981],[30.740015,-8.340007],[30.74001,-8.340006],[30.346086,-8.238257],[29.002912,-8.407032],[28.734867,-8.526559],[28.449871,-9.164918],[28.673682,-9.605925],[28.49607,-10.789884],[28.372253,-11.793647],[28.642417,-11.971569],[29.341548,-12.360744],[29.616001,-12.178895],[29.699614,-13.257227],[28.934286,-13.248958],[28.523562,-12.698604],[28.155109,-12.272481],[27.388799,-12.132747],[27.16442,-11.608748],[26.553088,-11.92444],[25.75231,-11.784965],[25.418118,-11.330936],[24.78317,-11.238694],[24.314516,-11.262826],[24.257155,-10.951993],[23.912215,-10.926826],[23.456791,-10.867863],[22.837345,-11.017622],[22.402798,-10.993075],[22.155268,-11.084801],[22.208753,-9.894796],[21.875182,-9.523708],[21.801801,-8.908707],[21.949131,-8.305901],[21.746456,-7.920085],[21.728111,-7.290872],[20.514748,-7.299606],[20.601823,-6.939318],[20.091622,-6.94309],[20.037723,-7.116361],[19.417502,-7.155429],[19.166613,-7.738184],[19.016752,-7.988246],[18.464176,-7.847014],[18.134222,-7.987678],[17.47297,-8.068551],[17.089996,-7.545689],[16.860191,-7.222298],[16.57318,-6.622645],[16.326528,-5.87747],[13.375597,-5.864241],[13.024869,-5.984389],[12.735171,-5.965682],[12.322432,-6.100092],[12.182337,-5.789931],[12.436688,-5.684304],[12.468004,-5.248362],[12.631612,-4.991271],[12.995517,-4.781103],[13.25824,-4.882957],[13.600235,-4.500138],[14.144956,-4.510009],[14.209035,-4.793092],[14.582604,-4.970239],[15.170992,-4.343507],[15.75354,-3.855165],[16.00629,-3.535133],[15.972803,-2.712392],[16.407092,-1.740927],[16.865307,-1.225816],[17.523716,-0.74383],[17.638645,-0.424832],[17.663553,-0.058084],[17.82654,0.288923],[17.774192,0.855659],[17.898835,1.741832],[18.094276,2.365722],[18.393792,2.900443],[18.453065,3.504386],[18.542982,4.201785],[18.932312,4.709506],[19.467784,5.031528],[20.290679,4.691678],[20.927591,4.322786],[21.659123,4.224342],[22.405124,4.02916],[22.704124,4.633051],[22.84148,4.710126],[23.297214,4.609693],[24.410531,5.108784],[24.805029,4.897247],[25.128833,4.927245],[25.278798,5.170408],[25.650455,5.256088],[26.402761,5.150875],[27.044065,5.127853],[27.374226,5.233944],[27.979977,4.408413],[28.428994,4.287155],[28.696678,4.455077],[29.159078,4.389267],[29.715995,4.600805],[29.9535,4.173699],[30.833852,3.509172],[30.83386,3.509166],[30.773347,2.339883],[31.174149,2.204465],[30.85267,1.849396],[30.468508,1.583805],[30.086154,1.062313],[29.875779,0.59738],[29.819503,-0.20531],[29.587838,-0.587406],[29.579466,-1.341313],[29.291887,-1.620056],[29.254835,-2.21511],[29.117479,-2.292211],[29.024926,-2.839258],[29.276384,-3.293907],[29.339998,-4.499983]]]}},{"type":"Feature","properties":{"ADMIN":"Somalia","NAME_EN":"Somalia","CONTINENT":"Africa","ADM0_A3":"SOM","ISO_A3":"SOM","NAME":"Somalia","ISO_A2":"SO","NAME_ZH":"索马里"},"geometry":{"type":"Polygon","coordinates":[[[41.58513,-1.68325],[40.993,-0.85829],[40.98105,2.78452],[41.855083,3.918912],[42.12861,4.23413],[42.76967,4.25259],[43.66087,4.95755],[44.9636,5.00162],[47.78942,8.003],[48.486736,8.837626],[48.93813,9.451749],[48.938233,9.9735],[48.938491,10.982327],[48.942005,11.394266],[48.948205,11.410617],[48.948205,11.410617],[49.26776,11.43033],[49.72862,11.5789],[50.25878,11.67957],[50.73202,12.0219],[51.1112,12.02464],[51.13387,11.74815],[51.04153,11.16651],[51.04531,10.6409],[50.83418,10.27972],[50.55239,9.19874],[50.07092,8.08173],[49.4527,6.80466],[48.59455,5.33911],[47.74079,4.2194],[46.56476,2.85529],[45.56399,2.04576],[44.06815,1.05283],[43.13597,0.2922],[42.04157,-0.91916],[41.81095,-1.44647],[41.58513,-1.68325]]]}},{"type":"Feature","properties":{"ADMIN":"Kenya","NAME_EN":"Kenya","CONTINENT":"Africa","ADM0_A3":"KEN","ISO_A3":"KEN","NAME":"Kenya","ISO_A2":"KE","NAME_ZH":"肯尼亚"},"geometry":{"type":"Polygon","coordinates":[[[39.20222,-4.67677],[37.7669,-3.67712],[37.69869,-3.09699],[34.07262,-1.05982],[33.903711,-0.95],[33.893569,0.109814],[34.18,0.515],[34.6721,1.17694],[35.03599,1.90584],[34.59607,3.05374],[34.47913,3.5556],[34.005,4.249885],[34.620196,4.847123],[35.298007,5.506],[35.817448,5.338232],[35.817448,4.776966],[36.159079,4.447864],[36.855093,4.447864],[38.120915,3.598605],[38.43697,3.58851],[38.67114,3.61607],[38.89251,3.50074],[39.559384,3.42206],[39.85494,3.83879],[40.76848,4.25702],[41.1718,3.91909],[41.855083,3.918912],[40.98105,2.78452],[40.993,-0.85829],[41.58513,-1.68325],[40.88477,-2.08255],[40.63785,-2.49979],[40.26304,-2.57309],[40.12119,-3.27768],[39.80006,-3.68116],[39.60489,-4.34653],[39.20222,-4.67677]]]}},{"type":"Feature","properties":{"ADMIN":"Sudan","NAME_EN":"Sudan","CONTINENT":"Africa","ADM0_A3":"SDN","ISO_A3":"SDN","NAME":"Sudan","ISO_A2":"SD","NAME_ZH":"苏丹"},"geometry":{"type":"Polygon","coordinates":[[[24.567369,8.229188],[23.805813,8.666319],[23.459013,8.954286],[23.394779,9.265068],[23.55725,9.681218],[23.554304,10.089255],[22.977544,10.714463],[22.864165,11.142395],[22.87622,11.38461],[22.50869,11.67936],[22.49762,12.26024],[22.28801,12.64605],[21.93681,12.58818],[22.03759,12.95546],[22.29658,13.37232],[22.18329,13.78648],[22.51202,14.09318],[22.30351,14.32682],[22.56795,14.94429],[23.02459,15.68072],[23.88689,15.61084],[23.83766,19.58047],[23.85,20],[25,20.00304],[25,22],[29.02,22],[32.9,22],[36.86623,22],[37.18872,21.01885],[36.96941,20.83744],[37.1147,19.80796],[37.48179,18.61409],[37.86276,18.36786],[38.41009,17.998307],[37.904,17.42754],[37.16747,17.26314],[36.85253,16.95655],[36.75389,16.29186],[36.32322,14.82249],[36.42951,14.42211],[36.27022,13.56333],[35.86363,12.57828],[35.26049,12.08286],[34.83163,11.31896],[34.73115,10.91017],[34.25745,10.63009],[33.96162,9.58358],[33.97498,8.68456],[33.963393,9.464285],[33.824963,9.484061],[33.842131,9.981915],[33.721959,10.325262],[33.206938,10.720112],[33.086766,11.441141],[33.206938,12.179338],[32.743419,12.248008],[32.67475,12.024832],[32.073892,11.97333],[32.314235,11.681484],[32.400072,11.080626],[31.850716,10.531271],[31.352862,9.810241],[30.837841,9.707237],[29.996639,10.290927],[29.618957,10.084919],[29.515953,9.793074],[29.000932,9.604232],[28.966597,9.398224],[27.97089,9.398224],[27.833551,9.604232],[27.112521,9.638567],[26.752006,9.466893],[26.477328,9.55273],[25.962307,10.136421],[25.790633,10.411099],[25.069604,10.27376],[24.794926,9.810241],[24.537415,8.917538],[24.194068,8.728696],[23.88698,8.61973],[24.567369,8.229188]]]}},{"type":"Feature","properties":{"ADMIN":"Chad","NAME_EN":"Chad","CONTINENT":"Africa","ADM0_A3":"TCD","ISO_A3":"TCD","NAME":"Chad","ISO_A2":"TD","NAME_ZH":"乍得"},"geometry":{"type":"Polygon","coordinates":[[[23.83766,19.58047],[23.88689,15.61084],[23.02459,15.68072],[22.56795,14.94429],[22.30351,14.32682],[22.51202,14.09318],[22.18329,13.78648],[22.29658,13.37232],[22.03759,12.95546],[21.93681,12.58818],[22.28801,12.64605],[22.49762,12.26024],[22.50869,11.67936],[22.87622,11.38461],[22.864165,11.142395],[22.231129,10.971889],[21.723822,10.567056],[21.000868,9.475985],[20.059685,9.012706],[19.094008,9.074847],[18.81201,8.982915],[18.911022,8.630895],[18.389555,8.281304],[17.96493,7.890914],[16.705988,7.508328],[16.456185,7.734774],[16.290562,7.754307],[16.106232,7.497088],[15.27946,7.421925],[15.436092,7.692812],[15.120866,8.38215],[14.979996,8.796104],[14.544467,8.965861],[13.954218,9.549495],[14.171466,10.021378],[14.627201,9.920919],[14.909354,9.992129],[15.467873,9.982337],[14.923565,10.891325],[14.960152,11.555574],[14.89336,12.21905],[14.495787,12.859396],[14.595781,13.330427],[13.954477,13.353449],[13.956699,13.996691],[13.540394,14.367134],[13.97217,15.68437],[15.247731,16.627306],[15.300441,17.92795],[15.685741,19.95718],[15.903247,20.387619],[15.487148,20.730415],[15.47106,21.04845],[15.096888,21.308519],[14.8513,22.86295],[15.86085,23.40972],[19.84926,21.49509],[23.83766,19.58047]]]}},{"type":"Feature","properties":{"ADMIN":"Haiti","NAME_EN":"Haiti","CONTINENT":"North America","ADM0_A3":"HTI","ISO_A3":"HTI","NAME":"Haiti","ISO_A2":"HT","NAME_ZH":"海地"},"geometry":{"type":"Polygon","coordinates":[[[-71.712361,19.714456],[-71.624873,19.169838],[-71.701303,18.785417],[-71.945112,18.6169],[-71.687738,18.31666],[-71.708305,18.044997],[-72.372476,18.214961],[-72.844411,18.145611],[-73.454555,18.217906],[-73.922433,18.030993],[-74.458034,18.34255],[-74.369925,18.664908],[-73.449542,18.526053],[-72.694937,18.445799],[-72.334882,18.668422],[-72.79165,19.101625],[-72.784105,19.483591],[-73.415022,19.639551],[-73.189791,19.915684],[-72.579673,19.871501],[-71.712361,19.714456]]]}},{"type":"Feature","properties":{"ADMIN":"Dominican Republic","NAME_EN":"Dominican Republic","CONTINENT":"North America","ADM0_A3":"DOM","ISO_A3":"DOM","NAME":"Dominican Rep.","ISO_A2":"DO","NAME_ZH":"多米尼加"},"geometry":{"type":"Polygon","coordinates":[[[-71.708305,18.044997],[-71.687738,18.31666],[-71.945112,18.6169],[-71.701303,18.785417],[-71.624873,19.169838],[-71.712361,19.714456],[-71.587304,19.884911],[-70.806706,19.880286],[-70.214365,19.622885],[-69.950815,19.648],[-69.76925,19.293267],[-69.222126,19.313214],[-69.254346,19.015196],[-68.809412,18.979074],[-68.317943,18.612198],[-68.689316,18.205142],[-69.164946,18.422648],[-69.623988,18.380713],[-69.952934,18.428307],[-70.133233,18.245915],[-70.517137,18.184291],[-70.669298,18.426886],[-70.99995,18.283329],[-71.40021,17.598564],[-71.657662,17.757573],[-71.708305,18.044997]]]}},{"type":"Feature","properties":{"ADMIN":"Russia","NAME_EN":"Russia","CONTINENT":"Europe","ADM0_A3":"RUS","ISO_A3":"RUS","NAME":"Russia","ISO_A2":"RU","NAME_ZH":"俄罗斯"},"geometry":{"type":"MultiPolygon","coordinates":[[[[178.7253,71.0988],[180,71.515714],[180,70.832199],[178.903425,70.78114],[178.7253,71.0988]]],[[[49.10116,46.39933],[48.64541,45.80629],[47.67591,45.64149],[46.68201,44.6092],[47.59094,43.66016],[47.49252,42.98658],[48.58437,41.80888],[48.584353,41.808869],[47.987283,41.405819],[47.815666,41.151416],[47.373315,41.219732],[46.686071,41.827137],[46.404951,41.860675],[45.7764,42.09244],[45.470279,42.502781],[44.537623,42.711993],[43.93121,42.55496],[43.75599,42.74083],[42.3944,43.2203],[40.92219,43.38215],[40.076965,43.553104],[39.955009,43.434998],[38.68,44.28],[37.53912,44.65721],[36.67546,45.24469],[37.40317,45.40451],[38.23295,46.24087],[37.67372,46.63657],[39.14767,47.04475],[39.1212,47.26336],[38.223538,47.10219],[38.255112,47.5464],[38.77057,47.82562],[39.738278,47.898937],[39.89562,48.23241],[39.67465,48.78382],[40.080789,49.30743],[40.06904,49.60105],[38.594988,49.926462],[38.010631,49.915662],[37.39346,50.383953],[36.626168,50.225591],[35.356116,50.577197],[35.37791,50.77394],[35.022183,51.207572],[34.224816,51.255993],[34.141978,51.566413],[34.391731,51.768882],[33.7527,52.335075],[32.715761,52.238465],[32.412058,52.288695],[32.15944,52.06125],[31.785992,52.101678],[31.78597,52.10168],[31.540018,52.742052],[31.305201,53.073996],[31.49764,53.16743],[32.304519,53.132726],[32.693643,53.351421],[32.405599,53.618045],[31.731273,53.794029],[31.791424,53.974639],[31.384472,54.157056],[30.757534,54.811771],[30.971836,55.081548],[30.873909,55.550976],[29.896294,55.789463],[29.371572,55.670091],[29.229513,55.918344],[28.176709,56.16913],[27.855282,56.759326],[27.770016,57.244258],[27.288185,57.474528],[27.716686,57.791899],[27.42015,58.72457],[28.131699,59.300825],[27.98112,59.47537],[27.981127,59.475373],[29.1177,60.02805],[28.070002,60.503519],[28.07,60.50352],[30.211107,61.780028],[31.139991,62.357693],[31.516092,62.867687],[30.035872,63.552814],[30.444685,64.204453],[29.54443,64.948672],[30.21765,65.80598],[29.054589,66.944286],[29.977426,67.698297],[28.445944,68.364613],[28.59193,69.064777],[29.39955,69.15692],[31.101042,69.558101],[31.10108,69.55811],[32.13272,69.90595],[33.77547,69.30142],[36.51396,69.06342],[40.29234,67.9324],[41.05987,67.45713],[41.12595,66.79158],[40.01583,66.26618],[38.38295,65.99953],[33.91871,66.75961],[33.18444,66.63253],[34.81477,65.90015],[34.878574,65.436213],[34.94391,64.41437],[36.23129,64.10945],[37.01273,63.84983],[37.14197,64.33471],[36.539579,64.76446],[37.17604,65.14322],[39.59345,64.52079],[40.4356,64.76446],[39.7626,65.49682],[42.09309,66.47623],[43.01604,66.41858],[43.94975,66.06908],[44.53226,66.75634],[43.69839,67.35245],[44.18795,67.95051],[43.45282,68.57079],[46.25,68.25],[46.82134,67.68997],[45.55517,67.56652],[45.56202,67.01005],[46.34915,66.66767],[47.89416,66.88455],[48.13876,67.52238],[50.22766,67.99867],[53.71743,68.85738],[54.47171,68.80815],[53.48582,68.20131],[54.72628,68.09702],[55.44268,68.43866],[57.31702,68.46628],[58.802,68.88082],[59.94142,68.27844],[61.07784,68.94069],[60.03,69.52],[60.55,69.85],[63.504,69.54739],[64.888115,69.234835],[68.51216,68.09233],[69.18068,68.61563],[68.16444,69.14436],[68.13522,69.35649],[66.93008,69.45461],[67.25976,69.92873],[66.72492,70.70889],[66.69466,71.02897],[68.54006,71.9345],[69.19636,72.84336],[69.94,73.04],[72.58754,72.77629],[72.79603,72.22006],[71.84811,71.40898],[72.47011,71.09019],[72.79188,70.39114],[72.5647,69.02085],[73.66787,68.4079],[73.2387,67.7404],[71.28,66.32],[72.42301,66.17267],[72.82077,66.53267],[73.92099,66.78946],[74.18651,67.28429],[75.052,67.76047],[74.46926,68.32899],[74.93584,68.98918],[73.84236,69.07146],[73.60187,69.62763],[74.3998,70.63175],[73.1011,71.44717],[74.89082,72.12119],[74.65926,72.83227],[75.15801,72.85497],[75.68351,72.30056],[75.28898,71.33556],[76.35911,71.15287],[75.90313,71.87401],[77.57665,72.26717],[79.65202,72.32011],[81.5,71.75],[80.61071,72.58285],[80.51109,73.6482],[82.25,73.85],[84.65526,73.80591],[86.8223,73.93688],[86.00956,74.45967],[87.16682,75.11643],[88.31571,75.14393],[90.26,75.64],[92.90058,75.77333],[93.23421,76.0472],[95.86,76.14],[96.67821,75.91548],[98.92254,76.44689],[100.75967,76.43028],[101.03532,76.86189],[101.99084,77.28754],[104.3516,77.69792],[106.06664,77.37389],[104.705,77.1274],[106.97013,76.97419],[107.24,76.48],[108.1538,76.72335],[111.07726,76.71],[113.33151,76.22224],[114.13417,75.84764],[113.88539,75.32779],[112.77918,75.03186],[110.15125,74.47673],[109.4,74.18],[110.64,74.04],[112.11919,73.78774],[113.01954,73.97693],[113.52958,73.33505],[113.96881,73.59488],[115.56782,73.75285],[118.77633,73.58772],[119.02,73.12],[123.20066,72.97122],[123.25777,73.73503],[125.38,73.56],[126.97644,73.56549],[128.59126,73.03871],[129.05157,72.39872],[128.46,71.98],[129.71599,71.19304],[131.28858,70.78699],[132.2535,71.8363],[133.85766,71.38642],[135.56193,71.65525],[137.49755,71.34763],[138.23409,71.62803],[139.86983,71.48783],[139.14791,72.41619],[140.46817,72.84941],[149.5,72.2],[150.35118,71.60643],[152.9689,70.84222],[157.00688,71.03141],[158.99779,70.86672],[159.83031,70.45324],[159.70866,69.72198],[160.94053,69.43728],[162.27907,69.64204],[164.05248,69.66823],[165.94037,69.47199],[167.83567,69.58269],[169.57763,68.6938],[170.81688,69.01363],[170.0082,69.65276],[170.45345,70.09703],[173.64391,69.81743],[175.72403,69.87725],[178.6,69.4],[180,68.963636],[180,64.979709],[179.99281,64.97433],[178.7072,64.53493],[177.41128,64.60821],[178.313,64.07593],[178.90825,63.25197],[179.37034,62.98262],[179.48636,62.56894],[179.22825,62.3041],[177.3643,62.5219],[174.56929,61.76915],[173.68013,61.65261],[172.15,60.95],[170.6985,60.33618],[170.33085,59.88177],[168.90046,60.57355],[166.29498,59.78855],[165.84,60.16],[164.87674,59.7316],[163.53929,59.86871],[163.21711,59.21101],[162.01733,58.24328],[162.05297,57.83912],[163.19191,57.61503],[163.05794,56.15924],[162.12958,56.12219],[161.70146,55.28568],[162.11749,54.85514],[160.36877,54.34433],[160.02173,53.20257],[158.53094,52.95868],[158.23118,51.94269],[156.78979,51.01105],[156.42,51.7],[155.99182,53.15895],[155.43366,55.38103],[155.91442,56.76792],[156.75815,57.3647],[156.81035,57.83204],[158.36433,58.05575],[160.15064,59.31477],[161.87204,60.343],[163.66969,61.1409],[164.47355,62.55061],[163.25842,62.46627],[162.65791,61.6425],[160.12148,60.54423],[159.30232,61.77396],[156.72068,61.43442],[154.21806,59.75818],[155.04375,59.14495],[152.81185,58.88385],[151.26573,58.78089],[151.33815,59.50396],[149.78371,59.65573],[148.54481,59.16448],[145.48722,59.33637],[142.19782,59.03998],[138.95848,57.08805],[135.12619,54.72959],[136.70171,54.60355],[137.19342,53.97732],[138.1647,53.75501],[138.80463,54.25455],[139.90151,54.18968],[141.34531,53.08957],[141.37923,52.23877],[140.59742,51.23967],[140.51308,50.04553],[140.06193,48.44671],[138.55472,46.99965],[138.21971,46.30795],[136.86232,45.1435],[135.51535,43.989],[134.86939,43.39821],[133.53687,42.81147],[132.90627,42.79849],[132.27807,43.28456],[130.93587,42.55274],[130.780005,42.22001],[130.780004,42.220008],[130.78,42.22],[130.779992,42.22001],[130.64,42.395],[130.64,42.395024],[130.633866,42.903015],[131.144688,42.92999],[131.288555,44.11152],[131.02519,44.96796],[131.883454,45.321162],[133.09712,45.14409],[133.769644,46.116927],[134.11235,47.21248],[134.50081,47.57845],[135.026311,48.47823],[133.373596,48.183442],[132.50669,47.78896],[130.98726,47.79013],[130.582293,48.729687],[129.397818,49.4406],[127.6574,49.76027],[127.287456,50.739797],[126.939157,51.353894],[126.564399,51.784255],[125.946349,52.792799],[125.068211,53.161045],[123.57147,53.4588],[122.245748,53.431726],[121.003085,53.251401],[120.177089,52.753886],[120.725789,52.516226],[120.7382,51.96411],[120.18208,51.64355],[119.27939,50.58292],[119.288461,50.142883],[117.879244,49.510983],[116.678801,49.888531],[115.485695,49.805177],[114.96211,50.140247],[114.362456,50.248303],[112.89774,49.543565],[111.581231,49.377968],[110.662011,49.130128],[109.402449,49.292961],[108.475167,49.282548],[107.868176,49.793705],[106.888804,50.274296],[105.886591,50.406019],[104.62158,50.27532],[103.676545,50.089966],[102.25589,50.51056],[102.06521,51.25991],[100.88948,51.516856],[99.981732,51.634006],[98.861491,52.047366],[97.82574,51.010995],[98.231762,50.422401],[97.25976,49.72605],[95.81402,49.97746],[94.815949,50.013433],[94.147566,50.480537],[93.10421,50.49529],[92.234712,50.802171],[90.713667,50.331812],[88.805567,49.470521],[87.751264,49.297198],[87.35997,49.214981],[86.829357,49.826675],[85.54127,49.692859],[85.11556,50.117303],[84.416377,50.3114],[83.935115,50.889246],[83.383004,51.069183],[81.945986,50.812196],[80.568447,51.388336],[80.03556,50.864751],[77.800916,53.404415],[76.525179,54.177003],[76.8911,54.490524],[74.38482,53.54685],[73.425679,53.48981],[73.508516,54.035617],[72.22415,54.376655],[71.180131,54.133285],[70.865267,55.169734],[69.068167,55.38525],[68.1691,54.970392],[65.66687,54.60125],[65.178534,54.354228],[61.4366,54.00625],[60.978066,53.664993],[61.699986,52.979996],[60.739993,52.719986],[60.927269,52.447548],[59.967534,51.96042],[61.588003,51.272659],[61.337424,50.79907],[59.932807,50.842194],[59.642282,50.545442],[58.36332,51.06364],[56.77798,51.04355],[55.71694,50.62171],[54.532878,51.02624],[52.328724,51.718652],[50.766648,51.692762],[48.702382,50.605128],[48.577841,49.87476],[47.54948,50.454698],[46.751596,49.356006],[47.043672,49.152039],[46.466446,48.394152],[47.31524,47.71585],[48.05725,47.74377],[48.694734,47.075628],[48.59325,46.56104],[49.10116,46.39933]]],[[[93.77766,81.0246],[95.940895,81.2504],[97.88385,80.746975],[100.186655,79.780135],[99.93976,78.88094],[97.75794,78.7562],[94.97259,79.044745],[93.31288,79.4265],[92.5454,80.14379],[91.18107,80.34146],[93.77766,81.0246]]],[[[102.837815,79.28129],[105.37243,78.71334],[105.07547,78.30689],[99.43814,77.921],[101.2649,79.23399],[102.08635,79.34641],[102.837815,79.28129]]],[[[138.831075,76.13676],[141.471615,76.09289],[145.086285,75.562625],[144.3,74.82],[140.61381,74.84768],[138.95544,74.61148],[136.97439,75.26167],[137.51176,75.94917],[138.831075,76.13676]]],[[[148.22223,75.345845],[150.73167,75.08406],[149.575925,74.68892],[147.977465,74.778355],[146.11919,75.17298],[146.358485,75.49682],[148.22223,75.345845]]],[[[139.86312,73.36983],[140.81171,73.76506],[142.06207,73.85758],[143.48283,73.47525],[143.60385,73.21244],[142.08763,73.20544],[140.038155,73.31692],[139.86312,73.36983]]],[[[44.846958,80.58981],[46.799139,80.771918],[48.318477,80.78401],[48.522806,80.514569],[49.09719,80.753986],[50.039768,80.918885],[51.522933,80.699726],[51.136187,80.54728],[49.793685,80.415428],[48.894411,80.339567],[48.754937,80.175468],[47.586119,80.010181],[46.502826,80.247247],[47.072455,80.559424],[44.846958,80.58981]]],[[[22.731099,54.327537],[20.892245,54.312525],[19.66064,54.426084],[19.888481,54.86616],[21.268449,55.190482],[22.315724,55.015299],[22.757764,54.856574],[22.651052,54.582741],[22.731099,54.327537]]],[[[53.50829,73.749814],[55.902459,74.627486],[55.631933,75.081412],[57.868644,75.60939],[61.170044,76.251883],[64.498368,76.439055],[66.210977,76.809782],[68.15706,76.939697],[68.852211,76.544811],[68.180573,76.233642],[64.637326,75.737755],[61.583508,75.260885],[58.477082,74.309056],[56.986786,73.333044],[55.419336,72.371268],[55.622838,71.540595],[57.535693,70.720464],[56.944979,70.632743],[53.677375,70.762658],[53.412017,71.206662],[51.601895,71.474759],[51.455754,72.014881],[52.478275,72.229442],[52.444169,72.774731],[54.427614,73.627548],[53.50829,73.749814]]],[[[142.914616,53.704578],[143.260848,52.74076],[143.235268,51.75666],[143.648007,50.7476],[144.654148,48.976391],[143.173928,49.306551],[142.558668,47.861575],[143.533492,46.836728],[143.505277,46.137908],[142.747701,46.740765],[142.09203,45.966755],[141.906925,46.805929],[142.018443,47.780133],[141.904445,48.859189],[142.1358,49.615163],[142.179983,50.952342],[141.594076,51.935435],[141.682546,53.301966],[142.606934,53.762145],[142.209749,54.225476],[142.654786,54.365881],[142.914616,53.704578]]],[[[-174.92825,67.20589],[-175.01425,66.58435],[-174.33983,66.33556],[-174.57182,67.06219],[-171.85731,66.91308],[-169.89958,65.97724],[-170.89107,65.54139],[-172.53025,65.43791],[-172.555,64.46079],[-172.95533,64.25269],[-173.89184,64.2826],[-174.65392,64.63125],[-175.98353,64.92288],[-176.20716,65.35667],[-177.22266,65.52024],[-178.35993,65.39052],[-178.90332,65.74044],[-178.68611,66.11211],[-179.88377,65.87456],[-179.43268,65.40411],[-180,64.979709],[-180,68.963636],[-177.55,68.2],[-174.92825,67.20589]]],[[[-178.69378,70.89302],[-180,70.832199],[-180,71.515714],[-179.871875,71.55762],[-179.02433,71.55553],[-177.577945,71.26948],[-177.663575,71.13277],[-178.69378,70.89302]]],[[[33.435988,45.971917],[33.699462,46.219573],[34.410402,46.005162],[34.732017,45.965666],[34.861792,45.768182],[35.012659,45.737725],[35.020788,45.651219],[35.510009,45.409993],[36.529998,45.46999],[36.334713,45.113216],[35.239999,44.939996],[33.882511,44.361479],[33.326421,44.564877],[33.546924,45.034771],[32.454174,45.327466],[32.630804,45.519186],[33.588162,45.851569],[33.435988,45.971917]]]]}},{"type":"Feature","properties":{"ADMIN":"The Bahamas","NAME_EN":"The Bahamas","CONTINENT":"North America","ADM0_A3":"BHS","ISO_A3":"BHS","NAME":"Bahamas","ISO_A2":"BS","NAME_ZH":"巴哈马"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-78.98,26.79],[-78.51,26.87],[-77.85,26.84],[-77.82,26.58],[-78.91,26.42],[-78.98,26.79]]],[[[-77.79,27.04],[-77,26.59],[-77.17255,25.87918],[-77.35641,26.00735],[-77.34,26.53],[-77.78802,26.92516],[-77.79,27.04]]],[[[-78.19087,25.2103],[-77.89,25.17],[-77.54,24.34],[-77.53466,23.75975],[-77.78,23.71],[-78.03405,24.28615],[-78.40848,24.57564],[-78.19087,25.2103]]]]}},{"type":"Feature","properties":{"ADMIN":"Falkland Islands","NAME_EN":"Falkland Islands","CONTINENT":"South America","ADM0_A3":"FLK","ISO_A3":"FLK","NAME":"Falkland Is.","ISO_A2":"FK","NAME_ZH":"福克兰群岛"},"geometry":{"type":"Polygon","coordinates":[[[-61.2,-51.85],[-60,-51.25],[-59.15,-51.5],[-58.55,-51.1],[-57.75,-51.55],[-58.05,-51.9],[-59.4,-52.2],[-59.85,-51.85],[-60.7,-52.3],[-61.2,-51.85]]]}},{"type":"Feature","properties":{"ADMIN":"Norway","NAME_EN":"Norway","CONTINENT":"Europe","ADM0_A3":"NOR","ISO_A3":"-99","NAME":"Norway","ISO_A2":"-99","NAME_ZH":"挪威"},"geometry":{"type":"MultiPolygon","coordinates":[[[[15.14282,79.67431],[15.52255,80.01608],[16.99085,80.05086],[18.25183,79.70175],[21.54383,78.95611],[19.02737,78.5626],[18.47172,77.82669],[17.59441,77.63796],[17.1182,76.80941],[15.91315,76.77045],[13.76259,77.38035],[14.66956,77.73565],[13.1706,78.02493],[11.22231,78.8693],[10.44453,79.65239],[13.17077,80.01046],[13.71852,79.66039],[15.14282,79.67431]]],[[[31.101042,69.558101],[29.39955,69.15692],[28.59193,69.064777],[29.015573,69.766491],[27.732292,70.164193],[26.179622,69.825299],[25.689213,69.092114],[24.735679,68.649557],[23.66205,68.891247],[22.356238,68.841741],[21.244936,69.370443],[20.645593,69.106247],[20.025269,69.065139],[19.87856,68.407194],[17.993868,68.567391],[17.729182,68.010552],[16.768879,68.013937],[16.108712,67.302456],[15.108411,66.193867],[13.55569,64.787028],[13.919905,64.445421],[13.571916,64.049114],[12.579935,64.066219],[11.930569,63.128318],[11.992064,61.800362],[12.631147,61.293572],[12.300366,60.117933],[11.468272,59.432393],[11.027369,58.856149],[10.356557,59.469807],[8.382,58.313288],[7.048748,58.078884],[5.665835,58.588155],[5.308234,59.663232],[4.992078,61.970998],[5.9129,62.614473],[8.553411,63.454008],[10.527709,64.486038],[12.358347,65.879726],[14.761146,67.810642],[16.435927,68.563205],[19.184028,69.817444],[21.378416,70.255169],[23.023742,70.202072],[24.546543,71.030497],[26.37005,70.986262],[28.165547,71.185474],[31.293418,70.453788],[30.005435,70.186259],[31.101042,69.558101]]],[[[27.407506,80.056406],[25.924651,79.517834],[23.024466,79.400012],[20.075188,79.566823],[19.897266,79.842362],[18.462264,79.85988],[17.368015,80.318896],[20.455992,80.598156],[21.907945,80.357679],[22.919253,80.657144],[25.447625,80.40734],[27.407506,80.056406]]],[[[24.72412,77.85385],[22.49032,77.44493],[20.72601,77.67704],[21.41611,77.93504],[20.8119,78.25463],[22.88426,78.45494],[23.28134,78.07954],[24.72412,77.85385]]]]}},{"type":"Feature","properties":{"ADMIN":"Greenland","NAME_EN":"Greenland","CONTINENT":"North America","ADM0_A3":"GRL","ISO_A3":"GRL","NAME":"Greenland","ISO_A2":"GL","NAME_ZH":"格陵兰"},"geometry":{"type":"Polygon","coordinates":[[[-46.76379,82.62796],[-43.40644,83.22516],[-39.89753,83.18018],[-38.62214,83.54905],[-35.08787,83.64513],[-27.10046,83.51966],[-20.84539,82.72669],[-22.69182,82.34165],[-26.51753,82.29765],[-31.9,82.2],[-31.39646,82.02154],[-27.85666,82.13178],[-24.84448,81.78697],[-22.90328,82.09317],[-22.07175,81.73449],[-23.16961,81.15271],[-20.62363,81.52462],[-15.76818,81.91245],[-12.77018,81.71885],[-12.20855,81.29154],[-16.28533,80.58004],[-16.85,80.35],[-20.04624,80.17708],[-17.73035,80.12912],[-18.9,79.4],[-19.70499,78.75128],[-19.67353,77.63859],[-18.47285,76.98565],[-20.03503,76.94434],[-21.67944,76.62795],[-19.83407,76.09808],[-19.59896,75.24838],[-20.66818,75.15585],[-19.37281,74.29561],[-21.59422,74.22382],[-20.43454,73.81713],[-20.76234,73.46436],[-22.17221,73.30955],[-23.56593,73.30663],[-22.31311,72.62928],[-22.29954,72.18409],[-24.27834,72.59788],[-24.79296,72.3302],[-23.44296,72.08016],[-22.13281,71.46898],[-21.75356,70.66369],[-23.53603,70.471],[-24.30702,70.85649],[-25.54341,71.43094],[-25.20135,70.75226],[-26.36276,70.22646],[-23.72742,70.18401],[-22.34902,70.12946],[-25.02927,69.2588],[-27.74737,68.47046],[-30.67371,68.12503],[-31.77665,68.12078],[-32.81105,67.73547],[-34.20196,66.67974],[-36.35284,65.9789],[-37.04378,65.93768],[-38.37505,65.69213],[-39.81222,65.45848],[-40.66899,64.83997],[-40.68281,64.13902],[-41.1887,63.48246],[-42.81938,62.68233],[-42.41666,61.90093],[-42.86619,61.07404],[-43.3784,60.09772],[-44.7875,60.03676],[-46.26364,60.85328],[-48.26294,60.85843],[-49.23308,61.40681],[-49.90039,62.38336],[-51.63325,63.62691],[-52.14014,64.27842],[-52.27659,65.1767],[-53.66166,66.09957],[-53.30161,66.8365],[-53.96911,67.18899],[-52.9804,68.35759],[-51.47536,68.72958],[-51.08041,69.14781],[-50.87122,69.9291],[-52.013585,69.574925],[-52.55792,69.42616],[-53.45629,69.283625],[-54.68336,69.61003],[-54.75001,70.28932],[-54.35884,70.821315],[-53.431315,70.835755],[-51.39014,70.56978],[-53.10937,71.20485],[-54.00422,71.54719],[-55,71.406537],[-55.83468,71.65444],[-54.71819,72.58625],[-55.32634,72.95861],[-56.12003,73.64977],[-57.32363,74.71026],[-58.59679,75.09861],[-58.58516,75.51727],[-61.26861,76.10238],[-63.39165,76.1752],[-66.06427,76.13486],[-68.50438,76.06141],[-69.66485,76.37975],[-71.40257,77.00857],[-68.77671,77.32312],[-66.76397,77.37595],[-71.04293,77.63595],[-73.297,78.04419],[-73.15938,78.43271],[-69.37345,78.91388],[-65.7107,79.39436],[-65.3239,79.75814],[-68.02298,80.11721],[-67.15129,80.51582],[-63.68925,81.21396],[-62.23444,81.3211],[-62.65116,81.77042],[-60.28249,82.03363],[-57.20744,82.19074],[-54.13442,82.19962],[-53.04328,81.88833],[-50.39061,82.43883],[-48.00386,82.06481],[-46.59984,81.985945],[-44.523,81.6607],[-46.9007,82.19979],[-46.76379,82.62796]]]}},{"type":"Feature","properties":{"ADMIN":"French Southern and Antarctic Lands","NAME_EN":"French Southern and Antarctic Lands","CONTINENT":"Seven seas (open ocean)","ADM0_A3":"ATF","ISO_A3":"ATF","NAME":"Fr. S. Antarctic Lands","ISO_A2":"TF","NAME_ZH":"法属南部和南极领地"},"geometry":{"type":"Polygon","coordinates":[[[68.935,-48.625],[69.58,-48.94],[70.525,-49.065],[70.56,-49.255],[70.28,-49.71],[68.745,-49.775],[68.72,-49.2425],[68.8675,-48.83],[68.935,-48.625]]]}},{"type":"Feature","properties":{"ADMIN":"East Timor","NAME_EN":"East Timor","CONTINENT":"Asia","ADM0_A3":"TLS","ISO_A3":"TLS","NAME":"Timor-Leste","ISO_A2":"TL","NAME_ZH":"东帝汶"},"geometry":{"type":"Polygon","coordinates":[[[124.968682,-8.89279],[125.086246,-8.656887],[125.947072,-8.432095],[126.644704,-8.398247],[126.957243,-8.273345],[127.335928,-8.397317],[126.967992,-8.668256],[125.925885,-9.106007],[125.08852,-9.393173],[125.07002,-9.089987],[124.968682,-8.89279]]]}},{"type":"Feature","properties":{"ADMIN":"South Africa","NAME_EN":"South Africa","CONTINENT":"Africa","ADM0_A3":"ZAF","ISO_A3":"ZAF","NAME":"South Africa","ISO_A2":"ZA","NAME_ZH":"南非"},"geometry":{"type":"Polygon","coordinates":[[[16.344977,-28.576705],[16.824017,-28.082162],[17.218929,-28.355943],[17.387497,-28.783514],[17.836152,-28.856378],[18.464899,-29.045462],[19.002127,-28.972443],[19.894734,-28.461105],[19.895768,-24.76779],[20.165726,-24.917962],[20.758609,-25.868136],[20.66647,-26.477453],[20.889609,-26.828543],[21.605896,-26.726534],[22.105969,-26.280256],[22.579532,-25.979448],[22.824271,-25.500459],[23.312097,-25.26869],[23.73357,-25.390129],[24.211267,-25.670216],[25.025171,-25.71967],[25.664666,-25.486816],[25.765849,-25.174845],[25.941652,-24.696373],[26.485753,-24.616327],[26.786407,-24.240691],[27.11941,-23.574323],[28.017236,-22.827754],[29.432188,-22.091313],[29.839037,-22.102216],[30.322883,-22.271612],[30.659865,-22.151567],[31.191409,-22.25151],[31.670398,-23.658969],[31.930589,-24.369417],[31.752408,-25.484284],[31.837778,-25.843332],[31.333158,-25.660191],[31.04408,-25.731452],[30.949667,-26.022649],[30.676609,-26.398078],[30.685962,-26.743845],[31.282773,-27.285879],[31.86806,-27.177927],[32.071665,-26.73382],[32.83012,-26.742192],[32.580265,-27.470158],[32.462133,-28.301011],[32.203389,-28.752405],[31.521001,-29.257387],[31.325561,-29.401978],[30.901763,-29.909957],[30.622813,-30.423776],[30.055716,-31.140269],[28.925553,-32.172041],[28.219756,-32.771953],[27.464608,-33.226964],[26.419452,-33.61495],[25.909664,-33.66704],[25.780628,-33.944646],[25.172862,-33.796851],[24.677853,-33.987176],[23.594043,-33.794474],[22.988189,-33.916431],[22.574157,-33.864083],[21.542799,-34.258839],[20.689053,-34.417175],[20.071261,-34.795137],[19.616405,-34.819166],[19.193278,-34.462599],[18.855315,-34.444306],[18.424643,-33.997873],[18.377411,-34.136521],[18.244499,-33.867752],[18.25008,-33.281431],[17.92519,-32.611291],[18.24791,-32.429131],[18.221762,-31.661633],[17.566918,-30.725721],[17.064416,-29.878641],[17.062918,-29.875954],[16.344977,-28.576705]],[[28.978263,-28.955597],[28.5417,-28.647502],[28.074338,-28.851469],[27.532511,-29.242711],[26.999262,-29.875954],[27.749397,-30.645106],[28.107205,-30.545732],[28.291069,-30.226217],[28.8484,-30.070051],[29.018415,-29.743766],[29.325166,-29.257387],[28.978263,-28.955597]]]}},{"type":"Feature","properties":{"ADMIN":"Lesotho","NAME_EN":"Lesotho","CONTINENT":"Africa","ADM0_A3":"LSO","ISO_A3":"LSO","NAME":"Lesotho","ISO_A2":"LS","NAME_ZH":"莱索托"},"geometry":{"type":"Polygon","coordinates":[[[28.978263,-28.955597],[29.325166,-29.257387],[29.018415,-29.743766],[28.8484,-30.070051],[28.291069,-30.226217],[28.107205,-30.545732],[27.749397,-30.645106],[26.999262,-29.875954],[27.532511,-29.242711],[28.074338,-28.851469],[28.5417,-28.647502],[28.978263,-28.955597]]]}},{"type":"Feature","properties":{"ADMIN":"Mexico","NAME_EN":"Mexico","CONTINENT":"North America","ADM0_A3":"MEX","ISO_A3":"MEX","NAME":"Mexico","ISO_A2":"MX","NAME_ZH":"墨西哥"},"geometry":{"type":"Polygon","coordinates":[[[-117.12776,32.53534],[-115.99135,32.61239],[-114.72139,32.72083],[-114.815,32.52528],[-113.30498,32.03914],[-111.02361,31.33472],[-109.035,31.34194],[-108.24194,31.34222],[-108.24,31.754854],[-106.50759,31.75452],[-106.1429,31.39995],[-105.63159,31.08383],[-105.03737,30.64402],[-104.70575,30.12173],[-104.45697,29.57196],[-103.94,29.27],[-103.11,28.97],[-102.48,29.76],[-101.6624,29.7793],[-100.9576,29.38071],[-100.45584,28.69612],[-100.11,28.11],[-99.52,27.54],[-99.3,26.84],[-99.02,26.37],[-98.24,26.06],[-97.53,25.84],[-97.140008,25.869997],[-97.528072,24.992144],[-97.702946,24.272343],[-97.776042,22.93258],[-97.872367,22.444212],[-97.699044,21.898689],[-97.38896,21.411019],[-97.189333,20.635433],[-96.525576,19.890931],[-96.292127,19.320371],[-95.900885,18.828024],[-94.839063,18.562717],[-94.42573,18.144371],[-93.548651,18.423837],[-92.786114,18.524839],[-92.037348,18.704569],[-91.407903,18.876083],[-90.77187,19.28412],[-90.53359,19.867418],[-90.451476,20.707522],[-90.278618,20.999855],[-89.601321,21.261726],[-88.543866,21.493675],[-87.658417,21.458846],[-87.05189,21.543543],[-86.811982,21.331515],[-86.845908,20.849865],[-87.383291,20.255405],[-87.621054,19.646553],[-87.43675,19.472403],[-87.58656,19.04013],[-87.837191,18.259816],[-88.090664,18.516648],[-88.300031,18.499982],[-88.490123,18.486831],[-88.848344,17.883198],[-89.029857,18.001511],[-89.150909,17.955468],[-89.14308,17.808319],[-90.067934,17.819326],[-91.00152,17.817595],[-91.002269,17.254658],[-91.453921,17.252177],[-91.08167,16.918477],[-90.711822,16.687483],[-90.600847,16.470778],[-90.438867,16.41011],[-90.464473,16.069562],[-91.74796,16.066565],[-92.229249,15.251447],[-92.087216,15.064585],[-92.20323,14.830103],[-92.22775,14.538829],[-93.359464,15.61543],[-93.875169,15.940164],[-94.691656,16.200975],[-95.250227,16.128318],[-96.053382,15.752088],[-96.557434,15.653515],[-97.263592,15.917065],[-98.01303,16.107312],[-98.947676,16.566043],[-99.697397,16.706164],[-100.829499,17.171071],[-101.666089,17.649026],[-101.918528,17.91609],[-102.478132,17.975751],[-103.50099,18.292295],[-103.917527,18.748572],[-104.99201,19.316134],[-105.493038,19.946767],[-105.731396,20.434102],[-105.397773,20.531719],[-105.500661,20.816895],[-105.270752,21.076285],[-105.265817,21.422104],[-105.603161,21.871146],[-105.693414,22.26908],[-106.028716,22.773752],[-106.90998,23.767774],[-107.915449,24.548915],[-108.401905,25.172314],[-109.260199,25.580609],[-109.444089,25.824884],[-109.291644,26.442934],[-109.801458,26.676176],[-110.391732,27.162115],[-110.641019,27.859876],[-111.178919,27.941241],[-111.759607,28.467953],[-112.228235,28.954409],[-112.271824,29.266844],[-112.809594,30.021114],[-113.163811,30.786881],[-113.148669,31.170966],[-113.871881,31.567608],[-114.205737,31.524045],[-114.776451,31.799532],[-114.9367,31.393485],[-114.771232,30.913617],[-114.673899,30.162681],[-114.330974,29.750432],[-113.588875,29.061611],[-113.424053,28.826174],[-113.271969,28.754783],[-113.140039,28.411289],[-112.962298,28.42519],[-112.761587,27.780217],[-112.457911,27.525814],[-112.244952,27.171727],[-111.616489,26.662817],[-111.284675,25.73259],[-110.987819,25.294606],[-110.710007,24.826004],[-110.655049,24.298595],[-110.172856,24.265548],[-109.771847,23.811183],[-109.409104,23.364672],[-109.433392,23.185588],[-109.854219,22.818272],[-110.031392,22.823078],[-110.295071,23.430973],[-110.949501,24.000964],[-111.670568,24.484423],[-112.182036,24.738413],[-112.148989,25.470125],[-112.300711,26.012004],[-112.777297,26.32196],[-113.464671,26.768186],[-113.59673,26.63946],[-113.848937,26.900064],[-114.465747,27.14209],[-115.055142,27.722727],[-114.982253,27.7982],[-114.570366,27.741485],[-114.199329,28.115003],[-114.162018,28.566112],[-114.931842,29.279479],[-115.518654,29.556362],[-115.887365,30.180794],[-116.25835,30.836464],[-116.721526,31.635744],[-117.12776,32.53534]]]}},{"type":"Feature","properties":{"ADMIN":"Uruguay","NAME_EN":"Uruguay","CONTINENT":"South America","ADM0_A3":"URY","ISO_A3":"URY","NAME":"Uruguay","ISO_A2":"UY","NAME_ZH":"乌拉圭"},"geometry":{"type":"Polygon","coordinates":[[[-57.625133,-30.216295],[-56.976026,-30.109686],[-55.973245,-30.883076],[-55.60151,-30.853879],[-54.572452,-31.494511],[-53.787952,-32.047243],[-53.209589,-32.727666],[-53.650544,-33.202004],[-53.373662,-33.768378],[-53.806426,-34.396815],[-54.935866,-34.952647],[-55.67409,-34.752659],[-56.215297,-34.859836],[-57.139685,-34.430456],[-57.817861,-34.462547],[-58.427074,-33.909454],[-58.349611,-33.263189],[-58.132648,-33.040567],[-58.14244,-32.044504],[-57.874937,-31.016556],[-57.625133,-30.216295]]]}},{"type":"Feature","properties":{"ADMIN":"Brazil","NAME_EN":"Brazil","CONTINENT":"South America","ADM0_A3":"BRA","ISO_A3":"BRA","NAME":"Brazil","ISO_A2":"BR","NAME_ZH":"巴西"},"geometry":{"type":"Polygon","coordinates":[[[-53.373662,-33.768378],[-53.650544,-33.202004],[-53.209589,-32.727666],[-53.787952,-32.047243],[-54.572452,-31.494511],[-55.60151,-30.853879],[-55.973245,-30.883076],[-56.976026,-30.109686],[-57.625133,-30.216295],[-56.2909,-28.852761],[-55.162286,-27.881915],[-54.490725,-27.474757],[-53.648735,-26.923473],[-53.628349,-26.124865],[-54.13005,-25.547639],[-54.625291,-25.739255],[-54.428946,-25.162185],[-54.293476,-24.5708],[-54.29296,-24.021014],[-54.652834,-23.839578],[-55.027902,-24.001274],[-55.400747,-23.956935],[-55.517639,-23.571998],[-55.610683,-22.655619],[-55.797958,-22.35693],[-56.473317,-22.0863],[-56.88151,-22.282154],[-57.937156,-22.090176],[-57.870674,-20.732688],[-58.166392,-20.176701],[-57.853802,-19.969995],[-57.949997,-19.400004],[-57.676009,-18.96184],[-57.498371,-18.174188],[-57.734558,-17.552468],[-58.280804,-17.27171],[-58.388058,-16.877109],[-58.24122,-16.299573],[-60.15839,-16.258284],[-60.542966,-15.09391],[-60.251149,-15.077219],[-60.264326,-14.645979],[-60.459198,-14.354007],[-60.503304,-13.775955],[-61.084121,-13.479384],[-61.713204,-13.489202],[-62.127081,-13.198781],[-62.80306,-13.000653],[-63.196499,-12.627033],[-64.316353,-12.461978],[-65.402281,-11.56627],[-65.321899,-10.895872],[-65.444837,-10.511451],[-65.338435,-9.761988],[-66.646908,-9.931331],[-67.173801,-10.306812],[-68.048192,-10.712059],[-68.271254,-11.014521],[-68.786158,-11.03638],[-69.529678,-10.951734],[-70.093752,-11.123972],[-70.548686,-11.009147],[-70.481894,-9.490118],[-71.302412,-10.079436],[-72.184891,-10.053598],[-72.563033,-9.520194],[-73.226713,-9.462213],[-73.015383,-9.032833],[-73.571059,-8.424447],[-73.987235,-7.52383],[-73.723401,-7.340999],[-73.724487,-6.918595],[-73.120027,-6.629931],[-73.219711,-6.089189],[-72.964507,-5.741251],[-72.891928,-5.274561],[-71.748406,-4.593983],[-70.928843,-4.401591],[-70.794769,-4.251265],[-69.893635,-4.298187],[-69.444102,-1.556287],[-69.420486,-1.122619],[-69.577065,-0.549992],[-70.020656,-0.185156],[-70.015566,0.541414],[-69.452396,0.706159],[-69.252434,0.602651],[-69.218638,0.985677],[-69.804597,1.089081],[-69.816973,1.714805],[-67.868565,1.692455],[-67.53781,2.037163],[-67.259998,1.719999],[-67.065048,1.130112],[-66.876326,1.253361],[-66.325765,0.724452],[-65.548267,0.789254],[-65.354713,1.095282],[-64.611012,1.328731],[-64.199306,1.492855],[-64.083085,1.916369],[-63.368788,2.2009],[-63.422867,2.411068],[-64.269999,2.497006],[-64.408828,3.126786],[-64.368494,3.79721],[-64.816064,4.056445],[-64.628659,4.148481],[-63.888343,4.02053],[-63.093198,3.770571],[-62.804533,4.006965],[-62.08543,4.162124],[-60.966893,4.536468],[-60.601179,4.918098],[-60.733574,5.200277],[-60.213683,5.244486],[-59.980959,5.014061],[-60.111002,4.574967],[-59.767406,4.423503],[-59.53804,3.958803],[-59.815413,3.606499],[-59.974525,2.755233],[-59.718546,2.24963],[-59.646044,1.786894],[-59.030862,1.317698],[-58.540013,1.268088],[-58.429477,1.463942],[-58.11345,1.507195],[-57.660971,1.682585],[-57.335823,1.948538],[-56.782704,1.863711],[-56.539386,1.899523],[-55.995698,1.817667],[-55.9056,2.021996],[-56.073342,2.220795],[-55.973322,2.510364],[-55.569755,2.421506],[-55.097587,2.523748],[-54.524754,2.311849],[-54.088063,2.105557],[-53.778521,2.376703],[-53.554839,2.334897],[-53.418465,2.053389],[-52.939657,2.124858],[-52.556425,2.504705],[-52.249338,3.241094],[-51.657797,4.156232],[-51.317146,4.203491],[-51.069771,3.650398],[-50.508875,1.901564],[-49.974076,1.736483],[-49.947101,1.04619],[-50.699251,0.222984],[-50.388211,-0.078445],[-48.620567,-0.235489],[-48.584497,-1.237805],[-47.824956,-0.581618],[-46.566584,-0.941028],[-44.905703,-1.55174],[-44.417619,-2.13775],[-44.581589,-2.691308],[-43.418791,-2.38311],[-41.472657,-2.912018],[-39.978665,-2.873054],[-38.500383,-3.700652],[-37.223252,-4.820946],[-36.452937,-5.109404],[-35.597796,-5.149504],[-35.235389,-5.464937],[-34.89603,-6.738193],[-34.729993,-7.343221],[-35.128212,-8.996401],[-35.636967,-9.649282],[-37.046519,-11.040721],[-37.683612,-12.171195],[-38.423877,-13.038119],[-38.673887,-13.057652],[-38.953276,-13.79337],[-38.882298,-15.667054],[-39.161092,-17.208407],[-39.267339,-17.867746],[-39.583521,-18.262296],[-39.760823,-19.599113],[-40.774741,-20.904512],[-40.944756,-21.937317],[-41.754164,-22.370676],[-41.988284,-22.97007],[-43.074704,-22.967693],[-44.647812,-23.351959],[-45.352136,-23.796842],[-46.472093,-24.088969],[-47.648972,-24.885199],[-48.495458,-25.877025],[-48.641005,-26.623698],[-48.474736,-27.175912],[-48.66152,-28.186135],[-48.888457,-28.674115],[-49.587329,-29.224469],[-50.696874,-30.984465],[-51.576226,-31.777698],[-52.256081,-32.24537],[-52.7121,-33.196578],[-53.373662,-33.768378]]]}},{"type":"Feature","properties":{"ADMIN":"Bolivia","NAME_EN":"Bolivia","CONTINENT":"South America","ADM0_A3":"BOL","ISO_A3":"BOL","NAME":"Bolivia","ISO_A2":"BO","NAME_ZH":"玻利维亚"},"geometry":{"type":"Polygon","coordinates":[[[-69.529678,-10.951734],[-68.786158,-11.03638],[-68.271254,-11.014521],[-68.048192,-10.712059],[-67.173801,-10.306812],[-66.646908,-9.931331],[-65.338435,-9.761988],[-65.444837,-10.511451],[-65.321899,-10.895872],[-65.402281,-11.56627],[-64.316353,-12.461978],[-63.196499,-12.627033],[-62.80306,-13.000653],[-62.127081,-13.198781],[-61.713204,-13.489202],[-61.084121,-13.479384],[-60.503304,-13.775955],[-60.459198,-14.354007],[-60.264326,-14.645979],[-60.251149,-15.077219],[-60.542966,-15.09391],[-60.15839,-16.258284],[-58.24122,-16.299573],[-58.388058,-16.877109],[-58.280804,-17.27171],[-57.734558,-17.552468],[-57.498371,-18.174188],[-57.676009,-18.96184],[-57.949997,-19.400004],[-57.853802,-19.969995],[-58.166392,-20.176701],[-58.183471,-19.868399],[-59.115042,-19.356906],[-60.043565,-19.342747],[-61.786326,-19.633737],[-62.265961,-20.513735],[-62.291179,-21.051635],[-62.685057,-22.249029],[-62.846468,-22.034985],[-63.986838,-21.993644],[-64.377021,-22.798091],[-64.964892,-22.075862],[-66.273339,-21.83231],[-67.106674,-22.735925],[-67.82818,-22.872919],[-68.219913,-21.494347],[-68.757167,-20.372658],[-68.442225,-19.405068],[-68.966818,-18.981683],[-69.100247,-18.260125],[-69.590424,-17.580012],[-68.959635,-16.500698],[-69.389764,-15.660129],[-69.160347,-15.323974],[-69.339535,-14.953195],[-68.948887,-14.453639],[-68.929224,-13.602684],[-68.88008,-12.899729],[-68.66508,-12.5613],[-69.529678,-10.951734]]]}},{"type":"Feature","properties":{"ADMIN":"Peru","NAME_EN":"Peru","CONTINENT":"South America","ADM0_A3":"PER","ISO_A3":"PER","NAME":"Peru","ISO_A2":"PE","NAME_ZH":"秘鲁"},"geometry":{"type":"Polygon","coordinates":[[[-69.893635,-4.298187],[-70.794769,-4.251265],[-70.928843,-4.401591],[-71.748406,-4.593983],[-72.891928,-5.274561],[-72.964507,-5.741251],[-73.219711,-6.089189],[-73.120027,-6.629931],[-73.724487,-6.918595],[-73.723401,-7.340999],[-73.987235,-7.52383],[-73.571059,-8.424447],[-73.015383,-9.032833],[-73.226713,-9.462213],[-72.563033,-9.520194],[-72.184891,-10.053598],[-71.302412,-10.079436],[-70.481894,-9.490118],[-70.548686,-11.009147],[-70.093752,-11.123972],[-69.529678,-10.951734],[-68.66508,-12.5613],[-68.88008,-12.899729],[-68.929224,-13.602684],[-68.948887,-14.453639],[-69.339535,-14.953195],[-69.160347,-15.323974],[-69.389764,-15.660129],[-68.959635,-16.500698],[-69.590424,-17.580012],[-69.858444,-18.092694],[-70.372572,-18.347975],[-71.37525,-17.773799],[-71.462041,-17.363488],[-73.44453,-16.359363],[-75.237883,-15.265683],[-76.009205,-14.649286],[-76.423469,-13.823187],[-76.259242,-13.535039],[-77.106192,-12.222716],[-78.092153,-10.377712],[-79.036953,-8.386568],[-79.44592,-7.930833],[-79.760578,-7.194341],[-80.537482,-6.541668],[-81.249996,-6.136834],[-80.926347,-5.690557],[-81.410943,-4.736765],[-81.09967,-4.036394],[-80.302561,-3.404856],[-80.184015,-3.821162],[-80.469295,-4.059287],[-80.442242,-4.425724],[-80.028908,-4.346091],[-79.624979,-4.454198],[-79.205289,-4.959129],[-78.639897,-4.547784],[-78.450684,-3.873097],[-77.837905,-3.003021],[-76.635394,-2.608678],[-75.544996,-1.56161],[-75.233723,-0.911417],[-75.373223,-0.152032],[-75.106625,-0.057205],[-74.441601,-0.53082],[-74.122395,-1.002833],[-73.659504,-1.260491],[-73.070392,-2.308954],[-72.325787,-2.434218],[-71.774761,-2.16979],[-71.413646,-2.342802],[-70.813476,-2.256865],[-70.047709,-2.725156],[-70.692682,-3.742872],[-70.394044,-3.766591],[-69.893635,-4.298187]]]}},{"type":"Feature","properties":{"ADMIN":"Colombia","NAME_EN":"Colombia","CONTINENT":"South America","ADM0_A3":"COL","ISO_A3":"COL","NAME":"Colombia","ISO_A2":"CO","NAME_ZH":"哥伦比亚"},"geometry":{"type":"Polygon","coordinates":[[[-66.876326,1.253361],[-67.065048,1.130112],[-67.259998,1.719999],[-67.53781,2.037163],[-67.868565,1.692455],[-69.816973,1.714805],[-69.804597,1.089081],[-69.218638,0.985677],[-69.252434,0.602651],[-69.452396,0.706159],[-70.015566,0.541414],[-70.020656,-0.185156],[-69.577065,-0.549992],[-69.420486,-1.122619],[-69.444102,-1.556287],[-69.893635,-4.298187],[-70.394044,-3.766591],[-70.692682,-3.742872],[-70.047709,-2.725156],[-70.813476,-2.256865],[-71.413646,-2.342802],[-71.774761,-2.16979],[-72.325787,-2.434218],[-73.070392,-2.308954],[-73.659504,-1.260491],[-74.122395,-1.002833],[-74.441601,-0.53082],[-75.106625,-0.057205],[-75.373223,-0.152032],[-75.801466,0.084801],[-76.292314,0.416047],[-76.57638,0.256936],[-77.424984,0.395687],[-77.668613,0.825893],[-77.855061,0.809925],[-78.855259,1.380924],[-78.990935,1.69137],[-78.617831,1.766404],[-78.662118,2.267355],[-78.42761,2.629556],[-77.931543,2.696606],[-77.510431,3.325017],[-77.12769,3.849636],[-77.496272,4.087606],[-77.307601,4.667984],[-77.533221,5.582812],[-77.318815,5.845354],[-77.476661,6.691116],[-77.881571,7.223771],[-77.753414,7.70984],[-77.431108,7.638061],[-77.242566,7.935278],[-77.474723,8.524286],[-77.353361,8.670505],[-76.836674,8.638749],[-76.086384,9.336821],[-75.6746,9.443248],[-75.664704,9.774003],[-75.480426,10.61899],[-74.906895,11.083045],[-74.276753,11.102036],[-74.197223,11.310473],[-73.414764,11.227015],[-72.627835,11.731972],[-72.238195,11.95555],[-71.75409,12.437303],[-71.399822,12.376041],[-71.137461,12.112982],[-71.331584,11.776284],[-71.973922,11.608672],[-72.227575,11.108702],[-72.614658,10.821975],[-72.905286,10.450344],[-73.027604,9.73677],[-73.304952,9.152],[-72.78873,9.085027],[-72.660495,8.625288],[-72.439862,8.405275],[-72.360901,8.002638],[-72.479679,7.632506],[-72.444487,7.423785],[-72.198352,7.340431],[-71.960176,6.991615],[-70.674234,7.087785],[-70.093313,6.960376],[-69.38948,6.099861],[-68.985319,6.206805],[-68.265052,6.153268],[-67.695087,6.267318],[-67.34144,6.095468],[-67.521532,5.55687],[-67.744697,5.221129],[-67.823012,4.503937],[-67.621836,3.839482],[-67.337564,3.542342],[-67.303173,3.318454],[-67.809938,2.820655],[-67.447092,2.600281],[-67.181294,2.250638],[-66.876326,1.253361]]]}},{"type":"Feature","properties":{"ADMIN":"Panama","NAME_EN":"Panama","CONTINENT":"North America","ADM0_A3":"PAN","ISO_A3":"PAN","NAME":"Panama","ISO_A2":"PA","NAME_ZH":"巴拿马"},"geometry":{"type":"Polygon","coordinates":[[[-77.353361,8.670505],[-77.474723,8.524286],[-77.242566,7.935278],[-77.431108,7.638061],[-77.753414,7.70984],[-77.881571,7.223771],[-78.214936,7.512255],[-78.429161,8.052041],[-78.182096,8.319182],[-78.435465,8.387705],[-78.622121,8.718124],[-79.120307,8.996092],[-79.557877,8.932375],[-79.760578,8.584515],[-80.164481,8.333316],[-80.382659,8.298409],[-80.480689,8.090308],[-80.00369,7.547524],[-80.276671,7.419754],[-80.421158,7.271572],[-80.886401,7.220541],[-81.059543,7.817921],[-81.189716,7.647906],[-81.519515,7.70661],[-81.721311,8.108963],[-82.131441,8.175393],[-82.390934,8.292362],[-82.820081,8.290864],[-82.850958,8.073823],[-82.965783,8.225028],[-82.913176,8.423517],[-82.829771,8.626295],[-82.868657,8.807266],[-82.719183,8.925709],[-82.927155,9.07433],[-82.932891,9.476812],[-82.546196,9.566135],[-82.187123,9.207449],[-82.207586,8.995575],[-81.808567,8.950617],[-81.714154,9.031955],[-81.439287,8.786234],[-80.947302,8.858504],[-80.521901,9.111072],[-79.9146,9.312765],[-79.573303,9.61161],[-79.021192,9.552931],[-79.05845,9.454565],[-78.500888,9.420459],[-78.055928,9.24773],[-77.729514,8.946844],[-77.353361,8.670505]]]}},{"type":"Feature","properties":{"ADMIN":"Costa Rica","NAME_EN":"Costa Rica","CONTINENT":"North America","ADM0_A3":"CRI","ISO_A3":"CRI","NAME":"Costa Rica","ISO_A2":"CR","NAME_ZH":"哥斯达黎加"},"geometry":{"type":"Polygon","coordinates":[[[-82.546196,9.566135],[-82.932891,9.476812],[-82.927155,9.07433],[-82.719183,8.925709],[-82.868657,8.807266],[-82.829771,8.626295],[-82.913176,8.423517],[-82.965783,8.225028],[-83.508437,8.446927],[-83.711474,8.656836],[-83.596313,8.830443],[-83.632642,9.051386],[-83.909886,9.290803],[-84.303402,9.487354],[-84.647644,9.615537],[-84.713351,9.908052],[-84.97566,10.086723],[-84.911375,9.795992],[-85.110923,9.55704],[-85.339488,9.834542],[-85.660787,9.933347],[-85.797445,10.134886],[-85.791709,10.439337],[-85.659314,10.754331],[-85.941725,10.895278],[-85.71254,11.088445],[-85.561852,11.217119],[-84.903003,10.952303],[-84.673069,11.082657],[-84.355931,10.999226],[-84.190179,10.79345],[-83.895054,10.726839],[-83.655612,10.938764],[-83.40232,10.395438],[-83.015677,9.992982],[-82.546196,9.566135]]]}},{"type":"Feature","properties":{"ADMIN":"Nicaragua","NAME_EN":"Nicaragua","CONTINENT":"North America","ADM0_A3":"NIC","ISO_A3":"NIC","NAME":"Nicaragua","ISO_A2":"NI","NAME_ZH":"尼加拉瓜"},"geometry":{"type":"Polygon","coordinates":[[[-83.655612,10.938764],[-83.895054,10.726839],[-84.190179,10.79345],[-84.355931,10.999226],[-84.673069,11.082657],[-84.903003,10.952303],[-85.561852,11.217119],[-85.71254,11.088445],[-86.058488,11.403439],[-86.52585,11.806877],[-86.745992,12.143962],[-87.167516,12.458258],[-87.668493,12.90991],[-87.557467,13.064552],[-87.392386,12.914018],[-87.316654,12.984686],[-87.005769,13.025794],[-86.880557,13.254204],[-86.733822,13.263093],[-86.755087,13.754845],[-86.520708,13.778487],[-86.312142,13.771356],[-86.096264,14.038187],[-85.801295,13.836055],[-85.698665,13.960078],[-85.514413,14.079012],[-85.165365,14.35437],[-85.148751,14.560197],[-85.052787,14.551541],[-84.924501,14.790493],[-84.820037,14.819587],[-84.649582,14.666805],[-84.449336,14.621614],[-84.228342,14.748764],[-83.975721,14.749436],[-83.628585,14.880074],[-83.489989,15.016267],[-83.147219,14.995829],[-83.233234,14.899866],[-83.284162,14.676624],[-83.182126,14.310703],[-83.4125,13.970078],[-83.519832,13.567699],[-83.552207,13.127054],[-83.498515,12.869292],[-83.473323,12.419087],[-83.626104,12.32085],[-83.719613,11.893124],[-83.650858,11.629032],[-83.85547,11.373311],[-83.808936,11.103044],[-83.655612,10.938764]]]}},{"type":"Feature","properties":{"ADMIN":"Honduras","NAME_EN":"Honduras","CONTINENT":"North America","ADM0_A3":"HND","ISO_A3":"HND","NAME":"Honduras","ISO_A2":"HN","NAME_ZH":"洪都拉斯"},"geometry":{"type":"Polygon","coordinates":[[[-83.147219,14.995829],[-83.489989,15.016267],[-83.628585,14.880074],[-83.975721,14.749436],[-84.228342,14.748764],[-84.449336,14.621614],[-84.649582,14.666805],[-84.820037,14.819587],[-84.924501,14.790493],[-85.052787,14.551541],[-85.148751,14.560197],[-85.165365,14.35437],[-85.514413,14.079012],[-85.698665,13.960078],[-85.801295,13.836055],[-86.096264,14.038187],[-86.312142,13.771356],[-86.520708,13.778487],[-86.755087,13.754845],[-86.733822,13.263093],[-86.880557,13.254204],[-87.005769,13.025794],[-87.316654,12.984686],[-87.489409,13.297535],[-87.793111,13.38448],[-87.723503,13.78505],[-87.859515,13.893312],[-88.065343,13.964626],[-88.503998,13.845486],[-88.541231,13.980155],[-88.843073,14.140507],[-89.058512,14.340029],[-89.353326,14.424133],[-89.145535,14.678019],[-89.22522,14.874286],[-89.154811,15.066419],[-88.68068,15.346247],[-88.225023,15.727722],[-88.121153,15.688655],[-87.901813,15.864458],[-87.61568,15.878799],[-87.522921,15.797279],[-87.367762,15.84694],[-86.903191,15.756713],[-86.440946,15.782835],[-86.119234,15.893449],[-86.001954,16.005406],[-85.683317,15.953652],[-85.444004,15.885749],[-85.182444,15.909158],[-84.983722,15.995923],[-84.52698,15.857224],[-84.368256,15.835158],[-84.063055,15.648244],[-83.773977,15.424072],[-83.410381,15.270903],[-83.147219,14.995829]]]}},{"type":"Feature","properties":{"ADMIN":"El Salvador","NAME_EN":"El Salvador","CONTINENT":"North America","ADM0_A3":"SLV","ISO_A3":"SLV","NAME":"El Salvador","ISO_A2":"SV","NAME_ZH":"萨尔瓦多"},"geometry":{"type":"Polygon","coordinates":[[[-89.353326,14.424133],[-89.058512,14.340029],[-88.843073,14.140507],[-88.541231,13.980155],[-88.503998,13.845486],[-88.065343,13.964626],[-87.859515,13.893312],[-87.723503,13.78505],[-87.793111,13.38448],[-87.904112,13.149017],[-88.483302,13.163951],[-88.843228,13.259734],[-89.256743,13.458533],[-89.812394,13.520622],[-90.095555,13.735338],[-90.064678,13.88197],[-89.721934,14.134228],[-89.534219,14.244816],[-89.587343,14.362586],[-89.353326,14.424133]]]}},{"type":"Feature","properties":{"ADMIN":"Guatemala","NAME_EN":"Guatemala","CONTINENT":"North America","ADM0_A3":"GTM","ISO_A3":"GTM","NAME":"Guatemala","ISO_A2":"GT","NAME_ZH":"危地马拉"},"geometry":{"type":"Polygon","coordinates":[[[-92.22775,14.538829],[-92.20323,14.830103],[-92.087216,15.064585],[-92.229249,15.251447],[-91.74796,16.066565],[-90.464473,16.069562],[-90.438867,16.41011],[-90.600847,16.470778],[-90.711822,16.687483],[-91.08167,16.918477],[-91.453921,17.252177],[-91.002269,17.254658],[-91.00152,17.817595],[-90.067934,17.819326],[-89.14308,17.808319],[-89.150806,17.015577],[-89.229122,15.886938],[-88.930613,15.887273],[-88.604586,15.70638],[-88.518364,15.855389],[-88.225023,15.727722],[-88.68068,15.346247],[-89.154811,15.066419],[-89.22522,14.874286],[-89.145535,14.678019],[-89.353326,14.424133],[-89.587343,14.362586],[-89.534219,14.244816],[-89.721934,14.134228],[-90.064678,13.88197],[-90.095555,13.735338],[-90.608624,13.909771],[-91.23241,13.927832],[-91.689747,14.126218],[-92.22775,14.538829]]]}},{"type":"Feature","properties":{"ADMIN":"Belize","NAME_EN":"Belize","CONTINENT":"North America","ADM0_A3":"BLZ","ISO_A3":"BLZ","NAME":"Belize","ISO_A2":"BZ","NAME_ZH":"伯利兹"},"geometry":{"type":"Polygon","coordinates":[[[-89.14308,17.808319],[-89.150909,17.955468],[-89.029857,18.001511],[-88.848344,17.883198],[-88.490123,18.486831],[-88.300031,18.499982],[-88.296336,18.353273],[-88.106813,18.348674],[-88.123479,18.076675],[-88.285355,17.644143],[-88.197867,17.489475],[-88.302641,17.131694],[-88.239518,17.036066],[-88.355428,16.530774],[-88.551825,16.265467],[-88.732434,16.233635],[-88.930613,15.887273],[-89.229122,15.886938],[-89.150806,17.015577],[-89.14308,17.808319]]]}},{"type":"Feature","properties":{"ADMIN":"Venezuela","NAME_EN":"Venezuela","CONTINENT":"South America","ADM0_A3":"VEN","ISO_A3":"VEN","NAME":"Venezuela","ISO_A2":"VE","NAME_ZH":"委内瑞拉"},"geometry":{"type":"Polygon","coordinates":[[[-60.733574,5.200277],[-60.601179,4.918098],[-60.966893,4.536468],[-62.08543,4.162124],[-62.804533,4.006965],[-63.093198,3.770571],[-63.888343,4.02053],[-64.628659,4.148481],[-64.816064,4.056445],[-64.368494,3.79721],[-64.408828,3.126786],[-64.269999,2.497006],[-63.422867,2.411068],[-63.368788,2.2009],[-64.083085,1.916369],[-64.199306,1.492855],[-64.611012,1.328731],[-65.354713,1.095282],[-65.548267,0.789254],[-66.325765,0.724452],[-66.876326,1.253361],[-67.181294,2.250638],[-67.447092,2.600281],[-67.809938,2.820655],[-67.303173,3.318454],[-67.337564,3.542342],[-67.621836,3.839482],[-67.823012,4.503937],[-67.744697,5.221129],[-67.521532,5.55687],[-67.34144,6.095468],[-67.695087,6.267318],[-68.265052,6.153268],[-68.985319,6.206805],[-69.38948,6.099861],[-70.093313,6.960376],[-70.674234,7.087785],[-71.960176,6.991615],[-72.198352,7.340431],[-72.444487,7.423785],[-72.479679,7.632506],[-72.360901,8.002638],[-72.439862,8.405275],[-72.660495,8.625288],[-72.78873,9.085027],[-73.304952,9.152],[-73.027604,9.73677],[-72.905286,10.450344],[-72.614658,10.821975],[-72.227575,11.108702],[-71.973922,11.608672],[-71.331584,11.776284],[-71.360006,11.539994],[-71.94705,11.423282],[-71.620868,10.96946],[-71.633064,10.446494],[-72.074174,9.865651],[-71.695644,9.072263],[-71.264559,9.137195],[-71.039999,9.859993],[-71.350084,10.211935],[-71.400623,10.968969],[-70.155299,11.375482],[-70.293843,11.846822],[-69.943245,12.162307],[-69.5843,11.459611],[-68.882999,11.443385],[-68.233271,10.885744],[-68.194127,10.554653],[-67.296249,10.545868],[-66.227864,10.648627],[-65.655238,10.200799],[-64.890452,10.077215],[-64.329479,10.389599],[-64.318007,10.641418],[-63.079322,10.701724],[-61.880946,10.715625],[-62.730119,10.420269],[-62.388512,9.948204],[-61.588767,9.873067],[-60.830597,9.38134],[-60.671252,8.580174],[-60.150096,8.602757],[-59.758285,8.367035],[-60.550588,7.779603],[-60.637973,7.415],[-60.295668,7.043911],[-60.543999,6.856584],[-61.159336,6.696077],[-61.139415,6.234297],[-61.410303,5.959068],[-60.733574,5.200277]]]}},{"type":"Feature","properties":{"ADMIN":"Guyana","NAME_EN":"Guyana","CONTINENT":"South America","ADM0_A3":"GUY","ISO_A3":"GUY","NAME":"Guyana","ISO_A2":"GY","NAME_ZH":"圭亚那"},"geometry":{"type":"Polygon","coordinates":[[[-56.539386,1.899523],[-56.782704,1.863711],[-57.335823,1.948538],[-57.660971,1.682585],[-58.11345,1.507195],[-58.429477,1.463942],[-58.540013,1.268088],[-59.030862,1.317698],[-59.646044,1.786894],[-59.718546,2.24963],[-59.974525,2.755233],[-59.815413,3.606499],[-59.53804,3.958803],[-59.767406,4.423503],[-60.111002,4.574967],[-59.980959,5.014061],[-60.213683,5.244486],[-60.733574,5.200277],[-61.410303,5.959068],[-61.139415,6.234297],[-61.159336,6.696077],[-60.543999,6.856584],[-60.295668,7.043911],[-60.637973,7.415],[-60.550588,7.779603],[-59.758285,8.367035],[-59.101684,7.999202],[-58.482962,7.347691],[-58.454876,6.832787],[-58.078103,6.809094],[-57.542219,6.321268],[-57.147436,5.97315],[-57.307246,5.073567],[-57.914289,4.812626],[-57.86021,4.576801],[-58.044694,4.060864],[-57.601569,3.334655],[-57.281433,3.333492],[-57.150098,2.768927],[-56.539386,1.899523]]]}},{"type":"Feature","properties":{"ADMIN":"Suriname","NAME_EN":"Suriname","CONTINENT":"South America","ADM0_A3":"SUR","ISO_A3":"SUR","NAME":"Suriname","ISO_A2":"SR","NAME_ZH":"苏里南"},"geometry":{"type":"Polygon","coordinates":[[[-54.524754,2.311849],[-55.097587,2.523748],[-55.569755,2.421506],[-55.973322,2.510364],[-56.073342,2.220795],[-55.9056,2.021996],[-55.995698,1.817667],[-56.539386,1.899523],[-57.150098,2.768927],[-57.281433,3.333492],[-57.601569,3.334655],[-58.044694,4.060864],[-57.86021,4.576801],[-57.914289,4.812626],[-57.307246,5.073567],[-57.147436,5.97315],[-55.949318,5.772878],[-55.84178,5.953125],[-55.03325,6.025291],[-53.958045,5.756548],[-54.478633,4.896756],[-54.399542,4.212611],[-54.006931,3.620038],[-54.181726,3.18978],[-54.269705,2.732392],[-54.524754,2.311849]]]}},{"type":"Feature","properties":{"ADMIN":"France","NAME_EN":"France","CONTINENT":"Europe","ADM0_A3":"FRA","ISO_A3":"-99","NAME":"France","ISO_A2":"-99","NAME_ZH":"法国"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-51.657797,4.156232],[-52.249338,3.241094],[-52.556425,2.504705],[-52.939657,2.124858],[-53.418465,2.053389],[-53.554839,2.334897],[-53.778521,2.376703],[-54.088063,2.105557],[-54.524754,2.311849],[-54.269705,2.732392],[-54.181726,3.18978],[-54.006931,3.620038],[-54.399542,4.212611],[-54.478633,4.896756],[-53.958045,5.756548],[-53.618453,5.646529],[-52.882141,5.409851],[-51.823343,4.565768],[-51.657797,4.156232]]],[[[6.18632,49.463803],[6.65823,49.201958],[8.099279,49.017784],[7.593676,48.333019],[7.466759,47.620582],[7.192202,47.449766],[6.736571,47.541801],[6.768714,47.287708],[6.037389,46.725779],[6.022609,46.27299],[6.5001,46.429673],[6.843593,45.991147],[6.802355,45.70858],[7.096652,45.333099],[6.749955,45.028518],[7.007562,44.254767],[7.549596,44.127901],[7.435185,43.693845],[6.529245,43.128892],[4.556963,43.399651],[3.100411,43.075201],[2.985999,42.473015],[1.826793,42.343385],[0.701591,42.795734],[0.338047,42.579546],[-1.502771,43.034014],[-1.901351,43.422802],[-1.384225,44.02261],[-1.193798,46.014918],[-2.225724,47.064363],[-2.963276,47.570327],[-4.491555,47.954954],[-4.59235,48.68416],[-3.295814,48.901692],[-1.616511,48.644421],[-1.933494,49.776342],[-0.989469,49.347376],[1.338761,50.127173],[1.639001,50.946606],[2.513573,51.148506],[2.658422,50.796848],[3.123252,50.780363],[3.588184,50.378992],[4.286023,49.907497],[4.799222,49.985373],[5.674052,49.529484],[5.897759,49.442667],[6.18632,49.463803]]],[[[8.746009,42.628122],[9.390001,43.009985],[9.560016,42.152492],[9.229752,41.380007],[8.775723,41.583612],[8.544213,42.256517],[8.746009,42.628122]]]]}},{"type":"Feature","properties":{"ADMIN":"Ecuador","NAME_EN":"Ecuador","CONTINENT":"South America","ADM0_A3":"ECU","ISO_A3":"ECU","NAME":"Ecuador","ISO_A2":"EC","NAME_ZH":"厄瓜多尔"},"geometry":{"type":"Polygon","coordinates":[[[-75.373223,-0.152032],[-75.233723,-0.911417],[-75.544996,-1.56161],[-76.635394,-2.608678],[-77.837905,-3.003021],[-78.450684,-3.873097],[-78.639897,-4.547784],[-79.205289,-4.959129],[-79.624979,-4.454198],[-80.028908,-4.346091],[-80.442242,-4.425724],[-80.469295,-4.059287],[-80.184015,-3.821162],[-80.302561,-3.404856],[-79.770293,-2.657512],[-79.986559,-2.220794],[-80.368784,-2.685159],[-80.967765,-2.246943],[-80.764806,-1.965048],[-80.933659,-1.057455],[-80.58337,-0.906663],[-80.399325,-0.283703],[-80.020898,0.36034],[-80.09061,0.768429],[-79.542762,0.982938],[-78.855259,1.380924],[-77.855061,0.809925],[-77.668613,0.825893],[-77.424984,0.395687],[-76.57638,0.256936],[-76.292314,0.416047],[-75.801466,0.084801],[-75.373223,-0.152032]]]}},{"type":"Feature","properties":{"ADMIN":"Puerto Rico","NAME_EN":"Puerto Rico","CONTINENT":"North America","ADM0_A3":"PRI","ISO_A3":"PRI","NAME":"Puerto Rico","ISO_A2":"PR","NAME_ZH":"波多黎各"},"geometry":{"type":"Polygon","coordinates":[[[-66.282434,18.514762],[-65.771303,18.426679],[-65.591004,18.228035],[-65.847164,17.975906],[-66.599934,17.981823],[-67.184162,17.946553],[-67.242428,18.37446],[-67.100679,18.520601],[-66.282434,18.514762]]]}},{"type":"Feature","properties":{"ADMIN":"Jamaica","NAME_EN":"Jamaica","CONTINENT":"North America","ADM0_A3":"JAM","ISO_A3":"JAM","NAME":"Jamaica","ISO_A2":"JM","NAME_ZH":"牙买加"},"geometry":{"type":"Polygon","coordinates":[[[-77.569601,18.490525],[-76.896619,18.400867],[-76.365359,18.160701],[-76.199659,17.886867],[-76.902561,17.868238],[-77.206341,17.701116],[-77.766023,17.861597],[-78.337719,18.225968],[-78.217727,18.454533],[-77.797365,18.524218],[-77.569601,18.490525]]]}},{"type":"Feature","properties":{"ADMIN":"Cuba","NAME_EN":"Cuba","CONTINENT":"North America","ADM0_A3":"CUB","ISO_A3":"CUB","NAME":"Cuba","ISO_A2":"CU","NAME_ZH":"古巴"},"geometry":{"type":"Polygon","coordinates":[[[-82.268151,23.188611],[-81.404457,23.117271],[-80.618769,23.10598],[-79.679524,22.765303],[-79.281486,22.399202],[-78.347434,22.512166],[-77.993296,22.277194],[-77.146422,21.657851],[-76.523825,21.20682],[-76.19462,21.220565],[-75.598222,21.016624],[-75.67106,20.735091],[-74.933896,20.693905],[-74.178025,20.284628],[-74.296648,20.050379],[-74.961595,19.923435],[-75.63468,19.873774],[-76.323656,19.952891],[-77.755481,19.855481],[-77.085108,20.413354],[-77.492655,20.673105],[-78.137292,20.739949],[-78.482827,21.028613],[-78.719867,21.598114],[-79.285,21.559175],[-80.217475,21.827324],[-80.517535,22.037079],[-81.820943,22.192057],[-82.169992,22.387109],[-81.795002,22.636965],[-82.775898,22.68815],[-83.494459,22.168518],[-83.9088,22.154565],[-84.052151,21.910575],[-84.54703,21.801228],[-84.974911,21.896028],[-84.447062,22.20495],[-84.230357,22.565755],[-83.77824,22.788118],[-83.267548,22.983042],[-82.510436,23.078747],[-82.268151,23.188611]]]}},{"type":"Feature","properties":{"ADMIN":"Zimbabwe","NAME_EN":"Zimbabwe","CONTINENT":"Africa","ADM0_A3":"ZWE","ISO_A3":"ZWE","NAME":"Zimbabwe","ISO_A2":"ZW","NAME_ZH":"津巴布韦"},"geometry":{"type":"Polygon","coordinates":[[[31.191409,-22.25151],[30.659865,-22.151567],[30.322883,-22.271612],[29.839037,-22.102216],[29.432188,-22.091313],[28.794656,-21.639454],[28.02137,-21.485975],[27.727228,-20.851802],[27.724747,-20.499059],[27.296505,-20.39152],[26.164791,-19.293086],[25.850391,-18.714413],[25.649163,-18.536026],[25.264226,-17.73654],[26.381935,-17.846042],[26.706773,-17.961229],[27.044427,-17.938026],[27.598243,-17.290831],[28.467906,-16.4684],[28.825869,-16.389749],[28.947463,-16.043051],[29.516834,-15.644678],[30.274256,-15.507787],[30.338955,-15.880839],[31.173064,-15.860944],[31.636498,-16.07199],[31.852041,-16.319417],[32.328239,-16.392074],[32.847639,-16.713398],[32.849861,-17.979057],[32.654886,-18.67209],[32.611994,-19.419383],[32.772708,-19.715592],[32.659743,-20.30429],[32.508693,-20.395292],[32.244988,-21.116489],[31.191409,-22.25151]]]}},{"type":"Feature","properties":{"ADMIN":"Botswana","NAME_EN":"Botswana","CONTINENT":"Africa","ADM0_A3":"BWA","ISO_A3":"BWA","NAME":"Botswana","ISO_A2":"BW","NAME_ZH":"博茨瓦纳"},"geometry":{"type":"Polygon","coordinates":[[[29.432188,-22.091313],[28.017236,-22.827754],[27.11941,-23.574323],[26.786407,-24.240691],[26.485753,-24.616327],[25.941652,-24.696373],[25.765849,-25.174845],[25.664666,-25.486816],[25.025171,-25.71967],[24.211267,-25.670216],[23.73357,-25.390129],[23.312097,-25.26869],[22.824271,-25.500459],[22.579532,-25.979448],[22.105969,-26.280256],[21.605896,-26.726534],[20.889609,-26.828543],[20.66647,-26.477453],[20.758609,-25.868136],[20.165726,-24.917962],[19.895768,-24.76779],[19.895458,-21.849157],[20.881134,-21.814327],[20.910641,-18.252219],[21.65504,-18.219146],[23.196858,-17.869038],[23.579006,-18.281261],[24.217365,-17.889347],[24.520705,-17.887125],[25.084443,-17.661816],[25.264226,-17.73654],[25.649163,-18.536026],[25.850391,-18.714413],[26.164791,-19.293086],[27.296505,-20.39152],[27.724747,-20.499059],[27.727228,-20.851802],[28.02137,-21.485975],[28.794656,-21.639454],[29.432188,-22.091313]]]}},{"type":"Feature","properties":{"ADMIN":"Namibia","NAME_EN":"Namibia","CONTINENT":"Africa","ADM0_A3":"NAM","ISO_A3":"NAM","NAME":"Namibia","ISO_A2":"NA","NAME_ZH":"纳米比亚"},"geometry":{"type":"Polygon","coordinates":[[[19.895768,-24.76779],[19.894734,-28.461105],[19.002127,-28.972443],[18.464899,-29.045462],[17.836152,-28.856378],[17.387497,-28.783514],[17.218929,-28.355943],[16.824017,-28.082162],[16.344977,-28.576705],[15.601818,-27.821247],[15.210472,-27.090956],[14.989711,-26.117372],[14.743214,-25.39292],[14.408144,-23.853014],[14.385717,-22.656653],[14.257714,-22.111208],[13.868642,-21.699037],[13.352498,-20.872834],[12.826845,-19.673166],[12.608564,-19.045349],[11.794919,-18.069129],[11.734199,-17.301889],[12.215461,-17.111668],[12.814081,-16.941343],[13.462362,-16.971212],[14.058501,-17.423381],[14.209707,-17.353101],[18.263309,-17.309951],[18.956187,-17.789095],[21.377176,-17.930636],[23.215048,-17.523116],[24.033862,-17.295843],[24.682349,-17.353411],[25.07695,-17.578823],[25.084443,-17.661816],[24.520705,-17.887125],[24.217365,-17.889347],[23.579006,-18.281261],[23.196858,-17.869038],[21.65504,-18.219146],[20.910641,-18.252219],[20.881134,-21.814327],[19.895458,-21.849157],[19.895768,-24.76779]]]}},{"type":"Feature","properties":{"ADMIN":"Senegal","NAME_EN":"Senegal","CONTINENT":"Africa","ADM0_A3":"SEN","ISO_A3":"SEN","NAME":"Senegal","ISO_A2":"SN","NAME_ZH":"塞内加尔"},"geometry":{"type":"Polygon","coordinates":[[[-16.713729,13.594959],[-17.126107,14.373516],[-17.625043,14.729541],[-17.185173,14.919477],[-16.700706,15.621527],[-16.463098,16.135036],[-16.12069,16.455663],[-15.623666,16.369337],[-15.135737,16.587282],[-14.577348,16.598264],[-14.099521,16.304302],[-13.435738,16.039383],[-12.830658,15.303692],[-12.17075,14.616834],[-12.124887,13.994727],[-11.927716,13.422075],[-11.553398,13.141214],[-11.467899,12.754519],[-11.513943,12.442988],[-11.658301,12.386583],[-12.203565,12.465648],[-12.278599,12.35444],[-12.499051,12.33209],[-13.217818,12.575874],[-13.700476,12.586183],[-15.548477,12.62817],[-15.816574,12.515567],[-16.147717,12.547762],[-16.677452,12.384852],[-16.841525,13.151394],[-15.931296,13.130284],[-15.691001,13.270353],[-15.511813,13.27857],[-15.141163,13.509512],[-14.712197,13.298207],[-14.277702,13.280585],[-13.844963,13.505042],[-14.046992,13.794068],[-14.376714,13.62568],[-14.687031,13.630357],[-15.081735,13.876492],[-15.39877,13.860369],[-15.624596,13.623587],[-16.713729,13.594959]]]}},{"type":"Feature","properties":{"ADMIN":"Mali","NAME_EN":"Mali","CONTINENT":"Africa","ADM0_A3":"MLI","ISO_A3":"MLI","NAME":"Mali","ISO_A2":"ML","NAME_ZH":"马里"},"geometry":{"type":"Polygon","coordinates":[[[-11.513943,12.442988],[-11.467899,12.754519],[-11.553398,13.141214],[-11.927716,13.422075],[-12.124887,13.994727],[-12.17075,14.616834],[-11.834208,14.799097],[-11.666078,15.388208],[-11.349095,15.411256],[-10.650791,15.132746],[-10.086846,15.330486],[-9.700255,15.264107],[-9.550238,15.486497],[-5.537744,15.50169],[-5.315277,16.201854],[-5.488523,16.325102],[-5.971129,20.640833],[-6.453787,24.956591],[-4.923337,24.974574],[-1.550055,22.792666],[1.823228,20.610809],[2.060991,20.142233],[2.683588,19.85623],[3.146661,19.693579],[3.158133,19.057364],[4.267419,19.155265],[4.27021,16.852227],[3.723422,16.184284],[3.638259,15.56812],[2.749993,15.409525],[1.385528,15.323561],[1.015783,14.968182],[0.374892,14.928908],[-0.266257,14.924309],[-0.515854,15.116158],[-1.066363,14.973815],[-2.001035,14.559008],[-2.191825,14.246418],[-2.967694,13.79815],[-3.103707,13.541267],[-3.522803,13.337662],[-4.006391,13.472485],[-4.280405,13.228444],[-4.427166,12.542646],[-5.220942,11.713859],[-5.197843,11.375146],[-5.470565,10.95127],[-5.404342,10.370737],[-5.816926,10.222555],[-6.050452,10.096361],[-6.205223,10.524061],[-6.493965,10.411303],[-6.666461,10.430811],[-6.850507,10.138994],[-7.622759,10.147236],[-7.89959,10.297382],[-8.029944,10.206535],[-8.335377,10.494812],[-8.282357,10.792597],[-8.407311,10.909257],[-8.620321,10.810891],[-8.581305,11.136246],[-8.376305,11.393646],[-8.786099,11.812561],[-8.905265,12.088358],[-9.127474,12.30806],[-9.327616,12.334286],[-9.567912,12.194243],[-9.890993,12.060479],[-10.165214,11.844084],[-10.593224,11.923975],[-10.87083,12.177887],[-11.036556,12.211245],[-11.297574,12.077971],[-11.456169,12.076834],[-11.513943,12.442988]]]}},{"type":"Feature","properties":{"ADMIN":"Mauritania","NAME_EN":"Mauritania","CONTINENT":"Africa","ADM0_A3":"MRT","ISO_A3":"MRT","NAME":"Mauritania","ISO_A2":"MR","NAME_ZH":"毛里塔尼亚"},"geometry":{"type":"Polygon","coordinates":[[[-17.063423,20.999752],[-16.845194,21.333323],[-12.929102,21.327071],[-13.118754,22.77122],[-12.874222,23.284832],[-11.937224,23.374594],[-11.969419,25.933353],[-8.687294,25.881056],[-8.6844,27.395744],[-4.923337,24.974574],[-6.453787,24.956591],[-5.971129,20.640833],[-5.488523,16.325102],[-5.315277,16.201854],[-5.537744,15.50169],[-9.550238,15.486497],[-9.700255,15.264107],[-10.086846,15.330486],[-10.650791,15.132746],[-11.349095,15.411256],[-11.666078,15.388208],[-11.834208,14.799097],[-12.17075,14.616834],[-12.830658,15.303692],[-13.435738,16.039383],[-14.099521,16.304302],[-14.577348,16.598264],[-15.135737,16.587282],[-15.623666,16.369337],[-16.12069,16.455663],[-16.463098,16.135036],[-16.549708,16.673892],[-16.270552,17.166963],[-16.146347,18.108482],[-16.256883,19.096716],[-16.377651,19.593817],[-16.277838,20.092521],[-16.536324,20.567866],[-17.063423,20.999752]]]}},{"type":"Feature","properties":{"ADMIN":"Benin","NAME_EN":"Benin","CONTINENT":"Africa","ADM0_A3":"BEN","ISO_A3":"BEN","NAME":"Benin","ISO_A2":"BJ","NAME_ZH":"贝宁"},"geometry":{"type":"Polygon","coordinates":[[[2.691702,6.258817],[1.865241,6.142158],[1.618951,6.832038],[1.664478,9.12859],[1.463043,9.334624],[1.425061,9.825395],[1.077795,10.175607],[0.772336,10.470808],[0.899563,10.997339],[1.24347,11.110511],[1.447178,11.547719],[1.935986,11.64115],[2.154474,11.94015],[2.490164,12.233052],[2.848643,12.235636],[3.61118,11.660167],[3.572216,11.327939],[3.797112,10.734746],[3.60007,10.332186],[3.705438,10.06321],[3.220352,9.444153],[2.912308,9.137608],[2.723793,8.506845],[2.749063,7.870734],[2.691702,6.258817]]]}},{"type":"Feature","properties":{"ADMIN":"Niger","NAME_EN":"Niger","CONTINENT":"Africa","ADM0_A3":"NER","ISO_A3":"NER","NAME":"Niger","ISO_A2":"NE","NAME_ZH":"尼日尔"},"geometry":{"type":"Polygon","coordinates":[[[14.8513,22.86295],[15.096888,21.308519],[15.47106,21.04845],[15.487148,20.730415],[15.903247,20.387619],[15.685741,19.95718],[15.300441,17.92795],[15.247731,16.627306],[13.97217,15.68437],[13.540394,14.367134],[13.956699,13.996691],[13.954477,13.353449],[14.595781,13.330427],[14.495787,12.859396],[14.213531,12.802035],[14.181336,12.483657],[13.995353,12.461565],[13.318702,13.556356],[13.083987,13.596147],[12.302071,13.037189],[11.527803,13.32898],[10.989593,13.387323],[10.701032,13.246918],[10.114814,13.277252],[9.524928,12.851102],[9.014933,12.826659],[7.804671,13.343527],[7.330747,13.098038],[6.820442,13.115091],[6.445426,13.492768],[5.443058,13.865924],[4.368344,13.747482],[4.107946,13.531216],[3.967283,12.956109],[3.680634,12.552903],[3.61118,11.660167],[2.848643,12.235636],[2.490164,12.233052],[2.154474,11.94015],[2.177108,12.625018],[1.024103,12.851826],[0.993046,13.33575],[0.429928,13.988733],[0.295646,14.444235],[0.374892,14.928908],[1.015783,14.968182],[1.385528,15.323561],[2.749993,15.409525],[3.638259,15.56812],[3.723422,16.184284],[4.27021,16.852227],[4.267419,19.155265],[5.677566,19.601207],[8.572893,21.565661],[11.999506,23.471668],[13.581425,23.040506],[14.143871,22.491289],[14.8513,22.86295]]]}},{"type":"Feature","properties":{"ADMIN":"Nigeria","NAME_EN":"Nigeria","CONTINENT":"Africa","ADM0_A3":"NGA","ISO_A3":"NGA","NAME":"Nigeria","ISO_A2":"NG","NAME_ZH":"尼日利亚"},"geometry":{"type":"Polygon","coordinates":[[[2.691702,6.258817],[2.749063,7.870734],[2.723793,8.506845],[2.912308,9.137608],[3.220352,9.444153],[3.705438,10.06321],[3.60007,10.332186],[3.797112,10.734746],[3.572216,11.327939],[3.61118,11.660167],[3.680634,12.552903],[3.967283,12.956109],[4.107946,13.531216],[4.368344,13.747482],[5.443058,13.865924],[6.445426,13.492768],[6.820442,13.115091],[7.330747,13.098038],[7.804671,13.343527],[9.014933,12.826659],[9.524928,12.851102],[10.114814,13.277252],[10.701032,13.246918],[10.989593,13.387323],[11.527803,13.32898],[12.302071,13.037189],[13.083987,13.596147],[13.318702,13.556356],[13.995353,12.461565],[14.181336,12.483657],[14.577178,12.085361],[14.468192,11.904752],[14.415379,11.572369],[13.57295,10.798566],[13.308676,10.160362],[13.1676,9.640626],[12.955468,9.417772],[12.753672,8.717763],[12.218872,8.305824],[12.063946,7.799808],[11.839309,7.397042],[11.745774,6.981383],[11.058788,6.644427],[10.497375,7.055358],[10.118277,7.03877],[9.522706,6.453482],[9.233163,6.444491],[8.757533,5.479666],[8.500288,4.771983],[7.462108,4.412108],[7.082596,4.464689],[6.698072,4.240594],[5.898173,4.262453],[5.362805,4.887971],[5.033574,5.611802],[4.325607,6.270651],[3.57418,6.2583],[2.691702,6.258817]]]}},{"type":"Feature","properties":{"ADMIN":"Cameroon","NAME_EN":"Cameroon","CONTINENT":"Africa","ADM0_A3":"CMR","ISO_A3":"CMR","NAME":"Cameroon","ISO_A2":"CM","NAME_ZH":"喀麦隆"},"geometry":{"type":"Polygon","coordinates":[[[14.495787,12.859396],[14.89336,12.21905],[14.960152,11.555574],[14.923565,10.891325],[15.467873,9.982337],[14.909354,9.992129],[14.627201,9.920919],[14.171466,10.021378],[13.954218,9.549495],[14.544467,8.965861],[14.979996,8.796104],[15.120866,8.38215],[15.436092,7.692812],[15.27946,7.421925],[14.776545,6.408498],[14.53656,6.226959],[14.459407,5.451761],[14.558936,5.030598],[14.478372,4.732605],[14.950953,4.210389],[15.03622,3.851367],[15.405396,3.335301],[15.862732,3.013537],[15.907381,2.557389],[16.012852,2.26764],[15.940919,1.727673],[15.146342,1.964015],[14.337813,2.227875],[13.075822,2.267097],[12.951334,2.321616],[12.35938,2.192812],[11.751665,2.326758],[11.276449,2.261051],[9.649158,2.283866],[9.795196,3.073404],[9.404367,3.734527],[8.948116,3.904129],[8.744924,4.352215],[8.488816,4.495617],[8.500288,4.771983],[8.757533,5.479666],[9.233163,6.444491],[9.522706,6.453482],[10.118277,7.03877],[10.497375,7.055358],[11.058788,6.644427],[11.745774,6.981383],[11.839309,7.397042],[12.063946,7.799808],[12.218872,8.305824],[12.753672,8.717763],[12.955468,9.417772],[13.1676,9.640626],[13.308676,10.160362],[13.57295,10.798566],[14.415379,11.572369],[14.468192,11.904752],[14.577178,12.085361],[14.181336,12.483657],[14.213531,12.802035],[14.495787,12.859396]]]}},{"type":"Feature","properties":{"ADMIN":"Togo","NAME_EN":"Togo","CONTINENT":"Africa","ADM0_A3":"TGO","ISO_A3":"TGO","NAME":"Togo","ISO_A2":"TG","NAME_ZH":"多哥"},"geometry":{"type":"Polygon","coordinates":[[[0.899563,10.997339],[0.772336,10.470808],[1.077795,10.175607],[1.425061,9.825395],[1.463043,9.334624],[1.664478,9.12859],[1.618951,6.832038],[1.865241,6.142158],[1.060122,5.928837],[0.836931,6.279979],[0.570384,6.914359],[0.490957,7.411744],[0.712029,8.312465],[0.461192,8.677223],[0.365901,9.465004],[0.36758,10.191213],[-0.049785,10.706918],[0.023803,11.018682],[0.899563,10.997339]]]}},{"type":"Feature","properties":{"ADMIN":"Ghana","NAME_EN":"Ghana","CONTINENT":"Africa","ADM0_A3":"GHA","ISO_A3":"GHA","NAME":"Ghana","ISO_A2":"GH","NAME_ZH":"加纳"},"geometry":{"type":"Polygon","coordinates":[[[0.023803,11.018682],[-0.049785,10.706918],[0.36758,10.191213],[0.365901,9.465004],[0.461192,8.677223],[0.712029,8.312465],[0.490957,7.411744],[0.570384,6.914359],[0.836931,6.279979],[1.060122,5.928837],[-0.507638,5.343473],[-1.063625,5.000548],[-1.964707,4.710462],[-2.856125,4.994476],[-2.810701,5.389051],[-3.24437,6.250472],[-2.983585,7.379705],[-2.56219,8.219628],[-2.827496,9.642461],[-2.963896,10.395335],[-2.940409,10.96269],[-1.203358,11.009819],[-0.761576,10.93693],[-0.438702,11.098341],[0.023803,11.018682]]]}},{"type":"Feature","properties":{"ADMIN":"Ivory Coast","NAME_EN":"Ivory Coast","CONTINENT":"Africa","ADM0_A3":"CIV","ISO_A3":"CIV","NAME":"Côte d'Ivoire","ISO_A2":"CI","NAME_ZH":"科特迪瓦"},"geometry":{"type":"Polygon","coordinates":[[[-8.029944,10.206535],[-7.89959,10.297382],[-7.622759,10.147236],[-6.850507,10.138994],[-6.666461,10.430811],[-6.493965,10.411303],[-6.205223,10.524061],[-6.050452,10.096361],[-5.816926,10.222555],[-5.404342,10.370737],[-4.954653,10.152714],[-4.779884,9.821985],[-4.330247,9.610835],[-3.980449,9.862344],[-3.511899,9.900326],[-2.827496,9.642461],[-2.56219,8.219628],[-2.983585,7.379705],[-3.24437,6.250472],[-2.810701,5.389051],[-2.856125,4.994476],[-3.311084,4.984296],[-4.00882,5.179813],[-4.649917,5.168264],[-5.834496,4.993701],[-6.528769,4.705088],[-7.518941,4.338288],[-7.712159,4.364566],[-7.635368,5.188159],[-7.539715,5.313345],[-7.570153,5.707352],[-7.993693,6.12619],[-8.311348,6.193033],[-8.60288,6.467564],[-8.385452,6.911801],[-8.485446,7.395208],[-8.439298,7.686043],[-8.280703,7.68718],[-8.221792,8.123329],[-8.299049,8.316444],[-8.203499,8.455453],[-7.8321,8.575704],[-8.079114,9.376224],[-8.309616,9.789532],[-8.229337,10.12902],[-8.029944,10.206535]]]}},{"type":"Feature","properties":{"ADMIN":"Guinea","NAME_EN":"Guinea","CONTINENT":"Africa","ADM0_A3":"GIN","ISO_A3":"GIN","NAME":"Guinea","ISO_A2":"GN","NAME_ZH":"几内亚"},"geometry":{"type":"Polygon","coordinates":[[[-13.700476,12.586183],[-13.217818,12.575874],[-12.499051,12.33209],[-12.278599,12.35444],[-12.203565,12.465648],[-11.658301,12.386583],[-11.513943,12.442988],[-11.456169,12.076834],[-11.297574,12.077971],[-11.036556,12.211245],[-10.87083,12.177887],[-10.593224,11.923975],[-10.165214,11.844084],[-9.890993,12.060479],[-9.567912,12.194243],[-9.327616,12.334286],[-9.127474,12.30806],[-8.905265,12.088358],[-8.786099,11.812561],[-8.376305,11.393646],[-8.581305,11.136246],[-8.620321,10.810891],[-8.407311,10.909257],[-8.282357,10.792597],[-8.335377,10.494812],[-8.029944,10.206535],[-8.229337,10.12902],[-8.309616,9.789532],[-8.079114,9.376224],[-7.8321,8.575704],[-8.203499,8.455453],[-8.299049,8.316444],[-8.221792,8.123329],[-8.280703,7.68718],[-8.439298,7.686043],[-8.722124,7.711674],[-8.926065,7.309037],[-9.208786,7.313921],[-9.403348,7.526905],[-9.33728,7.928534],[-9.755342,8.541055],[-10.016567,8.428504],[-10.230094,8.406206],[-10.505477,8.348896],[-10.494315,8.715541],[-10.65477,8.977178],[-10.622395,9.26791],[-10.839152,9.688246],[-11.117481,10.045873],[-11.917277,10.046984],[-12.150338,9.858572],[-12.425929,9.835834],[-12.596719,9.620188],[-12.711958,9.342712],[-13.24655,8.903049],[-13.685154,9.494744],[-14.074045,9.886167],[-14.330076,10.01572],[-14.579699,10.214467],[-14.693232,10.656301],[-14.839554,10.876572],[-15.130311,11.040412],[-14.685687,11.527824],[-14.382192,11.509272],[-14.121406,11.677117],[-13.9008,11.678719],[-13.743161,11.811269],[-13.828272,12.142644],[-13.718744,12.247186],[-13.700476,12.586183]]]}},{"type":"Feature","properties":{"ADMIN":"Guinea-Bissau","NAME_EN":"Guinea-Bissau","CONTINENT":"Africa","ADM0_A3":"GNB","ISO_A3":"GNB","NAME":"Guinea-Bissau","ISO_A2":"GW","NAME_ZH":"几内亚比绍"},"geometry":{"type":"Polygon","coordinates":[[[-16.677452,12.384852],[-16.147717,12.547762],[-15.816574,12.515567],[-15.548477,12.62817],[-13.700476,12.586183],[-13.718744,12.247186],[-13.828272,12.142644],[-13.743161,11.811269],[-13.9008,11.678719],[-14.121406,11.677117],[-14.382192,11.509272],[-14.685687,11.527824],[-15.130311,11.040412],[-15.66418,11.458474],[-16.085214,11.524594],[-16.314787,11.806515],[-16.308947,11.958702],[-16.613838,12.170911],[-16.677452,12.384852]]]}},{"type":"Feature","properties":{"ADMIN":"Liberia","NAME_EN":"Liberia","CONTINENT":"Africa","ADM0_A3":"LBR","ISO_A3":"LBR","NAME":"Liberia","ISO_A2":"LR","NAME_ZH":"利比里亚"},"geometry":{"type":"Polygon","coordinates":[[[-8.439298,7.686043],[-8.485446,7.395208],[-8.385452,6.911801],[-8.60288,6.467564],[-8.311348,6.193033],[-7.993693,6.12619],[-7.570153,5.707352],[-7.539715,5.313345],[-7.635368,5.188159],[-7.712159,4.364566],[-7.974107,4.355755],[-9.004794,4.832419],[-9.91342,5.593561],[-10.765384,6.140711],[-11.438779,6.785917],[-11.199802,7.105846],[-11.146704,7.396706],[-10.695595,7.939464],[-10.230094,8.406206],[-10.016567,8.428504],[-9.755342,8.541055],[-9.33728,7.928534],[-9.403348,7.526905],[-9.208786,7.313921],[-8.926065,7.309037],[-8.722124,7.711674],[-8.439298,7.686043]]]}},{"type":"Feature","properties":{"ADMIN":"Sierra Leone","NAME_EN":"Sierra Leone","CONTINENT":"Africa","ADM0_A3":"SLE","ISO_A3":"SLE","NAME":"Sierra Leone","ISO_A2":"SL","NAME_ZH":"塞拉利昂"},"geometry":{"type":"Polygon","coordinates":[[[-13.24655,8.903049],[-12.711958,9.342712],[-12.596719,9.620188],[-12.425929,9.835834],[-12.150338,9.858572],[-11.917277,10.046984],[-11.117481,10.045873],[-10.839152,9.688246],[-10.622395,9.26791],[-10.65477,8.977178],[-10.494315,8.715541],[-10.505477,8.348896],[-10.230094,8.406206],[-10.695595,7.939464],[-11.146704,7.396706],[-11.199802,7.105846],[-11.438779,6.785917],[-11.708195,6.860098],[-12.428099,7.262942],[-12.949049,7.798646],[-13.124025,8.163946],[-13.24655,8.903049]]]}},{"type":"Feature","properties":{"ADMIN":"Burkina Faso","NAME_EN":"Burkina Faso","CONTINENT":"Africa","ADM0_A3":"BFA","ISO_A3":"BFA","NAME":"Burkina Faso","ISO_A2":"BF","NAME_ZH":"布基纳法索"},"geometry":{"type":"Polygon","coordinates":[[[-5.404342,10.370737],[-5.470565,10.95127],[-5.197843,11.375146],[-5.220942,11.713859],[-4.427166,12.542646],[-4.280405,13.228444],[-4.006391,13.472485],[-3.522803,13.337662],[-3.103707,13.541267],[-2.967694,13.79815],[-2.191825,14.246418],[-2.001035,14.559008],[-1.066363,14.973815],[-0.515854,15.116158],[-0.266257,14.924309],[0.374892,14.928908],[0.295646,14.444235],[0.429928,13.988733],[0.993046,13.33575],[1.024103,12.851826],[2.177108,12.625018],[2.154474,11.94015],[1.935986,11.64115],[1.447178,11.547719],[1.24347,11.110511],[0.899563,10.997339],[0.023803,11.018682],[-0.438702,11.098341],[-0.761576,10.93693],[-1.203358,11.009819],[-2.940409,10.96269],[-2.963896,10.395335],[-2.827496,9.642461],[-3.511899,9.900326],[-3.980449,9.862344],[-4.330247,9.610835],[-4.779884,9.821985],[-4.954653,10.152714],[-5.404342,10.370737]]]}},{"type":"Feature","properties":{"ADMIN":"Central African Republic","NAME_EN":"Central African Republic","CONTINENT":"Africa","ADM0_A3":"CAF","ISO_A3":"CAF","NAME":"Central African Rep.","ISO_A2":"CF","NAME_ZH":"中非共和国"},"geometry":{"type":"Polygon","coordinates":[[[27.374226,5.233944],[27.044065,5.127853],[26.402761,5.150875],[25.650455,5.256088],[25.278798,5.170408],[25.128833,4.927245],[24.805029,4.897247],[24.410531,5.108784],[23.297214,4.609693],[22.84148,4.710126],[22.704124,4.633051],[22.405124,4.02916],[21.659123,4.224342],[20.927591,4.322786],[20.290679,4.691678],[19.467784,5.031528],[18.932312,4.709506],[18.542982,4.201785],[18.453065,3.504386],[17.8099,3.560196],[17.133042,3.728197],[16.537058,3.198255],[16.012852,2.26764],[15.907381,2.557389],[15.862732,3.013537],[15.405396,3.335301],[15.03622,3.851367],[14.950953,4.210389],[14.478372,4.732605],[14.558936,5.030598],[14.459407,5.451761],[14.53656,6.226959],[14.776545,6.408498],[15.27946,7.421925],[16.106232,7.497088],[16.290562,7.754307],[16.456185,7.734774],[16.705988,7.508328],[17.96493,7.890914],[18.389555,8.281304],[18.911022,8.630895],[18.81201,8.982915],[19.094008,9.074847],[20.059685,9.012706],[21.000868,9.475985],[21.723822,10.567056],[22.231129,10.971889],[22.864165,11.142395],[22.977544,10.714463],[23.554304,10.089255],[23.55725,9.681218],[23.394779,9.265068],[23.459013,8.954286],[23.805813,8.666319],[24.567369,8.229188],[25.114932,7.825104],[25.124131,7.500085],[25.796648,6.979316],[26.213418,6.546603],[26.465909,5.946717],[27.213409,5.550953],[27.374226,5.233944]]]}},{"type":"Feature","properties":{"ADMIN":"Republic of the Congo","NAME_EN":"Republic of the Congo","CONTINENT":"Africa","ADM0_A3":"COG","ISO_A3":"COG","NAME":"Congo","ISO_A2":"CG","NAME_ZH":"刚果共和国"},"geometry":{"type":"Polygon","coordinates":[[[18.453065,3.504386],[18.393792,2.900443],[18.094276,2.365722],[17.898835,1.741832],[17.774192,0.855659],[17.82654,0.288923],[17.663553,-0.058084],[17.638645,-0.424832],[17.523716,-0.74383],[16.865307,-1.225816],[16.407092,-1.740927],[15.972803,-2.712392],[16.00629,-3.535133],[15.75354,-3.855165],[15.170992,-4.343507],[14.582604,-4.970239],[14.209035,-4.793092],[14.144956,-4.510009],[13.600235,-4.500138],[13.25824,-4.882957],[12.995517,-4.781103],[12.62076,-4.438023],[12.318608,-4.60623],[11.914963,-5.037987],[11.093773,-3.978827],[11.855122,-3.426871],[11.478039,-2.765619],[11.820964,-2.514161],[12.495703,-2.391688],[12.575284,-1.948511],[13.109619,-2.42874],[13.992407,-2.470805],[14.29921,-1.998276],[14.425456,-1.333407],[14.316418,-0.552627],[13.843321,0.038758],[14.276266,1.19693],[14.026669,1.395677],[13.282631,1.314184],[13.003114,1.830896],[13.075822,2.267097],[14.337813,2.227875],[15.146342,1.964015],[15.940919,1.727673],[16.012852,2.26764],[16.537058,3.198255],[17.133042,3.728197],[17.8099,3.560196],[18.453065,3.504386]]]}},{"type":"Feature","properties":{"ADMIN":"Gabon","NAME_EN":"Gabon","CONTINENT":"Africa","ADM0_A3":"GAB","ISO_A3":"GAB","NAME":"Gabon","ISO_A2":"GA","NAME_ZH":"加蓬"},"geometry":{"type":"Polygon","coordinates":[[[11.276449,2.261051],[11.751665,2.326758],[12.35938,2.192812],[12.951334,2.321616],[13.075822,2.267097],[13.003114,1.830896],[13.282631,1.314184],[14.026669,1.395677],[14.276266,1.19693],[13.843321,0.038758],[14.316418,-0.552627],[14.425456,-1.333407],[14.29921,-1.998276],[13.992407,-2.470805],[13.109619,-2.42874],[12.575284,-1.948511],[12.495703,-2.391688],[11.820964,-2.514161],[11.478039,-2.765619],[11.855122,-3.426871],[11.093773,-3.978827],[10.066135,-2.969483],[9.405245,-2.144313],[8.797996,-1.111301],[8.830087,-0.779074],[9.04842,-0.459351],[9.291351,0.268666],[9.492889,1.01012],[9.830284,1.067894],[11.285079,1.057662],[11.276449,2.261051]]]}},{"type":"Feature","properties":{"ADMIN":"Equatorial Guinea","NAME_EN":"Equatorial Guinea","CONTINENT":"Africa","ADM0_A3":"GNQ","ISO_A3":"GNQ","NAME":"Eq. Guinea","ISO_A2":"GQ","NAME_ZH":"赤道几内亚"},"geometry":{"type":"Polygon","coordinates":[[[9.649158,2.283866],[11.276449,2.261051],[11.285079,1.057662],[9.830284,1.067894],[9.492889,1.01012],[9.305613,1.160911],[9.649158,2.283866]]]}},{"type":"Feature","properties":{"ADMIN":"Zambia","NAME_EN":"Zambia","CONTINENT":"Africa","ADM0_A3":"ZMB","ISO_A3":"ZMB","NAME":"Zambia","ISO_A2":"ZM","NAME_ZH":"赞比亚"},"geometry":{"type":"Polygon","coordinates":[[[30.74001,-8.340006],[31.157751,-8.594579],[31.556348,-8.762049],[32.191865,-8.930359],[32.759375,-9.230599],[33.231388,-9.676722],[33.485688,-10.525559],[33.31531,-10.79655],[33.114289,-11.607198],[33.306422,-12.435778],[32.991764,-12.783871],[32.688165,-13.712858],[33.214025,-13.97186],[30.179481,-14.796099],[30.274256,-15.507787],[29.516834,-15.644678],[28.947463,-16.043051],[28.825869,-16.389749],[28.467906,-16.4684],[27.598243,-17.290831],[27.044427,-17.938026],[26.706773,-17.961229],[26.381935,-17.846042],[25.264226,-17.73654],[25.084443,-17.661816],[25.07695,-17.578823],[24.682349,-17.353411],[24.033862,-17.295843],[23.215048,-17.523116],[22.562478,-16.898451],[21.887843,-16.08031],[21.933886,-12.898437],[24.016137,-12.911046],[23.930922,-12.565848],[24.079905,-12.191297],[23.904154,-11.722282],[24.017894,-11.237298],[23.912215,-10.926826],[24.257155,-10.951993],[24.314516,-11.262826],[24.78317,-11.238694],[25.418118,-11.330936],[25.75231,-11.784965],[26.553088,-11.92444],[27.16442,-11.608748],[27.388799,-12.132747],[28.155109,-12.272481],[28.523562,-12.698604],[28.934286,-13.248958],[29.699614,-13.257227],[29.616001,-12.178895],[29.341548,-12.360744],[28.642417,-11.971569],[28.372253,-11.793647],[28.49607,-10.789884],[28.673682,-9.605925],[28.449871,-9.164918],[28.734867,-8.526559],[29.002912,-8.407032],[30.346086,-8.238257],[30.74001,-8.340006]]]}},{"type":"Feature","properties":{"ADMIN":"Malawi","NAME_EN":"Malawi","CONTINENT":"Africa","ADM0_A3":"MWI","ISO_A3":"MWI","NAME":"Malawi","ISO_A2":"MW","NAME_ZH":"马拉维"},"geometry":{"type":"Polygon","coordinates":[[[32.759375,-9.230599],[33.73972,-9.41715],[33.940838,-9.693674],[34.28,-10.16],[34.559989,-11.52002],[34.280006,-12.280025],[34.559989,-13.579998],[34.907151,-13.565425],[35.267956,-13.887834],[35.686845,-14.611046],[35.771905,-15.896859],[35.339063,-16.10744],[35.03381,-16.8013],[34.381292,-16.18356],[34.307291,-15.478641],[34.517666,-15.013709],[34.459633,-14.61301],[34.064825,-14.35995],[33.7897,-14.451831],[33.214025,-13.97186],[32.688165,-13.712858],[32.991764,-12.783871],[33.306422,-12.435778],[33.114289,-11.607198],[33.31531,-10.79655],[33.485688,-10.525559],[33.231388,-9.676722],[32.759375,-9.230599]]]}},{"type":"Feature","properties":{"ADMIN":"Mozambique","NAME_EN":"Mozambique","CONTINENT":"Africa","ADM0_A3":"MOZ","ISO_A3":"MOZ","NAME":"Mozambique","ISO_A2":"MZ","NAME_ZH":"莫桑比克"},"geometry":{"type":"Polygon","coordinates":[[[34.559989,-11.52002],[35.312398,-11.439146],[36.514082,-11.720938],[36.775151,-11.594537],[37.47129,-11.56876],[37.82764,-11.26879],[38.427557,-11.285202],[39.521,-10.89688],[40.31659,-10.3171],[40.316586,-10.317098],[40.316589,-10.317096],[40.478387,-10.765441],[40.437253,-11.761711],[40.560811,-12.639177],[40.59962,-14.201975],[40.775475,-14.691764],[40.477251,-15.406294],[40.089264,-16.100774],[39.452559,-16.720891],[38.538351,-17.101023],[37.411133,-17.586368],[36.281279,-18.659688],[35.896497,-18.84226],[35.1984,-19.552811],[34.786383,-19.784012],[34.701893,-20.497043],[35.176127,-21.254361],[35.373428,-21.840837],[35.385848,-22.14],[35.562546,-22.09],[35.533935,-23.070788],[35.371774,-23.535359],[35.60747,-23.706563],[35.458746,-24.12261],[35.040735,-24.478351],[34.215824,-24.816314],[33.01321,-25.357573],[32.574632,-25.727318],[32.660363,-26.148584],[32.915955,-26.215867],[32.83012,-26.742192],[32.071665,-26.73382],[31.985779,-26.29178],[31.837778,-25.843332],[31.752408,-25.484284],[31.930589,-24.369417],[31.670398,-23.658969],[31.191409,-22.25151],[32.244988,-21.116489],[32.508693,-20.395292],[32.659743,-20.30429],[32.772708,-19.715592],[32.611994,-19.419383],[32.654886,-18.67209],[32.849861,-17.979057],[32.847639,-16.713398],[32.328239,-16.392074],[31.852041,-16.319417],[31.636498,-16.07199],[31.173064,-15.860944],[30.338955,-15.880839],[30.274256,-15.507787],[30.179481,-14.796099],[33.214025,-13.97186],[33.7897,-14.451831],[34.064825,-14.35995],[34.459633,-14.61301],[34.517666,-15.013709],[34.307291,-15.478641],[34.381292,-16.18356],[35.03381,-16.8013],[35.339063,-16.10744],[35.771905,-15.896859],[35.686845,-14.611046],[35.267956,-13.887834],[34.907151,-13.565425],[34.559989,-13.579998],[34.280006,-12.280025],[34.559989,-11.52002]]]}},{"type":"Feature","properties":{"ADMIN":"eSwatini","NAME_EN":"Eswatini","CONTINENT":"Africa","ADM0_A3":"SWZ","ISO_A3":"SWZ","NAME":"eSwatini","ISO_A2":"SZ","NAME_ZH":"斯威士兰"},"geometry":{"type":"Polygon","coordinates":[[[32.071665,-26.73382],[31.86806,-27.177927],[31.282773,-27.285879],[30.685962,-26.743845],[30.676609,-26.398078],[30.949667,-26.022649],[31.04408,-25.731452],[31.333158,-25.660191],[31.837778,-25.843332],[31.985779,-26.29178],[32.071665,-26.73382]]]}},{"type":"Feature","properties":{"ADMIN":"Angola","NAME_EN":"Angola","CONTINENT":"Africa","ADM0_A3":"AGO","ISO_A3":"AGO","NAME":"Angola","ISO_A2":"AO","NAME_ZH":"安哥拉"},"geometry":{"type":"MultiPolygon","coordinates":[[[[12.995517,-4.781103],[12.631612,-4.991271],[12.468004,-5.248362],[12.436688,-5.684304],[12.182337,-5.789931],[11.914963,-5.037987],[12.318608,-4.60623],[12.62076,-4.438023],[12.995517,-4.781103]]],[[[12.322432,-6.100092],[12.735171,-5.965682],[13.024869,-5.984389],[13.375597,-5.864241],[16.326528,-5.87747],[16.57318,-6.622645],[16.860191,-7.222298],[17.089996,-7.545689],[17.47297,-8.068551],[18.134222,-7.987678],[18.464176,-7.847014],[19.016752,-7.988246],[19.166613,-7.738184],[19.417502,-7.155429],[20.037723,-7.116361],[20.091622,-6.94309],[20.601823,-6.939318],[20.514748,-7.299606],[21.728111,-7.290872],[21.746456,-7.920085],[21.949131,-8.305901],[21.801801,-8.908707],[21.875182,-9.523708],[22.208753,-9.894796],[22.155268,-11.084801],[22.402798,-10.993075],[22.837345,-11.017622],[23.456791,-10.867863],[23.912215,-10.926826],[24.017894,-11.237298],[23.904154,-11.722282],[24.079905,-12.191297],[23.930922,-12.565848],[24.016137,-12.911046],[21.933886,-12.898437],[21.887843,-16.08031],[22.562478,-16.898451],[23.215048,-17.523116],[21.377176,-17.930636],[18.956187,-17.789095],[18.263309,-17.309951],[14.209707,-17.353101],[14.058501,-17.423381],[13.462362,-16.971212],[12.814081,-16.941343],[12.215461,-17.111668],[11.734199,-17.301889],[11.640096,-16.673142],[11.778537,-15.793816],[12.123581,-14.878316],[12.175619,-14.449144],[12.500095,-13.5477],[12.738479,-13.137906],[13.312914,-12.48363],[13.633721,-12.038645],[13.738728,-11.297863],[13.686379,-10.731076],[13.387328,-10.373578],[13.120988,-9.766897],[12.87537,-9.166934],[12.929061,-8.959091],[13.236433,-8.562629],[12.93304,-7.596539],[12.728298,-6.927122],[12.227347,-6.294448],[12.322432,-6.100092]]]]}},{"type":"Feature","properties":{"ADMIN":"Burundi","NAME_EN":"Burundi","CONTINENT":"Africa","ADM0_A3":"BDI","ISO_A3":"BDI","NAME":"Burundi","ISO_A2":"BI","NAME_ZH":"布隆迪"},"geometry":{"type":"Polygon","coordinates":[[[30.469674,-2.413855],[30.52766,-2.80762],[30.74301,-3.03431],[30.75224,-3.35931],[30.50554,-3.56858],[30.11632,-4.09012],[29.753512,-4.452389],[29.339998,-4.499983],[29.276384,-3.293907],[29.024926,-2.839258],[29.632176,-2.917858],[29.938359,-2.348487],[30.469674,-2.413855]]]}},{"type":"Feature","properties":{"ADMIN":"Palestine","NAME_EN":"Palestine","CONTINENT":"Asia","ADM0_A3":"PSX","ISO_A3":"PSE","NAME":"Palestine","ISO_A2":"PS","NAME_ZH":"巴勒斯坦"},"geometry":{"type":"MultiPolygon","coordinates":[[[[35.397561,31.489086],[34.927408,31.353435],[34.970507,31.616778],[35.225892,31.754341],[34.974641,31.866582],[35.18393,32.532511],[35.545665,32.393992],[35.545252,31.782505],[35.397561,31.489086]]],[[[34.2296,31.2208],[34.222,31.274],[34.222,31.38],[34.222,31.48],[34.232,31.535],[34.259,31.578],[34.308,31.595],[34.488,31.595],[34.556,31.575],[34.56,31.543],[34.55,31.396],[34.54,31.242],[34.456,31.221],[34.2296,31.2208]]]]}},{"type":"Feature","properties":{"ADMIN":"Israel","NAME_EN":"Israel","CONTINENT":"Asia","ADM0_A3":"ISR","ISO_A3":"ISR","NAME":"Israel","ISO_A2":"IL","NAME_ZH":"以色列"},"geometry":{"type":"Polygon","coordinates":[[[35.719918,32.709192],[35.545665,32.393992],[35.18393,32.532511],[34.974641,31.866582],[35.225892,31.754341],[34.970507,31.616778],[34.927408,31.353435],[35.397561,31.489086],[35.420918,31.100066],[34.922603,29.501326],[34.823243,29.761081],[34.26544,31.21936],[34.265435,31.219357],[34.265433,31.219361],[34.556372,31.548824],[34.488107,31.605539],[34.752587,32.072926],[34.955417,32.827376],[35.098457,33.080539],[35.126053,33.0909],[35.460709,33.08904],[35.552797,33.264275],[35.821101,33.277426],[35.836397,32.868123],[35.700798,32.716014],[35.719918,32.709192]]]}},{"type":"Feature","properties":{"ADMIN":"Lebanon","NAME_EN":"Lebanon","CONTINENT":"Asia","ADM0_A3":"LBN","ISO_A3":"LBN","NAME":"Lebanon","ISO_A2":"LB","NAME_ZH":"黎巴嫩"},"geometry":{"type":"Polygon","coordinates":[[[35.821101,33.277426],[35.552797,33.264275],[35.460709,33.08904],[35.126053,33.0909],[35.482207,33.90545],[35.979592,34.610058],[35.998403,34.644914],[36.448194,34.593935],[36.61175,34.201789],[36.06646,33.824912],[35.821101,33.277426]]]}},{"type":"Feature","properties":{"ADMIN":"Madagascar","NAME_EN":"Madagascar","CONTINENT":"Africa","ADM0_A3":"MDG","ISO_A3":"MDG","NAME":"Madagascar","ISO_A2":"MG","NAME_ZH":"马达加斯加"},"geometry":{"type":"Polygon","coordinates":[[[49.543519,-12.469833],[49.808981,-12.895285],[50.056511,-13.555761],[50.217431,-14.758789],[50.476537,-15.226512],[50.377111,-15.706069],[50.200275,-16.000263],[49.860606,-15.414253],[49.672607,-15.710204],[49.863344,-16.451037],[49.774564,-16.875042],[49.498612,-17.106036],[49.435619,-17.953064],[49.041792,-19.118781],[48.548541,-20.496888],[47.930749,-22.391501],[47.547723,-23.781959],[47.095761,-24.94163],[46.282478,-25.178463],[45.409508,-25.601434],[44.833574,-25.346101],[44.03972,-24.988345],[43.763768,-24.460677],[43.697778,-23.574116],[43.345654,-22.776904],[43.254187,-22.057413],[43.433298,-21.336475],[43.893683,-21.163307],[43.89637,-20.830459],[44.374325,-20.072366],[44.464397,-19.435454],[44.232422,-18.961995],[44.042976,-18.331387],[43.963084,-17.409945],[44.312469,-16.850496],[44.446517,-16.216219],[44.944937,-16.179374],[45.502732,-15.974373],[45.872994,-15.793454],[46.312243,-15.780018],[46.882183,-15.210182],[47.70513,-14.594303],[48.005215,-14.091233],[47.869047,-13.663869],[48.293828,-13.784068],[48.84506,-13.089175],[48.863509,-12.487868],[49.194651,-12.040557],[49.543519,-12.469833]]]}},{"type":"Feature","properties":{"ADMIN":"Gambia","NAME_EN":"The Gambia","CONTINENT":"Africa","ADM0_A3":"GMB","ISO_A3":"GMB","NAME":"Gambia","ISO_A2":"GM","NAME_ZH":"冈比亚"},"geometry":{"type":"Polygon","coordinates":[[[-16.713729,13.594959],[-15.624596,13.623587],[-15.39877,13.860369],[-15.081735,13.876492],[-14.687031,13.630357],[-14.376714,13.62568],[-14.046992,13.794068],[-13.844963,13.505042],[-14.277702,13.280585],[-14.712197,13.298207],[-15.141163,13.509512],[-15.511813,13.27857],[-15.691001,13.270353],[-15.931296,13.130284],[-16.841525,13.151394],[-16.713729,13.594959]]]}},{"type":"Feature","properties":{"ADMIN":"Tunisia","NAME_EN":"Tunisia","CONTINENT":"Africa","ADM0_A3":"TUN","ISO_A3":"TUN","NAME":"Tunisia","ISO_A2":"TN","NAME_ZH":"突尼斯"},"geometry":{"type":"Polygon","coordinates":[[[9.48214,30.307556],[9.055603,32.102692],[8.439103,32.506285],[8.430473,32.748337],[7.612642,33.344115],[7.524482,34.097376],[8.140981,34.655146],[8.376368,35.479876],[8.217824,36.433177],[8.420964,36.946427],[9.509994,37.349994],[10.210002,37.230002],[10.18065,36.724038],[11.028867,37.092103],[11.100026,36.899996],[10.600005,36.41],[10.593287,35.947444],[10.939519,35.698984],[10.807847,34.833507],[10.149593,34.330773],[10.339659,33.785742],[10.856836,33.76874],[11.108501,33.293343],[11.488787,33.136996],[11.432253,32.368903],[10.94479,32.081815],[10.636901,31.761421],[9.950225,31.37607],[10.056575,30.961831],[9.970017,30.539325],[9.48214,30.307556]]]}},{"type":"Feature","properties":{"ADMIN":"Algeria","NAME_EN":"Algeria","CONTINENT":"Africa","ADM0_A3":"DZA","ISO_A3":"DZA","NAME":"Algeria","ISO_A2":"DZ","NAME_ZH":"阿尔及利亚"},"geometry":{"type":"Polygon","coordinates":[[[-8.6844,27.395744],[-8.665124,27.589479],[-8.66559,27.656426],[-8.674116,28.841289],[-7.059228,29.579228],[-6.060632,29.7317],[-5.242129,30.000443],[-4.859646,30.501188],[-3.690441,30.896952],[-3.647498,31.637294],[-3.06898,31.724498],[-2.616605,32.094346],[-1.307899,32.262889],[-1.124551,32.651522],[-1.388049,32.864015],[-1.733455,33.919713],[-1.792986,34.527919],[-2.169914,35.168396],[-1.208603,35.714849],[-0.127454,35.888662],[0.503877,36.301273],[1.466919,36.605647],[3.161699,36.783905],[4.815758,36.865037],[5.32012,36.716519],[6.26182,37.110655],[7.330385,37.118381],[7.737078,36.885708],[8.420964,36.946427],[8.217824,36.433177],[8.376368,35.479876],[8.140981,34.655146],[7.524482,34.097376],[7.612642,33.344115],[8.430473,32.748337],[8.439103,32.506285],[9.055603,32.102692],[9.48214,30.307556],[9.805634,29.424638],[9.859998,28.95999],[9.683885,28.144174],[9.756128,27.688259],[9.629056,27.140953],[9.716286,26.512206],[9.319411,26.094325],[9.910693,25.365455],[9.948261,24.936954],[10.303847,24.379313],[10.771364,24.562532],[11.560669,24.097909],[11.999506,23.471668],[8.572893,21.565661],[5.677566,19.601207],[4.267419,19.155265],[3.158133,19.057364],[3.146661,19.693579],[2.683588,19.85623],[2.060991,20.142233],[1.823228,20.610809],[-1.550055,22.792666],[-4.923337,24.974574],[-8.6844,27.395744]]]}},{"type":"Feature","properties":{"ADMIN":"Jordan","NAME_EN":"Jordan","CONTINENT":"Asia","ADM0_A3":"JOR","ISO_A3":"JOR","NAME":"Jordan","ISO_A2":"JO","NAME_ZH":"约旦"},"geometry":{"type":"Polygon","coordinates":[[[35.545665,32.393992],[35.719918,32.709192],[36.834062,32.312938],[38.792341,33.378686],[39.195468,32.161009],[39.004886,32.010217],[37.002166,31.508413],[37.998849,30.5085],[37.66812,30.338665],[37.503582,30.003776],[36.740528,29.865283],[36.501214,29.505254],[36.068941,29.197495],[34.956037,29.356555],[34.922603,29.501326],[35.420918,31.100066],[35.397561,31.489086],[35.545252,31.782505],[35.545665,32.393992]]]}},{"type":"Feature","properties":{"ADMIN":"United Arab Emirates","NAME_EN":"United Arab Emirates","CONTINENT":"Asia","ADM0_A3":"ARE","ISO_A3":"ARE","NAME":"United Arab Emirates","ISO_A2":"AE","NAME_ZH":"阿拉伯联合酋长国"},"geometry":{"type":"Polygon","coordinates":[[[51.579519,24.245497],[51.757441,24.294073],[51.794389,24.019826],[52.577081,24.177439],[53.404007,24.151317],[54.008001,24.121758],[54.693024,24.797892],[55.439025,25.439145],[56.070821,26.055464],[56.261042,25.714606],[56.396847,24.924732],[55.886233,24.920831],[55.804119,24.269604],[55.981214,24.130543],[55.528632,23.933604],[55.525841,23.524869],[55.234489,23.110993],[55.208341,22.70833],[55.006803,22.496948],[52.000733,23.001154],[51.617708,24.014219],[51.579519,24.245497]]]}},{"type":"Feature","properties":{"ADMIN":"Qatar","NAME_EN":"Qatar","CONTINENT":"Asia","ADM0_A3":"QAT","ISO_A3":"QAT","NAME":"Qatar","ISO_A2":"QA","NAME_ZH":"卡塔尔"},"geometry":{"type":"Polygon","coordinates":[[[50.810108,24.754743],[50.743911,25.482424],[51.013352,26.006992],[51.286462,26.114582],[51.589079,25.801113],[51.6067,25.21567],[51.389608,24.627386],[51.112415,24.556331],[50.810108,24.754743]]]}},{"type":"Feature","properties":{"ADMIN":"Kuwait","NAME_EN":"Kuwait","CONTINENT":"Asia","ADM0_A3":"KWT","ISO_A3":"KWT","NAME":"Kuwait","ISO_A2":"KW","NAME_ZH":"科威特"},"geometry":{"type":"Polygon","coordinates":[[[47.974519,29.975819],[48.183189,29.534477],[48.093943,29.306299],[48.416094,28.552004],[47.708851,28.526063],[47.459822,29.002519],[46.568713,29.099025],[47.302622,30.05907],[47.974519,29.975819]]]}},{"type":"Feature","properties":{"ADMIN":"Iraq","NAME_EN":"Iraq","CONTINENT":"Asia","ADM0_A3":"IRQ","ISO_A3":"IRQ","NAME":"Iraq","ISO_A2":"IQ","NAME_ZH":"伊拉克"},"geometry":{"type":"Polygon","coordinates":[[[39.195468,32.161009],[38.792341,33.378686],[41.006159,34.419372],[41.383965,35.628317],[41.289707,36.358815],[41.837064,36.605854],[42.349591,37.229873],[42.779126,37.385264],[43.942259,37.256228],[44.293452,37.001514],[44.772677,37.170437],[45.420618,35.977546],[46.07634,35.677383],[46.151788,35.093259],[45.64846,34.748138],[45.416691,33.967798],[46.109362,33.017287],[47.334661,32.469155],[47.849204,31.709176],[47.685286,30.984853],[48.004698,30.985137],[48.014568,30.452457],[48.567971,29.926778],[47.974519,29.975819],[47.302622,30.05907],[46.568713,29.099025],[44.709499,29.178891],[41.889981,31.190009],[40.399994,31.889992],[39.195468,32.161009]]]}},{"type":"Feature","properties":{"ADMIN":"Oman","NAME_EN":"Oman","CONTINENT":"Asia","ADM0_A3":"OMN","ISO_A3":"OMN","NAME":"Oman","ISO_A2":"OM","NAME_ZH":"阿曼"},"geometry":{"type":"MultiPolygon","coordinates":[[[[55.208341,22.70833],[55.234489,23.110993],[55.525841,23.524869],[55.528632,23.933604],[55.981214,24.130543],[55.804119,24.269604],[55.886233,24.920831],[56.396847,24.924732],[56.84514,24.241673],[57.403453,23.878594],[58.136948,23.747931],[58.729211,23.565668],[59.180502,22.992395],[59.450098,22.660271],[59.80806,22.533612],[59.806148,22.310525],[59.442191,21.714541],[59.282408,21.433886],[58.861141,21.114035],[58.487986,20.428986],[58.034318,20.481437],[57.826373,20.243002],[57.665762,19.736005],[57.7887,19.06757],[57.694391,18.94471],[57.234264,18.947991],[56.609651,18.574267],[56.512189,18.087113],[56.283521,17.876067],[55.661492,17.884128],[55.269939,17.632309],[55.2749,17.228354],[54.791002,16.950697],[54.239253,17.044981],[53.570508,16.707663],[53.108573,16.651051],[52.782184,17.349742],[52.00001,19.000003],[54.999982,19.999994],[55.666659,22.000001],[55.208341,22.70833]]],[[[56.261042,25.714606],[56.070821,26.055464],[56.362017,26.395934],[56.485679,26.309118],[56.391421,25.895991],[56.261042,25.714606]]]]}},{"type":"Feature","properties":{"ADMIN":"Vanuatu","NAME_EN":"Vanuatu","CONTINENT":"Oceania","ADM0_A3":"VUT","ISO_A3":"VUT","NAME":"Vanuatu","ISO_A2":"VU","NAME_ZH":"瓦努阿图"},"geometry":{"type":"MultiPolygon","coordinates":[[[[167.216801,-15.891846],[167.844877,-16.466333],[167.515181,-16.59785],[167.180008,-16.159995],[167.216801,-15.891846]]],[[[166.793158,-15.668811],[166.649859,-15.392704],[166.629137,-14.626497],[167.107712,-14.93392],[167.270028,-15.740021],[167.001207,-15.614602],[166.793158,-15.668811]]]]}},{"type":"Feature","properties":{"ADMIN":"Cambodia","NAME_EN":"Cambodia","CONTINENT":"Asia","ADM0_A3":"KHM","ISO_A3":"KHM","NAME":"Cambodia","ISO_A2":"KH","NAME_ZH":"柬埔寨"},"geometry":{"type":"Polygon","coordinates":[[[102.584932,12.186595],[102.348099,13.394247],[102.988422,14.225721],[104.281418,14.416743],[105.218777,14.273212],[106.043946,13.881091],[106.496373,14.570584],[107.382727,14.202441],[107.614548,13.535531],[107.491403,12.337206],[105.810524,11.567615],[106.24967,10.961812],[105.199915,10.88931],[104.334335,10.486544],[103.49728,10.632555],[103.09069,11.153661],[102.584932,12.186595]]]}},{"type":"Feature","properties":{"ADMIN":"Thailand","NAME_EN":"Thailand","CONTINENT":"Asia","ADM0_A3":"THA","ISO_A3":"THA","NAME":"Thailand","ISO_A2":"TH","NAME_ZH":"泰国"},"geometry":{"type":"Polygon","coordinates":[[[105.218777,14.273212],[104.281418,14.416743],[102.988422,14.225721],[102.348099,13.394247],[102.584932,12.186595],[101.687158,12.64574],[100.83181,12.627085],[100.978467,13.412722],[100.097797,13.406856],[100.018733,12.307001],[99.478921,10.846367],[99.153772,9.963061],[99.222399,9.239255],[99.873832,9.207862],[100.279647,8.295153],[100.459274,7.429573],[101.017328,6.856869],[101.623079,6.740622],[102.141187,6.221636],[101.814282,5.810808],[101.154219,5.691384],[101.075516,6.204867],[100.259596,6.642825],[100.085757,6.464489],[99.690691,6.848213],[99.519642,7.343454],[98.988253,7.907993],[98.503786,8.382305],[98.339662,7.794512],[98.150009,8.350007],[98.25915,8.973923],[98.553551,9.93296],[99.038121,10.960546],[99.587286,11.892763],[99.196354,12.804748],[99.212012,13.269294],[99.097755,13.827503],[98.430819,14.622028],[98.192074,15.123703],[98.537376,15.308497],[98.903348,16.177824],[98.493761,16.837836],[97.859123,17.567946],[97.375896,18.445438],[97.797783,18.62708],[98.253724,19.708203],[98.959676,19.752981],[99.543309,20.186598],[100.115988,20.41785],[100.548881,20.109238],[100.606294,19.508344],[101.282015,19.462585],[101.035931,18.408928],[101.059548,17.512497],[102.113592,18.109102],[102.413005,17.932782],[102.998706,17.961695],[103.200192,18.309632],[103.956477,18.240954],[104.716947,17.428859],[104.779321,16.441865],[105.589039,15.570316],[105.544338,14.723934],[105.218777,14.273212]]]}},{"type":"Feature","properties":{"ADMIN":"Laos","NAME_EN":"Laos","CONTINENT":"Asia","ADM0_A3":"LAO","ISO_A3":"LAO","NAME":"Laos","ISO_A2":"LA","NAME_ZH":"老挝"},"geometry":{"type":"Polygon","coordinates":[[[107.382727,14.202441],[106.496373,14.570584],[106.043946,13.881091],[105.218777,14.273212],[105.544338,14.723934],[105.589039,15.570316],[104.779321,16.441865],[104.716947,17.428859],[103.956477,18.240954],[103.200192,18.309632],[102.998706,17.961695],[102.413005,17.932782],[102.113592,18.109102],[101.059548,17.512497],[101.035931,18.408928],[101.282015,19.462585],[100.606294,19.508344],[100.548881,20.109238],[100.115988,20.41785],[100.329101,20.786122],[101.180005,21.436573],[101.270026,21.201652],[101.80312,21.174367],[101.652018,22.318199],[102.170436,22.464753],[102.754896,21.675137],[103.203861,20.766562],[104.435,20.758733],[104.822574,19.886642],[104.183388,19.624668],[103.896532,19.265181],[105.094598,18.666975],[105.925762,17.485315],[106.556008,16.604284],[107.312706,15.908538],[107.564525,15.202173],[107.382727,14.202441]]]}},{"type":"Feature","properties":{"ADMIN":"Myanmar","NAME_EN":"Myanmar","CONTINENT":"Asia","ADM0_A3":"MMR","ISO_A3":"MMR","NAME":"Myanmar","ISO_A2":"MM","NAME_ZH":"缅甸"},"geometry":{"type":"Polygon","coordinates":[[[100.115988,20.41785],[99.543309,20.186598],[98.959676,19.752981],[98.253724,19.708203],[97.797783,18.62708],[97.375896,18.445438],[97.859123,17.567946],[98.493761,16.837836],[98.903348,16.177824],[98.537376,15.308497],[98.192074,15.123703],[98.430819,14.622028],[99.097755,13.827503],[99.212012,13.269294],[99.196354,12.804748],[99.587286,11.892763],[99.038121,10.960546],[98.553551,9.93296],[98.457174,10.675266],[98.764546,11.441292],[98.428339,12.032987],[98.509574,13.122378],[98.103604,13.64046],[97.777732,14.837286],[97.597072,16.100568],[97.16454,16.928734],[96.505769,16.427241],[95.369352,15.71439],[94.808405,15.803454],[94.188804,16.037936],[94.533486,17.27724],[94.324817,18.213514],[93.540988,19.366493],[93.663255,19.726962],[93.078278,19.855145],[92.368554,20.670883],[92.303234,21.475485],[92.652257,21.324048],[92.672721,22.041239],[93.166128,22.27846],[93.060294,22.703111],[93.286327,23.043658],[93.325188,24.078556],[94.106742,23.850741],[94.552658,24.675238],[94.603249,25.162495],[95.155153,26.001307],[95.124768,26.573572],[96.419366,27.264589],[97.133999,27.083774],[97.051989,27.699059],[97.402561,27.882536],[97.327114,28.261583],[97.911988,28.335945],[98.246231,27.747221],[98.68269,27.508812],[98.712094,26.743536],[98.671838,25.918703],[97.724609,25.083637],[97.60472,23.897405],[98.660262,24.063286],[98.898749,23.142722],[99.531992,22.949039],[99.240899,22.118314],[99.983489,21.742937],[100.416538,21.558839],[101.150033,21.849984],[101.180005,21.436573],[100.329101,20.786122],[100.115988,20.41785]]]}},{"type":"Feature","properties":{"ADMIN":"Vietnam","NAME_EN":"Vietnam","CONTINENT":"Asia","ADM0_A3":"VNM","ISO_A3":"VNM","NAME":"Vietnam","ISO_A2":"VN","NAME_ZH":"越南"},"geometry":{"type":"Polygon","coordinates":[[[104.334335,10.486544],[105.199915,10.88931],[106.24967,10.961812],[105.810524,11.567615],[107.491403,12.337206],[107.614548,13.535531],[107.382727,14.202441],[107.564525,15.202173],[107.312706,15.908538],[106.556008,16.604284],[105.925762,17.485315],[105.094598,18.666975],[103.896532,19.265181],[104.183388,19.624668],[104.822574,19.886642],[104.435,20.758733],[103.203861,20.766562],[102.754896,21.675137],[102.170436,22.464753],[102.706992,22.708795],[103.504515,22.703757],[104.476858,22.81915],[105.329209,23.352063],[105.811247,22.976892],[106.725403,22.794268],[106.567273,22.218205],[107.04342,21.811899],[108.05018,21.55238],[106.715068,20.696851],[105.881682,19.75205],[105.662006,19.058165],[106.426817,18.004121],[107.361954,16.697457],[108.269495,16.079742],[108.877107,15.276691],[109.33527,13.426028],[109.200136,11.666859],[108.36613,11.008321],[107.220929,10.364484],[106.405113,9.53084],[105.158264,8.59976],[104.795185,9.241038],[105.076202,9.918491],[104.334335,10.486544]]]}},{"type":"Feature","properties":{"ADMIN":"North Korea","NAME_EN":"North Korea","CONTINENT":"Asia","ADM0_A3":"PRK","ISO_A3":"PRK","NAME":"North Korea","ISO_A2":"KP","NAME_ZH":"朝鲜民主主义人民共和国"},"geometry":{"type":"MultiPolygon","coordinates":[[[[130.780004,42.220008],[130.780005,42.22001],[130.780007,42.220007],[130.780004,42.220008]]],[[[130.64,42.395024],[130.64,42.395],[130.779992,42.22001],[130.400031,42.280004],[129.965949,41.941368],[129.667362,41.601104],[129.705189,40.882828],[129.188115,40.661808],[129.0104,40.485436],[128.633368,40.189847],[127.967414,40.025413],[127.533436,39.75685],[127.50212,39.323931],[127.385434,39.213472],[127.783343,39.050898],[128.349716,38.612243],[128.205746,38.370397],[127.780035,38.304536],[127.073309,38.256115],[126.68372,37.804773],[126.237339,37.840378],[126.174759,37.749686],[125.689104,37.94001],[125.568439,37.752089],[125.27533,37.669071],[125.240087,37.857224],[124.981033,37.948821],[124.712161,38.108346],[124.985994,38.548474],[125.221949,38.665857],[125.132859,38.848559],[125.38659,39.387958],[125.321116,39.551385],[124.737482,39.660344],[124.265625,39.928493],[125.079942,40.569824],[126.182045,41.107336],[126.869083,41.816569],[127.343783,41.503152],[128.208433,41.466772],[128.052215,41.994285],[129.596669,42.424982],[129.994267,42.985387],[130.64,42.395024]]]]}},{"type":"Feature","properties":{"ADMIN":"South Korea","NAME_EN":"South Korea","CONTINENT":"Asia","ADM0_A3":"KOR","ISO_A3":"KOR","NAME":"South Korea","ISO_A2":"KR","NAME_ZH":"大韩民国"},"geometry":{"type":"Polygon","coordinates":[[[126.174759,37.749686],[126.237339,37.840378],[126.68372,37.804773],[127.073309,38.256115],[127.780035,38.304536],[128.205746,38.370397],[128.349716,38.612243],[129.21292,37.432392],[129.46045,36.784189],[129.468304,35.632141],[129.091377,35.082484],[128.18585,34.890377],[127.386519,34.475674],[126.485748,34.390046],[126.37392,34.93456],[126.559231,35.684541],[126.117398,36.725485],[126.860143,36.893924],[126.174759,37.749686]]]}},{"type":"Feature","properties":{"ADMIN":"Mongolia","NAME_EN":"Mongolia","CONTINENT":"Asia","ADM0_A3":"MNG","ISO_A3":"MNG","NAME":"Mongolia","ISO_A2":"MN","NAME_ZH":"蒙古国"},"geometry":{"type":"Polygon","coordinates":[[[87.751264,49.297198],[88.805567,49.470521],[90.713667,50.331812],[92.234712,50.802171],[93.10421,50.49529],[94.147566,50.480537],[94.815949,50.013433],[95.81402,49.97746],[97.25976,49.72605],[98.231762,50.422401],[97.82574,51.010995],[98.861491,52.047366],[99.981732,51.634006],[100.88948,51.516856],[102.06521,51.25991],[102.25589,50.51056],[103.676545,50.089966],[104.62158,50.27532],[105.886591,50.406019],[106.888804,50.274296],[107.868176,49.793705],[108.475167,49.282548],[109.402449,49.292961],[110.662011,49.130128],[111.581231,49.377968],[112.89774,49.543565],[114.362456,50.248303],[114.96211,50.140247],[115.485695,49.805177],[116.678801,49.888531],[116.191802,49.134598],[115.485282,48.135383],[115.742837,47.726545],[116.308953,47.85341],[117.295507,47.697709],[118.064143,48.06673],[118.866574,47.74706],[119.772824,47.048059],[119.66327,46.69268],[118.874326,46.805412],[117.421701,46.672733],[116.717868,46.388202],[115.985096,45.727235],[114.460332,45.339817],[113.463907,44.808893],[112.436062,45.011646],[111.873306,45.102079],[111.348377,44.457442],[111.667737,44.073176],[111.829588,43.743118],[111.129682,43.406834],[110.412103,42.871234],[109.243596,42.519446],[107.744773,42.481516],[106.129316,42.134328],[104.964994,41.59741],[104.522282,41.908347],[103.312278,41.907468],[101.83304,42.514873],[100.845866,42.663804],[99.515817,42.524691],[97.451757,42.74889],[96.349396,42.725635],[95.762455,43.319449],[95.306875,44.241331],[94.688929,44.352332],[93.480734,44.975472],[92.133891,45.115076],[90.94554,45.286073],[90.585768,45.719716],[90.970809,46.888146],[90.280826,47.693549],[88.854298,48.069082],[88.013832,48.599463],[87.751264,49.297198]]]}},{"type":"Feature","properties":{"ADMIN":"India","NAME_EN":"India","CONTINENT":"Asia","ADM0_A3":"IND","ISO_A3":"IND","NAME":"India","ISO_A2":"IN","NAME_ZH":"印度"},"geometry":{"type":"Polygon","coordinates":[[[97.327114,28.261583],[97.402561,27.882536],[97.051989,27.699059],[97.133999,27.083774],[96.419366,27.264589],[95.124768,26.573572],[95.155153,26.001307],[94.603249,25.162495],[94.552658,24.675238],[94.106742,23.850741],[93.325188,24.078556],[93.286327,23.043658],[93.060294,22.703111],[93.166128,22.27846],[92.672721,22.041239],[92.146035,23.627499],[91.869928,23.624346],[91.706475,22.985264],[91.158963,23.503527],[91.46773,24.072639],[91.915093,24.130414],[92.376202,24.976693],[91.799596,25.147432],[90.872211,25.132601],[89.920693,25.26975],[89.832481,25.965082],[89.355094,26.014407],[88.563049,26.446526],[88.209789,25.768066],[88.931554,25.238692],[88.306373,24.866079],[88.084422,24.501657],[88.69994,24.233715],[88.52977,23.631142],[88.876312,22.879146],[89.031961,22.055708],[88.888766,21.690588],[88.208497,21.703172],[86.975704,21.495562],[87.033169,20.743308],[86.499351,20.151638],[85.060266,19.478579],[83.941006,18.30201],[83.189217,17.671221],[82.192792,17.016636],[82.191242,16.556664],[81.692719,16.310219],[80.791999,15.951972],[80.324896,15.899185],[80.025069,15.136415],[80.233274,13.835771],[80.286294,13.006261],[79.862547,12.056215],[79.857999,10.357275],[79.340512,10.308854],[78.885345,9.546136],[79.18972,9.216544],[78.277941,8.933047],[77.941165,8.252959],[77.539898,7.965535],[76.592979,8.899276],[76.130061,10.29963],[75.746467,11.308251],[75.396101,11.781245],[74.864816,12.741936],[74.616717,13.992583],[74.443859,14.617222],[73.534199,15.990652],[73.119909,17.92857],[72.820909,19.208234],[72.824475,20.419503],[72.630533,21.356009],[71.175273,20.757441],[70.470459,20.877331],[69.16413,22.089298],[69.644928,22.450775],[69.349597,22.84318],[68.176645,23.691965],[68.842599,24.359134],[71.04324,24.356524],[70.844699,25.215102],[70.282873,25.722229],[70.168927,26.491872],[69.514393,26.940966],[70.616496,27.989196],[71.777666,27.91318],[72.823752,28.961592],[73.450638,29.976413],[74.42138,30.979815],[74.405929,31.692639],[75.258642,32.271105],[74.451559,32.7649],[74.104294,33.441473],[73.749948,34.317699],[74.240203,34.748887],[75.757061,34.504923],[76.871722,34.653544],[77.837451,35.49401],[78.912269,34.321936],[78.811086,33.506198],[79.208892,32.994395],[79.176129,32.48378],[78.458446,32.618164],[78.738894,31.515906],[79.721367,30.882715],[81.111256,30.183481],[80.476721,29.729865],[80.088425,28.79447],[81.057203,28.416095],[81.999987,27.925479],[83.304249,27.364506],[84.675018,27.234901],[85.251779,26.726198],[86.024393,26.630985],[87.227472,26.397898],[88.060238,26.414615],[88.174804,26.810405],[88.043133,27.445819],[88.120441,27.876542],[88.730326,28.086865],[88.814248,27.299316],[88.835643,27.098966],[89.744528,26.719403],[90.373275,26.875724],[91.217513,26.808648],[92.033484,26.83831],[92.103712,27.452614],[91.696657,27.771742],[92.503119,27.896876],[93.413348,28.640629],[94.56599,29.277438],[95.404802,29.031717],[96.117679,29.452802],[96.586591,28.83098],[96.248833,28.411031],[97.327114,28.261583]]]}},{"type":"Feature","properties":{"ADMIN":"Bangladesh","NAME_EN":"Bangladesh","CONTINENT":"Asia","ADM0_A3":"BGD","ISO_A3":"BGD","NAME":"Bangladesh","ISO_A2":"BD","NAME_ZH":"孟加拉国"},"geometry":{"type":"Polygon","coordinates":[[[92.672721,22.041239],[92.652257,21.324048],[92.303234,21.475485],[92.368554,20.670883],[92.082886,21.192195],[92.025215,21.70157],[91.834891,22.182936],[91.417087,22.765019],[90.496006,22.805017],[90.586957,22.392794],[90.272971,21.836368],[89.847467,22.039146],[89.70205,21.857116],[89.418863,21.966179],[89.031961,22.055708],[88.876312,22.879146],[88.52977,23.631142],[88.69994,24.233715],[88.084422,24.501657],[88.306373,24.866079],[88.931554,25.238692],[88.209789,25.768066],[88.563049,26.446526],[89.355094,26.014407],[89.832481,25.965082],[89.920693,25.26975],[90.872211,25.132601],[91.799596,25.147432],[92.376202,24.976693],[91.915093,24.130414],[91.46773,24.072639],[91.158963,23.503527],[91.706475,22.985264],[91.869928,23.624346],[92.146035,23.627499],[92.672721,22.041239]]]}},{"type":"Feature","properties":{"ADMIN":"Bhutan","NAME_EN":"Bhutan","CONTINENT":"Asia","ADM0_A3":"BTN","ISO_A3":"BTN","NAME":"Bhutan","ISO_A2":"BT","NAME_ZH":"不丹"},"geometry":{"type":"Polygon","coordinates":[[[91.696657,27.771742],[92.103712,27.452614],[92.033484,26.83831],[91.217513,26.808648],[90.373275,26.875724],[89.744528,26.719403],[88.835643,27.098966],[88.814248,27.299316],[89.47581,28.042759],[90.015829,28.296439],[90.730514,28.064954],[91.258854,28.040614],[91.696657,27.771742]]]}},{"type":"Feature","properties":{"ADMIN":"Nepal","NAME_EN":"Nepal","CONTINENT":"Asia","ADM0_A3":"NPL","ISO_A3":"NPL","NAME":"Nepal","ISO_A2":"NP","NAME_ZH":"尼泊尔"},"geometry":{"type":"Polygon","coordinates":[[[88.120441,27.876542],[88.043133,27.445819],[88.174804,26.810405],[88.060238,26.414615],[87.227472,26.397898],[86.024393,26.630985],[85.251779,26.726198],[84.675018,27.234901],[83.304249,27.364506],[81.999987,27.925479],[81.057203,28.416095],[80.088425,28.79447],[80.476721,29.729865],[81.111256,30.183481],[81.525804,30.422717],[82.327513,30.115268],[83.337115,29.463732],[83.898993,29.320226],[84.23458,28.839894],[85.011638,28.642774],[85.82332,28.203576],[86.954517,27.974262],[88.120441,27.876542]]]}},{"type":"Feature","properties":{"ADMIN":"Pakistan","NAME_EN":"Pakistan","CONTINENT":"Asia","ADM0_A3":"PAK","ISO_A3":"PAK","NAME":"Pakistan","ISO_A2":"PK","NAME_ZH":"巴基斯坦"},"geometry":{"type":"Polygon","coordinates":[[[77.837451,35.49401],[76.871722,34.653544],[75.757061,34.504923],[74.240203,34.748887],[73.749948,34.317699],[74.104294,33.441473],[74.451559,32.7649],[75.258642,32.271105],[74.405929,31.692639],[74.42138,30.979815],[73.450638,29.976413],[72.823752,28.961592],[71.777666,27.91318],[70.616496,27.989196],[69.514393,26.940966],[70.168927,26.491872],[70.282873,25.722229],[70.844699,25.215102],[71.04324,24.356524],[68.842599,24.359134],[68.176645,23.691965],[67.443667,23.944844],[67.145442,24.663611],[66.372828,25.425141],[64.530408,25.237039],[62.905701,25.218409],[61.497363,25.078237],[61.874187,26.239975],[63.316632,26.756532],[63.233898,27.217047],[62.755426,27.378923],[62.72783,28.259645],[61.771868,28.699334],[61.369309,29.303276],[60.874248,29.829239],[62.549857,29.318572],[63.550261,29.468331],[64.148002,29.340819],[64.350419,29.560031],[65.046862,29.472181],[66.346473,29.887943],[66.381458,30.738899],[66.938891,31.304911],[67.683394,31.303154],[67.792689,31.58293],[68.556932,31.71331],[68.926677,31.620189],[69.317764,31.901412],[69.262522,32.501944],[69.687147,33.105499],[70.323594,33.358533],[69.930543,34.02012],[70.881803,33.988856],[71.156773,34.348911],[71.115019,34.733126],[71.613076,35.153203],[71.498768,35.650563],[71.262348,36.074388],[71.846292,36.509942],[72.920025,36.720007],[74.067552,36.836176],[74.575893,37.020841],[75.158028,37.133031],[75.896897,36.666806],[76.192848,35.898403],[77.837451,35.49401]]]}},{"type":"Feature","properties":{"ADMIN":"Afghanistan","NAME_EN":"Afghanistan","CONTINENT":"Asia","ADM0_A3":"AFG","ISO_A3":"AFG","NAME":"Afghanistan","ISO_A2":"AF","NAME_ZH":"阿富汗"},"geometry":{"type":"Polygon","coordinates":[[[66.518607,37.362784],[67.075782,37.356144],[67.83,37.144994],[68.135562,37.023115],[68.859446,37.344336],[69.196273,37.151144],[69.518785,37.608997],[70.116578,37.588223],[70.270574,37.735165],[70.376304,38.138396],[70.806821,38.486282],[71.348131,38.258905],[71.239404,37.953265],[71.541918,37.905774],[71.448693,37.065645],[71.844638,36.738171],[72.193041,36.948288],[72.63689,37.047558],[73.260056,37.495257],[73.948696,37.421566],[74.980002,37.41999],[75.158028,37.133031],[74.575893,37.020841],[74.067552,36.836176],[72.920025,36.720007],[71.846292,36.509942],[71.262348,36.074388],[71.498768,35.650563],[71.613076,35.153203],[71.115019,34.733126],[71.156773,34.348911],[70.881803,33.988856],[69.930543,34.02012],[70.323594,33.358533],[69.687147,33.105499],[69.262522,32.501944],[69.317764,31.901412],[68.926677,31.620189],[68.556932,31.71331],[67.792689,31.58293],[67.683394,31.303154],[66.938891,31.304911],[66.381458,30.738899],[66.346473,29.887943],[65.046862,29.472181],[64.350419,29.560031],[64.148002,29.340819],[63.550261,29.468331],[62.549857,29.318572],[60.874248,29.829239],[61.781222,30.73585],[61.699314,31.379506],[60.941945,31.548075],[60.863655,32.18292],[60.536078,32.981269],[60.9637,33.528832],[60.52843,33.676446],[60.803193,34.404102],[61.210817,35.650072],[62.230651,35.270664],[62.984662,35.404041],[63.193538,35.857166],[63.982896,36.007957],[64.546479,36.312073],[64.746105,37.111818],[65.588948,37.305217],[65.745631,37.661164],[66.217385,37.39379],[66.518607,37.362784]]]}},{"type":"Feature","properties":{"ADMIN":"Tajikistan","NAME_EN":"Tajikistan","CONTINENT":"Asia","ADM0_A3":"TJK","ISO_A3":"TJK","NAME":"Tajikistan","ISO_A2":"TJ","NAME_ZH":"塔吉克斯坦"},"geometry":{"type":"Polygon","coordinates":[[[67.83,37.144994],[68.392033,38.157025],[68.176025,38.901553],[67.44222,39.140144],[67.701429,39.580478],[68.536416,39.533453],[69.011633,40.086158],[69.329495,40.727824],[70.666622,40.960213],[70.45816,40.496495],[70.601407,40.218527],[71.014198,40.244366],[70.648019,39.935754],[69.55961,40.103211],[69.464887,39.526683],[70.549162,39.604198],[71.784694,39.279463],[73.675379,39.431237],[73.928852,38.505815],[74.257514,38.606507],[74.864816,38.378846],[74.829986,37.990007],[74.980002,37.41999],[73.948696,37.421566],[73.260056,37.495257],[72.63689,37.047558],[72.193041,36.948288],[71.844638,36.738171],[71.448693,37.065645],[71.541918,37.905774],[71.239404,37.953265],[71.348131,38.258905],[70.806821,38.486282],[70.376304,38.138396],[70.270574,37.735165],[70.116578,37.588223],[69.518785,37.608997],[69.196273,37.151144],[68.859446,37.344336],[68.135562,37.023115],[67.83,37.144994]]]}},{"type":"Feature","properties":{"ADMIN":"Kyrgyzstan","NAME_EN":"Kyrgyzstan","CONTINENT":"Asia","ADM0_A3":"KGZ","ISO_A3":"KGZ","NAME":"Kyrgyzstan","ISO_A2":"KG","NAME_ZH":"吉尔吉斯斯坦"},"geometry":{"type":"Polygon","coordinates":[[[70.962315,42.266154],[71.186281,42.704293],[71.844638,42.845395],[73.489758,42.500894],[73.645304,43.091272],[74.212866,43.298339],[75.636965,42.8779],[76.000354,42.988022],[77.658392,42.960686],[79.142177,42.856092],[79.643645,42.496683],[80.25999,42.349999],[80.11943,42.123941],[78.543661,41.582243],[78.187197,41.185316],[76.904484,41.066486],[76.526368,40.427946],[75.467828,40.562072],[74.776862,40.366425],[73.822244,39.893973],[73.960013,39.660008],[73.675379,39.431237],[71.784694,39.279463],[70.549162,39.604198],[69.464887,39.526683],[69.55961,40.103211],[70.648019,39.935754],[71.014198,40.244366],[71.774875,40.145844],[73.055417,40.866033],[71.870115,41.3929],[71.157859,41.143587],[70.420022,41.519998],[71.259248,42.167711],[70.962315,42.266154]]]}},{"type":"Feature","properties":{"ADMIN":"Turkmenistan","NAME_EN":"Turkmenistan","CONTINENT":"Asia","ADM0_A3":"TKM","ISO_A3":"TKM","NAME":"Turkmenistan","ISO_A2":"TM","NAME_ZH":"土库曼斯坦"},"geometry":{"type":"Polygon","coordinates":[[[52.50246,41.783316],[52.944293,42.116034],[54.079418,42.324109],[54.755345,42.043971],[55.455251,41.259859],[55.968191,41.308642],[57.096391,41.32231],[56.932215,41.826026],[57.78653,42.170553],[58.629011,42.751551],[59.976422,42.223082],[60.083341,41.425146],[60.465953,41.220327],[61.547179,41.26637],[61.882714,41.084857],[62.37426,40.053886],[63.518015,39.363257],[64.170223,38.892407],[65.215999,38.402695],[66.54615,37.974685],[66.518607,37.362784],[66.217385,37.39379],[65.745631,37.661164],[65.588948,37.305217],[64.746105,37.111818],[64.546479,36.312073],[63.982896,36.007957],[63.193538,35.857166],[62.984662,35.404041],[62.230651,35.270664],[61.210817,35.650072],[61.123071,36.491597],[60.377638,36.527383],[59.234762,37.412988],[58.436154,37.522309],[57.330434,38.029229],[56.619366,38.121394],[56.180375,37.935127],[55.511578,37.964117],[54.800304,37.392421],[53.921598,37.198918],[53.735511,37.906136],[53.880929,38.952093],[53.101028,39.290574],[53.357808,39.975286],[52.693973,40.033629],[52.915251,40.876523],[53.858139,40.631034],[54.736845,40.951015],[54.008311,41.551211],[53.721713,42.123191],[52.91675,41.868117],[52.814689,41.135371],[52.50246,41.783316]]]}},{"type":"Feature","properties":{"ADMIN":"Iran","NAME_EN":"Iran","CONTINENT":"Asia","ADM0_A3":"IRN","ISO_A3":"IRN","NAME":"Iran","ISO_A2":"IR","NAME_ZH":"伊朗"},"geometry":{"type":"Polygon","coordinates":[[[48.567971,29.926778],[48.014568,30.452457],[48.004698,30.985137],[47.685286,30.984853],[47.849204,31.709176],[47.334661,32.469155],[46.109362,33.017287],[45.416691,33.967798],[45.64846,34.748138],[46.151788,35.093259],[46.07634,35.677383],[45.420618,35.977546],[44.772677,37.170437],[44.77267,37.17045],[44.225756,37.971584],[44.421403,38.281281],[44.109225,39.428136],[44.79399,39.713003],[44.952688,39.335765],[45.457722,38.874139],[46.143623,38.741201],[46.50572,38.770605],[47.685079,39.508364],[48.060095,39.582235],[48.355529,39.288765],[48.010744,38.794015],[48.634375,38.270378],[48.883249,38.320245],[49.199612,37.582874],[50.147771,37.374567],[50.842354,36.872814],[52.264025,36.700422],[53.82579,36.965031],[53.921598,37.198918],[54.800304,37.392421],[55.511578,37.964117],[56.180375,37.935127],[56.619366,38.121394],[57.330434,38.029229],[58.436154,37.522309],[59.234762,37.412988],[60.377638,36.527383],[61.123071,36.491597],[61.210817,35.650072],[60.803193,34.404102],[60.52843,33.676446],[60.9637,33.528832],[60.536078,32.981269],[60.863655,32.18292],[60.941945,31.548075],[61.699314,31.379506],[61.781222,30.73585],[60.874248,29.829239],[61.369309,29.303276],[61.771868,28.699334],[62.72783,28.259645],[62.755426,27.378923],[63.233898,27.217047],[63.316632,26.756532],[61.874187,26.239975],[61.497363,25.078237],[59.616134,25.380157],[58.525761,25.609962],[57.397251,25.739902],[56.970766,26.966106],[56.492139,27.143305],[55.72371,26.964633],[54.71509,26.480658],[53.493097,26.812369],[52.483598,27.580849],[51.520763,27.86569],[50.852948,28.814521],[50.115009,30.147773],[49.57685,29.985715],[48.941333,30.31709],[48.567971,29.926778]]]}},{"type":"Feature","properties":{"ADMIN":"Syria","NAME_EN":"Syria","CONTINENT":"Asia","ADM0_A3":"SYR","ISO_A3":"SYR","NAME":"Syria","ISO_A2":"SY","NAME_ZH":"叙利亚"},"geometry":{"type":"Polygon","coordinates":[[[35.719918,32.709192],[35.700798,32.716014],[35.836397,32.868123],[35.821101,33.277426],[36.06646,33.824912],[36.61175,34.201789],[36.448194,34.593935],[35.998403,34.644914],[35.905023,35.410009],[36.149763,35.821535],[36.41755,36.040617],[36.685389,36.259699],[36.739494,36.81752],[37.066761,36.623036],[38.167727,36.90121],[38.699891,36.712927],[39.52258,36.716054],[40.673259,37.091276],[41.212089,37.074352],[42.349591,37.229873],[41.837064,36.605854],[41.289707,36.358815],[41.383965,35.628317],[41.006159,34.419372],[38.792341,33.378686],[36.834062,32.312938],[35.719918,32.709192]]]}},{"type":"Feature","properties":{"ADMIN":"Armenia","NAME_EN":"Armenia","CONTINENT":"Asia","ADM0_A3":"ARM","ISO_A3":"ARM","NAME":"Armenia","ISO_A2":"AM","NAME_ZH":"亚美尼亚"},"geometry":{"type":"Polygon","coordinates":[[[46.50572,38.770605],[46.143623,38.741201],[45.735379,39.319719],[45.739978,39.473999],[45.298145,39.471751],[45.001987,39.740004],[44.79399,39.713003],[44.400009,40.005],[43.656436,40.253564],[43.752658,40.740201],[43.582746,41.092143],[44.97248,41.248129],[45.179496,40.985354],[45.560351,40.81229],[45.359175,40.561504],[45.891907,40.218476],[45.610012,39.899994],[46.034534,39.628021],[46.483499,39.464155],[46.50572,38.770605]]]}},{"type":"Feature","properties":{"ADMIN":"Sweden","NAME_EN":"Sweden","CONTINENT":"Europe","ADM0_A3":"SWE","ISO_A3":"SWE","NAME":"Sweden","ISO_A2":"SE","NAME_ZH":"瑞典"},"geometry":{"type":"Polygon","coordinates":[[[11.027369,58.856149],[11.468272,59.432393],[12.300366,60.117933],[12.631147,61.293572],[11.992064,61.800362],[11.930569,63.128318],[12.579935,64.066219],[13.571916,64.049114],[13.919905,64.445421],[13.55569,64.787028],[15.108411,66.193867],[16.108712,67.302456],[16.768879,68.013937],[17.729182,68.010552],[17.993868,68.567391],[19.87856,68.407194],[20.025269,69.065139],[20.645593,69.106247],[21.978535,68.616846],[23.539473,67.936009],[23.56588,66.396051],[23.903379,66.006927],[22.183173,65.723741],[21.213517,65.026005],[21.369631,64.413588],[19.778876,63.609554],[17.847779,62.7494],[17.119555,61.341166],[17.831346,60.636583],[18.787722,60.081914],[17.869225,58.953766],[16.829185,58.719827],[16.44771,57.041118],[15.879786,56.104302],[14.666681,56.200885],[14.100721,55.407781],[12.942911,55.361737],[12.625101,56.30708],[11.787942,57.441817],[11.027369,58.856149]]]}},{"type":"Feature","properties":{"ADMIN":"Belarus","NAME_EN":"Belarus","CONTINENT":"Europe","ADM0_A3":"BLR","ISO_A3":"BLR","NAME":"Belarus","ISO_A2":"BY","NAME_ZH":"白俄罗斯"},"geometry":{"type":"Polygon","coordinates":[[[28.176709,56.16913],[29.229513,55.918344],[29.371572,55.670091],[29.896294,55.789463],[30.873909,55.550976],[30.971836,55.081548],[30.757534,54.811771],[31.384472,54.157056],[31.791424,53.974639],[31.731273,53.794029],[32.405599,53.618045],[32.693643,53.351421],[32.304519,53.132726],[31.49764,53.16743],[31.305201,53.073996],[31.540018,52.742052],[31.78597,52.10168],[31.785992,52.101678],[30.927549,52.042353],[30.619454,51.822806],[30.555117,51.319503],[30.157364,51.416138],[29.254938,51.368234],[28.992835,51.602044],[28.617613,51.427714],[28.241615,51.572227],[27.454066,51.592303],[26.337959,51.832289],[25.327788,51.910656],[24.553106,51.888461],[24.005078,51.617444],[23.527071,51.578454],[23.508002,52.023647],[23.199494,52.486977],[23.799199,52.691099],[23.804935,53.089731],[23.527536,53.470122],[23.484128,53.912498],[24.450684,53.905702],[25.536354,54.282423],[25.768433,54.846963],[26.588279,55.167176],[26.494331,55.615107],[27.10246,55.783314],[28.176709,56.16913]]]}},{"type":"Feature","properties":{"ADMIN":"Ukraine","NAME_EN":"Ukraine","CONTINENT":"Europe","ADM0_A3":"UKR","ISO_A3":"UKR","NAME":"Ukraine","ISO_A2":"UA","NAME_ZH":"乌克兰"},"geometry":{"type":"Polygon","coordinates":[[[31.785992,52.101678],[32.15944,52.06125],[32.412058,52.288695],[32.715761,52.238465],[33.7527,52.335075],[34.391731,51.768882],[34.141978,51.566413],[34.224816,51.255993],[35.022183,51.207572],[35.37791,50.77394],[35.356116,50.577197],[36.626168,50.225591],[37.39346,50.383953],[38.010631,49.915662],[38.594988,49.926462],[40.06904,49.60105],[40.080789,49.30743],[39.67465,48.78382],[39.89562,48.23241],[39.738278,47.898937],[38.77057,47.82562],[38.255112,47.5464],[38.223538,47.10219],[37.425137,47.022221],[36.759855,46.6987],[35.823685,46.645964],[34.962342,46.273197],[35.012659,45.737725],[34.861792,45.768182],[34.732017,45.965666],[34.410402,46.005162],[33.699462,46.219573],[33.435988,45.971917],[33.298567,46.080598],[31.74414,46.333348],[31.675307,46.706245],[30.748749,46.5831],[30.377609,46.03241],[29.603289,45.293308],[29.149725,45.464925],[28.679779,45.304031],[28.233554,45.488283],[28.485269,45.596907],[28.659987,45.939987],[28.933717,46.25883],[28.862972,46.437889],[29.072107,46.517678],[29.170654,46.379262],[29.759972,46.349988],[30.024659,46.423937],[29.83821,46.525326],[29.908852,46.674361],[29.559674,46.928583],[29.415135,47.346645],[29.050868,47.510227],[29.122698,47.849095],[28.670891,48.118149],[28.259547,48.155562],[27.522537,48.467119],[26.857824,48.368211],[26.619337,48.220726],[26.19745,48.220881],[25.945941,47.987149],[25.207743,47.891056],[24.866317,47.737526],[24.402056,47.981878],[23.760958,47.985598],[23.142236,48.096341],[22.710531,47.882194],[22.64082,48.15024],[22.085608,48.422264],[22.280842,48.825392],[22.558138,49.085738],[22.776419,49.027395],[22.51845,49.476774],[23.426508,50.308506],[23.922757,50.424881],[24.029986,50.705407],[23.527071,51.578454],[24.005078,51.617444],[24.553106,51.888461],[25.327788,51.910656],[26.337959,51.832289],[27.454066,51.592303],[28.241615,51.572227],[28.617613,51.427714],[28.992835,51.602044],[29.254938,51.368234],[30.157364,51.416138],[30.555117,51.319503],[30.619454,51.822806],[30.927549,52.042353],[31.785992,52.101678]]]}},{"type":"Feature","properties":{"ADMIN":"Poland","NAME_EN":"Poland","CONTINENT":"Europe","ADM0_A3":"POL","ISO_A3":"POL","NAME":"Poland","ISO_A2":"PL","NAME_ZH":"波兰"},"geometry":{"type":"Polygon","coordinates":[[[23.484128,53.912498],[23.527536,53.470122],[23.804935,53.089731],[23.799199,52.691099],[23.199494,52.486977],[23.508002,52.023647],[23.527071,51.578454],[24.029986,50.705407],[23.922757,50.424881],[23.426508,50.308506],[22.51845,49.476774],[22.776419,49.027395],[22.558138,49.085738],[21.607808,49.470107],[20.887955,49.328772],[20.415839,49.431453],[19.825023,49.217125],[19.320713,49.571574],[18.909575,49.435846],[18.853144,49.49623],[18.392914,49.988629],[17.649445,50.049038],[17.554567,50.362146],[16.868769,50.473974],[16.719476,50.215747],[16.176253,50.422607],[16.238627,50.697733],[15.490972,50.78473],[15.016996,51.106674],[14.607098,51.745188],[14.685026,52.089947],[14.4376,52.62485],[14.074521,52.981263],[14.353315,53.248171],[14.119686,53.757029],[14.8029,54.050706],[16.363477,54.513159],[17.622832,54.851536],[18.620859,54.682606],[18.696255,54.438719],[19.66064,54.426084],[20.892245,54.312525],[22.731099,54.327537],[23.243987,54.220567],[23.484128,53.912498]]]}},{"type":"Feature","properties":{"ADMIN":"Austria","NAME_EN":"Austria","CONTINENT":"Europe","ADM0_A3":"AUT","ISO_A3":"AUT","NAME":"Austria","ISO_A2":"AT","NAME_ZH":"奥地利"},"geometry":{"type":"Polygon","coordinates":[[[16.979667,48.123497],[16.903754,47.714866],[16.340584,47.712902],[16.534268,47.496171],[16.202298,46.852386],[16.011664,46.683611],[15.137092,46.658703],[14.632472,46.431817],[13.806475,46.509306],[12.376485,46.767559],[12.153088,47.115393],[11.164828,46.941579],[11.048556,46.751359],[10.442701,46.893546],[9.932448,46.920728],[9.47997,47.10281],[9.632932,47.347601],[9.594226,47.525058],[9.896068,47.580197],[10.402084,47.302488],[10.544504,47.566399],[11.426414,47.523766],[12.141357,47.703083],[12.62076,47.672388],[12.932627,47.467646],[13.025851,47.637584],[12.884103,48.289146],[13.243357,48.416115],[13.595946,48.877172],[14.338898,48.555305],[14.901447,48.964402],[15.253416,49.039074],[16.029647,48.733899],[16.499283,48.785808],[16.960288,48.596982],[16.879983,48.470013],[16.979667,48.123497]]]}},{"type":"Feature","properties":{"ADMIN":"Hungary","NAME_EN":"Hungary","CONTINENT":"Europe","ADM0_A3":"HUN","ISO_A3":"HUN","NAME":"Hungary","ISO_A2":"HU","NAME_ZH":"匈牙利"},"geometry":{"type":"Polygon","coordinates":[[[22.085608,48.422264],[22.64082,48.15024],[22.710531,47.882194],[22.099768,47.672439],[21.626515,46.994238],[21.021952,46.316088],[20.220192,46.127469],[19.596045,46.17173],[18.829838,45.908878],[18.829825,45.908872],[18.456062,45.759481],[17.630066,45.951769],[16.882515,46.380632],[16.564808,46.503751],[16.370505,46.841327],[16.202298,46.852386],[16.534268,47.496171],[16.340584,47.712902],[16.903754,47.714866],[16.979667,48.123497],[17.488473,47.867466],[17.857133,47.758429],[18.696513,47.880954],[18.777025,48.081768],[19.174365,48.111379],[19.661364,48.266615],[19.769471,48.202691],[20.239054,48.327567],[20.473562,48.56285],[20.801294,48.623854],[21.872236,48.319971],[22.085608,48.422264]]]}},{"type":"Feature","properties":{"ADMIN":"Moldova","NAME_EN":"Moldova","CONTINENT":"Europe","ADM0_A3":"MDA","ISO_A3":"MDA","NAME":"Moldova","ISO_A2":"MD","NAME_ZH":"摩尔多瓦"},"geometry":{"type":"Polygon","coordinates":[[[26.619337,48.220726],[26.857824,48.368211],[27.522537,48.467119],[28.259547,48.155562],[28.670891,48.118149],[29.122698,47.849095],[29.050868,47.510227],[29.415135,47.346645],[29.559674,46.928583],[29.908852,46.674361],[29.83821,46.525326],[30.024659,46.423937],[29.759972,46.349988],[29.170654,46.379262],[29.072107,46.517678],[28.862972,46.437889],[28.933717,46.25883],[28.659987,45.939987],[28.485269,45.596907],[28.233554,45.488283],[28.054443,45.944586],[28.160018,46.371563],[28.12803,46.810476],[27.551166,47.405117],[27.233873,47.826771],[26.924176,48.123264],[26.619337,48.220726]]]}},{"type":"Feature","properties":{"ADMIN":"Romania","NAME_EN":"Romania","CONTINENT":"Europe","ADM0_A3":"ROU","ISO_A3":"ROU","NAME":"Romania","ISO_A2":"RO","NAME_ZH":"罗马尼亚"},"geometry":{"type":"Polygon","coordinates":[[[28.233554,45.488283],[28.679779,45.304031],[29.149725,45.464925],[29.603289,45.293308],[29.626543,45.035391],[29.141612,44.82021],[28.837858,44.913874],[28.558081,43.707462],[27.970107,43.812468],[27.2424,44.175986],[26.065159,43.943494],[25.569272,43.688445],[24.100679,43.741051],[23.332302,43.897011],[22.944832,43.823785],[22.65715,44.234923],[22.474008,44.409228],[22.705726,44.578003],[22.459022,44.702517],[22.145088,44.478422],[21.562023,44.768947],[21.483526,45.18117],[20.874313,45.416375],[20.762175,45.734573],[20.220192,46.127469],[21.021952,46.316088],[21.626515,46.994238],[22.099768,47.672439],[22.710531,47.882194],[23.142236,48.096341],[23.760958,47.985598],[24.402056,47.981878],[24.866317,47.737526],[25.207743,47.891056],[25.945941,47.987149],[26.19745,48.220881],[26.619337,48.220726],[26.924176,48.123264],[27.233873,47.826771],[27.551166,47.405117],[28.12803,46.810476],[28.160018,46.371563],[28.054443,45.944586],[28.233554,45.488283]]]}},{"type":"Feature","properties":{"ADMIN":"Lithuania","NAME_EN":"Lithuania","CONTINENT":"Europe","ADM0_A3":"LTU","ISO_A3":"LTU","NAME":"Lithuania","ISO_A2":"LT","NAME_ZH":"立陶宛"},"geometry":{"type":"Polygon","coordinates":[[[26.494331,55.615107],[26.588279,55.167176],[25.768433,54.846963],[25.536354,54.282423],[24.450684,53.905702],[23.484128,53.912498],[23.243987,54.220567],[22.731099,54.327537],[22.651052,54.582741],[22.757764,54.856574],[22.315724,55.015299],[21.268449,55.190482],[21.0558,56.031076],[22.201157,56.337802],[23.878264,56.273671],[24.860684,56.372528],[25.000934,56.164531],[25.533047,56.100297],[26.494331,55.615107]]]}},{"type":"Feature","properties":{"ADMIN":"Latvia","NAME_EN":"Latvia","CONTINENT":"Europe","ADM0_A3":"LVA","ISO_A3":"LVA","NAME":"Latvia","ISO_A2":"LV","NAME_ZH":"拉脱维亚"},"geometry":{"type":"Polygon","coordinates":[[[27.288185,57.474528],[27.770016,57.244258],[27.855282,56.759326],[28.176709,56.16913],[27.10246,55.783314],[26.494331,55.615107],[25.533047,56.100297],[25.000934,56.164531],[24.860684,56.372528],[23.878264,56.273671],[22.201157,56.337802],[21.0558,56.031076],[21.090424,56.783873],[21.581866,57.411871],[22.524341,57.753374],[23.318453,57.006236],[24.12073,57.025693],[24.312863,57.793424],[25.164594,57.970157],[25.60281,57.847529],[26.463532,57.476389],[27.288185,57.474528]]]}},{"type":"Feature","properties":{"ADMIN":"Estonia","NAME_EN":"Estonia","CONTINENT":"Europe","ADM0_A3":"EST","ISO_A3":"EST","NAME":"Estonia","ISO_A2":"EE","NAME_ZH":"爱沙尼亚"},"geometry":{"type":"Polygon","coordinates":[[[27.981127,59.475373],[27.98112,59.47537],[28.131699,59.300825],[27.42015,58.72457],[27.716686,57.791899],[27.288185,57.474528],[26.463532,57.476389],[25.60281,57.847529],[25.164594,57.970157],[24.312863,57.793424],[24.428928,58.383413],[24.061198,58.257375],[23.42656,58.612753],[23.339795,59.18724],[24.604214,59.465854],[25.864189,59.61109],[26.949136,59.445803],[27.981114,59.475388],[27.981127,59.475373]]]}},{"type":"Feature","properties":{"ADMIN":"Germany","NAME_EN":"Germany","CONTINENT":"Europe","ADM0_A3":"DEU","ISO_A3":"DEU","NAME":"Germany","ISO_A2":"DE","NAME_ZH":"德国"},"geometry":{"type":"Polygon","coordinates":[[[14.119686,53.757029],[14.353315,53.248171],[14.074521,52.981263],[14.4376,52.62485],[14.685026,52.089947],[14.607098,51.745188],[15.016996,51.106674],[14.570718,51.002339],[14.307013,51.117268],[14.056228,50.926918],[13.338132,50.733234],[12.966837,50.484076],[12.240111,50.266338],[12.415191,49.969121],[12.521024,49.547415],[13.031329,49.307068],[13.595946,48.877172],[13.243357,48.416115],[12.884103,48.289146],[13.025851,47.637584],[12.932627,47.467646],[12.62076,47.672388],[12.141357,47.703083],[11.426414,47.523766],[10.544504,47.566399],[10.402084,47.302488],[9.896068,47.580197],[9.594226,47.525058],[8.522612,47.830828],[8.317301,47.61358],[7.466759,47.620582],[7.593676,48.333019],[8.099279,49.017784],[6.65823,49.201958],[6.18632,49.463803],[6.242751,49.902226],[6.043073,50.128052],[6.156658,50.803721],[5.988658,51.851616],[6.589397,51.852029],[6.84287,52.22844],[7.092053,53.144043],[6.90514,53.482162],[7.100425,53.693932],[7.936239,53.748296],[8.121706,53.527792],[8.800734,54.020786],[8.572118,54.395646],[8.526229,54.962744],[9.282049,54.830865],[9.921906,54.983104],[9.93958,54.596642],[10.950112,54.363607],[10.939467,54.008693],[11.956252,54.196486],[12.51844,54.470371],[13.647467,54.075511],[14.119686,53.757029]]]}},{"type":"Feature","properties":{"ADMIN":"Bulgaria","NAME_EN":"Bulgaria","CONTINENT":"Europe","ADM0_A3":"BGR","ISO_A3":"BGR","NAME":"Bulgaria","ISO_A2":"BG","NAME_ZH":"保加利亚"},"geometry":{"type":"Polygon","coordinates":[[[22.65715,44.234923],[22.944832,43.823785],[23.332302,43.897011],[24.100679,43.741051],[25.569272,43.688445],[26.065159,43.943494],[27.2424,44.175986],[27.970107,43.812468],[28.558081,43.707462],[28.039095,43.293172],[27.673898,42.577892],[27.99672,42.007359],[27.135739,42.141485],[26.117042,41.826905],[26.106138,41.328899],[25.197201,41.234486],[24.492645,41.583896],[23.692074,41.309081],[22.952377,41.337994],[22.881374,41.999297],[22.380526,42.32026],[22.545012,42.461362],[22.436595,42.580321],[22.604801,42.898519],[22.986019,43.211161],[22.500157,43.642814],[22.410446,44.008063],[22.65715,44.234923]]]}},{"type":"Feature","properties":{"ADMIN":"Greece","NAME_EN":"Greece","CONTINENT":"Europe","ADM0_A3":"GRC","ISO_A3":"GRC","NAME":"Greece","ISO_A2":"GR","NAME_ZH":"希腊"},"geometry":{"type":"MultiPolygon","coordinates":[[[[26.290003,35.29999],[26.164998,35.004995],[24.724982,34.919988],[24.735007,35.084991],[23.514978,35.279992],[23.69998,35.705004],[24.246665,35.368022],[25.025015,35.424996],[25.769208,35.354018],[25.745023,35.179998],[26.290003,35.29999]]],[[[22.952377,41.337994],[23.692074,41.309081],[24.492645,41.583896],[25.197201,41.234486],[26.106138,41.328899],[26.117042,41.826905],[26.604196,41.562115],[26.294602,40.936261],[26.056942,40.824123],[25.447677,40.852545],[24.925848,40.947062],[23.714811,40.687129],[24.407999,40.124993],[23.899968,39.962006],[23.342999,39.960998],[22.813988,40.476005],[22.626299,40.256561],[22.849748,39.659311],[23.350027,39.190011],[22.973099,38.970903],[23.530016,38.510001],[24.025025,38.219993],[24.040011,37.655015],[23.115003,37.920011],[23.409972,37.409991],[22.774972,37.30501],[23.154225,36.422506],[22.490028,36.41],[21.670026,36.844986],[21.295011,37.644989],[21.120034,38.310323],[20.730032,38.769985],[20.217712,39.340235],[20.150016,39.624998],[20.615,40.110007],[20.674997,40.435],[20.99999,40.580004],[21.02004,40.842727],[21.674161,40.931275],[22.055378,41.149866],[22.597308,41.130487],[22.76177,41.3048],[22.952377,41.337994]]]]}},{"type":"Feature","properties":{"ADMIN":"Turkey","NAME_EN":"Turkey","CONTINENT":"Asia","ADM0_A3":"TUR","ISO_A3":"TUR","NAME":"Turkey","ISO_A2":"TR","NAME_ZH":"土耳其"},"geometry":{"type":"MultiPolygon","coordinates":[[[[44.772677,37.170437],[44.293452,37.001514],[43.942259,37.256228],[42.779126,37.385264],[42.349591,37.229873],[41.212089,37.074352],[40.673259,37.091276],[39.52258,36.716054],[38.699891,36.712927],[38.167727,36.90121],[37.066761,36.623036],[36.739494,36.81752],[36.685389,36.259699],[36.41755,36.040617],[36.149763,35.821535],[35.782085,36.274995],[36.160822,36.650606],[35.550936,36.565443],[34.714553,36.795532],[34.026895,36.21996],[32.509158,36.107564],[31.699595,36.644275],[30.621625,36.677865],[30.391096,36.262981],[29.699976,36.144357],[28.732903,36.676831],[27.641187,36.658822],[27.048768,37.653361],[26.318218,38.208133],[26.8047,38.98576],[26.170785,39.463612],[27.28002,40.420014],[28.819978,40.460011],[29.240004,41.219991],[31.145934,41.087622],[32.347979,41.736264],[33.513283,42.01896],[35.167704,42.040225],[36.913127,41.335358],[38.347665,40.948586],[39.512607,41.102763],[40.373433,41.013673],[41.554084,41.535656],[42.619549,41.583173],[43.582746,41.092143],[43.752658,40.740201],[43.656436,40.253564],[44.400009,40.005],[44.79399,39.713003],[44.109225,39.428136],[44.421403,38.281281],[44.225756,37.971584],[44.77267,37.17045],[44.772677,37.170437]]],[[[26.117042,41.826905],[27.135739,42.141485],[27.99672,42.007359],[28.115525,41.622886],[28.988443,41.299934],[28.806438,41.054962],[27.619017,40.999823],[27.192377,40.690566],[26.358009,40.151994],[26.043351,40.617754],[26.056942,40.824123],[26.294602,40.936261],[26.604196,41.562115],[26.117042,41.826905]]]]}},{"type":"Feature","properties":{"ADMIN":"Albania","NAME_EN":"Albania","CONTINENT":"Europe","ADM0_A3":"ALB","ISO_A3":"ALB","NAME":"Albania","ISO_A2":"AL","NAME_ZH":"阿尔巴尼亚"},"geometry":{"type":"Polygon","coordinates":[[[21.02004,40.842727],[20.99999,40.580004],[20.674997,40.435],[20.615,40.110007],[20.150016,39.624998],[19.98,39.694993],[19.960002,39.915006],[19.406082,40.250773],[19.319059,40.72723],[19.40355,41.409566],[19.540027,41.719986],[19.371769,41.877548],[19.371768,41.877551],[19.304486,42.195745],[19.738051,42.688247],[19.801613,42.500093],[20.0707,42.58863],[20.283755,42.32026],[20.52295,42.21787],[20.590247,41.855409],[20.590247,41.855404],[20.463175,41.515089],[20.605182,41.086226],[21.02004,40.842727]]]}},{"type":"Feature","properties":{"ADMIN":"Croatia","NAME_EN":"Croatia","CONTINENT":"Europe","ADM0_A3":"HRV","ISO_A3":"HRV","NAME":"Croatia","ISO_A2":"HR","NAME_ZH":"克罗地亚"},"geometry":{"type":"Polygon","coordinates":[[[16.564808,46.503751],[16.882515,46.380632],[17.630066,45.951769],[18.456062,45.759481],[18.829825,45.908872],[19.072769,45.521511],[19.390476,45.236516],[19.005485,44.860234],[18.553214,45.08159],[17.861783,45.06774],[17.002146,45.233777],[16.534939,45.211608],[16.318157,45.004127],[15.959367,45.233777],[15.750026,44.818712],[16.23966,44.351143],[16.456443,44.04124],[16.916156,43.667722],[17.297373,43.446341],[17.674922,43.028563],[18.56,42.65],[18.450017,42.479992],[18.450016,42.479991],[17.50997,42.849995],[16.930006,43.209998],[16.015385,43.507215],[15.174454,44.243191],[15.37625,44.317915],[14.920309,44.738484],[14.901602,45.07606],[14.258748,45.233777],[13.952255,44.802124],[13.656976,45.136935],[13.679403,45.484149],[13.71506,45.500324],[14.411968,45.466166],[14.595109,45.634941],[14.935244,45.471695],[15.327675,45.452316],[15.323954,45.731783],[15.67153,45.834154],[15.768733,46.238108],[16.564808,46.503751]]]}},{"type":"Feature","properties":{"ADMIN":"Switzerland","NAME_EN":"Switzerland","CONTINENT":"Europe","ADM0_A3":"CHE","ISO_A3":"CHE","NAME":"Switzerland","ISO_A2":"CH","NAME_ZH":"瑞士"},"geometry":{"type":"Polygon","coordinates":[[[9.594226,47.525058],[9.632932,47.347601],[9.47997,47.10281],[9.932448,46.920728],[10.442701,46.893546],[10.363378,46.483571],[9.922837,46.314899],[9.182882,46.440215],[8.966306,46.036932],[8.489952,46.005151],[8.31663,46.163642],[7.755992,45.82449],[7.273851,45.776948],[6.843593,45.991147],[6.5001,46.429673],[6.022609,46.27299],[6.037389,46.725779],[6.768714,47.287708],[6.736571,47.541801],[7.192202,47.449766],[7.466759,47.620582],[8.317301,47.61358],[8.522612,47.830828],[9.594226,47.525058]]]}},{"type":"Feature","properties":{"ADMIN":"Luxembourg","NAME_EN":"Luxembourg","CONTINENT":"Europe","ADM0_A3":"LUX","ISO_A3":"LUX","NAME":"Luxembourg","ISO_A2":"LU","NAME_ZH":"卢森堡"},"geometry":{"type":"Polygon","coordinates":[[[6.043073,50.128052],[6.242751,49.902226],[6.18632,49.463803],[5.897759,49.442667],[5.674052,49.529484],[5.782417,50.090328],[6.043073,50.128052]]]}},{"type":"Feature","properties":{"ADMIN":"Belgium","NAME_EN":"Belgium","CONTINENT":"Europe","ADM0_A3":"BEL","ISO_A3":"BEL","NAME":"Belgium","ISO_A2":"BE","NAME_ZH":"比利时"},"geometry":{"type":"Polygon","coordinates":[[[6.156658,50.803721],[6.043073,50.128052],[5.782417,50.090328],[5.674052,49.529484],[4.799222,49.985373],[4.286023,49.907497],[3.588184,50.378992],[3.123252,50.780363],[2.658422,50.796848],[2.513573,51.148506],[3.314971,51.345781],[3.315011,51.345777],[3.314971,51.345755],[4.047071,51.267259],[4.973991,51.475024],[5.606976,51.037298],[6.156658,50.803721]]]}},{"type":"Feature","properties":{"ADMIN":"Netherlands","NAME_EN":"Netherlands","CONTINENT":"Europe","ADM0_A3":"NLD","ISO_A3":"NLD","NAME":"Netherlands","ISO_A2":"NL","NAME_ZH":"荷兰"},"geometry":{"type":"Polygon","coordinates":[[[6.90514,53.482162],[7.092053,53.144043],[6.84287,52.22844],[6.589397,51.852029],[5.988658,51.851616],[6.156658,50.803721],[5.606976,51.037298],[4.973991,51.475024],[4.047071,51.267259],[3.314971,51.345755],[3.315011,51.345777],[3.830289,51.620545],[4.705997,53.091798],[6.074183,53.510403],[6.90514,53.482162]]]}},{"type":"Feature","properties":{"ADMIN":"Portugal","NAME_EN":"Portugal","CONTINENT":"Europe","ADM0_A3":"PRT","ISO_A3":"PRT","NAME":"Portugal","ISO_A2":"PT","NAME_ZH":"葡萄牙"},"geometry":{"type":"Polygon","coordinates":[[[-9.034818,41.880571],[-8.671946,42.134689],[-8.263857,42.280469],[-8.013175,41.790886],[-7.422513,41.792075],[-7.251309,41.918346],[-6.668606,41.883387],[-6.389088,41.381815],[-6.851127,41.111083],[-6.86402,40.330872],[-7.026413,40.184524],[-7.066592,39.711892],[-7.498632,39.629571],[-7.098037,39.030073],[-7.374092,38.373059],[-7.029281,38.075764],[-7.166508,37.803894],[-7.537105,37.428904],[-7.453726,37.097788],[-7.855613,36.838269],[-8.382816,36.97888],[-8.898857,36.868809],[-8.746101,37.651346],[-8.839998,38.266243],[-9.287464,38.358486],[-9.526571,38.737429],[-9.446989,39.392066],[-9.048305,39.755093],[-8.977353,40.159306],[-8.768684,40.760639],[-8.790853,41.184334],[-8.990789,41.543459],[-9.034818,41.880571]]]}},{"type":"Feature","properties":{"ADMIN":"Spain","NAME_EN":"Spain","CONTINENT":"Europe","ADM0_A3":"ESP","ISO_A3":"ESP","NAME":"Spain","ISO_A2":"ES","NAME_ZH":"西班牙"},"geometry":{"type":"Polygon","coordinates":[[[-7.453726,37.097788],[-7.537105,37.428904],[-7.166508,37.803894],[-7.029281,38.075764],[-7.374092,38.373059],[-7.098037,39.030073],[-7.498632,39.629571],[-7.066592,39.711892],[-7.026413,40.184524],[-6.86402,40.330872],[-6.851127,41.111083],[-6.389088,41.381815],[-6.668606,41.883387],[-7.251309,41.918346],[-7.422513,41.792075],[-8.013175,41.790886],[-8.263857,42.280469],[-8.671946,42.134689],[-9.034818,41.880571],[-8.984433,42.592775],[-9.392884,43.026625],[-7.97819,43.748338],[-6.754492,43.567909],[-5.411886,43.57424],[-4.347843,43.403449],[-3.517532,43.455901],[-1.901351,43.422802],[-1.502771,43.034014],[0.338047,42.579546],[0.701591,42.795734],[1.826793,42.343385],[2.985999,42.473015],[3.039484,41.89212],[2.091842,41.226089],[0.810525,41.014732],[0.721331,40.678318],[0.106692,40.123934],[-0.278711,39.309978],[0.111291,38.738514],[-0.467124,38.292366],[-0.683389,37.642354],[-1.438382,37.443064],[-2.146453,36.674144],[-3.415781,36.6589],[-4.368901,36.677839],[-4.995219,36.324708],[-5.37716,35.94685],[-5.866432,36.029817],[-6.236694,36.367677],[-6.520191,36.942913],[-7.453726,37.097788]]]}},{"type":"Feature","properties":{"ADMIN":"Ireland","NAME_EN":"Ireland","CONTINENT":"Europe","ADM0_A3":"IRL","ISO_A3":"IRL","NAME":"Ireland","ISO_A2":"IE","NAME_ZH":"爱尔兰"},"geometry":{"type":"Polygon","coordinates":[[[-6.197885,53.867565],[-6.032985,53.153164],[-6.788857,52.260118],[-8.561617,51.669301],[-9.977086,51.820455],[-9.166283,52.864629],[-9.688525,53.881363],[-8.327987,54.664519],[-7.572168,55.131622],[-7.366031,54.595841],[-7.572168,54.059956],[-6.95373,54.073702],[-6.197885,53.867565]]]}},{"type":"Feature","properties":{"ADMIN":"New Caledonia","NAME_EN":"New Caledonia","CONTINENT":"Oceania","ADM0_A3":"NCL","ISO_A3":"NCL","NAME":"New Caledonia","ISO_A2":"NC","NAME_ZH":"新喀里多尼亚"},"geometry":{"type":"Polygon","coordinates":[[[165.77999,-21.080005],[166.599991,-21.700019],[167.120011,-22.159991],[166.740035,-22.399976],[166.189732,-22.129708],[165.474375,-21.679607],[164.829815,-21.14982],[164.167995,-20.444747],[164.029606,-20.105646],[164.459967,-20.120012],[165.020036,-20.459991],[165.460009,-20.800022],[165.77999,-21.080005]]]}},{"type":"Feature","properties":{"ADMIN":"Solomon Islands","NAME_EN":"Solomon Islands","CONTINENT":"Oceania","ADM0_A3":"SLB","ISO_A3":"SLB","NAME":"Solomon Is.","ISO_A2":"SB","NAME_ZH":"所罗门群岛"},"geometry":{"type":"MultiPolygon","coordinates":[[[[162.119025,-10.482719],[162.398646,-10.826367],[161.700032,-10.820011],[161.319797,-10.204751],[161.917383,-10.446701],[162.119025,-10.482719]]],[[[161.679982,-9.599982],[161.529397,-9.784312],[160.788253,-8.917543],[160.579997,-8.320009],[160.920028,-8.320009],[161.280006,-9.120011],[161.679982,-9.599982]]],[[[160.852229,-9.872937],[160.462588,-9.89521],[159.849447,-9.794027],[159.640003,-9.63998],[159.702945,-9.24295],[160.362956,-9.400304],[160.688518,-9.610162],[160.852229,-9.872937]]],[[[159.640003,-8.020027],[159.875027,-8.33732],[159.917402,-8.53829],[159.133677,-8.114181],[158.586114,-7.754824],[158.21115,-7.421872],[158.359978,-7.320018],[158.820001,-7.560003],[159.640003,-8.020027]]],[[[157.14,-7.021638],[157.538426,-7.34782],[157.33942,-7.404767],[156.90203,-7.176874],[156.491358,-6.765943],[156.542828,-6.599338],[157.14,-7.021638]]]]}},{"type":"Feature","properties":{"ADMIN":"New Zealand","NAME_EN":"New Zealand","CONTINENT":"Oceania","ADM0_A3":"NZL","ISO_A3":"NZL","NAME":"New Zealand","ISO_A2":"NZ","NAME_ZH":"新西兰"},"geometry":{"type":"MultiPolygon","coordinates":[[[[176.885824,-40.065978],[176.508017,-40.604808],[176.01244,-41.289624],[175.239567,-41.688308],[175.067898,-41.425895],[174.650973,-41.281821],[175.22763,-40.459236],[174.900157,-39.908933],[173.824047,-39.508854],[173.852262,-39.146602],[174.574802,-38.797683],[174.743474,-38.027808],[174.697017,-37.381129],[174.292028,-36.711092],[174.319004,-36.534824],[173.840997,-36.121981],[173.054171,-35.237125],[172.636005,-34.529107],[173.007042,-34.450662],[173.551298,-35.006183],[174.32939,-35.265496],[174.612009,-36.156397],[175.336616,-37.209098],[175.357596,-36.526194],[175.808887,-36.798942],[175.95849,-37.555382],[176.763195,-37.881253],[177.438813,-37.961248],[178.010354,-37.579825],[178.517094,-37.695373],[178.274731,-38.582813],[177.97046,-39.166343],[177.206993,-39.145776],[176.939981,-39.449736],[177.032946,-39.879943],[176.885824,-40.065978]]],[[[169.667815,-43.555326],[170.52492,-43.031688],[171.12509,-42.512754],[171.569714,-41.767424],[171.948709,-41.514417],[172.097227,-40.956104],[172.79858,-40.493962],[173.020375,-40.919052],[173.247234,-41.331999],[173.958405,-40.926701],[174.247587,-41.349155],[174.248517,-41.770008],[173.876447,-42.233184],[173.22274,-42.970038],[172.711246,-43.372288],[173.080113,-43.853344],[172.308584,-43.865694],[171.452925,-44.242519],[171.185138,-44.897104],[170.616697,-45.908929],[169.831422,-46.355775],[169.332331,-46.641235],[168.411354,-46.619945],[167.763745,-46.290197],[166.676886,-46.219917],[166.509144,-45.852705],[167.046424,-45.110941],[168.303763,-44.123973],[168.949409,-43.935819],[169.667815,-43.555326]]]]}},{"type":"Feature","properties":{"ADMIN":"Australia","NAME_EN":"Australia","CONTINENT":"Oceania","ADM0_A3":"AUS","ISO_A3":"AUS","NAME":"Australia","ISO_A2":"AU","NAME_ZH":"澳大利亚"},"geometry":{"type":"MultiPolygon","coordinates":[[[[147.689259,-40.808258],[148.289068,-40.875438],[148.359865,-42.062445],[148.017301,-42.407024],[147.914052,-43.211522],[147.564564,-42.937689],[146.870343,-43.634597],[146.663327,-43.580854],[146.048378,-43.549745],[145.43193,-42.693776],[145.29509,-42.03361],[144.718071,-41.162552],[144.743755,-40.703975],[145.397978,-40.792549],[146.364121,-41.137695],[146.908584,-41.000546],[147.689259,-40.808258]]],[[[126.148714,-32.215966],[125.088623,-32.728751],[124.221648,-32.959487],[124.028947,-33.483847],[123.659667,-33.890179],[122.811036,-33.914467],[122.183064,-34.003402],[121.299191,-33.821036],[120.580268,-33.930177],[119.893695,-33.976065],[119.298899,-34.509366],[119.007341,-34.464149],[118.505718,-34.746819],[118.024972,-35.064733],[117.295507,-35.025459],[116.625109,-35.025097],[115.564347,-34.386428],[115.026809,-34.196517],[115.048616,-33.623425],[115.545123,-33.487258],[115.714674,-33.259572],[115.679379,-32.900369],[115.801645,-32.205062],[115.689611,-31.612437],[115.160909,-30.601594],[114.997043,-30.030725],[115.040038,-29.461095],[114.641974,-28.810231],[114.616498,-28.516399],[114.173579,-28.118077],[114.048884,-27.334765],[113.477498,-26.543134],[113.338953,-26.116545],[113.778358,-26.549025],[113.440962,-25.621278],[113.936901,-25.911235],[114.232852,-26.298446],[114.216161,-25.786281],[113.721255,-24.998939],[113.625344,-24.683971],[113.393523,-24.384764],[113.502044,-23.80635],[113.706993,-23.560215],[113.843418,-23.059987],[113.736552,-22.475475],[114.149756,-21.755881],[114.225307,-22.517488],[114.647762,-21.82952],[115.460167,-21.495173],[115.947373,-21.068688],[116.711615,-20.701682],[117.166316,-20.623599],[117.441545,-20.746899],[118.229559,-20.374208],[118.836085,-20.263311],[118.987807,-20.044203],[119.252494,-19.952942],[119.805225,-19.976506],[120.85622,-19.683708],[121.399856,-19.239756],[121.655138,-18.705318],[122.241665,-18.197649],[122.286624,-17.798603],[122.312772,-17.254967],[123.012574,-16.4052],[123.433789,-17.268558],[123.859345,-17.069035],[123.503242,-16.596506],[123.817073,-16.111316],[124.258287,-16.327944],[124.379726,-15.56706],[124.926153,-15.0751],[125.167275,-14.680396],[125.670087,-14.51007],[125.685796,-14.230656],[126.125149,-14.347341],[126.142823,-14.095987],[126.582589,-13.952791],[127.065867,-13.817968],[127.804633,-14.276906],[128.35969,-14.86917],[128.985543,-14.875991],[129.621473,-14.969784],[129.4096,-14.42067],[129.888641,-13.618703],[130.339466,-13.357376],[130.183506,-13.10752],[130.617795,-12.536392],[131.223495,-12.183649],[131.735091,-12.302453],[132.575298,-12.114041],[132.557212,-11.603012],[131.824698,-11.273782],[132.357224,-11.128519],[133.019561,-11.376411],[133.550846,-11.786515],[134.393068,-12.042365],[134.678632,-11.941183],[135.298491,-12.248606],[135.882693,-11.962267],[136.258381,-12.049342],[136.492475,-11.857209],[136.95162,-12.351959],[136.685125,-12.887223],[136.305407,-13.29123],[135.961758,-13.324509],[136.077617,-13.724278],[135.783836,-14.223989],[135.428664,-14.715432],[135.500184,-14.997741],[136.295175,-15.550265],[137.06536,-15.870762],[137.580471,-16.215082],[138.303217,-16.807604],[138.585164,-16.806622],[139.108543,-17.062679],[139.260575,-17.371601],[140.215245,-17.710805],[140.875463,-17.369069],[141.07111,-16.832047],[141.274095,-16.38887],[141.398222,-15.840532],[141.702183,-15.044921],[141.56338,-14.561333],[141.63552,-14.270395],[141.519869,-13.698078],[141.65092,-12.944688],[141.842691,-12.741548],[141.68699,-12.407614],[141.928629,-11.877466],[142.118488,-11.328042],[142.143706,-11.042737],[142.51526,-10.668186],[142.79731,-11.157355],[142.866763,-11.784707],[143.115947,-11.90563],[143.158632,-12.325656],[143.522124,-12.834358],[143.597158,-13.400422],[143.561811,-13.763656],[143.922099,-14.548311],[144.563714,-14.171176],[144.894908,-14.594458],[145.374724,-14.984976],[145.271991,-15.428205],[145.48526,-16.285672],[145.637033,-16.784918],[145.888904,-16.906926],[146.160309,-17.761655],[146.063674,-18.280073],[146.387478,-18.958274],[147.471082,-19.480723],[148.177602,-19.955939],[148.848414,-20.39121],[148.717465,-20.633469],[149.28942,-21.260511],[149.678337,-22.342512],[150.077382,-22.122784],[150.482939,-22.556142],[150.727265,-22.402405],[150.899554,-23.462237],[151.609175,-24.076256],[152.07354,-24.457887],[152.855197,-25.267501],[153.136162,-26.071173],[153.161949,-26.641319],[153.092909,-27.2603],[153.569469,-28.110067],[153.512108,-28.995077],[153.339095,-29.458202],[153.069241,-30.35024],[153.089602,-30.923642],[152.891578,-31.640446],[152.450002,-32.550003],[151.709117,-33.041342],[151.343972,-33.816023],[151.010555,-34.31036],[150.714139,-35.17346],[150.32822,-35.671879],[150.075212,-36.420206],[149.946124,-37.109052],[149.997284,-37.425261],[149.423882,-37.772681],[148.304622,-37.809061],[147.381733,-38.219217],[146.922123,-38.606532],[146.317922,-39.035757],[145.489652,-38.593768],[144.876976,-38.417448],[145.032212,-37.896188],[144.485682,-38.085324],[143.609974,-38.809465],[142.745427,-38.538268],[142.17833,-38.380034],[141.606582,-38.308514],[140.638579,-38.019333],[139.992158,-37.402936],[139.806588,-36.643603],[139.574148,-36.138362],[139.082808,-35.732754],[138.120748,-35.612296],[138.449462,-35.127261],[138.207564,-34.384723],[137.71917,-35.076825],[136.829406,-35.260535],[137.352371,-34.707339],[137.503886,-34.130268],[137.890116,-33.640479],[137.810328,-32.900007],[136.996837,-33.752771],[136.372069,-34.094766],[135.989043,-34.890118],[135.208213,-34.47867],[135.239218,-33.947953],[134.613417,-33.222778],[134.085904,-32.848072],[134.273903,-32.617234],[132.990777,-32.011224],[132.288081,-31.982647],[131.326331,-31.495803],[129.535794,-31.590423],[128.240938,-31.948489],[127.102867,-32.282267],[126.148714,-32.215966]]]]}},{"type":"Feature","properties":{"ADMIN":"Sri Lanka","NAME_EN":"Sri Lanka","CONTINENT":"Asia","ADM0_A3":"LKA","ISO_A3":"LKA","NAME":"Sri Lanka","ISO_A2":"LK","NAME_ZH":"斯里兰卡"},"geometry":{"type":"Polygon","coordinates":[[[81.787959,7.523055],[81.637322,6.481775],[81.21802,6.197141],[80.348357,5.96837],[79.872469,6.763463],[79.695167,8.200843],[80.147801,9.824078],[80.838818,9.268427],[81.304319,8.564206],[81.787959,7.523055]]]}},{"type":"Feature","properties":{"ADMIN":"China","NAME_EN":"People's Republic of China","CONTINENT":"Asia","ADM0_A3":"CHN","ISO_A3":"CHN","NAME":"China","ISO_A2":"CN","NAME_ZH":"中国"},"geometry":{"type":"MultiPolygon","coordinates":[[[[109.47521,18.197701],[108.655208,18.507682],[108.626217,19.367888],[109.119056,19.821039],[110.211599,20.101254],[110.786551,20.077534],[111.010051,19.69593],[110.570647,19.255879],[110.339188,18.678395],[109.47521,18.197701]]],[[[80.25999,42.349999],[80.18015,42.920068],[80.866206,43.180362],[79.966106,44.917517],[81.947071,45.317027],[82.458926,45.53965],[83.180484,47.330031],[85.16429,47.000956],[85.720484,47.452969],[85.768233,48.455751],[86.598776,48.549182],[87.35997,49.214981],[87.751264,49.297198],[88.013832,48.599463],[88.854298,48.069082],[90.280826,47.693549],[90.970809,46.888146],[90.585768,45.719716],[90.94554,45.286073],[92.133891,45.115076],[93.480734,44.975472],[94.688929,44.352332],[95.306875,44.241331],[95.762455,43.319449],[96.349396,42.725635],[97.451757,42.74889],[99.515817,42.524691],[100.845866,42.663804],[101.83304,42.514873],[103.312278,41.907468],[104.522282,41.908347],[104.964994,41.59741],[106.129316,42.134328],[107.744773,42.481516],[109.243596,42.519446],[110.412103,42.871234],[111.129682,43.406834],[111.829588,43.743118],[111.667737,44.073176],[111.348377,44.457442],[111.873306,45.102079],[112.436062,45.011646],[113.463907,44.808893],[114.460332,45.339817],[115.985096,45.727235],[116.717868,46.388202],[117.421701,46.672733],[118.874326,46.805412],[119.66327,46.69268],[119.772824,47.048059],[118.866574,47.74706],[118.064143,48.06673],[117.295507,47.697709],[116.308953,47.85341],[115.742837,47.726545],[115.485282,48.135383],[116.191802,49.134598],[116.678801,49.888531],[117.879244,49.510983],[119.288461,50.142883],[119.27939,50.58292],[120.18208,51.64355],[120.7382,51.96411],[120.725789,52.516226],[120.177089,52.753886],[121.003085,53.251401],[122.245748,53.431726],[123.57147,53.4588],[125.068211,53.161045],[125.946349,52.792799],[126.564399,51.784255],[126.939157,51.353894],[127.287456,50.739797],[127.6574,49.76027],[129.397818,49.4406],[130.582293,48.729687],[130.98726,47.79013],[132.50669,47.78896],[133.373596,48.183442],[135.026311,48.47823],[134.50081,47.57845],[134.11235,47.21248],[133.769644,46.116927],[133.09712,45.14409],[131.883454,45.321162],[131.02519,44.96796],[131.288555,44.11152],[131.144688,42.92999],[130.633866,42.903015],[130.64,42.395024],[129.994267,42.985387],[129.596669,42.424982],[128.052215,41.994285],[128.208433,41.466772],[127.343783,41.503152],[126.869083,41.816569],[126.182045,41.107336],[125.079942,40.569824],[124.265625,39.928493],[122.86757,39.637788],[122.131388,39.170452],[121.054554,38.897471],[121.585995,39.360854],[121.376757,39.750261],[122.168595,40.422443],[121.640359,40.94639],[120.768629,40.593388],[119.639602,39.898056],[119.023464,39.252333],[118.042749,39.204274],[117.532702,38.737636],[118.059699,38.061476],[118.87815,37.897325],[118.911636,37.448464],[119.702802,37.156389],[120.823457,37.870428],[121.711259,37.481123],[122.357937,37.454484],[122.519995,36.930614],[121.104164,36.651329],[120.637009,36.11144],[119.664562,35.609791],[119.151208,34.909859],[120.227525,34.360332],[120.620369,33.376723],[121.229014,32.460319],[121.908146,31.692174],[121.891919,30.949352],[121.264257,30.676267],[121.503519,30.142915],[122.092114,29.83252],[121.938428,29.018022],[121.684439,28.225513],[121.125661,28.135673],[120.395473,27.053207],[119.585497,25.740781],[118.656871,24.547391],[117.281606,23.624501],[115.890735,22.782873],[114.763827,22.668074],[114.152547,22.22376],[113.80678,22.54834],[113.241078,22.051367],[111.843592,21.550494],[110.785466,21.397144],[110.444039,20.341033],[109.889861,20.282457],[109.627655,21.008227],[109.864488,21.395051],[108.522813,21.715212],[108.05018,21.55238],[107.04342,21.811899],[106.567273,22.218205],[106.725403,22.794268],[105.811247,22.976892],[105.329209,23.352063],[104.476858,22.81915],[103.504515,22.703757],[102.706992,22.708795],[102.170436,22.464753],[101.652018,22.318199],[101.80312,21.174367],[101.270026,21.201652],[101.180005,21.436573],[101.150033,21.849984],[100.416538,21.558839],[99.983489,21.742937],[99.240899,22.118314],[99.531992,22.949039],[98.898749,23.142722],[98.660262,24.063286],[97.60472,23.897405],[97.724609,25.083637],[98.671838,25.918703],[98.712094,26.743536],[98.68269,27.508812],[98.246231,27.747221],[97.911988,28.335945],[97.327114,28.261583],[96.248833,28.411031],[96.586591,28.83098],[96.117679,29.452802],[95.404802,29.031717],[94.56599,29.277438],[93.413348,28.640629],[92.503119,27.896876],[91.696657,27.771742],[91.258854,28.040614],[90.730514,28.064954],[90.015829,28.296439],[89.47581,28.042759],[88.814248,27.299316],[88.730326,28.086865],[88.120441,27.876542],[86.954517,27.974262],[85.82332,28.203576],[85.011638,28.642774],[84.23458,28.839894],[83.898993,29.320226],[83.337115,29.463732],[82.327513,30.115268],[81.525804,30.422717],[81.111256,30.183481],[79.721367,30.882715],[78.738894,31.515906],[78.458446,32.618164],[79.176129,32.48378],[79.208892,32.994395],[78.811086,33.506198],[78.912269,34.321936],[77.837451,35.49401],[76.192848,35.898403],[75.896897,36.666806],[75.158028,37.133031],[74.980002,37.41999],[74.829986,37.990007],[74.864816,38.378846],[74.257514,38.606507],[73.928852,38.505815],[73.675379,39.431237],[73.960013,39.660008],[73.822244,39.893973],[74.776862,40.366425],[75.467828,40.562072],[76.526368,40.427946],[76.904484,41.066486],[78.187197,41.185316],[78.543661,41.582243],[80.11943,42.123941],[80.25999,42.349999]]]]}},{"type":"Feature","properties":{"ADMIN":"Taiwan, China","NAME_EN":"Taiwan, China","CONTINENT":"Asia","ADM0_A3":"TWN","ISO_A3":"TWN","NAME":"Taiwan, China","ISO_A2":"TW","NAME_ZH":"中国(台湾)"},"geometry":{"type":"Polygon","coordinates":[[[121.777818,24.394274],[121.175632,22.790857],[120.74708,21.970571],[120.220083,22.814861],[120.106189,23.556263],[120.69468,24.538451],[121.495044,25.295459],[121.951244,24.997596],[121.777818,24.394274]]]}},{"type":"Feature","properties":{"ADMIN":"Italy","NAME_EN":"Italy","CONTINENT":"Europe","ADM0_A3":"ITA","ISO_A3":"ITA","NAME":"Italy","ISO_A2":"IT","NAME_ZH":"意大利"},"geometry":{"type":"MultiPolygon","coordinates":[[[[10.442701,46.893546],[11.048556,46.751359],[11.164828,46.941579],[12.153088,47.115393],[12.376485,46.767559],[13.806475,46.509306],[13.69811,46.016778],[13.93763,45.591016],[13.141606,45.736692],[12.328581,45.381778],[12.383875,44.885374],[12.261453,44.600482],[12.589237,44.091366],[13.526906,43.587727],[14.029821,42.761008],[15.14257,41.95514],[15.926191,41.961315],[16.169897,41.740295],[15.889346,41.541082],[16.785002,41.179606],[17.519169,40.877143],[18.376687,40.355625],[18.480247,40.168866],[18.293385,39.810774],[17.73838,40.277671],[16.869596,40.442235],[16.448743,39.795401],[17.17149,39.4247],[17.052841,38.902871],[16.635088,38.843572],[16.100961,37.985899],[15.684087,37.908849],[15.687963,38.214593],[15.891981,38.750942],[16.109332,38.964547],[15.718814,39.544072],[15.413613,40.048357],[14.998496,40.172949],[14.703268,40.60455],[14.060672,40.786348],[13.627985,41.188287],[12.888082,41.25309],[12.106683,41.704535],[11.191906,42.355425],[10.511948,42.931463],[10.200029,43.920007],[9.702488,44.036279],[8.888946,44.366336],[8.428561,44.231228],[7.850767,43.767148],[7.435185,43.693845],[7.549596,44.127901],[7.007562,44.254767],[6.749955,45.028518],[7.096652,45.333099],[6.802355,45.70858],[6.843593,45.991147],[7.273851,45.776948],[7.755992,45.82449],[8.31663,46.163642],[8.489952,46.005151],[8.966306,46.036932],[9.182882,46.440215],[9.922837,46.314899],[10.363378,46.483571],[10.442701,46.893546]]],[[[14.761249,38.143874],[15.520376,38.231155],[15.160243,37.444046],[15.309898,37.134219],[15.099988,36.619987],[14.335229,36.996631],[13.826733,37.104531],[12.431004,37.61295],[12.570944,38.126381],[13.741156,38.034966],[14.761249,38.143874]]],[[[8.709991,40.899984],[9.210012,41.209991],[9.809975,40.500009],[9.669519,39.177376],[9.214818,39.240473],[8.806936,38.906618],[8.428302,39.171847],[8.388253,40.378311],[8.159998,40.950007],[8.709991,40.899984]]]]}},{"type":"Feature","properties":{"ADMIN":"Denmark","NAME_EN":"Denmark","CONTINENT":"Europe","ADM0_A3":"DNK","ISO_A3":"DNK","NAME":"Denmark","ISO_A2":"DK","NAME_ZH":"丹麦"},"geometry":{"type":"MultiPolygon","coordinates":[[[[9.921906,54.983104],[9.282049,54.830865],[8.526229,54.962744],[8.120311,55.517723],[8.089977,56.540012],[8.256582,56.809969],[8.543438,57.110003],[9.424469,57.172066],[9.775559,57.447941],[10.580006,57.730017],[10.546106,57.215733],[10.25,56.890016],[10.369993,56.609982],[10.912182,56.458621],[10.667804,56.081383],[10.369993,56.190007],[9.649985,55.469999],[9.921906,54.983104]]],[[[12.370904,56.111407],[12.690006,55.609991],[12.089991,54.800015],[11.043543,55.364864],[10.903914,55.779955],[12.370904,56.111407]]]]}},{"type":"Feature","properties":{"ADMIN":"United Kingdom","NAME_EN":"United Kingdom","CONTINENT":"Europe","ADM0_A3":"GBR","ISO_A3":"GBR","NAME":"United Kingdom","ISO_A2":"GB","NAME_ZH":"英国"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-6.197885,53.867565],[-6.95373,54.073702],[-7.572168,54.059956],[-7.366031,54.595841],[-7.572168,55.131622],[-6.733847,55.17286],[-5.661949,54.554603],[-6.197885,53.867565]]],[[[-3.093831,53.404547],[-3.09208,53.404441],[-2.945009,53.985],[-3.614701,54.600937],[-3.630005,54.615013],[-4.844169,54.790971],[-5.082527,55.061601],[-4.719112,55.508473],[-5.047981,55.783986],[-5.586398,55.311146],[-5.644999,56.275015],[-6.149981,56.78501],[-5.786825,57.818848],[-5.009999,58.630013],[-4.211495,58.550845],[-3.005005,58.635],[-4.073828,57.553025],[-3.055002,57.690019],[-1.959281,57.6848],[-2.219988,56.870017],[-3.119003,55.973793],[-2.085009,55.909998],[-2.005676,55.804903],[-1.114991,54.624986],[-0.430485,54.464376],[0.184981,53.325014],[0.469977,52.929999],[1.681531,52.73952],[1.559988,52.099998],[1.050562,51.806761],[1.449865,51.289428],[0.550334,50.765739],[-0.787517,50.774989],[-2.489998,50.500019],[-2.956274,50.69688],[-3.617448,50.228356],[-4.542508,50.341837],[-5.245023,49.96],[-5.776567,50.159678],[-4.30999,51.210001],[-3.414851,51.426009],[-3.422719,51.426848],[-4.984367,51.593466],[-5.267296,51.9914],[-4.222347,52.301356],[-4.770013,52.840005],[-4.579999,53.495004],[-3.093831,53.404547]]]]}},{"type":"Feature","properties":{"ADMIN":"Iceland","NAME_EN":"Iceland","CONTINENT":"Europe","ADM0_A3":"ISL","ISO_A3":"ISL","NAME":"Iceland","ISO_A2":"IS","NAME_ZH":"冰岛"},"geometry":{"type":"Polygon","coordinates":[[[-14.508695,66.455892],[-14.739637,65.808748],[-13.609732,65.126671],[-14.909834,64.364082],[-17.794438,63.678749],[-18.656246,63.496383],[-19.972755,63.643635],[-22.762972,63.960179],[-21.778484,64.402116],[-23.955044,64.89113],[-22.184403,65.084968],[-22.227423,65.378594],[-24.326184,65.611189],[-23.650515,66.262519],[-22.134922,66.410469],[-20.576284,65.732112],[-19.056842,66.276601],[-17.798624,65.993853],[-16.167819,66.526792],[-14.508695,66.455892]]]}},{"type":"Feature","properties":{"ADMIN":"Azerbaijan","NAME_EN":"Azerbaijan","CONTINENT":"Asia","ADM0_A3":"AZE","ISO_A3":"AZE","NAME":"Azerbaijan","ISO_A2":"AZ","NAME_ZH":"阿塞拜疆"},"geometry":{"type":"MultiPolygon","coordinates":[[[[46.404951,41.860675],[46.686071,41.827137],[47.373315,41.219732],[47.815666,41.151416],[47.987283,41.405819],[48.584353,41.808869],[49.110264,41.282287],[49.618915,40.572924],[50.08483,40.526157],[50.392821,40.256561],[49.569202,40.176101],[49.395259,39.399482],[49.223228,39.049219],[48.856532,38.815486],[48.883249,38.320245],[48.634375,38.270378],[48.010744,38.794015],[48.355529,39.288765],[48.060095,39.582235],[47.685079,39.508364],[46.50572,38.770605],[46.483499,39.464155],[46.034534,39.628021],[45.610012,39.899994],[45.891907,40.218476],[45.359175,40.561504],[45.560351,40.81229],[45.179496,40.985354],[44.97248,41.248129],[45.217426,41.411452],[45.962601,41.123873],[46.501637,41.064445],[46.637908,41.181673],[46.145432,41.722802],[46.404951,41.860675]]],[[[46.143623,38.741201],[45.457722,38.874139],[44.952688,39.335765],[44.79399,39.713003],[45.001987,39.740004],[45.298145,39.471751],[45.739978,39.473999],[45.735379,39.319719],[46.143623,38.741201]]]]}},{"type":"Feature","properties":{"ADMIN":"Georgia","NAME_EN":"Georgia","CONTINENT":"Asia","ADM0_A3":"GEO","ISO_A3":"GEO","NAME":"Georgia","ISO_A2":"GE","NAME_ZH":"格鲁吉亚"},"geometry":{"type":"Polygon","coordinates":[[[39.955009,43.434998],[40.076965,43.553104],[40.92219,43.38215],[42.3944,43.2203],[43.75599,42.74083],[43.93121,42.55496],[44.537623,42.711993],[45.470279,42.502781],[45.7764,42.09244],[46.404951,41.860675],[46.145432,41.722802],[46.637908,41.181673],[46.501637,41.064445],[45.962601,41.123873],[45.217426,41.411452],[44.97248,41.248129],[43.582746,41.092143],[42.619549,41.583173],[41.554084,41.535656],[41.703171,41.962943],[41.45347,42.645123],[40.875469,43.013628],[40.321394,43.128634],[39.955009,43.434998]]]}},{"type":"Feature","properties":{"ADMIN":"Philippines","NAME_EN":"Philippines","CONTINENT":"Asia","ADM0_A3":"PHL","ISO_A3":"PHL","NAME":"Philippines","ISO_A2":"PH","NAME_ZH":"菲律宾"},"geometry":{"type":"MultiPolygon","coordinates":[[[[120.833896,12.704496],[120.323436,13.466413],[121.180128,13.429697],[121.527394,13.06959],[121.26219,12.20556],[120.833896,12.704496]]],[[[122.586089,9.981045],[122.837081,10.261157],[122.947411,10.881868],[123.49885,10.940624],[123.337774,10.267384],[124.077936,11.232726],[123.982438,10.278779],[123.623183,9.950091],[123.309921,9.318269],[122.995883,9.022189],[122.380055,9.713361],[122.586089,9.981045]]],[[[126.376814,8.414706],[126.478513,7.750354],[126.537424,7.189381],[126.196773,6.274294],[125.831421,7.293715],[125.363852,6.786485],[125.683161,6.049657],[125.396512,5.581003],[124.219788,6.161355],[123.93872,6.885136],[124.243662,7.36061],[123.610212,7.833527],[123.296071,7.418876],[122.825506,7.457375],[122.085499,6.899424],[121.919928,7.192119],[122.312359,8.034962],[122.942398,8.316237],[123.487688,8.69301],[123.841154,8.240324],[124.60147,8.514158],[124.764612,8.960409],[125.471391,8.986997],[125.412118,9.760335],[126.222714,9.286074],[126.306637,8.782487],[126.376814,8.414706]]],[[[118.504581,9.316383],[117.174275,8.3675],[117.664477,9.066889],[118.386914,9.6845],[118.987342,10.376292],[119.511496,11.369668],[119.689677,10.554291],[119.029458,10.003653],[118.504581,9.316383]]],[[[122.336957,18.224883],[122.174279,17.810283],[122.515654,17.093505],[122.252311,16.262444],[121.662786,15.931018],[121.50507,15.124814],[121.728829,14.328376],[122.258925,14.218202],[122.701276,14.336541],[123.950295,13.782131],[123.855107,13.237771],[124.181289,12.997527],[124.077419,12.536677],[123.298035,13.027526],[122.928652,13.55292],[122.671355,13.185836],[122.03465,13.784482],[121.126385,13.636687],[120.628637,13.857656],[120.679384,14.271016],[120.991819,14.525393],[120.693336,14.756671],[120.564145,14.396279],[120.070429,14.970869],[119.920929,15.406347],[119.883773,16.363704],[120.286488,16.034629],[120.390047,17.599081],[120.715867,18.505227],[121.321308,18.504065],[121.937601,18.218552],[122.246006,18.47895],[122.336957,18.224883]]],[[[122.03837,11.415841],[121.883548,11.891755],[122.483821,11.582187],[123.120217,11.58366],[123.100838,11.165934],[122.637714,10.741308],[122.00261,10.441017],[121.967367,10.905691],[122.03837,11.415841]]],[[[125.502552,12.162695],[125.783465,11.046122],[125.011884,11.311455],[125.032761,10.975816],[125.277449,10.358722],[124.801819,10.134679],[124.760168,10.837995],[124.459101,10.88993],[124.302522,11.495371],[124.891013,11.415583],[124.87799,11.79419],[124.266762,12.557761],[125.227116,12.535721],[125.502552,12.162695]]]]}},{"type":"Feature","properties":{"ADMIN":"Malaysia","NAME_EN":"Malaysia","CONTINENT":"Asia","ADM0_A3":"MYS","ISO_A3":"MYS","NAME":"Malaysia","ISO_A2":"MY","NAME_ZH":"马来西亚"},"geometry":{"type":"MultiPolygon","coordinates":[[[[100.085757,6.464489],[100.259596,6.642825],[101.075516,6.204867],[101.154219,5.691384],[101.814282,5.810808],[102.141187,6.221636],[102.371147,6.128205],[102.961705,5.524495],[103.381215,4.855001],[103.438575,4.181606],[103.332122,3.726698],[103.429429,3.382869],[103.502448,2.791019],[103.854674,2.515454],[104.247932,1.631141],[104.228811,1.293048],[103.519707,1.226334],[102.573615,1.967115],[101.390638,2.760814],[101.27354,3.270292],[100.695435,3.93914],[100.557408,4.76728],[100.196706,5.312493],[100.30626,6.040562],[100.085757,6.464489]]],[[[117.882035,4.137551],[117.015214,4.306094],[115.865517,4.306559],[115.519078,3.169238],[115.134037,2.821482],[114.621355,1.430688],[113.80585,1.217549],[112.859809,1.49779],[112.380252,1.410121],[111.797548,0.904441],[111.159138,0.976478],[110.514061,0.773131],[109.830227,1.338136],[109.66326,2.006467],[110.396135,1.663775],[111.168853,1.850637],[111.370081,2.697303],[111.796928,2.885897],[112.995615,3.102395],[113.712935,3.893509],[114.204017,4.525874],[114.659596,4.007637],[114.869557,4.348314],[115.347461,4.316636],[115.4057,4.955228],[115.45071,5.44773],[116.220741,6.143191],[116.725103,6.924771],[117.129626,6.928053],[117.643393,6.422166],[117.689075,5.98749],[118.347691,5.708696],[119.181904,5.407836],[119.110694,5.016128],[118.439727,4.966519],[118.618321,4.478202],[117.882035,4.137551]]]]}},{"type":"Feature","properties":{"ADMIN":"Brunei","NAME_EN":"Brunei","CONTINENT":"Asia","ADM0_A3":"BRN","ISO_A3":"BRN","NAME":"Brunei","ISO_A2":"BN","NAME_ZH":"文莱"},"geometry":{"type":"Polygon","coordinates":[[[115.45071,5.44773],[115.4057,4.955228],[115.347461,4.316636],[114.869557,4.348314],[114.659596,4.007637],[114.204017,4.525874],[114.599961,4.900011],[115.45071,5.44773]]]}},{"type":"Feature","properties":{"ADMIN":"Slovenia","NAME_EN":"Slovenia","CONTINENT":"Europe","ADM0_A3":"SVN","ISO_A3":"SVN","NAME":"Slovenia","ISO_A2":"SI","NAME_ZH":"斯洛文尼亚"},"geometry":{"type":"Polygon","coordinates":[[[13.806475,46.509306],[14.632472,46.431817],[15.137092,46.658703],[16.011664,46.683611],[16.202298,46.852386],[16.370505,46.841327],[16.564808,46.503751],[15.768733,46.238108],[15.67153,45.834154],[15.323954,45.731783],[15.327675,45.452316],[14.935244,45.471695],[14.595109,45.634941],[14.411968,45.466166],[13.71506,45.500324],[13.93763,45.591016],[13.69811,46.016778],[13.806475,46.509306]]]}},{"type":"Feature","properties":{"ADMIN":"Finland","NAME_EN":"Finland","CONTINENT":"Europe","ADM0_A3":"FIN","ISO_A3":"FIN","NAME":"Finland","ISO_A2":"FI","NAME_ZH":"芬兰"},"geometry":{"type":"Polygon","coordinates":[[[28.59193,69.064777],[28.445944,68.364613],[29.977426,67.698297],[29.054589,66.944286],[30.21765,65.80598],[29.54443,64.948672],[30.444685,64.204453],[30.035872,63.552814],[31.516092,62.867687],[31.139991,62.357693],[30.211107,61.780028],[28.07,60.50352],[28.070002,60.503519],[28.069998,60.503517],[26.255173,60.423961],[24.496624,60.057316],[22.869695,59.846373],[22.290764,60.391921],[21.322244,60.72017],[21.544866,61.705329],[21.059211,62.607393],[21.536029,63.189735],[22.442744,63.81781],[24.730512,64.902344],[25.398068,65.111427],[25.294043,65.534346],[23.903379,66.006927],[23.56588,66.396051],[23.539473,67.936009],[21.978535,68.616846],[20.645593,69.106247],[21.244936,69.370443],[22.356238,68.841741],[23.66205,68.891247],[24.735679,68.649557],[25.689213,69.092114],[26.179622,69.825299],[27.732292,70.164193],[29.015573,69.766491],[28.59193,69.064777]]]}},{"type":"Feature","properties":{"ADMIN":"Slovakia","NAME_EN":"Slovakia","CONTINENT":"Europe","ADM0_A3":"SVK","ISO_A3":"SVK","NAME":"Slovakia","ISO_A2":"SK","NAME_ZH":"斯洛伐克"},"geometry":{"type":"Polygon","coordinates":[[[22.558138,49.085738],[22.280842,48.825392],[22.085608,48.422264],[21.872236,48.319971],[20.801294,48.623854],[20.473562,48.56285],[20.239054,48.327567],[19.769471,48.202691],[19.661364,48.266615],[19.174365,48.111379],[18.777025,48.081768],[18.696513,47.880954],[17.857133,47.758429],[17.488473,47.867466],[16.979667,48.123497],[16.879983,48.470013],[16.960288,48.596982],[17.101985,48.816969],[17.545007,48.800019],[17.886485,48.903475],[17.913512,48.996493],[18.104973,49.043983],[18.170498,49.271515],[18.399994,49.315001],[18.554971,49.495015],[18.853144,49.49623],[18.909575,49.435846],[19.320713,49.571574],[19.825023,49.217125],[20.415839,49.431453],[20.887955,49.328772],[21.607808,49.470107],[22.558138,49.085738]]]}},{"type":"Feature","properties":{"ADMIN":"Czechia","NAME_EN":"Czech Republic","CONTINENT":"Europe","ADM0_A3":"CZE","ISO_A3":"CZE","NAME":"Czechia","ISO_A2":"CZ","NAME_ZH":"捷克"},"geometry":{"type":"Polygon","coordinates":[[[15.016996,51.106674],[15.490972,50.78473],[16.238627,50.697733],[16.176253,50.422607],[16.719476,50.215747],[16.868769,50.473974],[17.554567,50.362146],[17.649445,50.049038],[18.392914,49.988629],[18.853144,49.49623],[18.554971,49.495015],[18.399994,49.315001],[18.170498,49.271515],[18.104973,49.043983],[17.913512,48.996493],[17.886485,48.903475],[17.545007,48.800019],[17.101985,48.816969],[16.960288,48.596982],[16.499283,48.785808],[16.029647,48.733899],[15.253416,49.039074],[14.901447,48.964402],[14.338898,48.555305],[13.595946,48.877172],[13.031329,49.307068],[12.521024,49.547415],[12.415191,49.969121],[12.240111,50.266338],[12.966837,50.484076],[13.338132,50.733234],[14.056228,50.926918],[14.307013,51.117268],[14.570718,51.002339],[15.016996,51.106674]]]}},{"type":"Feature","properties":{"ADMIN":"Eritrea","NAME_EN":"Eritrea","CONTINENT":"Africa","ADM0_A3":"ERI","ISO_A3":"ERI","NAME":"Eritrea","ISO_A2":"ER","NAME_ZH":"厄立特里亚"},"geometry":{"type":"Polygon","coordinates":[[[36.42951,14.42211],[36.32322,14.82249],[36.75389,16.29186],[36.85253,16.95655],[37.16747,17.26314],[37.904,17.42754],[38.41009,17.998307],[38.990623,16.840626],[39.26611,15.922723],[39.814294,15.435647],[41.179275,14.49108],[41.734952,13.921037],[42.276831,13.343992],[42.589576,13.000421],[43.081226,12.699639],[42.779642,12.455416],[42.35156,12.54223],[42.00975,12.86582],[41.59856,13.45209],[41.1552,13.77333],[40.8966,14.11864],[40.02625,14.51959],[39.34061,14.53155],[39.0994,14.74064],[38.51295,14.50547],[37.90607,14.95943],[37.59377,14.2131],[36.42951,14.42211]]]}},{"type":"Feature","properties":{"ADMIN":"Japan","NAME_EN":"Japan","CONTINENT":"Asia","ADM0_A3":"JPN","ISO_A3":"JPN","NAME":"Japan","ISO_A2":"JP","NAME_ZH":"日本"},"geometry":{"type":"MultiPolygon","coordinates":[[[[141.884601,39.180865],[140.959489,38.174001],[140.976388,37.142074],[140.59977,36.343983],[140.774074,35.842877],[140.253279,35.138114],[138.975528,34.6676],[137.217599,34.606286],[135.792983,33.464805],[135.120983,33.849071],[135.079435,34.596545],[133.340316,34.375938],[132.156771,33.904933],[130.986145,33.885761],[132.000036,33.149992],[131.33279,31.450355],[130.686318,31.029579],[130.20242,31.418238],[130.447676,32.319475],[129.814692,32.61031],[129.408463,33.296056],[130.353935,33.604151],[130.878451,34.232743],[131.884229,34.749714],[132.617673,35.433393],[134.608301,35.731618],[135.677538,35.527134],[136.723831,37.304984],[137.390612,36.827391],[138.857602,37.827485],[139.426405,38.215962],[140.05479,39.438807],[139.883379,40.563312],[140.305783,41.195005],[141.368973,41.37856],[141.914263,39.991616],[141.884601,39.180865]]],[[[144.613427,43.960883],[145.320825,44.384733],[145.543137,43.262088],[144.059662,42.988358],[143.18385,41.995215],[141.611491,42.678791],[141.067286,41.584594],[139.955106,41.569556],[139.817544,42.563759],[140.312087,43.333273],[141.380549,43.388825],[141.671952,44.772125],[141.967645,45.551483],[143.14287,44.510358],[143.910162,44.1741],[144.613427,43.960883]]],[[[132.371176,33.463642],[132.924373,34.060299],[133.492968,33.944621],[133.904106,34.364931],[134.638428,34.149234],[134.766379,33.806335],[134.203416,33.201178],[133.79295,33.521985],[133.280268,33.28957],[133.014858,32.704567],[132.363115,32.989382],[132.371176,33.463642]]]]}},{"type":"Feature","properties":{"ADMIN":"Paraguay","NAME_EN":"Paraguay","CONTINENT":"South America","ADM0_A3":"PRY","ISO_A3":"PRY","NAME":"Paraguay","ISO_A2":"PY","NAME_ZH":"巴拉圭"},"geometry":{"type":"Polygon","coordinates":[[[-58.166392,-20.176701],[-57.870674,-20.732688],[-57.937156,-22.090176],[-56.88151,-22.282154],[-56.473317,-22.0863],[-55.797958,-22.35693],[-55.610683,-22.655619],[-55.517639,-23.571998],[-55.400747,-23.956935],[-55.027902,-24.001274],[-54.652834,-23.839578],[-54.29296,-24.021014],[-54.293476,-24.5708],[-54.428946,-25.162185],[-54.625291,-25.739255],[-54.788795,-26.621786],[-55.695846,-27.387837],[-56.486702,-27.548499],[-57.60976,-27.395899],[-58.618174,-27.123719],[-57.63366,-25.603657],[-57.777217,-25.16234],[-58.807128,-24.771459],[-60.028966,-24.032796],[-60.846565,-23.880713],[-62.685057,-22.249029],[-62.291179,-21.051635],[-62.265961,-20.513735],[-61.786326,-19.633737],[-60.043565,-19.342747],[-59.115042,-19.356906],[-58.183471,-19.868399],[-58.166392,-20.176701]]]}},{"type":"Feature","properties":{"ADMIN":"Yemen","NAME_EN":"Yemen","CONTINENT":"Asia","ADM0_A3":"YEM","ISO_A3":"YEM","NAME":"Yemen","ISO_A2":"YE","NAME_ZH":"也门"},"geometry":{"type":"Polygon","coordinates":[[[52.00001,19.000003],[52.782184,17.349742],[53.108573,16.651051],[52.385206,16.382411],[52.191729,15.938433],[52.168165,15.59742],[51.172515,15.17525],[49.574576,14.708767],[48.679231,14.003202],[48.238947,13.94809],[47.938914,14.007233],[47.354454,13.59222],[46.717076,13.399699],[45.877593,13.347764],[45.62505,13.290946],[45.406459,13.026905],[45.144356,12.953938],[44.989533,12.699587],[44.494576,12.721653],[44.175113,12.58595],[43.482959,12.6368],[43.222871,13.22095],[43.251448,13.767584],[43.087944,14.06263],[42.892245,14.802249],[42.604873,15.213335],[42.805015,15.261963],[42.702438,15.718886],[42.823671,15.911742],[42.779332,16.347891],[43.218375,16.66689],[43.115798,17.08844],[43.380794,17.579987],[43.791519,17.319977],[44.062613,17.410359],[45.216651,17.433329],[45.399999,17.333335],[46.366659,17.233315],[46.749994,17.283338],[47.000005,16.949999],[47.466695,17.116682],[48.183344,18.166669],[49.116672,18.616668],[52.00001,19.000003]]]}},{"type":"Feature","properties":{"ADMIN":"Saudi Arabia","NAME_EN":"Saudi Arabia","CONTINENT":"Asia","ADM0_A3":"SAU","ISO_A3":"SAU","NAME":"Saudi Arabia","ISO_A2":"SA","NAME_ZH":"沙特阿拉伯"},"geometry":{"type":"Polygon","coordinates":[[[34.956037,29.356555],[36.068941,29.197495],[36.501214,29.505254],[36.740528,29.865283],[37.503582,30.003776],[37.66812,30.338665],[37.998849,30.5085],[37.002166,31.508413],[39.004886,32.010217],[39.195468,32.161009],[40.399994,31.889992],[41.889981,31.190009],[44.709499,29.178891],[46.568713,29.099025],[47.459822,29.002519],[47.708851,28.526063],[48.416094,28.552004],[48.807595,27.689628],[49.299554,27.461218],[49.470914,27.109999],[50.152422,26.689663],[50.212935,26.277027],[50.113303,25.943972],[50.239859,25.60805],[50.527387,25.327808],[50.660557,24.999896],[50.810108,24.754743],[51.112415,24.556331],[51.389608,24.627386],[51.579519,24.245497],[51.617708,24.014219],[52.000733,23.001154],[55.006803,22.496948],[55.208341,22.70833],[55.666659,22.000001],[54.999982,19.999994],[52.00001,19.000003],[49.116672,18.616668],[48.183344,18.166669],[47.466695,17.116682],[47.000005,16.949999],[46.749994,17.283338],[46.366659,17.233315],[45.399999,17.333335],[45.216651,17.433329],[44.062613,17.410359],[43.791519,17.319977],[43.380794,17.579987],[43.115798,17.08844],[43.218375,16.66689],[42.779332,16.347891],[42.649573,16.774635],[42.347989,17.075806],[42.270888,17.474722],[41.754382,17.833046],[41.221391,18.6716],[40.939341,19.486485],[40.247652,20.174635],[39.801685,20.338862],[39.139399,21.291905],[39.023696,21.986875],[39.066329,22.579656],[38.492772,23.688451],[38.02386,24.078686],[37.483635,24.285495],[37.154818,24.858483],[37.209491,25.084542],[36.931627,25.602959],[36.639604,25.826228],[36.249137,26.570136],[35.640182,27.37652],[35.130187,28.063352],[34.632336,28.058546],[34.787779,28.607427],[34.83222,28.957483],[34.956037,29.356555]]]}},{"type":"Feature","properties":{"ADMIN":"Antarctica","NAME_EN":"Antarctica","CONTINENT":"Antarctica","ADM0_A3":"ATA","ISO_A3":"ATA","NAME":"Antarctica","ISO_A2":"AQ","NAME_ZH":"南极洲"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-48.660616,-78.047019],[-48.151396,-78.04707],[-46.662857,-77.831476],[-45.154758,-78.04707],[-43.920828,-78.478103],[-43.48995,-79.08556],[-43.372438,-79.516645],[-43.333267,-80.026123],[-44.880537,-80.339644],[-46.506174,-80.594357],[-48.386421,-80.829485],[-50.482107,-81.025442],[-52.851988,-80.966685],[-54.164259,-80.633528],[-53.987991,-80.222028],[-51.853134,-79.94773],[-50.991326,-79.614623],[-50.364595,-79.183487],[-49.914131,-78.811209],[-49.306959,-78.458569],[-48.660616,-78.047018],[-48.660616,-78.047019]]],[[[-66.290031,-80.255773],[-64.037688,-80.294944],[-61.883246,-80.39287],[-61.138976,-79.981371],[-60.610119,-79.628679],[-59.572095,-80.040179],[-59.865849,-80.549657],[-60.159656,-81.000327],[-62.255393,-80.863178],[-64.488125,-80.921934],[-65.741666,-80.588827],[-65.741666,-80.549657],[-66.290031,-80.255773]]],[[[-73.915819,-71.269345],[-73.915819,-71.269344],[-73.230331,-71.15178],[-72.074717,-71.190951],[-71.780962,-70.681473],[-71.72218,-70.309196],[-71.741791,-69.505782],[-71.173815,-69.035475],[-70.253252,-68.87874],[-69.724447,-69.251017],[-69.489422,-69.623346],[-69.058518,-70.074016],[-68.725541,-70.505153],[-68.451346,-70.955823],[-68.333834,-71.406493],[-68.510128,-71.798407],[-68.784297,-72.170736],[-69.959471,-72.307885],[-71.075889,-72.503842],[-72.388134,-72.484257],[-71.8985,-72.092343],[-73.073622,-72.229492],[-74.19004,-72.366693],[-74.953895,-72.072757],[-75.012625,-71.661258],[-73.915819,-71.269345]]],[[[-102.330725,-71.894164],[-102.330725,-71.894164],[-101.703967,-71.717792],[-100.430919,-71.854993],[-98.98155,-71.933334],[-97.884743,-72.070535],[-96.787937,-71.952971],[-96.20035,-72.521205],[-96.983765,-72.442864],[-98.198083,-72.482035],[-99.432013,-72.442864],[-100.783455,-72.50162],[-101.801868,-72.305663],[-102.330725,-71.894164]]],[[[-122.621735,-73.657778],[-122.621735,-73.657777],[-122.406245,-73.324619],[-121.211511,-73.50099],[-119.918851,-73.657725],[-118.724143,-73.481353],[-119.292119,-73.834097],[-120.232217,-74.08881],[-121.62283,-74.010468],[-122.621735,-73.657778]]],[[[-127.28313,-73.461769],[-127.28313,-73.461768],[-126.558472,-73.246226],[-125.559566,-73.481353],[-124.031882,-73.873268],[-124.619469,-73.834097],[-125.912181,-73.736118],[-127.28313,-73.461769]]],[[[-163.712896,-78.595667],[-163.712896,-78.595667],[-163.105801,-78.223338],[-161.245113,-78.380176],[-160.246208,-78.693645],[-159.482405,-79.046338],[-159.208184,-79.497059],[-161.127601,-79.634209],[-162.439847,-79.281465],[-163.027408,-78.928774],[-163.066604,-78.869966],[-163.712896,-78.595667]]],[[[180,-84.71338],[180,-90],[-180,-90],[-180,-84.71338],[-179.942499,-84.721443],[-179.058677,-84.139412],[-177.256772,-84.452933],[-177.140807,-84.417941],[-176.084673,-84.099259],[-175.947235,-84.110449],[-175.829882,-84.117914],[-174.382503,-84.534323],[-173.116559,-84.117914],[-172.889106,-84.061019],[-169.951223,-83.884647],[-168.999989,-84.117914],[-168.530199,-84.23739],[-167.022099,-84.570497],[-164.182144,-84.82521],[-161.929775,-85.138731],[-158.07138,-85.37391],[-155.192253,-85.09956],[-150.942099,-85.295517],[-148.533073,-85.609038],[-145.888918,-85.315102],[-143.107718,-85.040752],[-142.892279,-84.570497],[-146.829068,-84.531274],[-150.060732,-84.296146],[-150.902928,-83.904232],[-153.586201,-83.68869],[-153.409907,-83.23802],[-153.037759,-82.82652],[-152.665637,-82.454192],[-152.861517,-82.042692],[-154.526299,-81.768394],[-155.29018,-81.41565],[-156.83745,-81.102129],[-154.408787,-81.160937],[-152.097662,-81.004151],[-150.648293,-81.337309],[-148.865998,-81.043373],[-147.22075,-80.671045],[-146.417749,-80.337938],[-146.770286,-79.926439],[-148.062947,-79.652089],[-149.531901,-79.358205],[-151.588416,-79.299397],[-153.390322,-79.162248],[-155.329376,-79.064269],[-155.975668,-78.69194],[-157.268302,-78.378419],[-158.051768,-78.025676],[-158.365134,-76.889207],[-157.875474,-76.987238],[-156.974573,-77.300759],[-155.329376,-77.202728],[-153.742832,-77.065579],[-152.920247,-77.496664],[-151.33378,-77.398737],[-150.00195,-77.183143],[-148.748486,-76.908845],[-147.612483,-76.575738],[-146.104409,-76.47776],[-146.143528,-76.105431],[-146.496091,-75.733154],[-146.20231,-75.380411],[-144.909624,-75.204039],[-144.322037,-75.537197],[-142.794353,-75.34124],[-141.638764,-75.086475],[-140.209007,-75.06689],[-138.85759,-74.968911],[-137.5062,-74.733783],[-136.428901,-74.518241],[-135.214583,-74.302699],[-134.431194,-74.361455],[-133.745654,-74.439848],[-132.257168,-74.302699],[-130.925311,-74.479019],[-129.554284,-74.459433],[-128.242038,-74.322284],[-126.890622,-74.420263],[-125.402082,-74.518241],[-124.011496,-74.479019],[-122.562152,-74.498604],[-121.073613,-74.518241],[-119.70256,-74.479019],[-118.684145,-74.185083],[-117.469801,-74.028348],[-116.216312,-74.243891],[-115.021552,-74.067519],[-113.944331,-73.714828],[-113.297988,-74.028348],[-112.945452,-74.38104],[-112.299083,-74.714198],[-111.261059,-74.420263],[-110.066325,-74.79254],[-108.714909,-74.910103],[-107.559346,-75.184454],[-106.149148,-75.125698],[-104.876074,-74.949326],[-103.367949,-74.988497],[-102.016507,-75.125698],[-100.645531,-75.302018],[-100.1167,-74.870933],[-100.763043,-74.537826],[-101.252703,-74.185083],[-102.545337,-74.106742],[-103.113313,-73.734413],[-103.328752,-73.362084],[-103.681289,-72.61753],[-102.917485,-72.754679],[-101.60524,-72.813436],[-100.312528,-72.754679],[-99.13738,-72.911414],[-98.118889,-73.20535],[-97.688037,-73.558041],[-96.336595,-73.616849],[-95.043961,-73.4797],[-93.672907,-73.283743],[-92.439003,-73.166179],[-91.420564,-73.401307],[-90.088733,-73.322914],[-89.226951,-72.558722],[-88.423951,-73.009393],[-87.268337,-73.185764],[-86.014822,-73.087786],[-85.192236,-73.4797],[-83.879991,-73.518871],[-82.665646,-73.636434],[-81.470913,-73.851977],[-80.687447,-73.4797],[-80.295791,-73.126956],[-79.296886,-73.518871],[-77.925858,-73.420892],[-76.907367,-73.636434],[-76.221879,-73.969541],[-74.890049,-73.871614],[-73.852024,-73.65602],[-72.833533,-73.401307],[-71.619215,-73.264157],[-70.209042,-73.146542],[-68.935916,-73.009393],[-67.956622,-72.79385],[-67.369061,-72.480329],[-67.134036,-72.049244],[-67.251548,-71.637745],[-67.56494,-71.245831],[-67.917477,-70.853917],[-68.230843,-70.462055],[-68.485452,-70.109311],[-68.544209,-69.717397],[-68.446282,-69.325535],[-67.976233,-68.953206],[-67.5845,-68.541707],[-67.427843,-68.149844],[-67.62367,-67.718759],[-67.741183,-67.326845],[-67.251548,-66.876175],[-66.703184,-66.58224],[-66.056815,-66.209963],[-65.371327,-65.89639],[-64.568276,-65.602506],[-64.176542,-65.171423],[-63.628152,-64.897073],[-63.001394,-64.642308],[-62.041686,-64.583552],[-61.414928,-64.270031],[-60.709855,-64.074074],[-59.887269,-63.95651],[-59.162585,-63.701745],[-58.594557,-63.388224],[-57.811143,-63.27066],[-57.223582,-63.525425],[-57.59573,-63.858532],[-58.614143,-64.152467],[-59.045073,-64.36801],[-59.789342,-64.211223],[-60.611928,-64.309202],[-61.297416,-64.54433],[-62.0221,-64.799094],[-62.51176,-65.09303],[-62.648858,-65.484942],[-62.590128,-65.857219],[-62.120079,-66.190326],[-62.805567,-66.425505],[-63.74569,-66.503847],[-64.294106,-66.837004],[-64.881693,-67.150474],[-65.508425,-67.58161],[-65.665082,-67.953887],[-65.312545,-68.365335],[-64.783715,-68.678908],[-63.961103,-68.913984],[-63.1973,-69.227556],[-62.785955,-69.619419],[-62.570516,-69.991747],[-62.276736,-70.383661],[-61.806661,-70.716768],[-61.512906,-71.089045],[-61.375809,-72.010074],[-61.081977,-72.382351],[-61.003661,-72.774265],[-60.690269,-73.166179],[-60.827367,-73.695242],[-61.375809,-74.106742],[-61.96337,-74.439848],[-63.295201,-74.576997],[-63.74569,-74.92974],[-64.352836,-75.262847],[-65.860987,-75.635124],[-67.192818,-75.79191],[-68.446282,-76.007452],[-69.797724,-76.222995],[-70.600724,-76.634494],[-72.206776,-76.673665],[-73.969536,-76.634494],[-75.555977,-76.712887],[-77.24037,-76.712887],[-76.926979,-77.104802],[-75.399294,-77.28107],[-74.282876,-77.55542],[-73.656119,-77.908112],[-74.772536,-78.221633],[-76.4961,-78.123654],[-77.925858,-78.378419],[-77.984666,-78.789918],[-78.023785,-79.181833],[-76.848637,-79.514939],[-76.633224,-79.887216],[-75.360097,-80.259545],[-73.244852,-80.416331],[-71.442946,-80.69063],[-70.013163,-81.004151],[-68.191646,-81.317672],[-65.704279,-81.474458],[-63.25603,-81.748757],[-61.552026,-82.042692],[-59.691416,-82.37585],[-58.712121,-82.846106],[-58.222487,-83.218434],[-57.008117,-82.865691],[-55.362894,-82.571755],[-53.619771,-82.258235],[-51.543644,-82.003521],[-49.76135,-81.729171],[-47.273931,-81.709586],[-44.825708,-81.846735],[-42.808363,-82.081915],[-42.16202,-81.65083],[-40.771433,-81.356894],[-38.244818,-81.337309],[-36.26667,-81.121715],[-34.386397,-80.906172],[-32.310296,-80.769023],[-30.097098,-80.592651],[-28.549802,-80.337938],[-29.254901,-79.985195],[-29.685805,-79.632503],[-29.685805,-79.260226],[-31.624808,-79.299397],[-33.681324,-79.456132],[-35.639912,-79.456132],[-35.914107,-79.083855],[-35.77701,-78.339248],[-35.326546,-78.123654],[-33.896763,-77.888526],[-32.212369,-77.65345],[-30.998051,-77.359515],[-29.783732,-77.065579],[-28.882779,-76.673665],[-27.511752,-76.497345],[-26.160336,-76.360144],[-25.474822,-76.281803],[-23.927552,-76.24258],[-22.458598,-76.105431],[-21.224694,-75.909474],[-20.010375,-75.674346],[-18.913543,-75.439218],[-17.522982,-75.125698],[-16.641589,-74.79254],[-15.701491,-74.498604],[-15.40771,-74.106742],[-16.46532,-73.871614],[-16.112784,-73.460114],[-15.446855,-73.146542],[-14.408805,-72.950585],[-13.311973,-72.715457],[-12.293508,-72.401936],[-11.510067,-72.010074],[-11.020433,-71.539767],[-10.295774,-71.265416],[-9.101015,-71.324224],[-8.611381,-71.65733],[-7.416622,-71.696501],[-7.377451,-71.324224],[-6.868232,-70.93231],[-5.790985,-71.030289],[-5.536375,-71.402617],[-4.341667,-71.461373],[-3.048981,-71.285053],[-1.795492,-71.167438],[-0.659489,-71.226246],[-0.228637,-71.637745],[0.868195,-71.304639],[1.886686,-71.128267],[3.022638,-70.991118],[4.139055,-70.853917],[5.157546,-70.618789],[6.273912,-70.462055],[7.13572,-70.246512],[7.742866,-69.893769],[8.48711,-70.148534],[9.525135,-70.011333],[10.249845,-70.48164],[10.817821,-70.834332],[11.953824,-70.638375],[12.404287,-70.246512],[13.422778,-69.972162],[14.734998,-70.030918],[15.126757,-70.403247],[15.949342,-70.030918],[17.026589,-69.913354],[18.201711,-69.874183],[19.259373,-69.893769],[20.375739,-70.011333],[21.452985,-70.07014],[21.923034,-70.403247],[22.569403,-70.697182],[23.666184,-70.520811],[24.841357,-70.48164],[25.977309,-70.48164],[27.093726,-70.462055],[28.09258,-70.324854],[29.150242,-70.20729],[30.031583,-69.93294],[30.971733,-69.75662],[31.990172,-69.658641],[32.754053,-69.384291],[33.302443,-68.835642],[33.870419,-68.502588],[34.908495,-68.659271],[35.300202,-69.012014],[36.16201,-69.247142],[37.200035,-69.168748],[37.905108,-69.52144],[38.649404,-69.776205],[39.667894,-69.541077],[40.020431,-69.109941],[40.921358,-68.933621],[41.959434,-68.600514],[42.938702,-68.463313],[44.113876,-68.267408],[44.897291,-68.051866],[45.719928,-67.816738],[46.503343,-67.601196],[47.44344,-67.718759],[48.344419,-67.366068],[48.990736,-67.091718],[49.930885,-67.111303],[50.753471,-66.876175],[50.949325,-66.523484],[51.791547,-66.249133],[52.614133,-66.053176],[53.613038,-65.89639],[54.53355,-65.818049],[55.414943,-65.876805],[56.355041,-65.974783],[57.158093,-66.249133],[57.255968,-66.680218],[58.137361,-67.013324],[58.744508,-67.287675],[59.939318,-67.405239],[60.605221,-67.679589],[61.427806,-67.953887],[62.387489,-68.012695],[63.19049,-67.816738],[64.052349,-67.405239],[64.992447,-67.620729],[65.971715,-67.738345],[66.911864,-67.855909],[67.891133,-67.934302],[68.890038,-67.934302],[69.712624,-68.972791],[69.673453,-69.227556],[69.555941,-69.678226],[68.596258,-69.93294],[67.81274,-70.305268],[67.949889,-70.697182],[69.066307,-70.677545],[68.929157,-71.069459],[68.419989,-71.441788],[67.949889,-71.853287],[68.71377,-72.166808],[69.869307,-72.264787],[71.024895,-72.088415],[71.573285,-71.696501],[71.906288,-71.324224],[72.454627,-71.010703],[73.08141,-70.716768],[73.33602,-70.364024],[73.864877,-69.874183],[74.491557,-69.776205],[75.62756,-69.737034],[76.626465,-69.619419],[77.644904,-69.462684],[78.134539,-69.07077],[78.428371,-68.698441],[79.113859,-68.326216],[80.093127,-68.071503],[80.93535,-67.875546],[81.483792,-67.542388],[82.051767,-67.366068],[82.776426,-67.209282],[83.775331,-67.30726],[84.676206,-67.209282],[85.655527,-67.091718],[86.752359,-67.150474],[87.477017,-66.876175],[87.986289,-66.209911],[88.358411,-66.484261],[88.828408,-66.954568],[89.67063,-67.150474],[90.630365,-67.228867],[91.5901,-67.111303],[92.608539,-67.189696],[93.548637,-67.209282],[94.17542,-67.111303],[95.017591,-67.170111],[95.781472,-67.385653],[96.682399,-67.248504],[97.759646,-67.248504],[98.68021,-67.111303],[99.718182,-67.248504],[100.384188,-66.915346],[100.893356,-66.58224],[101.578896,-66.30789],[102.832411,-65.563284],[103.478676,-65.700485],[104.242557,-65.974783],[104.90846,-66.327527],[106.181561,-66.934931],[107.160881,-66.954568],[108.081393,-66.954568],[109.15864,-66.837004],[110.235835,-66.699804],[111.058472,-66.425505],[111.74396,-66.13157],[112.860378,-66.092347],[113.604673,-65.876805],[114.388088,-66.072762],[114.897308,-66.386283],[115.602381,-66.699804],[116.699161,-66.660633],[117.384701,-66.915346],[118.57946,-67.170111],[119.832924,-67.268089],[120.871,-67.189696],[121.654415,-66.876175],[122.320369,-66.562654],[123.221296,-66.484261],[124.122274,-66.621462],[125.160247,-66.719389],[126.100396,-66.562654],[127.001427,-66.562654],[127.882768,-66.660633],[128.80328,-66.758611],[129.704259,-66.58224],[130.781454,-66.425505],[131.799945,-66.386283],[132.935896,-66.386283],[133.85646,-66.288304],[134.757387,-66.209963],[135.031582,-65.72007],[135.070753,-65.308571],[135.697485,-65.582869],[135.873805,-66.033591],[136.206705,-66.44509],[136.618049,-66.778197],[137.460271,-66.954568],[138.596223,-66.895761],[139.908442,-66.876175],[140.809421,-66.817367],[142.121692,-66.817367],[143.061842,-66.797782],[144.374061,-66.837004],[145.490427,-66.915346],[146.195552,-67.228867],[145.999699,-67.601196],[146.646067,-67.895131],[147.723263,-68.130259],[148.839629,-68.385024],[150.132314,-68.561292],[151.483705,-68.71813],[152.502247,-68.874813],[153.638199,-68.894502],[154.284567,-68.561292],[155.165857,-68.835642],[155.92979,-69.149215],[156.811132,-69.384291],[158.025528,-69.482269],[159.181013,-69.599833],[159.670699,-69.991747],[160.80665,-70.226875],[161.570479,-70.579618],[162.686897,-70.736353],[163.842434,-70.716768],[164.919681,-70.775524],[166.11444,-70.755938],[167.309095,-70.834332],[168.425616,-70.971481],[169.463589,-71.20666],[170.501665,-71.402617],[171.20679,-71.696501],[171.089227,-72.088415],[170.560422,-72.441159],[170.109958,-72.891829],[169.75737,-73.24452],[169.287321,-73.65602],[167.975101,-73.812806],[167.387489,-74.165498],[166.094803,-74.38104],[165.644391,-74.772954],[164.958851,-75.145283],[164.234193,-75.458804],[163.822797,-75.870303],[163.568239,-76.24258],[163.47026,-76.693302],[163.489897,-77.065579],[164.057873,-77.457442],[164.273363,-77.82977],[164.743464,-78.182514],[166.604126,-78.319611],[166.995781,-78.750748],[165.193876,-78.907483],[163.666217,-79.123025],[161.766385,-79.162248],[160.924162,-79.730482],[160.747894,-80.200737],[160.316964,-80.573066],[159.788211,-80.945395],[161.120016,-81.278501],[161.629287,-81.690001],[162.490992,-82.062278],[163.705336,-82.395435],[165.095949,-82.708956],[166.604126,-83.022477],[168.895665,-83.335998],[169.404782,-83.825891],[172.283934,-84.041433],[172.477049,-84.117914],[173.224083,-84.41371],[175.985672,-84.158997],[178.277212,-84.472518],[180,-84.71338]]]]}},{"type":"Feature","properties":{"ADMIN":"Northern Cyprus","NAME_EN":"Turkish Republic of Northern Cyprus","CONTINENT":"Asia","ADM0_A3":"CYN","ISO_A3":"-99","NAME":"N. Cyprus","ISO_A2":"-99","NAME_ZH":"北塞浦路斯土耳其共和国"},"geometry":{"type":"Polygon","coordinates":[[[32.73178,35.140026],[32.802474,35.145504],[32.946961,35.386703],[33.667227,35.373216],[34.576474,35.671596],[33.900804,35.245756],[33.973617,35.058506],[33.86644,35.093595],[33.675392,35.017863],[33.525685,35.038688],[33.475817,35.000345],[33.455922,35.101424],[33.383833,35.162712],[33.190977,35.173125],[32.919572,35.087833],[32.73178,35.140026]]]}},{"type":"Feature","properties":{"ADMIN":"Cyprus","NAME_EN":"Cyprus","CONTINENT":"Asia","ADM0_A3":"CYP","ISO_A3":"CYP","NAME":"Cyprus","ISO_A2":"CY","NAME_ZH":"塞浦路斯"},"geometry":{"type":"Polygon","coordinates":[[[32.73178,35.140026],[32.919572,35.087833],[33.190977,35.173125],[33.383833,35.162712],[33.455922,35.101424],[33.475817,35.000345],[33.525685,35.038688],[33.675392,35.017863],[33.86644,35.093595],[33.973617,35.058506],[34.004881,34.978098],[32.979827,34.571869],[32.490296,34.701655],[32.256667,35.103232],[32.73178,35.140026]]]}},{"type":"Feature","properties":{"ADMIN":"Morocco","NAME_EN":"Morocco","CONTINENT":"Africa","ADM0_A3":"MAR","ISO_A3":"MAR","NAME":"Morocco","ISO_A2":"MA","NAME_ZH":"摩洛哥"},"geometry":{"type":"Polygon","coordinates":[[[-2.169914,35.168396],[-1.792986,34.527919],[-1.733455,33.919713],[-1.388049,32.864015],[-1.124551,32.651522],[-1.307899,32.262889],[-2.616605,32.094346],[-3.06898,31.724498],[-3.647498,31.637294],[-3.690441,30.896952],[-4.859646,30.501188],[-5.242129,30.000443],[-6.060632,29.7317],[-7.059228,29.579228],[-8.674116,28.841289],[-8.66559,27.656426],[-8.817828,27.656426],[-8.794884,27.120696],[-9.413037,27.088476],[-9.735343,26.860945],[-10.189424,26.860945],[-10.551263,26.990808],[-11.392555,26.883424],[-11.71822,26.104092],[-12.030759,26.030866],[-12.500963,24.770116],[-13.89111,23.691009],[-14.221168,22.310163],[-14.630833,21.86094],[-14.750955,21.5006],[-17.002962,21.420734],[-17.020428,21.42231],[-16.973248,21.885745],[-16.589137,22.158234],[-16.261922,22.67934],[-16.326414,23.017768],[-15.982611,23.723358],[-15.426004,24.359134],[-15.089332,24.520261],[-14.824645,25.103533],[-14.800926,25.636265],[-14.43994,26.254418],[-13.773805,26.618892],[-13.139942,27.640148],[-13.121613,27.654148],[-12.618837,28.038186],[-11.688919,28.148644],[-10.900957,28.832142],[-10.399592,29.098586],[-9.564811,29.933574],[-9.814718,31.177736],[-9.434793,32.038096],[-9.300693,32.564679],[-8.657476,33.240245],[-7.654178,33.697065],[-6.912544,34.110476],[-6.244342,35.145865],[-5.929994,35.759988],[-5.193863,35.755182],[-4.591006,35.330712],[-3.640057,35.399855],[-2.604306,35.179093],[-2.169914,35.168396]]]}},{"type":"Feature","properties":{"ADMIN":"Egypt","NAME_EN":"Egypt","CONTINENT":"Africa","ADM0_A3":"EGY","ISO_A3":"EGY","NAME":"Egypt","ISO_A2":"EG","NAME_ZH":"埃及"},"geometry":{"type":"Polygon","coordinates":[[[36.86623,22],[32.9,22],[29.02,22],[25,22],[25,25.6825],[25,29.238655],[24.70007,30.04419],[24.95762,30.6616],[24.80287,31.08929],[25.16482,31.56915],[26.49533,31.58568],[27.45762,31.32126],[28.45048,31.02577],[28.91353,30.87005],[29.68342,31.18686],[30.09503,31.4734],[30.97693,31.55586],[31.68796,31.4296],[31.96041,30.9336],[32.19247,31.26034],[32.99392,31.02407],[33.7734,30.96746],[34.265435,31.219357],[34.26544,31.21936],[34.823243,29.761081],[34.9226,29.50133],[34.64174,29.09942],[34.42655,28.34399],[34.15451,27.8233],[33.92136,27.6487],[33.58811,27.97136],[33.13676,28.41765],[32.42323,29.85108],[32.32046,29.76043],[32.73482,28.70523],[33.34876,27.69989],[34.10455,26.14227],[34.47387,25.59856],[34.79507,25.03375],[35.69241,23.92671],[35.49372,23.75237],[35.52598,23.10244],[36.69069,22.20485],[36.86623,22]]]}},{"type":"Feature","properties":{"ADMIN":"Libya","NAME_EN":"Libya","CONTINENT":"Africa","ADM0_A3":"LBY","ISO_A3":"LBY","NAME":"Libya","ISO_A2":"LY","NAME_ZH":"利比亚"},"geometry":{"type":"Polygon","coordinates":[[[25,22],[25,20.00304],[23.85,20],[23.83766,19.58047],[19.84926,21.49509],[15.86085,23.40972],[14.8513,22.86295],[14.143871,22.491289],[13.581425,23.040506],[11.999506,23.471668],[11.560669,24.097909],[10.771364,24.562532],[10.303847,24.379313],[9.948261,24.936954],[9.910693,25.365455],[9.319411,26.094325],[9.716286,26.512206],[9.629056,27.140953],[9.756128,27.688259],[9.683885,28.144174],[9.859998,28.95999],[9.805634,29.424638],[9.48214,30.307556],[9.970017,30.539325],[10.056575,30.961831],[9.950225,31.37607],[10.636901,31.761421],[10.94479,32.081815],[11.432253,32.368903],[11.488787,33.136996],[12.66331,32.79278],[13.08326,32.87882],[13.91868,32.71196],[15.24563,32.26508],[15.71394,31.37626],[16.61162,31.18218],[18.02109,30.76357],[19.08641,30.26639],[19.57404,30.52582],[20.05335,30.98576],[19.82033,31.75179],[20.13397,32.2382],[20.85452,32.7068],[21.54298,32.8432],[22.89576,32.63858],[23.2368,32.19149],[23.60913,32.18726],[23.9275,32.01667],[24.92114,31.89936],[25.16482,31.56915],[24.80287,31.08929],[24.95762,30.6616],[24.70007,30.04419],[25,29.238655],[25,25.6825],[25,22]]]}},{"type":"Feature","properties":{"ADMIN":"Ethiopia","NAME_EN":"Ethiopia","CONTINENT":"Africa","ADM0_A3":"ETH","ISO_A3":"ETH","NAME":"Ethiopia","ISO_A2":"ET","NAME_ZH":"埃塞俄比亚"},"geometry":{"type":"Polygon","coordinates":[[[47.78942,8.003],[44.9636,5.00162],[43.66087,4.95755],[42.76967,4.25259],[42.12861,4.23413],[41.855083,3.918912],[41.1718,3.91909],[40.76848,4.25702],[39.85494,3.83879],[39.559384,3.42206],[38.89251,3.50074],[38.67114,3.61607],[38.43697,3.58851],[38.120915,3.598605],[36.855093,4.447864],[36.159079,4.447864],[35.817448,4.776966],[35.817448,5.338232],[35.298007,5.506],[34.70702,6.59422],[34.25032,6.82607],[34.0751,7.22595],[33.56829,7.71334],[32.95418,7.78497],[33.2948,8.35458],[33.8255,8.37916],[33.97498,8.68456],[33.96162,9.58358],[34.25745,10.63009],[34.73115,10.91017],[34.83163,11.31896],[35.26049,12.08286],[35.86363,12.57828],[36.27022,13.56333],[36.42951,14.42211],[37.59377,14.2131],[37.90607,14.95943],[38.51295,14.50547],[39.0994,14.74064],[39.34061,14.53155],[40.02625,14.51959],[40.8966,14.11864],[41.1552,13.77333],[41.59856,13.45209],[42.00975,12.86582],[42.35156,12.54223],[42,12.1],[41.66176,11.6312],[41.73959,11.35511],[41.75557,11.05091],[42.31414,11.0342],[42.55493,11.10511],[42.776852,10.926879],[42.55876,10.57258],[42.92812,10.02194],[43.29699,9.54048],[43.67875,9.18358],[46.94834,7.99688],[47.78942,8.003]]]}},{"type":"Feature","properties":{"ADMIN":"Djibouti","NAME_EN":"Djibouti","CONTINENT":"Africa","ADM0_A3":"DJI","ISO_A3":"DJI","NAME":"Djibouti","ISO_A2":"DJ","NAME_ZH":"吉布提"},"geometry":{"type":"Polygon","coordinates":[[[42.35156,12.54223],[42.779642,12.455416],[43.081226,12.699639],[43.317852,12.390148],[43.286381,11.974928],[42.715874,11.735641],[43.145305,11.46204],[42.776852,10.926879],[42.55493,11.10511],[42.31414,11.0342],[41.75557,11.05091],[41.73959,11.35511],[41.66176,11.6312],[42,12.1],[42.35156,12.54223]]]}},{"type":"Feature","properties":{"ADMIN":"Somaliland","NAME_EN":"Somaliland","CONTINENT":"Africa","ADM0_A3":"SOL","ISO_A3":"-99","NAME":"Somaliland","ISO_A2":"-99","NAME_ZH":"索马里兰"},"geometry":{"type":"Polygon","coordinates":[[[48.948205,11.410617],[48.948205,11.410617],[48.942005,11.394266],[48.938491,10.982327],[48.938233,9.9735],[48.93813,9.451749],[48.486736,8.837626],[47.78942,8.003],[46.94834,7.99688],[43.67875,9.18358],[43.29699,9.54048],[42.92812,10.02194],[42.55876,10.57258],[42.776852,10.926879],[43.145305,11.46204],[43.47066,11.27771],[43.666668,10.864169],[44.117804,10.445538],[44.614259,10.442205],[45.556941,10.698029],[46.645401,10.816549],[47.525658,11.127228],[48.021596,11.193064],[48.378784,11.375482],[48.948206,11.410622],[48.948205,11.410617]]]}},{"type":"Feature","properties":{"ADMIN":"Uganda","NAME_EN":"Uganda","CONTINENT":"Africa","ADM0_A3":"UGA","ISO_A3":"UGA","NAME":"Uganda","ISO_A2":"UG","NAME_ZH":"乌干达"},"geometry":{"type":"Polygon","coordinates":[[[33.903711,-0.95],[31.86617,-1.02736],[30.76986,-1.01455],[30.419105,-1.134659],[29.821519,-1.443322],[29.579466,-1.341313],[29.587838,-0.587406],[29.819503,-0.20531],[29.875779,0.59738],[30.086154,1.062313],[30.468508,1.583805],[30.85267,1.849396],[31.174149,2.204465],[30.773347,2.339883],[30.83386,3.509166],[30.833852,3.509172],[31.24556,3.7819],[31.88145,3.55827],[32.68642,3.79232],[33.39,3.79],[34.005,4.249885],[34.47913,3.5556],[34.59607,3.05374],[35.03599,1.90584],[34.6721,1.17694],[34.18,0.515],[33.893569,0.109814],[33.903711,-0.95]]]}},{"type":"Feature","properties":{"ADMIN":"Rwanda","NAME_EN":"Rwanda","CONTINENT":"Africa","ADM0_A3":"RWA","ISO_A3":"RWA","NAME":"Rwanda","ISO_A2":"RW","NAME_ZH":"卢旺达"},"geometry":{"type":"Polygon","coordinates":[[[30.419105,-1.134659],[30.816135,-1.698914],[30.758309,-2.28725],[30.46967,-2.41383],[30.469674,-2.413855],[29.938359,-2.348487],[29.632176,-2.917858],[29.024926,-2.839258],[29.117479,-2.292211],[29.254835,-2.21511],[29.291887,-1.620056],[29.579466,-1.341313],[29.821519,-1.443322],[30.419105,-1.134659]]]}},{"type":"Feature","properties":{"ADMIN":"Bosnia and Herzegovina","NAME_EN":"Bosnia and Herzegovina","CONTINENT":"Europe","ADM0_A3":"BIH","ISO_A3":"BIH","NAME":"Bosnia and Herz.","ISO_A2":"BA","NAME_ZH":"波斯尼亚和黑塞哥维那"},"geometry":{"type":"Polygon","coordinates":[[[18.56,42.65],[17.674922,43.028563],[17.297373,43.446341],[16.916156,43.667722],[16.456443,44.04124],[16.23966,44.351143],[15.750026,44.818712],[15.959367,45.233777],[16.318157,45.004127],[16.534939,45.211608],[17.002146,45.233777],[17.861783,45.06774],[18.553214,45.08159],[19.005485,44.860234],[19.00548,44.86023],[19.36803,44.863],[19.11761,44.42307],[19.59976,44.03847],[19.454,43.5681],[19.21852,43.52384],[19.03165,43.43253],[18.70648,43.20011],[18.56,42.65]]]}},{"type":"Feature","properties":{"ADMIN":"North Macedonia","NAME_EN":"North Macedonia","CONTINENT":"Europe","ADM0_A3":"MKD","ISO_A3":"MKD","NAME":"North Macedonia","ISO_A2":"MK","NAME_ZH":"北马其顿"},"geometry":{"type":"Polygon","coordinates":[[[22.380526,42.32026],[22.881374,41.999297],[22.952377,41.337994],[22.76177,41.3048],[22.597308,41.130487],[22.055378,41.149866],[21.674161,40.931275],[21.02004,40.842727],[20.605182,41.086226],[20.463175,41.515089],[20.590247,41.855404],[20.590247,41.855409],[20.71731,41.84711],[20.76216,42.05186],[21.3527,42.2068],[21.576636,42.245224],[21.91708,42.30364],[22.380526,42.32026]]]}},{"type":"Feature","properties":{"ADMIN":"Republic of Serbia","NAME_EN":"Serbia","CONTINENT":"Europe","ADM0_A3":"SRB","ISO_A3":"SRB","NAME":"Serbia","ISO_A2":"RS","NAME_ZH":"塞尔维亚"},"geometry":{"type":"MultiPolygon","coordinates":[[[[18.829825,45.908872],[18.829838,45.908878],[19.596045,46.17173],[20.220192,46.127469],[20.762175,45.734573],[20.874313,45.416375],[21.483526,45.18117],[21.562023,44.768947],[22.145088,44.478422],[22.459022,44.702517],[22.705726,44.578003],[22.474008,44.409228],[22.65715,44.234923],[22.410446,44.008063],[22.500157,43.642814],[22.986019,43.211161],[22.604801,42.898519],[22.436595,42.580321],[22.545012,42.461362],[22.380526,42.32026],[21.91708,42.30364],[21.576636,42.245224],[21.54332,42.32025],[21.66292,42.43922],[21.77505,42.6827],[21.63302,42.67717],[21.43866,42.86255],[21.27421,42.90959],[21.143395,43.068685],[20.95651,43.13094],[20.81448,43.27205],[20.63508,43.21671],[20.49679,42.88469],[20.25758,42.81275],[20.3398,42.89852],[19.95857,43.10604],[19.63,43.21378],[19.48389,43.35229],[19.21852,43.52384],[19.454,43.5681],[19.59976,44.03847],[19.11761,44.42307],[19.36803,44.863],[19.00548,44.86023],[19.005485,44.860234],[19.390476,45.236516],[19.072769,45.521511],[18.829825,45.908872]]],[[[20.590247,41.855409],[20.52295,42.21787],[20.283755,42.32026],[20.0707,42.58863],[20.25758,42.81275],[20.49679,42.88469],[20.63508,43.21671],[20.81448,43.27205],[20.95651,43.13094],[21.143395,43.068685],[21.27421,42.90959],[21.43866,42.86255],[21.63302,42.67717],[21.77505,42.6827],[21.66292,42.43922],[21.54332,42.32025],[21.576636,42.245224],[21.3527,42.2068],[20.76216,42.05186],[20.71731,41.84711],[20.590247,41.855409]]]]}},{"type":"Feature","properties":{"ADMIN":"Montenegro","NAME_EN":"Montenegro","CONTINENT":"Europe","ADM0_A3":"MNE","ISO_A3":"MNE","NAME":"Montenegro","ISO_A2":"ME","NAME_ZH":"黑山"},"geometry":{"type":"Polygon","coordinates":[[[20.0707,42.58863],[19.801613,42.500093],[19.738051,42.688247],[19.304486,42.195745],[19.371768,41.877551],[19.16246,41.95502],[18.88214,42.28151],[18.450017,42.479992],[18.56,42.65],[18.70648,43.20011],[19.03165,43.43253],[19.21852,43.52384],[19.48389,43.35229],[19.63,43.21378],[19.95857,43.10604],[20.3398,42.89852],[20.25758,42.81275],[20.0707,42.58863]]]}},{"type":"Feature","properties":{"ADMIN":"Trinidad and Tobago","NAME_EN":"Trinidad and Tobago","CONTINENT":"North America","ADM0_A3":"TTO","ISO_A3":"TTO","NAME":"Trinidad and Tobago","ISO_A2":"TT","NAME_ZH":"特立尼达和多巴哥"},"geometry":{"type":"Polygon","coordinates":[[[-61.68,10.76],[-61.105,10.89],[-60.895,10.855],[-60.935,10.11],[-61.77,10],[-61.95,10.09],[-61.66,10.365],[-61.68,10.76]]]}},{"type":"Feature","properties":{"ADMIN":"South Sudan","NAME_EN":"South Sudan","CONTINENT":"Africa","ADM0_A3":"SDS","ISO_A3":"SSD","NAME":"S. Sudan","ISO_A2":"SS","NAME_ZH":"南苏丹"},"geometry":{"type":"Polygon","coordinates":[[[30.833852,3.509172],[29.9535,4.173699],[29.715995,4.600805],[29.159078,4.389267],[28.696678,4.455077],[28.428994,4.287155],[27.979977,4.408413],[27.374226,5.233944],[27.213409,5.550953],[26.465909,5.946717],[26.213418,6.546603],[25.796648,6.979316],[25.124131,7.500085],[25.114932,7.825104],[24.567369,8.229188],[23.88698,8.61973],[24.194068,8.728696],[24.537415,8.917538],[24.794926,9.810241],[25.069604,10.27376],[25.790633,10.411099],[25.962307,10.136421],[26.477328,9.55273],[26.752006,9.466893],[27.112521,9.638567],[27.833551,9.604232],[27.97089,9.398224],[28.966597,9.398224],[29.000932,9.604232],[29.515953,9.793074],[29.618957,10.084919],[29.996639,10.290927],[30.837841,9.707237],[31.352862,9.810241],[31.850716,10.531271],[32.400072,11.080626],[32.314235,11.681484],[32.073892,11.97333],[32.67475,12.024832],[32.743419,12.248008],[33.206938,12.179338],[33.086766,11.441141],[33.206938,10.720112],[33.721959,10.325262],[33.842131,9.981915],[33.824963,9.484061],[33.963393,9.464285],[33.97498,8.68456],[33.8255,8.37916],[33.2948,8.35458],[32.95418,7.78497],[33.56829,7.71334],[34.0751,7.22595],[34.25032,6.82607],[34.70702,6.59422],[35.298007,5.506],[34.620196,4.847123],[34.005,4.249885],[33.39,3.79],[32.68642,3.79232],[31.88145,3.55827],[31.24556,3.7819],[30.833852,3.509172]]]}}]} \ No newline at end of file diff --git a/frontend/public/earth/index.html b/frontend/public/earth/index.html index c6f374ae..933f9e70 100644 --- a/frontend/public/earth/index.html +++ b/frontend/public/earth/index.html @@ -51,9 +51,57 @@ document.documentElement.style.setProperty("--hud-scale", clampedScale.toFixed(3)); })(); + (function applyInitialHudPanelVisibility() { + var panelIds = ["legend", "earth-stats", "media-panel", "layer-toggles"]; + var scope = window.innerWidth <= 820 ? "mobile" : "desktop"; + var raw = ""; + try { + raw = + window.localStorage.getItem("planet.earth.settings.v2") || + window.localStorage.getItem("planet.earth.settings.v1") || + ""; + } catch (_error) { + return; + } + if (!raw) return; + + var parsed; + try { + parsed = JSON.parse(raw); + } catch (_error) { + return; + } + if (!parsed || typeof parsed !== "object") return; + + var scopedVisibility = + parsed.views && + parsed.views[scope] && + parsed.views[scope].panelVisibility && + typeof parsed.views[scope].panelVisibility === "object" + ? parsed.views[scope].panelVisibility + : null; + var legacyVisibility = + scope === "desktop" && parsed.panelVisibility && typeof parsed.panelVisibility === "object" + ? parsed.panelVisibility + : null; + var source = scopedVisibility || legacyVisibility; + if (!source) return; + + var version = Number(parsed && parsed.version) || 0; + for (var i = 0; i < panelIds.length; i += 1) { + var panelId = panelIds[i]; + if (panelId === "media-panel" && scope === "desktop" && version < 5) { + continue; + } + if (source[panelId] === false) { + document.documentElement.classList.add("hud-preload-hidden-" + panelId); + } + } + })(); + - + @@ -192,13 +240,13 @@ -
- cloud +
+ partly_cloudy_day
- 大气云图 - 全球云层覆盖 + 气象 + 云图与风场
-
@@ -936,7 +984,7 @@
星空亮度
-
100%
+
200%
地球与地表
@@ -962,6 +1010,36 @@
+
+
+ 地表色调 + 切换地表呈色风格 +
+
+ + + +
+
+
+
+ 地表亮度 + 调节地表光照与贴图明暗 +
+
+ + 100% +
+
地球默认大小 @@ -993,11 +1071,11 @@ min="0.05" max="1" step="0.01" - value="0.62" + value="0.68" data-terrain-opacity-slider aria-label="移动端调整地形透明度" > - 62% + 68%
@@ -1021,6 +1099,47 @@
+ +
气象
+
+
+ 气象图层 + 选择气象开启时显示的气象数据图层。 +
+
+ + +
+
+ +
卫星
近景标签显示阈值
-
400%
+
330%
标签数量上限最多显示的卫星名称数量
-
36
+
16