feat: 完成登录与栅格下载桌面端
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
"""4G/5G 20 米栅格的中文列,名称与门户弹窗一致。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
NETWORKS = (
|
||||
{"value": "NR", "label": "5G"},
|
||||
{"value": "LTE", "label": "4G"},
|
||||
)
|
||||
|
||||
IDENTITY = (
|
||||
("月份分区", "intmonthid"),
|
||||
("时间周期", "datatime"),
|
||||
("地市", "city_name"),
|
||||
("区县", "area_name"),
|
||||
("区域属性", "area_type"),
|
||||
("微网格ID", "wgrid_id"),
|
||||
("场景唯一标签", "scene"),
|
||||
("20米栅格ID", "grid20_id"),
|
||||
("经度", "longitude"),
|
||||
("纬度", "latitude"),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Column:
|
||||
label: str
|
||||
field: str
|
||||
source: str
|
||||
|
||||
|
||||
def _pairs(*items: tuple[str, str]) -> tuple[tuple[str, str], ...]:
|
||||
return items
|
||||
|
||||
|
||||
_NR_GROUPS: dict[str, tuple[str, tuple[tuple[str, str], ...]]] = {
|
||||
"rsrp": (
|
||||
"RSRP(dBm)",
|
||||
_pairs(
|
||||
("中国移动SSB-RSRP(dBm)", "ssb_rsrp_yd"),
|
||||
("中国移动RSRP低于-120的MR数", "rsrp_lt_neg120_yd"),
|
||||
("中国移动RSRP低于-115的MR数", "rsrp_lt_neg115_yd"),
|
||||
("中国移动RSRP低于-110的MR数", "rsrp_lt_neg110_yd"),
|
||||
("中国移动RSRP低于-108的MR数", "rsrp_lt_neg108_yd"),
|
||||
("中国移动RSRP低于-105的MR数", "rsrp_lt_neg105_yd"),
|
||||
("中国移动RSRP低于-100的MR数", "rsrp_lt_neg100_yd"),
|
||||
("中国移动RSRP低于-95的MR数", "rsrp_lt_neg95_yd"),
|
||||
("中国移动RSRP低于-90的MR数", "rsrp_lt_neg90_yd"),
|
||||
),
|
||||
),
|
||||
"dlsinr": ("DLSINR(dB)", _pairs(("中国移动SSB-DLSINR(dB)", "ssb_dlsinr_yd"))),
|
||||
"worse": (
|
||||
"5G覆盖劣于竞对",
|
||||
_pairs(
|
||||
("中国移动RSRP低于-105的弱覆盖比例(%)", "mr_dl_lt105_weak_cover_rate_yd"),
|
||||
("中国电联RSRP低于-105的弱覆盖比例(%)", "mr_dl_lt105_weak_cover_rate_dl"),
|
||||
("中国移动下行质差MR比例(SSB)(%)", "mr_dl_bad_cell_rate_yd"),
|
||||
("中国移动重叠覆盖MR比例(SSB)(%)", "mr_overlap_rate_yd"),
|
||||
),
|
||||
),
|
||||
"cover": (
|
||||
"5G覆盖率占比",
|
||||
_pairs(
|
||||
("中国移动覆盖优良样本点", "mr_dl_excellent_cell_yd"),
|
||||
("中国移动5G驻留比(5G全量终端)(%)", "nr_flux_rate_all_yd"),
|
||||
("中国移动5G驻留比(5G开关打开终端)(%)", "nr_flux_rate_open_yd"),
|
||||
("中国移动5G驻留比分母(5G开关打开终端)", "nr_flux_rate_den_open_yd"),
|
||||
),
|
||||
),
|
||||
"weak": (
|
||||
"5G弱覆盖比例",
|
||||
_pairs(
|
||||
("中国移动RSRP低于-110的弱覆盖比例(%)", "mr_dl_lt110_weak_cover_rate_yd"),
|
||||
("中国移动RSRP低于-105的弱覆盖比例(%)", "mr_dl_lt105_weak_cover_rate_yd"),
|
||||
),
|
||||
),
|
||||
"samples": ("5G采样点数量", _pairs(("中国移动MR总数", "mro_total_yd"))),
|
||||
}
|
||||
|
||||
_LTE_GROUPS: dict[str, tuple[str, tuple[tuple[str, str], ...]]] = {
|
||||
"rsrp": (
|
||||
"RSRP(dBm)",
|
||||
_pairs(
|
||||
("中国移动RSRP(dBm)", "rsrp_yd"),
|
||||
("中国移动RSRP低于-120的MR数", "rsrp_lt_neg120_yd"),
|
||||
("中国移动RSRP低于-115的MR数", "rsrp_lt_neg115_yd"),
|
||||
("中国移动RSRP低于-110的MR数", "rsrp_lt_neg110_yd"),
|
||||
("中国移动RSRP低于-108的MR数", "rsrp_lt_neg108_yd"),
|
||||
("中国移动RSRP低于-105的MR数", "rsrp_lt_neg105_yd"),
|
||||
("中国移动RSRP低于-100的MR数", "rsrp_lt_neg100_yd"),
|
||||
("中国移动RSRP低于-95的MR数", "rsrp_lt_neg95_yd"),
|
||||
("中国移动RSRP低于-90的MR数", "rsrp_lt_neg90_yd"),
|
||||
),
|
||||
),
|
||||
"dlsinr": ("DLSINR(dB)", _pairs(("中国移动DLSINR(dB)", "dlsinr_yd"))),
|
||||
"worse": (
|
||||
"4G覆盖劣于竞对",
|
||||
_pairs(
|
||||
("中国移动RSRP低于-110的弱覆盖比例(%)", "mr_dl_lt110_weak_cover_rate_yd"),
|
||||
("中国电联RSRP低于-110的弱覆盖比例(%)", "mr_dl_lt110_weak_cover_rate_dl"),
|
||||
("中国移动下行质差MR比例(%)", "mr_dl_bad_cell_rate_yd"),
|
||||
("中国移动重叠覆盖MR比例(%)", "mr_overlap_rate_yd"),
|
||||
),
|
||||
),
|
||||
"cover": ("4G覆盖率占比", _pairs(("中国移动覆盖优良样本点", "mr_dl_excellent_cell_yd"))),
|
||||
"weak": (
|
||||
"4G弱覆盖比例",
|
||||
_pairs(
|
||||
("中国移动RSRP低于-110的弱覆盖比例(%)", "mr_dl_lt110_weak_cover_rate_yd"),
|
||||
("中国移动RSRP低于-105的弱覆盖比例(%)", "mr_dl_lt105_weak_cover_rate_yd"),
|
||||
),
|
||||
),
|
||||
"samples": (
|
||||
"4G采样点数量",
|
||||
_pairs(
|
||||
("中国移动MR总数", "mro_total_yd"),
|
||||
("中国移动5G终端总MR数", "ue_num_nr_yd"),
|
||||
),
|
||||
),
|
||||
}
|
||||
|
||||
GROUP_ORDER = ("rsrp", "dlsinr", "worse", "cover", "weak", "samples")
|
||||
|
||||
|
||||
def group_table(network: str) -> dict[str, tuple[str, tuple[tuple[str, str], ...]]]:
|
||||
if network == "LTE":
|
||||
return _LTE_GROUPS
|
||||
if network == "NR":
|
||||
return _NR_GROUPS
|
||||
raise ValueError("网络类型只支持 4G 或 5G")
|
||||
|
||||
|
||||
def cell_columns(network: str) -> list[Column]:
|
||||
nr = network == "NR"
|
||||
weak_count = "rsrp_lt_neg105" if nr else "rsrp_lt_neg110"
|
||||
return [
|
||||
Column("序号", "_index", "cell"),
|
||||
Column("小区ID", "cgi", "cell"),
|
||||
Column("MR总数", "mro_total", "cell"),
|
||||
Column("RSRP(dBm)", "ssb_rsrp" if nr else "rsrp", "cell"),
|
||||
Column("DLSINR(dB)", "ssb_dlsinr" if nr else "dlsinr", "cell"),
|
||||
Column("下行弱覆盖MR比例(%)", "mr_dl_weak_cover_rate", "cell"),
|
||||
Column("下行弱覆盖MR数量", weak_count, "cell"),
|
||||
]
|
||||
|
||||
|
||||
def columns_for(network: str, groups: list[str] | None) -> list[Column]:
|
||||
table = group_table(network)
|
||||
selected = [item for item in GROUP_ORDER if groups is None or item in groups]
|
||||
unknown = [item for item in (groups or []) if item not in table]
|
||||
if unknown:
|
||||
raise ValueError("未知的下载项目: " + "、".join(unknown))
|
||||
columns = [Column(label, field, "grid") for label, field in IDENTITY]
|
||||
seen = {column.field for column in columns}
|
||||
for key in selected:
|
||||
for label, field in table[key][1]:
|
||||
if field in seen:
|
||||
continue
|
||||
seen.add(field)
|
||||
columns.append(Column(label, field, "grid"))
|
||||
columns.extend(cell_columns(network))
|
||||
return columns
|
||||
|
||||
|
||||
def meta_groups(network: str) -> list[dict]:
|
||||
table = group_table(network)
|
||||
return [
|
||||
{
|
||||
"id": key,
|
||||
"label": table[key][0],
|
||||
"columns": [label for label, _field in table[key][1]],
|
||||
}
|
||||
for key in GROUP_ORDER
|
||||
]
|
||||
@@ -0,0 +1,96 @@
|
||||
"""从区域表里读取栅格 ID。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
from pathlib import Path
|
||||
|
||||
_HEADER_KEYS = {
|
||||
"栅格id",
|
||||
"20米栅格id",
|
||||
"grid20_id",
|
||||
"grid_id",
|
||||
"栅格",
|
||||
"栅格编号",
|
||||
}
|
||||
|
||||
|
||||
def normalize_id(value) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
text = str(value).strip().strip("\ufeff")
|
||||
if text.endswith(".0") and text[:-2].isdigit():
|
||||
text = text[:-2]
|
||||
if not text or not text.isdigit():
|
||||
return ""
|
||||
return text
|
||||
|
||||
|
||||
def _header_index(header: list[str]) -> int | None:
|
||||
for index, name in enumerate(header):
|
||||
key = name.strip().lower().replace(" ", "").replace("_", "")
|
||||
raw = name.strip().lower().replace(" ", "")
|
||||
if raw in _HEADER_KEYS or key in {"栅格id", "20米栅格id", "grid20id", "gridid"}:
|
||||
return index
|
||||
if "栅格" in name and "id" in raw:
|
||||
return index
|
||||
return None
|
||||
|
||||
|
||||
def parse_table(rows: list[list]) -> list[str]:
|
||||
if not rows:
|
||||
return []
|
||||
header = ["" if cell is None else str(cell).strip() for cell in rows[0]]
|
||||
column = _header_index(header)
|
||||
start = 0
|
||||
if column is None:
|
||||
column = 0
|
||||
if not normalize_id(header[0] if header else ""):
|
||||
start = 1
|
||||
else:
|
||||
start = 1
|
||||
found: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for row in rows[start:]:
|
||||
if column >= len(row):
|
||||
continue
|
||||
grid_id = normalize_id(row[column])
|
||||
if not grid_id or grid_id in seen:
|
||||
continue
|
||||
seen.add(grid_id)
|
||||
found.append(grid_id)
|
||||
return found
|
||||
|
||||
|
||||
def _decode_csv(raw: bytes) -> str:
|
||||
for encoding in ("utf-8-sig", "utf-8", "gbk"):
|
||||
try:
|
||||
return raw.decode(encoding)
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return raw.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def parse_upload(path: Path) -> list[str]:
|
||||
suffix = path.suffix.lower()
|
||||
if suffix == ".xlsx":
|
||||
from openpyxl import load_workbook
|
||||
|
||||
book = load_workbook(path, read_only=True, data_only=True)
|
||||
try:
|
||||
sheet = book.active
|
||||
rows = [list(row) for row in sheet.iter_rows(values_only=True)]
|
||||
finally:
|
||||
book.close()
|
||||
return parse_table(rows)
|
||||
if suffix not in {".csv", ".txt", ""}:
|
||||
raise ValueError("区域表只支持 CSV、TXT 或 XLSX")
|
||||
text = _decode_csv(path.read_bytes())
|
||||
sample = text[:4096]
|
||||
try:
|
||||
dialect = csv.Sniffer().sniff(sample, delimiters=",\t;|")
|
||||
except csv.Error:
|
||||
dialect = csv.excel
|
||||
reader = csv.reader(io.StringIO(text), dialect)
|
||||
return parse_table([list(row) for row in reader if any(str(cell).strip() for cell in row)])
|
||||
@@ -0,0 +1,358 @@
|
||||
"""下载任务:协程并发查询,单个写者实时落盘。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from app.platform.client import NqiClient, NqiError
|
||||
from app.features.download.fields import columns_for
|
||||
from app.features.download.journal import CsvJournal
|
||||
from app.features.download.rows import build_rows
|
||||
from app.shared.paths import DOWNLOAD_DIR
|
||||
|
||||
DATA_DIR = DOWNLOAD_DIR
|
||||
|
||||
|
||||
@dataclass
|
||||
class DownloadJob:
|
||||
id: str
|
||||
directory: Path
|
||||
network: str
|
||||
city_code: str
|
||||
city_name: str
|
||||
month: str
|
||||
groups: list[str]
|
||||
concurrency: int
|
||||
grid_ids: list[str]
|
||||
csv_path: Path
|
||||
created_at: str
|
||||
status: str = "queued"
|
||||
message: str = ""
|
||||
completed: int = 0
|
||||
failed: int = 0
|
||||
written_rows: int = 0
|
||||
failures: list[dict[str, str]] = field(default_factory=list)
|
||||
subscribers: list[asyncio.Queue] = field(default_factory=list)
|
||||
task: asyncio.Task | None = None
|
||||
cancel_event: asyncio.Event = field(default_factory=asyncio.Event)
|
||||
|
||||
@property
|
||||
def total(self) -> int:
|
||||
return len(self.grid_ids)
|
||||
|
||||
def is_active(self) -> bool:
|
||||
return self.task is not None and not self.task.done()
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"status": self.status,
|
||||
"message": self.message,
|
||||
"network": self.network,
|
||||
"cityCode": self.city_code,
|
||||
"cityName": self.city_name,
|
||||
"month": self.month,
|
||||
"concurrency": self.concurrency,
|
||||
"total": self.total,
|
||||
"completed": self.completed,
|
||||
"failed": self.failed,
|
||||
"writtenRows": self.written_rows,
|
||||
"csvPath": str(self.csv_path),
|
||||
"failures": self.failures[-20:],
|
||||
"createdAt": self.created_at,
|
||||
"name": f"{'5G' if self.network == 'NR' else '4G'} · {self.city_name} · {self.month}",
|
||||
}
|
||||
|
||||
def save(self) -> None:
|
||||
payload = {
|
||||
"id": self.id,
|
||||
"network": self.network,
|
||||
"cityCode": self.city_code,
|
||||
"cityName": self.city_name,
|
||||
"month": self.month,
|
||||
"groups": self.groups,
|
||||
"concurrency": self.concurrency,
|
||||
"gridIds": self.grid_ids,
|
||||
"csvPath": str(self.csv_path),
|
||||
"createdAt": self.created_at,
|
||||
"status": self.status,
|
||||
"message": self.message,
|
||||
"completed": self.completed,
|
||||
"failed": self.failed,
|
||||
"writtenRows": self.written_rows,
|
||||
"failures": self.failures[-50:],
|
||||
}
|
||||
(self.directory / "job.json").write_text(
|
||||
json.dumps(payload, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
async def emit(self, kind: str, **extra) -> None:
|
||||
event = {"type": kind, **self.snapshot(), **extra}
|
||||
for subscriber in list(self.subscribers):
|
||||
await subscriber.put(event)
|
||||
|
||||
|
||||
class JobManager:
|
||||
def __init__(self) -> None:
|
||||
self.jobs: dict[str, DownloadJob] = {}
|
||||
|
||||
def create(
|
||||
self,
|
||||
*,
|
||||
network: str,
|
||||
city_code: str,
|
||||
city_name: str,
|
||||
month: str,
|
||||
groups: list[str],
|
||||
concurrency: int,
|
||||
grid_ids: list[str],
|
||||
csv_path: Path | None,
|
||||
) -> DownloadJob:
|
||||
job_id = uuid.uuid4().hex
|
||||
directory = DATA_DIR / job_id
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
target = csv_path or directory / f"栅格_{'5G' if network == 'NR' else '4G'}_{city_name}_{month}.csv"
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
job = DownloadJob(
|
||||
id=job_id,
|
||||
directory=directory,
|
||||
network=network,
|
||||
city_code=city_code,
|
||||
city_name=city_name,
|
||||
month=month,
|
||||
groups=groups,
|
||||
concurrency=concurrency,
|
||||
grid_ids=grid_ids,
|
||||
csv_path=target,
|
||||
created_at=datetime.now().isoformat(timespec="seconds"),
|
||||
)
|
||||
job.save()
|
||||
self.jobs[job_id] = job
|
||||
return job
|
||||
|
||||
def get(self, job_id: str) -> DownloadJob:
|
||||
job = self.jobs.get(job_id)
|
||||
if job is None:
|
||||
job = self._load(job_id)
|
||||
self.jobs[job_id] = job
|
||||
return job
|
||||
|
||||
def list_jobs(self) -> list[dict]:
|
||||
if not DATA_DIR.exists():
|
||||
return []
|
||||
items = []
|
||||
for directory in sorted(DATA_DIR.iterdir(), reverse=True):
|
||||
path = directory / "job.json"
|
||||
if not path.exists():
|
||||
continue
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
continue
|
||||
job_id = data.get("id")
|
||||
if job_id in self.jobs:
|
||||
job = self.jobs[job_id]
|
||||
snap = job.snapshot()
|
||||
if snap["status"] == "running" and not job.is_active():
|
||||
snap["status"] = "cancelled"
|
||||
snap["message"] = "已中断"
|
||||
items.append(snap)
|
||||
continue
|
||||
status = data.get("status") or "queued"
|
||||
message = data.get("message") or ""
|
||||
if status == "running":
|
||||
status = "cancelled"
|
||||
message = "已中断"
|
||||
finished, written = _progress_stats(directory)
|
||||
items.append(
|
||||
{
|
||||
"id": job_id,
|
||||
"status": status,
|
||||
"message": message,
|
||||
"network": data.get("network"),
|
||||
"cityCode": data.get("cityCode"),
|
||||
"cityName": data.get("cityName"),
|
||||
"month": data.get("month"),
|
||||
"concurrency": data.get("concurrency") or 4,
|
||||
"total": len(data.get("gridIds") or []),
|
||||
"completed": finished or data.get("completed") or 0,
|
||||
"failed": data.get("failed") or 0,
|
||||
"writtenRows": written or data.get("writtenRows") or 0,
|
||||
"csvPath": data.get("csvPath"),
|
||||
"failures": data.get("failures") or [],
|
||||
"createdAt": data.get("createdAt"),
|
||||
"name": f"{'5G' if data.get('network') == 'NR' else '4G'} · {data.get('cityName') or ''} · {data.get('month') or ''}",
|
||||
}
|
||||
)
|
||||
return items[:20]
|
||||
|
||||
def _load(self, job_id: str) -> DownloadJob:
|
||||
if not re_fullmatch_hex(job_id):
|
||||
raise NqiError("任务不存在")
|
||||
path = DATA_DIR / job_id / "job.json"
|
||||
if not path.exists():
|
||||
raise NqiError("任务不存在")
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
return DownloadJob(
|
||||
id=data["id"],
|
||||
directory=path.parent,
|
||||
network=data["network"],
|
||||
city_code=data["cityCode"],
|
||||
city_name=data["cityName"],
|
||||
month=data["month"],
|
||||
groups=list(data.get("groups") or []),
|
||||
concurrency=int(data.get("concurrency") or 4),
|
||||
grid_ids=[str(item) for item in data.get("gridIds") or []],
|
||||
csv_path=Path(data["csvPath"]),
|
||||
created_at=data.get("createdAt") or "",
|
||||
status=data.get("status") or "queued",
|
||||
message=data.get("message") or "",
|
||||
completed=int(data.get("completed") or 0),
|
||||
failed=int(data.get("failed") or 0),
|
||||
written_rows=int(data.get("writtenRows") or 0),
|
||||
failures=list(data.get("failures") or []),
|
||||
)
|
||||
|
||||
|
||||
def _progress_stats(directory: Path) -> tuple[int, int]:
|
||||
path = directory / "progress.jsonl"
|
||||
if not path.exists():
|
||||
return 0, 0
|
||||
finished = 0
|
||||
written = 0
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
text = line.strip()
|
||||
if not text:
|
||||
continue
|
||||
try:
|
||||
record = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
break
|
||||
finished += 1
|
||||
written += int(record.get("rows") or 0)
|
||||
return finished, written
|
||||
|
||||
|
||||
def re_fullmatch_hex(value: str) -> bool:
|
||||
return len(value) == 32 and all(char in "0123456789abcdef" for char in value)
|
||||
|
||||
|
||||
async def run_download(job: DownloadJob, client: NqiClient) -> None:
|
||||
columns = columns_for(job.network, job.groups)
|
||||
journal = CsvJournal(job.csv_path, job.directory / "progress.jsonl", [column.label for column in columns])
|
||||
job.status = "running"
|
||||
job.message = "准备中"
|
||||
job.save()
|
||||
await job.emit("progress")
|
||||
try:
|
||||
layer = await client.layer_code(city_code=job.city_code, month=job.month, network=job.network)
|
||||
service_code = layer["serviceCode"]
|
||||
journal.open()
|
||||
job.completed = len(journal.completed)
|
||||
job.written_rows = journal.written_rows
|
||||
job.failures = []
|
||||
job.failed = 0
|
||||
pending = [grid_id for grid_id in job.grid_ids if grid_id not in journal.completed]
|
||||
job.message = "下载中"
|
||||
await job.emit("progress")
|
||||
if not pending:
|
||||
job.status = "done"
|
||||
job.message = "已完成"
|
||||
job.save()
|
||||
await job.emit("done")
|
||||
return
|
||||
await _pump(job, client, journal, columns, service_code, pending)
|
||||
except asyncio.CancelledError:
|
||||
job.status = "cancelled"
|
||||
job.message = "已停止"
|
||||
job.save()
|
||||
await job.emit("cancelled")
|
||||
raise
|
||||
except Exception as exc:
|
||||
job.status = "error"
|
||||
job.message = str(exc) or "下载失败"
|
||||
job.save()
|
||||
await job.emit("error")
|
||||
finally:
|
||||
journal.close()
|
||||
|
||||
|
||||
async def _pump(job, client, journal, columns, service_code: str, pending: list[str]) -> None:
|
||||
ids: asyncio.Queue[str] = asyncio.Queue()
|
||||
results: asyncio.Queue = asyncio.Queue()
|
||||
for grid_id in pending:
|
||||
ids.put_nowait(grid_id)
|
||||
|
||||
async def worker() -> None:
|
||||
while not job.cancel_event.is_set():
|
||||
try:
|
||||
grid_id = ids.get_nowait()
|
||||
except asyncio.QueueEmpty:
|
||||
return
|
||||
error = ""
|
||||
rows = None
|
||||
for attempt in range(2):
|
||||
if job.cancel_event.is_set():
|
||||
return
|
||||
try:
|
||||
properties = await client.grid_feature(service_code, grid_id)
|
||||
cells = await client.cell_rows(service_code, grid_id, job.network)
|
||||
rows = build_rows(grid_id, properties, cells, columns)
|
||||
error = ""
|
||||
break
|
||||
except Exception as exc:
|
||||
error = str(exc) or "下载失败"
|
||||
if attempt == 0:
|
||||
await asyncio.sleep(0.4)
|
||||
if rows is None:
|
||||
await results.put(("err", grid_id, error))
|
||||
else:
|
||||
await results.put(("ok", grid_id, rows))
|
||||
|
||||
async def writer() -> None:
|
||||
while True:
|
||||
item = await results.get()
|
||||
if item is None:
|
||||
return
|
||||
kind, grid_id, payload = item
|
||||
if kind == "ok":
|
||||
written = journal.write_rows(grid_id, payload)
|
||||
job.completed += 1
|
||||
job.written_rows = journal.written_rows
|
||||
if written == 0:
|
||||
job.written_rows = journal.written_rows
|
||||
else:
|
||||
job.failed += 1
|
||||
job.failures.append({"id": grid_id, "message": payload})
|
||||
job.message = f"已完成 {job.completed}/{job.total},失败 {job.failed}"
|
||||
job.save()
|
||||
await job.emit("progress")
|
||||
|
||||
async def finish_workers() -> None:
|
||||
await asyncio.gather(*(worker() for _ in range(job.concurrency)))
|
||||
await results.put(None)
|
||||
|
||||
closer = asyncio.create_task(finish_workers())
|
||||
try:
|
||||
await writer()
|
||||
await closer
|
||||
finally:
|
||||
if not closer.done():
|
||||
closer.cancel()
|
||||
unfinished = job.completed + job.failed < job.total
|
||||
if job.cancel_event.is_set() and unfinished:
|
||||
job.status = "cancelled"
|
||||
job.message = "已停止"
|
||||
job.save()
|
||||
await job.emit("cancelled")
|
||||
return
|
||||
job.status = "done" if job.failed == 0 else "done_with_errors"
|
||||
job.message = "已完成" if job.failed == 0 else f"{job.failed} 个失败"
|
||||
job.save()
|
||||
await job.emit("done")
|
||||
@@ -0,0 +1,115 @@
|
||||
"""单写者 CSV。未记入进度的尾部会在下次打开时丢掉并重新下载。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class CsvJournal:
|
||||
def __init__(self, csv_path: Path, progress_path: Path, headers: list[str]):
|
||||
self.csv_path = csv_path
|
||||
self.progress_path = progress_path
|
||||
self.headers = headers
|
||||
self.completed: set[str] = set()
|
||||
self.written_rows = 0
|
||||
self._file = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def open(self) -> None:
|
||||
self.csv_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
records = self._read_progress()
|
||||
size = self.csv_path.stat().st_size if self.csv_path.exists() else 0
|
||||
kept: list[dict] = []
|
||||
previous = 0
|
||||
for record in records:
|
||||
offset = int(record["offset"])
|
||||
if offset < previous or offset > size:
|
||||
break
|
||||
kept.append(
|
||||
{
|
||||
"id": str(record["id"]),
|
||||
"offset": offset,
|
||||
"rows": int(record.get("rows") or 0),
|
||||
}
|
||||
)
|
||||
previous = offset
|
||||
self.completed = {item["id"] for item in kept}
|
||||
self.written_rows = sum(int(item.get("rows") or 0) for item in kept)
|
||||
self._file = open(self.csv_path, "a+b")
|
||||
if kept:
|
||||
self._file.truncate(previous)
|
||||
self._file.seek(previous)
|
||||
self._rewrite_progress(kept)
|
||||
return
|
||||
self.written_rows = 0
|
||||
self._file.truncate(0)
|
||||
self._file.seek(0)
|
||||
self._file.write(b"\xef\xbb\xbf" + self._encode(self.headers))
|
||||
self._file.flush()
|
||||
os.fsync(self._file.fileno())
|
||||
self.progress_path.write_text("", encoding="utf-8")
|
||||
|
||||
def write_rows(self, grid_id: str, rows: list[list[str]]) -> int:
|
||||
if not rows:
|
||||
raise ValueError("至少要写出一行")
|
||||
with self._lock:
|
||||
if grid_id in self.completed:
|
||||
return 0
|
||||
if self._file is None:
|
||||
raise RuntimeError("下载文件还没有打开")
|
||||
blob = b"".join(self._encode(row) for row in rows)
|
||||
self._file.write(blob)
|
||||
self._file.flush()
|
||||
os.fsync(self._file.fileno())
|
||||
offset = self._file.tell()
|
||||
record = {"id": grid_id, "offset": offset, "rows": len(rows)}
|
||||
self.written_rows += len(rows)
|
||||
with self.progress_path.open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
self.completed.add(grid_id)
|
||||
return len(rows)
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._file = None
|
||||
|
||||
def _encode(self, row: list[str]) -> bytes:
|
||||
buffer = io.StringIO(newline="")
|
||||
writer = csv.writer(buffer, lineterminator="\r\n")
|
||||
writer.writerow(row)
|
||||
return buffer.getvalue().encode("utf-8")
|
||||
|
||||
def _read_progress(self) -> list[dict]:
|
||||
if not self.progress_path.exists():
|
||||
return []
|
||||
records: list[dict] = []
|
||||
for line in self.progress_path.read_text(encoding="utf-8").splitlines():
|
||||
text = line.strip()
|
||||
if not text:
|
||||
continue
|
||||
try:
|
||||
record = json.loads(text)
|
||||
records.append(
|
||||
{
|
||||
"id": str(record["id"]),
|
||||
"offset": int(record["offset"]),
|
||||
"rows": int(record.get("rows") or 0),
|
||||
}
|
||||
)
|
||||
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
|
||||
break
|
||||
return records
|
||||
|
||||
def _rewrite_progress(self, records: list[dict]) -> None:
|
||||
lines = [json.dumps(item, ensure_ascii=False) for item in records]
|
||||
text = ("\n".join(lines) + "\n") if lines else ""
|
||||
self.progress_path.write_text(text, encoding="utf-8")
|
||||
@@ -0,0 +1,228 @@
|
||||
"""栅格下载接口。工单、回单等功能各自放在 features 下,不写进这里。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
|
||||
from app.features.download.fields import IDENTITY, NETWORKS, cell_columns, columns_for, meta_groups
|
||||
from app.features.download.ids import parse_upload
|
||||
from app.features.download.jobs import run_download
|
||||
from app.platform.client import NqiError
|
||||
from app.platform.constants import CITIES
|
||||
from app.shared.state import state
|
||||
|
||||
logger = logging.getLogger("nqi.download")
|
||||
router = APIRouter(prefix="/api/download", tags=["download"])
|
||||
MONTH_RE = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
|
||||
|
||||
|
||||
def _bad(message: str, status: int = 400) -> HTTPException:
|
||||
return HTTPException(status_code=status, detail=message)
|
||||
|
||||
|
||||
def _sse(payload: dict) -> str:
|
||||
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
def start_job(job_id: str) -> None:
|
||||
job = state.jobs.get(job_id)
|
||||
client = state.require_client()
|
||||
if job.is_active():
|
||||
raise _bad("这个任务正在下载")
|
||||
job.cancel_event = asyncio.Event()
|
||||
job.status = "queued"
|
||||
job.save()
|
||||
|
||||
async def runner() -> None:
|
||||
await run_download(job, client)
|
||||
|
||||
task = asyncio.create_task(runner())
|
||||
job.task = task
|
||||
|
||||
def _done(finished: asyncio.Task) -> None:
|
||||
if finished.cancelled():
|
||||
return
|
||||
error = finished.exception()
|
||||
if error:
|
||||
logger.exception("下载任务异常", exc_info=error)
|
||||
|
||||
task.add_done_callback(_done)
|
||||
|
||||
|
||||
@router.get("/meta")
|
||||
async def meta() -> dict:
|
||||
return {
|
||||
"networks": list(NETWORKS),
|
||||
"cities": CITIES,
|
||||
"groups": {"NR": meta_groups("NR"), "LTE": meta_groups("LTE")},
|
||||
"fixed": {
|
||||
"grid": [label for label, _field in IDENTITY],
|
||||
"cell": {
|
||||
"NR": [column.label for column in cell_columns("NR")],
|
||||
"LTE": [column.label for column in cell_columns("LTE")],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/jobs")
|
||||
async def list_jobs() -> dict:
|
||||
state.require_client()
|
||||
return {"jobs": state.jobs.list_jobs()}
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}")
|
||||
async def get_job(job_id: str) -> dict:
|
||||
state.require_client()
|
||||
try:
|
||||
job = state.jobs.get(job_id)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc), 404) from exc
|
||||
return job.snapshot()
|
||||
|
||||
|
||||
@router.post("/jobs")
|
||||
async def create_job(
|
||||
file: UploadFile = File(...),
|
||||
network: str = Form(...),
|
||||
city_code: str = Form(...),
|
||||
month: str = Form(...),
|
||||
groups: str = Form("[]"),
|
||||
concurrency: int = Form(8),
|
||||
output_dir: str = Form(""),
|
||||
) -> dict:
|
||||
state.require_client()
|
||||
if network not in {"NR", "LTE"}:
|
||||
raise _bad("网络只支持 4G 或 5G")
|
||||
city = next((item for item in CITIES if item["code"] == city_code), None)
|
||||
if city is None:
|
||||
raise _bad("请选择地市")
|
||||
if not MONTH_RE.fullmatch(month):
|
||||
raise _bad("月份格式应为 YYYY-MM")
|
||||
try:
|
||||
selected = json.loads(groups)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise _bad("下载项目格式不正确") from exc
|
||||
if not isinstance(selected, list) or any(not isinstance(item, str) for item in selected):
|
||||
raise _bad("下载项目格式不正确")
|
||||
try:
|
||||
columns_for(network, selected)
|
||||
except ValueError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
workers = min(32, max(1, int(concurrency)))
|
||||
suffix = Path(file.filename or "grids.csv").suffix.lower()
|
||||
if suffix not in {".csv", ".txt", ".xlsx"}:
|
||||
raise _bad("区域表只支持 CSV、TXT 或 XLSX")
|
||||
raw = await file.read()
|
||||
if not raw:
|
||||
raise _bad("区域表是空的")
|
||||
if len(raw) > 20 * 1024 * 1024:
|
||||
raise _bad("区域表不能超过 20MB")
|
||||
target: Path | None = None
|
||||
if output_dir.strip():
|
||||
folder = Path(output_dir.strip())
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
label = "5G" if network == "NR" else "4G"
|
||||
target = folder / f"栅格_{label}_{city['name']}_{month}.csv"
|
||||
job = state.jobs.create(
|
||||
network=network,
|
||||
city_code=city["code"],
|
||||
city_name=city["name"],
|
||||
month=month,
|
||||
groups=selected,
|
||||
concurrency=workers,
|
||||
grid_ids=[],
|
||||
csv_path=target,
|
||||
)
|
||||
source = job.directory / f"source{suffix}"
|
||||
source.write_bytes(raw)
|
||||
try:
|
||||
grid_ids = parse_upload(source)
|
||||
except Exception as exc:
|
||||
shutil.rmtree(job.directory, ignore_errors=True)
|
||||
state.jobs.jobs.pop(job.id, None)
|
||||
raise _bad(f"读取区域表失败:{exc}") from exc
|
||||
if not grid_ids:
|
||||
shutil.rmtree(job.directory, ignore_errors=True)
|
||||
state.jobs.jobs.pop(job.id, None)
|
||||
raise _bad("区域表里没有栅格 ID")
|
||||
job.grid_ids = grid_ids
|
||||
job.save()
|
||||
start_job(job.id)
|
||||
return job.snapshot()
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/cancel")
|
||||
async def cancel_job(job_id: str) -> dict:
|
||||
state.require_client()
|
||||
try:
|
||||
job = state.jobs.get(job_id)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc), 404) from exc
|
||||
if not job.is_active():
|
||||
raise _bad("这个任务没有在下载")
|
||||
job.cancel_event.set()
|
||||
job.message = "正在停止"
|
||||
return job.snapshot()
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/resume")
|
||||
async def resume_job(job_id: str) -> dict:
|
||||
state.require_client()
|
||||
try:
|
||||
job = state.jobs.get(job_id)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc), 404) from exc
|
||||
if job.is_active():
|
||||
raise _bad("这个任务正在下载")
|
||||
if job.status == "done":
|
||||
raise _bad("这个任务已经完成")
|
||||
start_job(job.id)
|
||||
return job.snapshot()
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}/events")
|
||||
async def job_events(job_id: str) -> StreamingResponse:
|
||||
state.require_client()
|
||||
try:
|
||||
job = state.jobs.get(job_id)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc), 404) from exc
|
||||
queue: asyncio.Queue = asyncio.Queue()
|
||||
job.subscribers.append(queue)
|
||||
|
||||
async def stream():
|
||||
try:
|
||||
yield _sse({"type": "snapshot", **job.snapshot()})
|
||||
if job.status in {"done", "done_with_errors", "cancelled", "error"} and not job.is_active():
|
||||
return
|
||||
while True:
|
||||
event = await queue.get()
|
||||
yield _sse(event)
|
||||
if event.get("type") in {"done", "error", "cancelled"}:
|
||||
return
|
||||
finally:
|
||||
if queue in job.subscribers:
|
||||
job.subscribers.remove(queue)
|
||||
|
||||
return StreamingResponse(stream(), media_type="text/event-stream")
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}/file")
|
||||
async def job_file(job_id: str) -> FileResponse:
|
||||
state.require_client()
|
||||
try:
|
||||
job = state.jobs.get(job_id)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc), 404) from exc
|
||||
if not job.csv_path.exists():
|
||||
raise _bad("文件还没有生成", 404)
|
||||
return FileResponse(job.csv_path, filename=job.csv_path.name)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""把一个栅格的指标和小区明细铺成 CSV 行。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
|
||||
from app.features.download.fields import Column
|
||||
|
||||
|
||||
def format_value(field: str, value) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, str) and value.strip().lower() in {"", "none", "null"}:
|
||||
return ""
|
||||
if field == "datatime":
|
||||
text = str(value).strip().replace("T", " ")
|
||||
return text[:19]
|
||||
if isinstance(value, bool):
|
||||
return "1" if value else "0"
|
||||
if isinstance(value, int) and not isinstance(value, bool):
|
||||
return str(value)
|
||||
if isinstance(value, float):
|
||||
if math.isnan(value) or math.isinf(value):
|
||||
return ""
|
||||
if value.is_integer() and abs(value) < 10**15:
|
||||
return str(int(value))
|
||||
return json.dumps(value, ensure_ascii=False)
|
||||
return str(value)
|
||||
|
||||
|
||||
def build_rows(
|
||||
grid_id: str,
|
||||
properties: dict | None,
|
||||
cells: list[dict] | None,
|
||||
columns: list[Column],
|
||||
) -> list[list[str]]:
|
||||
"""一个栅格多小区时每个小区一行;没有小区时仍保留一行,小区列留空。"""
|
||||
props = dict(properties or {})
|
||||
if props.get("grid20_id") in (None, ""):
|
||||
props["grid20_id"] = grid_id
|
||||
records = cells or [None]
|
||||
rows: list[list[str]] = []
|
||||
for index, cell in enumerate(records, start=1):
|
||||
row: list[str] = []
|
||||
for column in columns:
|
||||
if column.source == "grid":
|
||||
row.append(format_value(column.field, props.get(column.field)))
|
||||
continue
|
||||
if cell is None:
|
||||
row.append("")
|
||||
continue
|
||||
if column.field == "_index":
|
||||
row.append(str(index))
|
||||
continue
|
||||
row.append(format_value(column.field, cell.get(column.field)))
|
||||
rows.append(row)
|
||||
return rows
|
||||
Reference in New Issue
Block a user