feat: 工参按地市和日期入库,先查库再从大数据平台取
即席查询取工参属性,OpenCode 导出当天全市 CGI 和经纬度,按 CGI 合并后存成快照;即席查询失败或 CGI 对不上时改由 OpenCode 一并导出属性。拆除前后的工参日期按库优先、逐月回溯的规则选取,多个任务取同一天时只取一次。即席查询 getTableCount 出错不再被当成 0 行。
This commit is contained in:
@@ -0,0 +1,437 @@
|
||||
"""评估用的 4G/5G 小区工参:按地市、日期整份保存,任务先查库,没有再去大数据平台取。
|
||||
|
||||
一份快照 = 即席查询当天的工参(经纬度是脱敏的)+ OpenCode 导出的当天 CGI 与经纬度,按 CGI 合并,
|
||||
OpenCode 里没有坐标的小区经纬度留空。即席查询取不到,或者它给的 CGI 和 OpenCode 那份对不上时,
|
||||
改由 OpenCode 把属性列一起导出。OpenCode 那份按 eff_from_date/eff_to_date 取当天有效的记录,是日期口径的基准。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import math
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import delete, exists, insert, select, update
|
||||
from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.models import GongcanCell, GongcanSnapshot, utcnow
|
||||
from app.nqi import adhoc
|
||||
from app.nqi.client import NqiClient, NqiError
|
||||
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")}
|
||||
NAMED_FIELDS = {
|
||||
"4G": {"cell_name": "cell_name", "site_name": "station_name", "node_id": "enodeb_id", "node_name": "enodeb_name"},
|
||||
"5G": {"cell_name": "nrcell_name", "site_name": "station_name", "node_id": "gnodeb_id", "node_name": "gnodeb_name"},
|
||||
}
|
||||
SHARED_FIELDS = ("network_type", "area", "town", "state", "cover_type", "frequency_band", "vendor", "azimuth")
|
||||
COORDS = ("longitude", "latitude")
|
||||
MATCH_RATIO = 0.98
|
||||
FAILED_COOLDOWN = timedelta(minutes=10)
|
||||
STALE_LOADING = timedelta(minutes=40)
|
||||
|
||||
|
||||
class GongcanError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class GongcanMissing(GongcanError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Target:
|
||||
"""一个评估任务的对象:一个或几个 CGI,或者一个站点名。"""
|
||||
|
||||
cgis: tuple[str, ...] = ()
|
||||
site: str = ""
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if bool(self.cgis) == bool(self.site):
|
||||
raise ValueError("目标要么给 CGI,要么给站点名称")
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
return f"站点 {self.site}" if self.site else f"小区 {'、'.join(self.cgis)}"
|
||||
|
||||
|
||||
def attribute_columns(tech: str) -> tuple[str, ...]:
|
||||
return tuple(NAMED_FIELDS[tech].values()) + SHARED_FIELDS
|
||||
|
||||
|
||||
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 错列。"""
|
||||
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)]
|
||||
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))
|
||||
return files
|
||||
|
||||
|
||||
def key_of(row: dict, tech: str) -> str:
|
||||
for name in KEYS[tech]:
|
||||
value = str(row.get(name) or "").strip()
|
||||
if value:
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
def valid_coordinate(lon: object, lat: object) -> tuple[float | None, float | None]:
|
||||
try:
|
||||
lon_value, lat_value = float(lon), float(lat)
|
||||
except (TypeError, ValueError):
|
||||
return None, None
|
||||
if 70 <= lon_value <= 140 and 15 <= lat_value <= 55:
|
||||
return lon_value, lat_value
|
||||
return None, None
|
||||
|
||||
|
||||
def coordinates(rows: list[dict], tech: str) -> dict[str, tuple[float, float]]:
|
||||
"""4G 表一行一个天线,同一 CGI 会有多行,取第一条有效坐标。"""
|
||||
found: dict[str, tuple[float, float]] = {}
|
||||
for row in rows:
|
||||
key = key_of(row, tech)
|
||||
if not key or key in found:
|
||||
continue
|
||||
lon, lat = valid_coordinate(row.get("longitude"), row.get("latitude"))
|
||||
if lon is not None:
|
||||
found[key] = (lat, lon)
|
||||
return found
|
||||
|
||||
|
||||
def build_cells(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> list[dict]:
|
||||
coords = coordinates(coord_rows, tech)
|
||||
mapping = {**NAMED_FIELDS[tech], **{name: name for name in SHARED_FIELDS}}
|
||||
cells: dict[str, dict] = {}
|
||||
for row in attr_rows:
|
||||
key = key_of(row, tech)
|
||||
if not key or key in cells:
|
||||
continue
|
||||
lat, lon = coords.get(key, (None, None))
|
||||
cell = {"tech": tech, "cgi": key, "latitude": lat, "longitude": lon}
|
||||
for target, source in mapping.items():
|
||||
cell[target] = str(row.get(source) or "").strip()
|
||||
cells[key] = cell
|
||||
return list(cells.values())
|
||||
|
||||
|
||||
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[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
|
||||
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)
|
||||
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 = [cell for tech in TECHS for cell in build_cells(attrs[tech], rows[tech], tech)]
|
||||
if not any(cell["tech"] == "4G" for cell in cells) or not any(cell["tech"] == "5G" for cell in cells):
|
||||
raise GongcanError(f"{city} {day} 的工参是空的")
|
||||
return cells, source
|
||||
|
||||
|
||||
_SNAPSHOT = GongcanSnapshot.__table__
|
||||
_CELL = GongcanCell.__table__
|
||||
|
||||
|
||||
def _aware(value: datetime) -> datetime:
|
||||
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def claim_snapshot(engine: Engine, city: str, day: date, now: datetime) -> int | None:
|
||||
"""抢到取数权返回快照 id;已就绪、别人正在取、或刚失败还在冷却时返回 None。"""
|
||||
try:
|
||||
with engine.begin() as connection:
|
||||
result = connection.execute(
|
||||
insert(_SNAPSHOT).values(city=city, snapshot_date=day, status="loading", error="", created_at=now, updated_at=now)
|
||||
)
|
||||
return int(result.inserted_primary_key[0])
|
||||
except IntegrityError:
|
||||
pass
|
||||
with engine.begin() as connection:
|
||||
row = connection.execute(
|
||||
select(_SNAPSHOT.c.id, _SNAPSHOT.c.status, _SNAPSHOT.c.updated_at).where(_SNAPSHOT.c.city == city, _SNAPSHOT.c.snapshot_date == day)
|
||||
).first()
|
||||
if row is None or row.status == "ready":
|
||||
return None
|
||||
wait = FAILED_COOLDOWN if row.status == "failed" else STALE_LOADING
|
||||
if _aware(row.updated_at) > now - wait:
|
||||
return None
|
||||
taken = connection.execute(
|
||||
update(_SNAPSHOT)
|
||||
.where(_SNAPSHOT.c.id == row.id, _SNAPSHOT.c.status == row.status, _SNAPSHOT.c.updated_at <= now - wait)
|
||||
.values(status="loading", error="", updated_at=now)
|
||||
)
|
||||
return int(row.id) if taken.rowcount == 1 else None
|
||||
|
||||
|
||||
def save_snapshot(engine: Engine, snapshot_id: int, cells: list[dict], source: str, now: datetime) -> None:
|
||||
with engine.begin() as connection:
|
||||
connection.execute(delete(_CELL).where(_CELL.c.snapshot_id == snapshot_id))
|
||||
for start in range(0, len(cells), 2000):
|
||||
connection.execute(insert(_CELL), [{**cell, "snapshot_id": snapshot_id} for cell in cells[start:start + 2000]])
|
||||
connection.execute(
|
||||
update(_SNAPSHOT)
|
||||
.where(_SNAPSHOT.c.id == snapshot_id)
|
||||
.values(
|
||||
status="ready",
|
||||
attr_source=source,
|
||||
lte_cells=sum(1 for cell in cells if cell["tech"] == "4G"),
|
||||
nr_cells=sum(1 for cell in cells if cell["tech"] == "5G"),
|
||||
located_cells=sum(1 for cell in cells if cell["latitude"] is not None),
|
||||
error="",
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def fail_snapshot(engine: Engine, snapshot_id: int, error: str, now: datetime) -> None:
|
||||
with engine.begin() as connection:
|
||||
connection.execute(update(_SNAPSHOT).where(_SNAPSHOT.c.id == snapshot_id).values(status="failed", error=error[:500], updated_at=now))
|
||||
|
||||
|
||||
def _has_target(target: Target):
|
||||
condition = _CELL.c.site_name == target.site if target.site else _CELL.c.cgi.in_(target.cgis)
|
||||
return exists(select(_CELL.c.id).where(_CELL.c.snapshot_id == _SNAPSHOT.c.id, condition))
|
||||
|
||||
|
||||
def _ready(city: str, start: date, end: date):
|
||||
return (_SNAPSHOT.c.city == city, _SNAPSHOT.c.status == "ready", _SNAPSHOT.c.snapshot_date >= start, _SNAPSHOT.c.snapshot_date < end)
|
||||
|
||||
|
||||
class GongcanStore:
|
||||
"""快照的读写和按需取数。loader 负责从平台取一份快照,测试里可以换成假的。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
engine: Engine,
|
||||
loader: Callable[[str, date], Awaitable[tuple[list[dict], str]]],
|
||||
*,
|
||||
poll_seconds: float = 10.0,
|
||||
wait_timeout: timedelta = timedelta(minutes=45),
|
||||
clock: Callable[[], datetime] = utcnow,
|
||||
):
|
||||
self.engine = engine
|
||||
self.loader = loader
|
||||
self.poll_seconds = poll_seconds
|
||||
self.wait_timeout = wait_timeout
|
||||
self.clock = clock
|
||||
|
||||
def ready_dates(self, city: str, start: date, end: date) -> list[date]:
|
||||
"""start <= 日期 < end 的已就绪快照。"""
|
||||
with self.engine.connect() as connection:
|
||||
return sorted(connection.execute(select(_SNAPSHOT.c.snapshot_date).where(*_ready(city, start, end))).scalars())
|
||||
|
||||
def dates_with_target(self, city: str, target: Target, start: date, end: date) -> list[date]:
|
||||
with self.engine.connect() as connection:
|
||||
query = select(_SNAPSHOT.c.snapshot_date).where(*_ready(city, start, end), _has_target(target))
|
||||
return sorted(connection.execute(query).scalars())
|
||||
|
||||
def has_target(self, city: str, day: date, target: Target) -> bool:
|
||||
return bool(self.dates_with_target(city, target, day, day + timedelta(days=1)))
|
||||
|
||||
def cells(self, city: str, day: date) -> list[dict]:
|
||||
columns = [column for column in _CELL.c if column.name not in ("id", "snapshot_id")]
|
||||
with self.engine.connect() as connection:
|
||||
query = select(*columns).join(_SNAPSHOT, _SNAPSHOT.c.id == _CELL.c.snapshot_id).where(*_ready(city, day, day + timedelta(days=1)))
|
||||
return [dict(row._mapping) for row in connection.execute(query)]
|
||||
|
||||
def _state(self, city: str, day: date):
|
||||
with self.engine.connect() as connection:
|
||||
return connection.execute(
|
||||
select(_SNAPSHOT.c.status, _SNAPSHOT.c.error).where(_SNAPSHOT.c.city == city, _SNAPSHOT.c.snapshot_date == day)
|
||||
).first()
|
||||
|
||||
async def ensure(self, city: str, day: date) -> None:
|
||||
"""库里没有这一天就去平台取。别的任务正在取同一天时等它,不重复取。"""
|
||||
deadline = self.clock() + self.wait_timeout
|
||||
while True:
|
||||
state = self._state(city, day)
|
||||
if state is not None and state.status == "ready":
|
||||
return
|
||||
snapshot_id = claim_snapshot(self.engine, city, day, self.clock())
|
||||
if snapshot_id is not None:
|
||||
await self._load(snapshot_id, city, day)
|
||||
return
|
||||
state = self._state(city, day)
|
||||
if state is not None and state.status == "failed":
|
||||
raise GongcanError(f"{city} {day} 的工参刚取失败,稍后再试:{state.error}")
|
||||
if self.clock() > deadline:
|
||||
raise GongcanError(f"等待 {city} {day} 的工参超时")
|
||||
await asyncio.sleep(self.poll_seconds)
|
||||
|
||||
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())
|
||||
except BaseException as exc:
|
||||
fail_snapshot(self.engine, snapshot_id, f"{type(exc).__name__}: {exc}", self.clock())
|
||||
raise
|
||||
logger.info("工参快照 %s %s 已入库:%s 个小区,属性来自 %s", city, day, len(cells), source)
|
||||
|
||||
|
||||
def platform_loader(nqi: NqiClient, *, use_adhoc: bool = True) -> Callable[[str, date], Awaitable[tuple[list[dict], str]]]:
|
||||
oc = OpenCode(nqi)
|
||||
|
||||
async def load(city: str, day: date) -> tuple[list[dict], str]:
|
||||
return await fetch_snapshot(nqi, oc, city, day, use_adhoc=use_adhoc)
|
||||
|
||||
return load
|
||||
|
||||
|
||||
def china_today() -> date:
|
||||
return (datetime.now(timezone.utc) + timedelta(hours=8)).date()
|
||||
|
||||
|
||||
def month_start(day: date, offset: int = 0) -> date:
|
||||
index = day.year * 12 + day.month - 1 + offset
|
||||
return date(index // 12, index % 12 + 1, 1)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AfterPick:
|
||||
day: date
|
||||
target_present: bool
|
||||
|
||||
|
||||
async def pick_before(store: GongcanStore, city: str, target: Target, removal: date, months: int = 3) -> date:
|
||||
"""拆除前用的工参日期。
|
||||
|
||||
库里拆除日前、近 months 个月(从 months 个月前的 1 号算起)有目标的快照,取最晚的一份;
|
||||
没有就从拆除日上个月 1 号起逐月往前,库里没有的那天才去平台取,取到有目标的为止。
|
||||
"""
|
||||
earliest = month_start(removal, -months)
|
||||
found = store.dates_with_target(city, target, earliest, removal)
|
||||
if found:
|
||||
return found[-1]
|
||||
stored = set(store.ready_dates(city, earliest, removal))
|
||||
for back in range(1, months + 1):
|
||||
day = month_start(removal, -back)
|
||||
if day in stored:
|
||||
continue
|
||||
await store.ensure(city, day)
|
||||
if store.has_target(city, day, target):
|
||||
return day
|
||||
raise GongcanMissing(f"拆除前 {months} 个月的工参里都没有{target.label}")
|
||||
|
||||
|
||||
async def pick_after(store: GongcanStore, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
|
||||
"""拆除后用的工参日期,越接近今天越好。
|
||||
|
||||
库里拆除日之后、目标已经不在的快照取最晚的一份;都还在时,最晚那份是昨天就直接用,
|
||||
不是就去平台取昨天的。目标仍在只做标记,不算失败。拆除日还没过去时返回 None。
|
||||
"""
|
||||
yesterday = today - timedelta(days=1)
|
||||
if yesterday <= removal:
|
||||
return None
|
||||
start = removal + timedelta(days=1)
|
||||
stored = store.ready_dates(city, start, today)
|
||||
present = set(store.dates_with_target(city, target, start, today))
|
||||
absent = [day for day in stored if day not in present]
|
||||
if absent:
|
||||
return AfterPick(absent[-1], False)
|
||||
if stored and stored[-1] == yesterday:
|
||||
return AfterPick(yesterday, True)
|
||||
await store.ensure(city, yesterday)
|
||||
return AfterPick(yesterday, store.has_target(city, yesterday, target))
|
||||
|
||||
|
||||
def is_indoor(cell: dict) -> bool:
|
||||
return "W-" in (cell.get("cell_name") or "")
|
||||
|
||||
|
||||
def evaluable(cell: dict) -> bool:
|
||||
"""与模板工具入库规则一致:去室分(小区名含 W-)和 4G 的 NB-IoT。"""
|
||||
return not is_indoor(cell) and not (cell.get("tech") == "4G" and (cell.get("network_type") or "").upper() == "NB-IOT")
|
||||
|
||||
|
||||
def haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
||||
p1, p2 = math.radians(lat1), math.radians(lat2)
|
||||
a = math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lon2 - lon1) / 2) ** 2
|
||||
return 2 * 6371000.0 * math.asin(math.sqrt(a))
|
||||
|
||||
|
||||
def target_center(cells: list[dict]) -> tuple[float, float] | None:
|
||||
"""目标坐标取室外小区的平均;全是室分时用全部有坐标的小区。"""
|
||||
located = [cell for cell in cells if cell.get("latitude") is not None]
|
||||
chosen = [cell for cell in located if evaluable(cell)] or located
|
||||
if not chosen:
|
||||
return None
|
||||
return sum(cell["latitude"] for cell in chosen) / len(chosen), sum(cell["longitude"] for cell in chosen) / len(chosen)
|
||||
|
||||
|
||||
def nearest_sites(
|
||||
cells: list[dict],
|
||||
lat: float,
|
||||
lon: float,
|
||||
*,
|
||||
exclude: set[str],
|
||||
k: int = 3,
|
||||
exclude_keywords: tuple[str, ...] = ("微小",),
|
||||
) -> list[tuple[str, float]]:
|
||||
"""站点坐标取其可评估小区坐标的平均,按到目标的距离取最近 k 个,1 米内的视为同址不算。"""
|
||||
sums: dict[str, list[float]] = {}
|
||||
for cell in cells:
|
||||
site = cell.get("site_name") or ""
|
||||
if cell.get("latitude") is None or not site or site in exclude or not evaluable(cell):
|
||||
continue
|
||||
if any(word in (cell.get("cell_name") or "") for word in exclude_keywords):
|
||||
continue
|
||||
acc = sums.setdefault(site, [0.0, 0.0, 0.0])
|
||||
acc[0] += cell["latitude"]
|
||||
acc[1] += cell["longitude"]
|
||||
acc[2] += 1
|
||||
found = []
|
||||
for site, (lat_sum, lon_sum, count) in sums.items():
|
||||
dist = haversine(lat, lon, lat_sum / count, lon_sum / count)
|
||||
if dist >= 1.0:
|
||||
found.append((site, round(dist, 1)))
|
||||
found.sort(key=lambda item: item[1])
|
||||
return found[:k]
|
||||
@@ -32,6 +32,8 @@ APP_TABLES = {
|
||||
"celldata",
|
||||
"collection_source",
|
||||
"export_task",
|
||||
"gongcan_snapshot",
|
||||
"gongcan_cell",
|
||||
}
|
||||
_UNSAFE = re.compile(r"[^0-9A-Za-z_]+")
|
||||
_CHUNK = 300
|
||||
|
||||
+48
-2
@@ -1,8 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from sqlalchemy import JSON, Boolean, DateTime, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy import JSON, BigInteger, Boolean, Date, DateTime, Float, ForeignKey, Index, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
|
||||
@@ -82,6 +82,52 @@ class CollectionSource(Base):
|
||||
last_error: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class GongcanSnapshot(Base):
|
||||
"""某地市某一天的全量 4G/5G 小区工参。status 兼作取数锁:loading 时别的任务等它。"""
|
||||
|
||||
__tablename__ = "gongcan_snapshot"
|
||||
__table_args__ = (UniqueConstraint("city", "snapshot_date", name="uq_gongcan_city_date"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
city: Mapped[str] = mapped_column(String(32))
|
||||
snapshot_date: Mapped[date] = mapped_column(Date)
|
||||
status: Mapped[str] = mapped_column(String(16), default="loading")
|
||||
attr_source: Mapped[str] = mapped_column(String(16), default="")
|
||||
lte_cells: Mapped[int] = mapped_column(Integer, default=0)
|
||||
nr_cells: Mapped[int] = mapped_column(Integer, default=0)
|
||||
located_cells: Mapped[int] = mapped_column(Integer, default=0)
|
||||
error: Mapped[str] = mapped_column(Text, default="")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
|
||||
|
||||
class GongcanCell(Base):
|
||||
__tablename__ = "gongcan_cell"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("snapshot_id", "cgi", "tech", name="uq_gongcan_cell"),
|
||||
Index("ix_gongcan_cell_site", "snapshot_id", "site_name"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True)
|
||||
snapshot_id: Mapped[int] = mapped_column(ForeignKey("gongcan_snapshot.id", ondelete="CASCADE"))
|
||||
tech: Mapped[str] = mapped_column(String(4))
|
||||
cgi: Mapped[str] = mapped_column(String(64))
|
||||
cell_name: Mapped[str] = mapped_column(Text, default="")
|
||||
site_name: Mapped[str] = mapped_column(Text, default="")
|
||||
latitude: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
longitude: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
network_type: Mapped[str] = mapped_column(Text, default="")
|
||||
node_id: Mapped[str] = mapped_column(Text, default="")
|
||||
node_name: Mapped[str] = mapped_column(Text, default="")
|
||||
area: Mapped[str] = mapped_column(Text, default="")
|
||||
town: Mapped[str] = mapped_column(Text, default="")
|
||||
state: Mapped[str] = mapped_column(Text, default="")
|
||||
cover_type: Mapped[str] = mapped_column(Text, default="")
|
||||
frequency_band: Mapped[str] = mapped_column(Text, default="")
|
||||
vendor: Mapped[str] = mapped_column(Text, default="")
|
||||
azimuth: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class ExportTask(Base):
|
||||
__tablename__ = "export_task"
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from datetime import date, datetime, timedelta
|
||||
from urllib.parse import urlencode
|
||||
|
||||
@@ -156,9 +158,7 @@ async def export_table(
|
||||
"result": json.dumps({"result": selected}, ensure_ascii=False),
|
||||
"where": json.dumps(where, ensure_ascii=False),
|
||||
}
|
||||
counted = await _post_json(client, f"{PAGE}/getTableCount", common)
|
||||
total = int(counted.get("count") or 0) if isinstance(counted, dict) else 0
|
||||
index_count = str(counted.get("indexcount") or "0") if isinstance(counted, dict) else "0"
|
||||
total, index_count = await _count(client, common)
|
||||
rows: list[dict] = []
|
||||
start_at = 0
|
||||
pages = 0
|
||||
@@ -192,6 +192,88 @@ async def export_table(
|
||||
return title, columns, rows
|
||||
|
||||
|
||||
async def export_day(
|
||||
client: NqiClient,
|
||||
tablename: str,
|
||||
day: date,
|
||||
city: str,
|
||||
fields: tuple[str, ...],
|
||||
*,
|
||||
page_size: int = PAGE_SIZE,
|
||||
pause_seconds: float = 0.3,
|
||||
) -> list[dict]:
|
||||
"""取一张表某一天、某个地市的指定几列。
|
||||
|
||||
维度有多个可选值时(如“小区,网格,地市,分公司”“天粒度”),按页面默认取第一个并去掉“粒度”。
|
||||
翻页按实际返回的行数推进,平台把每页压到更少时也不会漏行;取不全就报错。
|
||||
"""
|
||||
await ensure_session(client)
|
||||
columns = await _columns(client, tablename)
|
||||
selected = [column for column in columns if column.get("columnname") in fields]
|
||||
missing = set(fields) - {str(column.get("columnname")) for column in selected}
|
||||
if missing:
|
||||
raise NqiError(f"{tablename} 缺少字段:{'、'.join(sorted(missing))}")
|
||||
head = columns[0]
|
||||
common = {
|
||||
"geographicdimension": _first_choice(head.get("geographicdimension")),
|
||||
"timedimension": _first_choice(head.get("timedimension")).removesuffix("粒度"),
|
||||
"enodebField": head.get("enodeb_field") or "",
|
||||
"cgiField": head.get("cgi_field") or "",
|
||||
"timeField": head.get("time_field") or "starttime",
|
||||
"cellField": head.get("cell_field") or "",
|
||||
"cityField": head.get("city_field") or "city",
|
||||
"result": json.dumps({"result": [_field(column) for column in selected]}, ensure_ascii=False),
|
||||
"where": json.dumps(_where(head, _start(day), _end(day), city), ensure_ascii=False),
|
||||
}
|
||||
total, index_count = await _count(client, common)
|
||||
rows: list[dict] = []
|
||||
pages = 0
|
||||
while len(rows) < total:
|
||||
pages += 1
|
||||
if pages > MAX_PAGES:
|
||||
raise NqiError("数据行数超出单次导出上限")
|
||||
page = await _post_json(
|
||||
client,
|
||||
f"{PAGE}/getTable",
|
||||
{
|
||||
**common,
|
||||
**_column_form(selected),
|
||||
"draw": pages,
|
||||
"start": len(rows),
|
||||
"length": page_size,
|
||||
"indexcount": index_count,
|
||||
"total": total,
|
||||
"order[0][column]": 0,
|
||||
"order[0][dir]": "desc",
|
||||
"search[value]": "",
|
||||
"search[regex]": "false",
|
||||
},
|
||||
)
|
||||
data = page.get("data") if isinstance(page, dict) else None
|
||||
batch = [item for item in data if isinstance(item, dict)] if isinstance(data, list) else []
|
||||
if not batch:
|
||||
break
|
||||
rows.extend(batch)
|
||||
if pause_seconds:
|
||||
await asyncio.sleep(pause_seconds)
|
||||
if len(rows) < total:
|
||||
raise NqiError(f"{tablename} 只取到 {len(rows)} 行,应有 {total} 行")
|
||||
return rows
|
||||
|
||||
|
||||
def _first_choice(value: object) -> str:
|
||||
return re.split(r"[,,.、]", str(value or ""))[0].strip()
|
||||
|
||||
|
||||
async def _count(client: NqiClient, common: dict) -> tuple[int, str]:
|
||||
"""平台出错时返回 {"stat":"0"},没有 count。不能当成 0 行。"""
|
||||
counted = await _post_json(client, f"{PAGE}/getTableCount", common)
|
||||
if not isinstance(counted, dict) or "count" not in counted:
|
||||
message = counted.get("message") if isinstance(counted, dict) else ""
|
||||
raise NqiError(f"即席查询没有返回行数{f':{message}' if message and message != 'null' else ''}")
|
||||
return int(counted.get("count") or 0), str(counted.get("indexcount") or "0")
|
||||
|
||||
|
||||
def _field(column: dict) -> dict:
|
||||
return {
|
||||
"feildtype": column.get("fieldtype") or "",
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
"""大数据平台 OpenCode 取数。
|
||||
|
||||
平台 AI 只能用 adhoc_query 技能把 SQL 结果导出成 CSV。程序给它写死的导出命令,
|
||||
再按导出脚本的输出、实际执行的 SQL 和文件内容核对结果,AI 回复的文字只记录不采信。
|
||||
一个任务一个会话、一个 /workspace/tasks/<任务> 目录,取完先让 AI 删目录,再删会话。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import posixpath
|
||||
import random
|
||||
import re
|
||||
import shlex
|
||||
import string
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
|
||||
import httpx
|
||||
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
||||
from app.nqi.constants import ORIGIN
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
|
||||
OPENCODE = f"{ORIGIN}/pro-opencode"
|
||||
PROVISION_PID = "LXWXYWGZT"
|
||||
WORKSPACE = "/workspace"
|
||||
TASKS_DIR = "tasks"
|
||||
MODEL_ID = "DeepSeek-V4-Flash-0731-w8a8"
|
||||
EXPORT_SCRIPT = "script/download-file-all-async.py"
|
||||
SAVED = re.compile(r"文件已保存至[::]\s*(\S+)")
|
||||
EMPTY_RESULT = "服务端响应体为空"
|
||||
EFFECTIVE = ("eff_from_date", "eff_to_date")
|
||||
_NAME = re.compile(r"^[0-9A-Za-z_]{1,80}$")
|
||||
_FILENAME = re.compile(r"^[0-9A-Za-z_]{1,60}\.csv$")
|
||||
_SHELL_UNSAFE = ('"', "`", "$", "\\", "\n", "\r")
|
||||
_BASE62 = string.digits + string.ascii_letters
|
||||
|
||||
|
||||
class OpenCodeError(NqiError):
|
||||
pass
|
||||
|
||||
|
||||
def task_dir_name(key: str) -> str:
|
||||
"""目录名只留字母、数字和下划线。CGI 的横线也换掉,带中文的另加摘要避免重名。"""
|
||||
text = (key or "").strip()
|
||||
if not text:
|
||||
raise ValueError("任务名称为空")
|
||||
name = re.sub(r"_+", "_", re.sub(r"[^0-9A-Za-z]+", "_", text)).strip("_")
|
||||
if not name or re.search(r"[^\x00-\x7f]", text):
|
||||
digest = hashlib.sha1(text.encode("utf-8")).hexdigest()[:10]
|
||||
name = f"{name[:60]}_{digest}".strip("_")
|
||||
return name[:80]
|
||||
|
||||
|
||||
def sql_text(value: str) -> str:
|
||||
text = str(value)
|
||||
if any(char in text for char in _SHELL_UNSAFE):
|
||||
raise ValueError("取值里有不能放进导出命令的字符")
|
||||
return "'" + text.replace("'", "''") + "'"
|
||||
|
||||
|
||||
def day_sql(day: date) -> str:
|
||||
"""平台在 AI 前面会把 YYYY-MM-DD 换成占位符,还原时会串号,所以日期不写成这种字面量。"""
|
||||
return f"make_date({day.year}, {day.month}, {day.day})"
|
||||
|
||||
|
||||
def snapshot_where(city: str, day: date) -> str:
|
||||
expr = day_sql(day)
|
||||
return f"city = {sql_text(city)} and eff_from_date <= {expr} and eff_to_date > {expr}"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExportFile:
|
||||
task: str
|
||||
phase: str
|
||||
filename: str
|
||||
sql: str
|
||||
day: date
|
||||
required: tuple[str, ...]
|
||||
key: str = ""
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not _NAME.match(self.task) or not _NAME.match(self.phase):
|
||||
raise ValueError("任务或阶段名称不合法")
|
||||
if not _FILENAME.match(self.filename):
|
||||
raise ValueError("文件名不合法")
|
||||
if any(char in self.sql for char in _SHELL_UNSAFE):
|
||||
raise ValueError("SQL 里有不能放进导出命令的字符")
|
||||
if not self.required:
|
||||
raise ValueError("没有指定必需的列")
|
||||
if not self.key:
|
||||
object.__setattr__(self, "key", f"{self.phase}/{self.filename.rsplit('.', 1)[0]}")
|
||||
|
||||
@property
|
||||
def save_dir(self) -> str:
|
||||
return f"{WORKSPACE}/{TASKS_DIR}/{self.task}/{self.phase}"
|
||||
|
||||
@property
|
||||
def path(self) -> str:
|
||||
return f"{self.save_dir}/{self.filename}"
|
||||
|
||||
def command(self) -> str:
|
||||
return f'python {EXPORT_SCRIPT} --sql "{self.sql}" --save-dir "{self.save_dir}" --filename "{self.filename}"'
|
||||
|
||||
def retry(self, attempt: int) -> "ExportFile":
|
||||
stem = re.sub(r"_r\d+$", "", self.filename.rsplit(".", 1)[0])
|
||||
return ExportFile(self.task, self.phase, f"{stem}_r{attempt}.csv", self.sql, self.day, self.required, self.key)
|
||||
|
||||
|
||||
def export_prompt(files: list[ExportFile]) -> str:
|
||||
lines = [
|
||||
"请加载并严格遵循 adhoc_query 技能完成数据导出。这是程序发起的自动任务,没有人会回答问题:",
|
||||
f"不要询问、不要确认、不要预览数据,直接在 adhoc_query 技能目录下按顺序执行下面 {len(files)} 条命令,每条单独执行。",
|
||||
"SQL 已经过校验,一个字符都不能改,也不要按技能规范重写。",
|
||||
"",
|
||||
]
|
||||
lines += _numbered_commands(files)
|
||||
lines += [
|
||||
"",
|
||||
"要求:",
|
||||
"1. 导出脚本会自己创建保存目录;不得使用其他目录,不得改文件名。",
|
||||
"2. 只执行这些导出命令,不要额外查询或统计。某条失败时继续执行后面的命令。",
|
||||
"3. 全部执行完后,每条命令输出一行结果,成功写 DONE <序号> <保存的绝对路径>,失败写 FAIL <序号> <错误原因>。",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def redo_prompt(files: list[ExportFile]) -> str:
|
||||
lines = ["刚才有命令执行时 SQL 被改动了,导出的数据不能用。", "请原样执行下面的命令,SQL、目录、文件名都不能做任何修改:", ""]
|
||||
lines += _numbered_commands(files)
|
||||
lines += ["", "全部执行完后,每条命令输出一行结果,成功写 DONE <序号> <保存的绝对路径>,失败写 FAIL <序号> <错误原因>。"]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def cleanup_prompt(task: str) -> str:
|
||||
"""直接给出删除命令会被平台的安全规则拒绝,用自然语言说明要删的目录。"""
|
||||
folder = f"{WORKSPACE}/{TASKS_DIR}/{task}"
|
||||
return (
|
||||
f"现在清理掉这个任务下载的数据:删除 {folder} 目录及其中的全部文件。"
|
||||
f"只删除这一个目录,不要动 {WORKSPACE} 下的其他内容。"
|
||||
f"删除后确认该目录已不存在,最后单独输出一行:CLEANED {task}"
|
||||
)
|
||||
|
||||
|
||||
def _numbered_commands(files: list[ExportFile]) -> list[str]:
|
||||
lines = []
|
||||
for index, item in enumerate(files, 1):
|
||||
lines += [f"[{index}]", "```bash", item.command(), "```"]
|
||||
return lines
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileEvidence:
|
||||
saved: bool = False
|
||||
empty: bool = False
|
||||
sql_same: bool | None = None
|
||||
commands: int = 0
|
||||
|
||||
|
||||
def reply_parts(messages: list[dict], message_id: str):
|
||||
for message in messages:
|
||||
info = message.get("info") or {}
|
||||
if info.get("role") == "assistant" and info.get("parentID") == message_id:
|
||||
yield from message.get("parts") or []
|
||||
|
||||
|
||||
def judge_export(messages: list[dict], message_id: str, files: list[ExportFile]) -> dict[str, FileEvidence]:
|
||||
"""只认 bash 工具里实际执行的命令和导出脚本的输出。"""
|
||||
by_path = {item.path: item for item in files}
|
||||
evidence = {item.key: FileEvidence() for item in files}
|
||||
for part in reply_parts(messages, message_id):
|
||||
if part.get("type") != "tool" or part.get("tool") != "bash":
|
||||
continue
|
||||
state = part.get("state") or {}
|
||||
command = str((state.get("input") or {}).get("command") or "")
|
||||
output = str(state.get("output") or (state.get("metadata") or {}).get("output") or "")
|
||||
segments = [s for s in re.split(r"\s*(?:&&|;|\n)\s*", command) if EXPORT_SCRIPT.rsplit("/", 1)[-1] in s]
|
||||
for segment in segments:
|
||||
options = _options(segment)
|
||||
for item in files:
|
||||
if posixpath.normpath(options.get("--save-dir", "")) != item.save_dir or options.get("--filename") != item.filename:
|
||||
continue
|
||||
found = evidence[item.key]
|
||||
found.commands += 1
|
||||
found.sql_same = options.get("--sql") == item.sql
|
||||
if len(segments) == 1 and EMPTY_RESULT in output and not SAVED.search(output):
|
||||
found.empty = True
|
||||
for saved in SAVED.findall(output):
|
||||
item = by_path.get(posixpath.normpath(saved))
|
||||
if item:
|
||||
evidence[item.key].saved = True
|
||||
return evidence
|
||||
|
||||
|
||||
def _options(command: str) -> dict[str, str]:
|
||||
try:
|
||||
tokens = shlex.split(command)
|
||||
except ValueError:
|
||||
return {}
|
||||
found = {}
|
||||
for index, token in enumerate(tokens[:-1]):
|
||||
if token in ("--sql", "--save-dir", "--filename"):
|
||||
found[token] = tokens[index + 1]
|
||||
return found
|
||||
|
||||
|
||||
@dataclass
|
||||
class CsvTable:
|
||||
header: list[str] = field(default_factory=list)
|
||||
rows: list[dict[str, str]] = field(default_factory=list)
|
||||
bad_rows: int = 0
|
||||
outside_day: int = 0
|
||||
missing: list[str] = field(default_factory=list)
|
||||
empty: bool = False
|
||||
|
||||
@property
|
||||
def ok(self) -> bool:
|
||||
return self.empty or (not self.missing and not self.outside_day)
|
||||
|
||||
|
||||
def parse_export_csv(content: str, required: tuple[str, ...], day: date) -> CsvTable:
|
||||
"""列顺序和 SQL 里写的不一样,一律按表头名取值。列数不对的行是逗号错列,直接丢弃。
|
||||
|
||||
带有效期两列时,逐行核对 day 落在 [eff_from_date, eff_to_date) 里,防止 SQL 里的日期被换掉。
|
||||
"""
|
||||
rows = list(csv.reader(io.StringIO(content.lstrip("\ufeff"))))
|
||||
if not rows:
|
||||
return CsvTable(missing=list(required))
|
||||
header = [name.strip().lower() for name in rows[0]]
|
||||
good = [dict(zip(header, row)) for row in rows[1:] if len(row) == len(header)]
|
||||
outside = 0
|
||||
if all(name in header for name in EFFECTIVE):
|
||||
target = day.isoformat()
|
||||
outside = sum(1 for row in good if not (row["eff_from_date"][:10] <= target < row["eff_to_date"][:10]))
|
||||
return CsvTable(
|
||||
header=header,
|
||||
rows=good,
|
||||
bad_rows=len(rows) - 1 - len(good),
|
||||
outside_day=outside,
|
||||
missing=[name for name in required if name not in header],
|
||||
)
|
||||
|
||||
|
||||
_last_ms = 0
|
||||
_counter = 0
|
||||
|
||||
|
||||
def ascending_id(prefix: str) -> str:
|
||||
"""与平台前端相同的编号:毫秒时间戳乘 4096 加序号取 48 位,再接 14 位随机字符。"""
|
||||
global _last_ms, _counter
|
||||
now_ms = int(time.time() * 1000)
|
||||
if now_ms != _last_ms:
|
||||
_last_ms, _counter = now_ms, 0
|
||||
_counter += 1
|
||||
value = (now_ms * 0x1000 + _counter) & ((1 << 48) - 1)
|
||||
return f"{prefix}_{value.to_bytes(6, 'big').hex()}{''.join(random.choice(_BASE62) for _ in range(14))}"
|
||||
|
||||
|
||||
class OpenCode:
|
||||
def __init__(self, nqi: NqiClient, *, model: str = MODEL_ID, poll_seconds: float = 3.0):
|
||||
self.nqi = nqi
|
||||
self.model = model
|
||||
self.poll_seconds = poll_seconds
|
||||
self.ticket = nqi.ticket()
|
||||
self.base = ""
|
||||
self.headers = {"Accept": "*/*", "Origin": ORIGIN, "x-opencode-directory": "%2Fworkspace"}
|
||||
|
||||
async def provision(self) -> str:
|
||||
"""provision 会下发 opencode_route,会话页会下发 oc_castgc,之后接口才认。"""
|
||||
if not self.ticket:
|
||||
raise NqiAuthError("登录已失效,请重新登录")
|
||||
page = {"Accept": "text/html,application/xhtml+xml,*/*;q=0.8", "Referer": f"{ORIGIN}/pro-portal/struts/portal/index.html"}
|
||||
response = await self.nqi._request(
|
||||
"GET",
|
||||
f"{OPENCODE}/api/provision",
|
||||
params={"random": str(random.random()), "__PID": PROVISION_PID, "token": self.ticket},
|
||||
headers=page,
|
||||
follow_redirects=False,
|
||||
)
|
||||
location = response.headers.get("location", "")
|
||||
if "/cas/login" in location:
|
||||
raise NqiAuthError("登录已失效,请重新登录")
|
||||
found = re.match(r"^/pro-opencode/([^/]+)/", location)
|
||||
if response.status_code not in (301, 302, 303, 307, 308) or not found:
|
||||
raise OpenCodeError("没有打开大数据平台的 AI 工作区")
|
||||
self.base = f"{OPENCODE}/{found.group(1)}"
|
||||
self.headers["Referer"] = f"{self.base}/L3dvcmtzcGFjZQ/session"
|
||||
response = await self.nqi._request("GET", f"{ORIGIN}{location}", headers=page, follow_redirects=False)
|
||||
if response.status_code != 200:
|
||||
raise OpenCodeError("没有打开大数据平台的 AI 工作区")
|
||||
return found.group(1)
|
||||
|
||||
async def _call(self, method: str, path: str, *, params: dict | None = None, body: dict | None = None, tickets: bool = True) -> httpx.Response:
|
||||
if not self.base:
|
||||
raise OpenCodeError("还没有打开 AI 工作区")
|
||||
query = dict(params or {})
|
||||
if tickets:
|
||||
query["tickets"] = self.ticket
|
||||
headers = dict(self.headers)
|
||||
kwargs: dict = {"params": query, "headers": headers, "follow_redirects": False, "timeout": httpx.Timeout(60.0, connect=15.0)}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
kwargs["content"] = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
response = await self.nqi._request(method, f"{self.base}/{path}", **kwargs)
|
||||
if response.status_code in (301, 302, 303, 307, 308) and "/cas/login" in response.headers.get("location", ""):
|
||||
raise NqiAuthError("登录已失效,请重新登录")
|
||||
return response
|
||||
|
||||
async def _json(self, method: str, path: str, **kwargs):
|
||||
response = await self._call(method, path, **kwargs)
|
||||
if response.status_code >= 400:
|
||||
raise OpenCodeError(f"AI 工作区接口返回 {response.status_code}")
|
||||
if not response.content:
|
||||
return None
|
||||
try:
|
||||
return response.json()
|
||||
except json.JSONDecodeError as exc:
|
||||
raise OpenCodeError("AI 工作区返回的内容无法识别") from exc
|
||||
|
||||
async def create_session(self) -> str:
|
||||
data = await self._json(
|
||||
"POST",
|
||||
"session",
|
||||
params={"directory": WORKSPACE},
|
||||
body={"agent": "build", "model": {"id": self.model, "providerID": self.model}},
|
||||
)
|
||||
if not isinstance(data, dict) or not data.get("id"):
|
||||
raise OpenCodeError("没有建立 AI 会话")
|
||||
return str(data["id"])
|
||||
|
||||
async def prompt(self, session_id: str, text: str) -> str:
|
||||
message_id = ascending_id("msg")
|
||||
body = {
|
||||
"messageID": message_id,
|
||||
"agent": "build",
|
||||
"model": {"modelID": self.model, "providerID": self.model},
|
||||
"parts": [{"id": ascending_id("prt"), "type": "text", "text": text}],
|
||||
}
|
||||
response = await self._call("POST", f"session/{session_id}/prompt_async", body=body)
|
||||
if response.status_code >= 400:
|
||||
raise OpenCodeError(f"发送指令失败 {response.status_code}")
|
||||
return message_id
|
||||
|
||||
async def wait_reply(self, session_id: str, message_id: str, timeout: float = 1200) -> list[dict]:
|
||||
"""会话回到空闲,且这条指令的最后一步正常结束或出错,才算回复完成。"""
|
||||
started = time.monotonic()
|
||||
while True:
|
||||
status = await self._json("GET", "session/status") or {}
|
||||
busy = (status.get(session_id) or {}).get("type", "idle") != "idle"
|
||||
for kind in ("permission", "question"):
|
||||
waiting = [item for item in await self._json("GET", kind, params={"directory": WORKSPACE}) or [] if item.get("sessionID") == session_id]
|
||||
if waiting:
|
||||
raise OpenCodeError("平台 AI 在等人工确认,自动任务无法继续")
|
||||
messages = await self._json("GET", f"session/{session_id}/message") or []
|
||||
steps = [m.get("info") or {} for m in messages if (m.get("info") or {}).get("role") == "assistant" and (m.get("info") or {}).get("parentID") == message_id]
|
||||
last = steps[-1] if steps else {}
|
||||
finished = bool(last) and (last.get("time") or {}).get("completed") and last.get("finish") not in (None, "tool-calls", "unknown")
|
||||
if not busy and (finished or last.get("error")):
|
||||
if last.get("error"):
|
||||
logger.info("OpenCode 回复出错: %s", json.dumps(last["error"], ensure_ascii=False)[:300])
|
||||
return messages
|
||||
if time.monotonic() - started > timeout:
|
||||
raise OpenCodeError("平台 AI 回复超时")
|
||||
await asyncio.sleep(self.poll_seconds)
|
||||
|
||||
async def list_dir(self, path: str) -> list[dict]:
|
||||
return await self._json("GET", "file", params={"path": path, "directory": WORKSPACE}) or []
|
||||
|
||||
async def read_text(self, path: str) -> str:
|
||||
data = await self._json("GET", "file/content", params={"path": path, "directory": WORKSPACE}, tickets=False)
|
||||
if not isinstance(data, dict) or data.get("type") != "text":
|
||||
raise OpenCodeError("导出文件不是文本")
|
||||
return str(data.get("content") or "")
|
||||
|
||||
async def delete_session(self, session_id: str) -> bool:
|
||||
response = await self._call("DELETE", f"session/{session_id}")
|
||||
return response.status_code < 400
|
||||
|
||||
async def export(self, session_id: str, files: list[ExportFile], retries: int = 2) -> dict[str, CsvTable]:
|
||||
"""SQL 被改、没有落盘或文件不合格的,换新文件名重做,最多 retries 次。"""
|
||||
results: dict[str, CsvTable] = {}
|
||||
todo = list(files)
|
||||
for attempt in range(retries + 1):
|
||||
message_id = await self.prompt(session_id, export_prompt(todo) if attempt == 0 else redo_prompt(todo))
|
||||
messages = await self.wait_reply(session_id, message_id)
|
||||
evidence = judge_export(messages, message_id, todo)
|
||||
failed = []
|
||||
for item in todo:
|
||||
found = evidence[item.key]
|
||||
if found.sql_same is not True:
|
||||
logger.info("OpenCode 导出 %s 没有按原 SQL 执行", item.key)
|
||||
failed.append(item)
|
||||
elif found.empty:
|
||||
results[item.key] = CsvTable(empty=True)
|
||||
elif not found.saved:
|
||||
logger.info("OpenCode 导出 %s 没有保存文件", item.key)
|
||||
failed.append(item)
|
||||
else:
|
||||
table = parse_export_csv(await self.read_text(posixpath.relpath(item.path, WORKSPACE)), item.required, item.day)
|
||||
if table.ok:
|
||||
results[item.key] = table
|
||||
else:
|
||||
logger.info("OpenCode 导出 %s 内容不合格: 缺列 %s,日期不符 %s 行", item.key, table.missing, table.outside_day)
|
||||
failed.append(item)
|
||||
if not failed:
|
||||
return results
|
||||
todo = [item.retry(attempt + 1) for item in failed]
|
||||
raise OpenCodeError("导出失败:" + "、".join(item.key for item in todo))
|
||||
|
||||
async def cleanup(self, session_id: str, task: str) -> bool:
|
||||
if not _NAME.match(task):
|
||||
raise ValueError("任务名称不合法")
|
||||
message_id = await self.prompt(session_id, cleanup_prompt(task))
|
||||
await self.wait_reply(session_id, message_id, timeout=300)
|
||||
names = {entry.get("name") for entry in await self.list_dir(TASKS_DIR)}
|
||||
return task not in names
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def task_session(oc: OpenCode, task: str) -> AsyncIterator[str]:
|
||||
"""建会话给一个任务用,结束时不论成败都清目录、删会话。清理失败只记日志,不盖掉原来的错误。"""
|
||||
if not oc.base:
|
||||
await oc.provision()
|
||||
session_id = await oc.create_session()
|
||||
try:
|
||||
yield session_id
|
||||
finally:
|
||||
try:
|
||||
if not await oc.cleanup(session_id, task):
|
||||
logger.info("OpenCode 任务目录 %s 没有删掉", task)
|
||||
except NqiError as exc:
|
||||
logger.info("OpenCode 任务 %s 清理未完成: %s", task, exc)
|
||||
try:
|
||||
await oc.delete_session(session_id)
|
||||
except NqiError as exc:
|
||||
logger.info("OpenCode 会话 %s 删除未完成: %s", session_id, exc)
|
||||
Reference in New Issue
Block a user