feat: 工参属性全部由 OpenCode 同一条 SQL 导出;即席查询表没有时间列时不加时间条件
即席查询的 4G/5G 小区工参表没有日期列、4G 只有当前记录,取不到历史日工参,工参不再走即席查询。即席查询的表配置写了 time_field 而表里没有这一列时,按页面做法不带时间条件。
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
"""评估用的 4G/5G 小区工参:按地市、日期整份保存,任务先查库,没有再去大数据平台取。
|
||||
|
||||
一份快照 = 即席查询当天的工参(经纬度是脱敏的)+ OpenCode 导出的当天 CGI 与经纬度,按 CGI 合并,
|
||||
OpenCode 里没有坐标的小区经纬度留空。即席查询取不到,或者它给的 CGI 和 OpenCode 那份对不上时,
|
||||
改由 OpenCode 把属性列一起导出。OpenCode 那份按 eff_from_date/eff_to_date 取当天有效的记录,是日期口径的基准。
|
||||
一份快照由 OpenCode 在一条提示词里导出:全市当天有效(eff_from_date <= 当天 < eff_to_date)的 4G、5G 工参,
|
||||
CGI、经纬度和属性在同一条 SQL 里,没有有效坐标的小区经纬度留空。
|
||||
即席查询的工参表没有日期列,4G 只有当前记录,取不到历史日,所以工参不走即席查询。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,14 +20,12 @@ from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.models import CellData4G, CellData5G, GongcanSnapshot, utcnow
|
||||
from app.nqi import adhoc
|
||||
from app.nqi.client import NqiClient, NqiError
|
||||
from app.nqi.client import NqiClient
|
||||
from app.nqi.opencode import EFFECTIVE, ExportFile, OpenCode, snapshot_where, task_session
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
|
||||
TECHS = ("4G", "5G")
|
||||
ADHOC_TABLES = {"4G": "appdbv3.v_a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"}
|
||||
PLATFORM_TABLES = {"4G": "appdbv3.a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"}
|
||||
KEYS = {"4G": ("cgi",), "5G": ("ncgi", "cgi")}
|
||||
KEY_COLUMN = {"4G": "cgi", "5G": "ncgi"}
|
||||
@@ -38,7 +36,6 @@ ATTRIBUTES = {
|
||||
}
|
||||
CELL_TABLES = {"4G": CellData4G.__table__, "5G": CellData5G.__table__}
|
||||
COORDS = ("longitude", "latitude")
|
||||
MATCH_RATIO = 0.98
|
||||
FAILED_COOLDOWN = timedelta(minutes=10)
|
||||
STALE_LOADING = timedelta(minutes=40)
|
||||
|
||||
@@ -67,30 +64,19 @@ class Target:
|
||||
return f"站点 {self.site}" if self.site else f"小区 {'、'.join(self.cgis)}"
|
||||
|
||||
|
||||
def attribute_columns(tech: str) -> tuple[str, ...]:
|
||||
return ATTRIBUTES[tech]
|
||||
|
||||
|
||||
def adhoc_fields(tech: str) -> tuple[str, ...]:
|
||||
return KEYS[tech] + attribute_columns(tech)
|
||||
|
||||
|
||||
def snapshot_task_name(city: str, day: date) -> str:
|
||||
"""OpenCode 目录名不带日期样式的数字,平台的脱敏会把它当日期改掉。"""
|
||||
return "gc_" + hashlib.sha1(f"{city}|{day.isoformat()}".encode("utf-8")).hexdigest()[:12]
|
||||
|
||||
|
||||
def platform_files(task: str, city: str, day: date, *, attributes: bool) -> list[ExportFile]:
|
||||
"""全市当天有效的工参。只要坐标时三四列;要属性时文字列把英文逗号换成中文逗号,避免 CSV 错列。"""
|
||||
def platform_files(task: str, city: str, day: date) -> list[ExportFile]:
|
||||
"""全市当天有效的工参。文字列把英文逗号换成中文逗号,避免 CSV 错列。"""
|
||||
files = []
|
||||
for tech, name in (("4G", "lte"), ("5G", "nr")):
|
||||
columns = KEYS[tech] + COORDS + EFFECTIVE
|
||||
select_list = list(columns)
|
||||
if attributes:
|
||||
columns += attribute_columns(tech)
|
||||
select_list += [f"replace({column}::text, ',', ',') as {column}" for column in attribute_columns(tech)]
|
||||
plain = KEYS[tech] + COORDS + EFFECTIVE
|
||||
select_list = list(plain) + [f"replace({column}::text, ',', ',') as {column}" for column in ATTRIBUTES[tech]]
|
||||
sql = f"select {', '.join(select_list)} from {PLATFORM_TABLES[tech]} where {snapshot_where(city, day)}"
|
||||
files.append(ExportFile(task, "attr" if attributes else "xy", f"{name}.csv", sql, day, columns))
|
||||
files.append(ExportFile(task, "gc", f"{name}.csv", sql, day, plain + ATTRIBUTES[tech]))
|
||||
return files
|
||||
|
||||
|
||||
@@ -125,11 +111,11 @@ def coordinates(rows: list[dict], tech: str) -> dict[str, tuple[float, float]]:
|
||||
return found
|
||||
|
||||
|
||||
def build_cells(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> list[dict]:
|
||||
"""按 CellData_4G / CellData_5G 的列名组成一行一个小区。"""
|
||||
coords = coordinates(coord_rows, tech)
|
||||
def build_cells(rows: list[dict], tech: str) -> list[dict]:
|
||||
"""按 CellData_4G / CellData_5G 的列名组成一行一个小区,属性取该 CGI 的第一行。"""
|
||||
coords = coordinates(rows, tech)
|
||||
cells: dict[str, dict] = {}
|
||||
for row in attr_rows:
|
||||
for row in rows:
|
||||
key = key_of(row, tech)
|
||||
if not key or key in cells:
|
||||
continue
|
||||
@@ -158,42 +144,16 @@ def unified(row, tech: str) -> dict:
|
||||
return item
|
||||
|
||||
|
||||
def key_overlap(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> float:
|
||||
left = {key_of(row, tech) for row in attr_rows} - {""}
|
||||
right = {key_of(row, tech) for row in coord_rows} - {""}
|
||||
if not left or not right:
|
||||
return 0.0
|
||||
return len(left & right) / len(left | right)
|
||||
|
||||
|
||||
async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *, use_adhoc: bool = True) -> tuple[dict[str, list[dict]], str]:
|
||||
"""从大数据平台取一份快照,返回按制式分开的小区行和属性来源(adhoc / opencode)。"""
|
||||
attrs: dict[str, list[dict]] | None = None
|
||||
if use_adhoc:
|
||||
try:
|
||||
attrs = {tech: await adhoc.export_day(nqi, ADHOC_TABLES[tech], day, city, adhoc_fields(tech)) for tech in TECHS}
|
||||
except NqiError as exc:
|
||||
logger.info("即席查询取 %s %s 工参未成功,改由 OpenCode 导出属性: %s", city, day, exc)
|
||||
attrs = None
|
||||
async def fetch_snapshot(oc: OpenCode, city: str, day: date) -> dict[str, list[dict]]:
|
||||
"""从大数据平台取一份快照,返回按制式分开的小区行。"""
|
||||
task = snapshot_task_name(city, day)
|
||||
async with task_session(oc, task) as session_id:
|
||||
files = platform_files(task, city, day, attributes=attrs is None)
|
||||
files = platform_files(task, city, day)
|
||||
tables = await oc.export(session_id, files)
|
||||
rows = {tech: tables[item.key].rows for tech, item in zip(TECHS, files)}
|
||||
if attrs is not None:
|
||||
ratios = {tech: key_overlap(attrs[tech], rows[tech], tech) for tech in TECHS}
|
||||
if min(ratios.values()) < MATCH_RATIO:
|
||||
logger.info("即席查询的 CGI 与 OpenCode 当天快照重合 %s,改用 OpenCode 的属性", ratios)
|
||||
attrs = None
|
||||
files = platform_files(task, city, day, attributes=True)
|
||||
tables = await oc.export(session_id, files)
|
||||
rows = {tech: tables[item.key].rows for tech, item in zip(TECHS, files)}
|
||||
source = "adhoc" if attrs is not None else "opencode"
|
||||
attrs = attrs if attrs is not None else rows
|
||||
cells = {tech: build_cells(attrs[tech], rows[tech], tech) for tech in TECHS}
|
||||
cells = {tech: build_cells(tables[item.key].rows, tech) for tech, item in zip(TECHS, files)}
|
||||
if not all(cells.values()):
|
||||
raise GongcanError(f"{city} {day} 的工参是空的")
|
||||
return cells, source
|
||||
return cells
|
||||
|
||||
|
||||
_SNAPSHOT = GongcanSnapshot.__table__
|
||||
@@ -230,7 +190,7 @@ def claim_snapshot(engine: Engine, city: str, day: date, now: datetime) -> int |
|
||||
return int(row.id) if taken.rowcount == 1 else None
|
||||
|
||||
|
||||
def save_snapshot(engine: Engine, snapshot_id: int, cells: dict[str, list[dict]], source: str, now: datetime) -> None:
|
||||
def save_snapshot(engine: Engine, snapshot_id: int, cells: dict[str, list[dict]], now: datetime) -> None:
|
||||
with engine.begin() as connection:
|
||||
for tech, table in CELL_TABLES.items():
|
||||
rows = cells.get(tech) or []
|
||||
@@ -242,7 +202,7 @@ def save_snapshot(engine: Engine, snapshot_id: int, cells: dict[str, list[dict]]
|
||||
.where(_SNAPSHOT.c.id == snapshot_id)
|
||||
.values(
|
||||
status="ready",
|
||||
attr_source=source,
|
||||
attr_source="opencode",
|
||||
lte_cells=len(cells.get("4G") or []),
|
||||
nr_cells=len(cells.get("5G") or []),
|
||||
located_cells=sum(1 for rows in cells.values() for row in rows if row["latitude"] is not None),
|
||||
@@ -275,7 +235,7 @@ class GongcanStore:
|
||||
def __init__(
|
||||
self,
|
||||
engine: Engine,
|
||||
loader: Callable[[str, date], Awaitable[tuple[dict[str, list[dict]], str]]],
|
||||
loader: Callable[[str, date], Awaitable[dict[str, list[dict]]]],
|
||||
*,
|
||||
poll_seconds: float = 10.0,
|
||||
wait_timeout: timedelta = timedelta(minutes=45),
|
||||
@@ -338,19 +298,19 @@ class GongcanStore:
|
||||
|
||||
async def _load(self, snapshot_id: int, city: str, day: date) -> None:
|
||||
try:
|
||||
cells, source = await self.loader(city, day)
|
||||
save_snapshot(self.engine, snapshot_id, cells, source, self.clock())
|
||||
cells = await self.loader(city, day)
|
||||
save_snapshot(self.engine, snapshot_id, cells, self.clock())
|
||||
except BaseException as exc:
|
||||
fail_snapshot(self.engine, snapshot_id, f"{type(exc).__name__}: {exc}", self.clock())
|
||||
raise
|
||||
logger.info("工参快照 %s %s 已入库:4G %s 个、5G %s 个小区,属性来自 %s", city, day, len(cells.get("4G") or []), len(cells.get("5G") or []), source)
|
||||
logger.info("工参快照 %s %s 已入库:4G %s 个、5G %s 个小区", city, day, len(cells.get("4G") or []), len(cells.get("5G") or []))
|
||||
|
||||
|
||||
def platform_loader(nqi: NqiClient, *, use_adhoc: bool = True) -> Callable[[str, date], Awaitable[tuple[dict[str, list[dict]], str]]]:
|
||||
def platform_loader(nqi: NqiClient) -> Callable[[str, date], Awaitable[dict[str, list[dict]]]]:
|
||||
oc = OpenCode(nqi)
|
||||
|
||||
async def load(city: str, day: date) -> tuple[dict[str, list[dict]], str]:
|
||||
return await fetch_snapshot(nqi, oc, city, day, use_adhoc=use_adhoc)
|
||||
async def load(city: str, day: date) -> dict[str, list[dict]]:
|
||||
return await fetch_snapshot(oc, city, day)
|
||||
|
||||
return load
|
||||
|
||||
|
||||
Reference in New Issue
Block a user