"""Excel 读取层(polars + fastexcel / calamine)。 约定: * 所有单元格先按文本读入(`infer_schema_length=0`),再按需转数值/时间, 避免网管导出的 "\t2026-09-01 00:00:00\t"、千分位、空串等脏数据导致类型推断失败。 * 文件类型一律靠"表头特征"识别,不依赖文件名,方便后续网页上传任意命名。 """ from __future__ import annotations import re from pathlib import Path from typing import Iterable import polars as pl from . import config # ---------------------------------------------------------------- 基础工具 _TS_COLS = ("开始时间", "记录开始时间", "数据时间") _CGI_COLS = ("NCGI", "CGI", "小区表示") def _norm(name: str) -> str: """列名归一化:去空白、全角括号转半角,便于模糊匹配。""" return ( str(name) .replace("\u3000", "") .replace(" ", "") .replace("(", "(") .replace(")", ")") .strip() ) def sheet_names(path: str | Path) -> list[str]: import fastexcel return list(fastexcel.read_excel(str(path)).sheet_names) def read_table(path: str | Path, sheet_name: str | None = None) -> pl.DataFrame: """读取一张表为全文本 DataFrame,列名与单元格均做去空白处理。""" kwargs: dict = {"infer_schema_length": 0, "has_header": True} if sheet_name is not None: kwargs["sheet_name"] = sheet_name df = pl.read_excel(str(path), **kwargs) df.columns = [_norm(c) for c in df.columns] # 去重列名(网管报表偶有同名表头) seen: dict[str, int] = {} new_cols = [] for c in df.columns: if c in seen: seen[c] += 1 new_cols.append(f"{c}_{seen[c]}") else: seen[c] = 0 new_cols.append(c) df.columns = new_cols # 文本列去首尾空白/制表符 str_cols = [c for c, t in df.schema.items() if t == pl.String] if str_cols: df = df.with_columns([pl.col(c).str.strip_chars().alias(c) for c in str_cols]) return df def _find_col(df: pl.DataFrame, *candidates: str) -> str | None: norm_map = {_norm(c): c for c in df.columns} for cand in candidates: key = _norm(cand) if key in norm_map: return norm_map[key] return None def _find_col_like(df: pl.DataFrame, *patterns: str) -> str | None: """按子串匹配列名(全部 pattern 命中即匹配)。""" for c in df.columns: n = _norm(c) if all(_norm(p) in n for p in patterns): return c return None def _to_float(df: pl.DataFrame, col: str, alias: str) -> pl.Expr: return ( pl.col(col) .str.replace_all(",", "") .cast(pl.Float64, strict=False) .alias(alias) ) def _to_ts(df: pl.DataFrame, col: str) -> pl.Expr: return ( pl.col(col) .str.replace("T", " ") .str.slice(0, 19) .str.to_datetime("%Y-%m-%d %H:%M:%S", strict=False) .alias("ts") ) # ---------------------------------------------------------------- 类型识别 FLOW_METRICS = ("traffic_gb", "rrc_max", "mr_weak_pct", "access_rate", "drop_rate") # 低效拆除模板需要的附加列(老报表没有时为空,多报表互补 upsert) FLOW_EXTRA = ( "freq", # 频点 "freq_band", # 使用频段(识别 3D-MIMO 用) "bandwidth", # 小区带宽 "sector_name", # 所属共站同覆盖区域名 → 模板「扇区名称」 "high_traffic_warn", # 是否高流量预警小区(集团高负荷预警) "high_load_expand", # 是否高负荷待扩容小区 "rrc_max_abs", # 自忙时RRC连接最大数 "util_peak", # 自忙时峰值利用率 "mr_total", # (移动)总采样点数 "mr_weak_cnt", # (移动)采样点数量(大于-110) "unicom_cov", # (联通采集时)移动覆盖率-110 → 移动联通竞对采样点大于-110占比 "telecom_cov", # (电信采集时)移动覆盖率-110 → 移动电信竞对采样点大于-110占比 "weak_cell", # 是否弱覆盖小区 "worse_unicom", # 是否劣化于联通 "worse_telecom", # 是否劣化于电信 ) # 数值型附加列(补缺失列时用 Float64,其余按文本) FLOW_EXTRA_NUMERIC = ("bandwidth", "rrc_max_abs", "util_peak", "mr_total", "mr_weak_cnt", "unicom_cov", "telecom_cov") # 「是/否」类附加列(读入后统一归一化为 是/否) FLOW_EXTRA_YN = ("high_traffic_warn", "high_load_expand", "weak_cell", "worse_unicom", "worse_telecom") # 「是/否」类字段的取值归一化(网管报表里可能是 t/f、true/false、1/0、是/否) _YN_TRUE = {"t", "true", "y", "yes", "1", "是"} _YN_FALSE = {"f", "false", "n", "no", "0", "否"} def norm_freq(value: object) -> str: """频点归一化(用作模板「频段」列的展示值): ``E1/D7/A频段`` → ``E/D/A``;F1/F2、FDD900、FDD1800、3D-MIMO 原样保留。""" s = str(value or "").strip().upper().replace(" ", "").replace("(", "(").replace(")", ")") if not s: return "" if "3D-MIMO" in s or "3DMIMO" in s: return "3D-MIMO" for prefix in ("FDD1800", "FDD900"): if s.startswith(prefix): return prefix if s in ("F1", "F2"): return s s = re.sub(r"(频段)+$", "", s) s = re.sub(r"\d+$", "", s) return s def equiv_carriers(freq: object, freq_band: object, bandwidth: object) -> float | None: """频点 + 带宽 → 等效20M载波数。 规则(与需求给出的映射表一致,已用全量数据核对): * TDD(F1/F2/E/D/A/NB)= 带宽/20; * FDD(FDD1800/FDD900)= 带宽/20 × 1.5; * 使用频段含 3D-MIMO 的小区固定 2.5(覆盖报表自带值 2.0)。 映射不上的(缺频点或带宽)返回 None,模板留空。 """ band = norm_freq(freq) fb = str(freq_band or "").upper().replace(" ", "") if "3D-MIMO" in fb or "3DMIMO" in fb or band == "3D-MIMO": return 2.5 if not band or bandwidth is None: return None try: bw = float(bandwidth) except (TypeError, ValueError): return None k = 1.5 if band in ("FDD1800", "FDD900") else 1.0 return round(bw / 20.0 * k, 4) def _norm_yn(value: object) -> str | None: """t/f、true/false、1/0、是/否 → 是/否;识别不了返回 None。""" s = str(value or "").strip().lower() if not s: return None if s in _YN_TRUE: return "是" if s in _YN_FALSE: return "否" return None def _flow_columns(df: pl.DataFrame) -> dict[str, str]: """返回该表能提供的流量指标列映射 {标准字段: 原列名}。""" found: dict[str, str] = {} c = _find_col_like(df, "日平均4G流量") if c is None: c = _find_col_like(df, "PDCP层上下行总流量") if c: found["traffic_gb"] = c c = _find_col_like(df, "自忙时有效RRC连接最大数") if c is None: c = _find_col_like(df, "日均RRC连接平均数") if c: found["rrc_max"] = c c = _find_col_like(df, "弱覆盖采样", "-110", "占比") if c: found["mr_weak_pct"] = c c = _find_col_like(df, "无线接通率") if c: found["access_rate"] = c c = _find_col_like(df, "无线掉线率") if c: found["drop_rate"] = c return found def _ts_col(df: pl.DataFrame) -> str | None: for cand in _TS_COLS: c = _find_col(df, cand) if c: return c return _find_col_like(df, "开始时间") def _cgi_col(df: pl.DataFrame) -> str | None: for cand in _CGI_COLS: c = _find_col(df, cand) if c: return c return None def classify(df: pl.DataFrame) -> str: cols = set(df.columns) if "退网工单类型" in cols and ({"小区名", "CGI"} & cols): return "demand" ts, cgi = _ts_col(df), _cgi_col(df) if ts and cgi and _flow_columns(df): return "flow" if {"纬度", "经度", "小区名称"} <= cols: return "gongcan" return "unknown" def gongcan_tech(df: pl.DataFrame) -> str: return "5G" if ("小区NCGI" in df.columns or _find_col(df, "小区NCGI")) else "4G" # ---------------------------------------------------------------- 业务读取 def read_gongcan(path: str | Path, stats: dict | None = None) -> tuple[str, pl.DataFrame]: """读取工参,返回 (制式, 标准列 DataFrame)。 ``stats`` 可选,传入空 dict 时回填各步过滤的丢弃行数,便于入库日志展示。 """ df = read_table(path) tech = gongcan_tech(df) cgi = _find_col(df, "CGI", "小区NCGI") cell = _find_col(df, "小区名称") lat = _find_col(df, "纬度") lon = _find_col(df, "经度") site = _find_col(df, "所属站点名称", "所属局站", "所属基站名称") if not all([cgi, cell, lat, lon, site]): raise ValueError(f"工参缺少必要列(CGI/小区名称/经纬度/站点名称):{Path(path).name}") if stats is not None: stats["rows_raw"] = df.height # 过滤(第一步):站点类型为「微小站 / 皮站」的整行剔除 # 这一步放在选列之前,保证后续所有过滤、去重都在干净数据上进行 stype = _find_col(df, "站点类型") dropped_type = 0 if stype: before = df.height df = df.filter( ~pl.col(stype) .fill_null("") .str.strip_chars() .is_in(list(config.GONGCAN_EXCLUDE_SITE_TYPES)) ) dropped_type = before - df.height if stats is not None: stats["dropped_site_type"] = dropped_type stats["site_type_column"] = bool(stype) out = df.select( pl.col(cgi).alias("cgi"), pl.col(cell).alias("cell_name"), pl.col(lat).cast(pl.Float64, strict=False).alias("lat"), pl.col(lon).cast(pl.Float64, strict=False).alias("lon"), pl.col(site).alias("site_name"), ).with_columns(pl.lit(tech).alias("tech")) # 过滤:小区名称包含 "W-" 的去掉(室分/W 频段特殊小区,按需求剔除) before_w = out.height out = out.filter(~pl.col("cell_name").fill_null("").str.contains("W-", literal=True)) if stats is not None: stats["dropped_w"] = before_w - out.height if tech == "4G": # 过滤:网络制式去掉 NB-IoT mode = _find_col(df, "网络制式") if mode: before_nb = out.height keep = ( df.select(pl.col(cgi).alias("cgi"), pl.col(mode).alias("_mode")) .unique(subset=["cgi"], keep="last") .filter(~pl.col("_mode").fill_null("").str.contains("NB-IoT", literal=True)) .select("cgi") ) out = out.join(keep, on="cgi", how="semi") if stats is not None: stats["dropped_nbiot"] = before_nb - out.height out = ( out.filter(pl.col("cgi").is_not_null() & (pl.col("cgi") != "")) .unique(subset=["cgi"], keep="last") .sort("cgi") ) if stats is not None: stats["rows"] = out.height return tech, out def read_demand(path: str | Path, sheet_name: str | None = None) -> pl.DataFrame: """读取需求清单(拆站清单)。""" names = sheet_names(path) target = sheet_name if target is None: target = next((n for n in names if _norm(n) == "拆站清单"), names[0]) df = read_table(path, target) col = lambda *c: _find_col(df, *c) # noqa: E731 mapping = { "county": col("区县", "县区"), "cell_name": col("小区名"), "cgi": col("CGI"), "sector": col("扇区"), "site_name": col("物理站名(综资站点)", "物理站名(综资站点)"), "applicant": col("发起人"), "retire_reason": col("是否已发邮件安排拆除"), "need_date": col("需求日期"), "order_type": col("退网工单类型"), } missing = [k for k, v in mapping.items() if v is None and k in ("cell_name", "cgi", "order_type")] if missing: raise ValueError(f"需求清单缺少必要列:{missing}") exprs = [] for key, src in mapping.items(): exprs.append(pl.col(src).alias(key) if src else pl.lit(None).alias(key)) out = df.select(exprs) out = out.with_columns( pl.col("cell_name").fill_null("").str.replace(r"-\d+$", "").alias("logical_site"), pl.col("cgi").fill_null("").alias("cgi"), ) out = out.filter(pl.col("cgi") != "") out = out.with_row_index("id").with_columns((pl.col("id") + 1).cast(pl.Int64).alias("id")) return out def read_flow(path: str | Path) -> pl.DataFrame | None: """读取单个流量/质量报表,返回标准列(ts/cgi/指标 + 低效拆除附加列)。 无法识别时返回 None。附加列(频点/带宽/扇区名称/两个是否标志)老报表没有时为空。 """ df = read_table(path) if classify(df) != "flow": return None ts_col = _ts_col(df) cgi_col = _cgi_col(df) metrics = _flow_columns(df) if not (ts_col and cgi_col and metrics): return None exprs: list[pl.Expr] = [_to_ts(df, ts_col), pl.col(cgi_col).alias("cgi")] for key, src in metrics.items(): # mr_weak_pct 匹配到的列「(移动)弱覆盖采样点大于-110占比」本身就是弱覆盖占比, # 直接使用(此前误做 100-x 换算,语义相反) exprs.append(_to_float(df, src, key)) # ---- 低效拆除附加列(存在才取,取不到整列为空);与指标列同一次 select freq_col = _find_col(df, "频点") band_col = _find_col(df, "使用频段") bw_col = _find_col(df, "小区带宽") sector_col = _find_col(df, "所属共站同覆盖区域名") or _find_col(df, "共站同覆盖区域名") warn_col = _find_col(df, "是否高流量预警小区(集团高负荷预警)") load_col = _find_col(df, "是否高负荷待扩容小区") # 第 1 节新增列:LTE 周报提供 RRC/利用率,MR 月报提供采样点/覆盖率/三个是否标志; # 5G 容量周报提供「自忙时小区PRB利用率」(两报表 CGI 不重叠,可共用 util_peak) rrc_abs_col = _find_col_like(df, "自忙时RRC连接最大数") util_col = _find_col_like(df, "自忙时峰值利用率") or _find_col_like(df, "自忙时小区PRB利用率") mr_total_col = _find_col(df, "(移动)总采样点数") mr_weak_cnt_col = _find_col(df, "(移动)采样点数量(大于-110)") unicom_cov_col = _find_col_like(df, "联通采集时", "移动覆盖率-110") telecom_cov_col = _find_col_like(df, "电信采集时", "移动覆盖率-110") weak_col = _find_col(df, "是否弱覆盖小区") worse_u_col = _find_col(df, "是否劣化于联通") worse_t_col = _find_col(df, "是否劣化于电信") if freq_col: exprs.append(pl.col(freq_col).fill_null("").alias("freq")) if band_col: exprs.append(pl.col(band_col).fill_null("").alias("freq_band")) if bw_col: exprs.append(_to_float(df, bw_col, "bandwidth")) if sector_col: exprs.append(pl.col(sector_col).fill_null("").alias("sector_name")) for key, col in (("high_traffic_warn", warn_col), ("high_load_expand", load_col)): if col: exprs.append(pl.col(col).alias(key)) for key, col in ( ("rrc_max_abs", rrc_abs_col), ("util_peak", util_col), ("mr_total", mr_total_col), ("mr_weak_cnt", mr_weak_cnt_col), ("unicom_cov", unicom_cov_col), ("telecom_cov", telecom_cov_col), ): if col: exprs.append(_to_float(df, col, key)) for key, col in ( ("weak_cell", weak_col), ("worse_unicom", worse_u_col), ("worse_telecom", worse_t_col), ): if col: exprs.append(pl.col(col).alias(key)) out = df.select(exprs).filter(pl.col("ts").is_not_null() & (pl.col("cgi") != "")) # 是/否归一化;空串→null for key in FLOW_EXTRA_YN: if key in out.columns: out = out.with_columns( pl.col(key) .map_elements(_norm_yn, return_dtype=pl.String) .alias(key) ) # 补齐缺失列,保证列集合固定(指标列与数值附加列是数值,其余是文本) numeric = set(FLOW_METRICS) | set(FLOW_EXTRA_NUMERIC) for key in (*FLOW_METRICS, *FLOW_EXTRA): if key not in out.columns: dtype = pl.Float64 if key in numeric else pl.String out = out.with_columns(pl.lit(None, dtype=dtype).alias(key)) return out.select(["ts", "cgi", *FLOW_METRICS, *FLOW_EXTRA]).unique( subset=["ts", "cgi"], keep="last", maintain_order=True ) def sniff(path: str | Path) -> tuple[str, dict]: """轻量探测:返回 (kind, 摘要信息),用于导入前的分类与日志。 清单文件首个工作表往往不是「拆站清单」,因此先按工作表名定位; 模板文件本身不参与入库,直接归为 ``template`` 跳过。 """ path = Path(path) try: names = sheet_names(path) except Exception as exc: # noqa: BLE001 return "error", {"error": str(exc)} if "模板" in path.stem: return "template", {"sheets": names} target = next((n for n in names if _norm(n) == "拆站清单"), None) try: df = read_table(path, target) except Exception as exc: # noqa: BLE001 return "error", {"error": str(exc)} kind = classify(df) if kind == "unknown": # 退网站点审核信息表(模板类)兜底识别 try: raw = read_table(path, names[0]) if names else df if {"区县", "逻辑站点名称"} <= set(raw.columns): return "template", {"sheets": names} except Exception: # noqa: BLE001 pass return "unknown", {"sheets": names, "columns": df.columns[:12]} info: dict = {"rows": df.height, "columns": len(df.columns), "sheets": names} if target: info["sheet"] = target if kind == "gongcan": info["tech"] = gongcan_tech(df) elif kind == "flow": info["metrics"] = sorted(_flow_columns(df)) return kind, info def expand_paths(paths: Iterable[str | Path]) -> list[Path]: out: list[Path] = [] for p in paths: p = Path(p) if p.is_dir(): out.extend(sorted(x for x in p.rglob("*.xlsx") if not x.name.startswith("~$"))) elif p.suffix.lower() in (".xlsx", ".xlsm") and not p.name.startswith("~$"): out.append(p) return out __all__ = [ "read_table", "sheet_names", "classify", "read_gongcan", "read_demand", "read_flow", "sniff", "expand_paths", "FLOW_METRICS", "FLOW_EXTRA", "norm_freq", "equiv_carriers", ]