diff --git a/CHANGELOG.md b/CHANGELOG.md index 3940ea6..abfc86d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # 更新日志 +## 0.1.5 · 2026-11-18 + +- 玩家概览与近期战绩图片加宽,排版更紧凑,表格数字不再拆行。 +- 玩家概览新增综合评分、称号和五维雷达图,分别展示胜负预期与实际胜率。 +- 近期风格改用中文兵种标签,精简指标说明。 + ## 0.1.4 · 2026-11-18 - 图片页脚改用 GitHub Logo。 diff --git a/README.md b/README.md index 287ebbd..76fdc06 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ AstrBot 原生《断箭》(Broken Arrow)战绩查询插件。以简洁排版展示玩家概览、近期战绩与单局核心数据,支持图片战报和默认账号绑定,不依赖大模型。 -近期战绩提供彩色评分;单局战报包含赛前预测、双方对比、兵种构成和玩家数据。 +用 `ba me` 查看综合评分、称号和五维雷达图。图中的「胜负预期」衡量近期战果相对赛前预期的表现;「实际胜率」是近期已知胜负对局中获胜的比例。`ba recent` 查看逐局评分,`ba last` 查看最近一局的赛前预测、双方对比和玩家数据。 > 数据来源 [BATrace](https://dash.batrace.top/),如有帮助请支持该平台。更新内容见 [更新日志](CHANGELOG.md)。 @@ -89,7 +89,7 @@ ba stats @群友 - 运行要求:AstrBot **4.29.4 及以上**,QQ(OneBot v11);详细测试与验证记录见 [验证记录](docs/VALIDATION.md)。 - 开源协议:项目采用 **Apache-2.0**;`scoring.py` 的 ba-dragon 移植部分及 `assets/scoring-model.json` 保留上游 **MIT** 许可,完整文本见 [ba-dragon 许可](docs/BA_DRAGON_LICENSE.txt)。 -- 致谢与参考:[BATrace](https://dash.batrace.top/)(战绩数据源)、[AlexanderHYu/ba-dragon](https://github.com/AlexanderHYu/ba-dragon)(逐局评分模型及接口参考)、[benx1n/wows-stats-bot](https://github.com/benx1n/wows-stats-bot)、[timeance/astrbot_plugin_openai_native](https://github.com/timeance/astrbot_plugin_openai_native)、AstrBot(详见 [第三方说明](docs/THIRD_PARTY.md))。 +- 致谢与参考:[BATrace](https://dash.batrace.top/)(战绩数据源)、[AlexanderHYu/ba-dragon](https://github.com/AlexanderHYu/ba-dragon)(评分模型及接口参考)、[benx1n/wows-stats-bot](https://github.com/benx1n/wows-stats-bot)、[timeance/astrbot_plugin_openai_native](https://github.com/timeance/astrbot_plugin_openai_native)、AstrBot(详见 [第三方说明](docs/THIRD_PARTY.md))。 ```sh python -m pip install -r requirements-dev.txt diff --git a/assets/scoring-model.json b/assets/scoring-model.json index 6f5a775..2345ae8 100644 --- a/assets/scoring-model.json +++ b/assets/scoring-model.json @@ -1 +1 @@ -{"version":2,"fittedAt":"2026-11-12","expect":{"scale":400,"afkPenalty":500},"catSplit":{"recon":{"recon":1},"infantry":{"inf":0.86,"aa":0.14},"vehicles":{"armor":1},"support":{"arty":0.365,"aa":0.435},"logistic":{},"helicopters":{"heli":0.557},"aircrafts":{"jet":0.973}},"avgRoles":{"armor":0.256,"inf":0.164,"recon":0.133,"arty":0.095,"aa":0.139,"heli":0.047,"jet":0.165},"weights":{"kd":0.5,"con":0.5,"obj":0,"out":0.5},"outSd":0.4541,"marks":{"dragon":0.8,"qu":0.2},"units":{"1":["armor",55],"2":["recon",260],"3":["armor",65],"4":["arty",140],"5":["arty",75],"6":["armor",45],"7":[null,70],"8":["heli",110],"9":["armor",130],"10":["aa",90],"11":["arty",200],"12":["aa",170],"13":["armor",390],"14":["armor",80],"15":["armor",55],"16":["armor",70],"17":[null,110],"19":["heli",90],"20":["aa",110],"21":["recon",70],"22":["armor",45],"23":["recon",35],"24":["armor",85],"25":["armor",70],"26":["armor",50],"27":["aa",110],"28":["recon",70],"29":["recon",50],"30":["armor",60],"31":["aa",150],"33":["armor",45],"34":["aa",140],"35":["recon",45],"37":["recon",90],"40":["arty",90],"41":["armor",50],"44":["jet",225],"46":["heli",135],"47":["armor",20],"48":["recon",40],"49":["recon",45],"50":["arty",80],"51":["recon",55],"52":[null,40],"53":["armor",205],"54":["armor",260],"57":["inf",60],"60":["inf",65],"61":["recon",70],"62":["inf",70],"63":["inf",80],"65":["recon",85],"66":["inf",125],"68":["recon",75],"69":["aa",90],"70":["inf",110],"72":["inf",90],"73":["aa",100],"74":["inf",60],"75":["inf",60],"76":["recon",90],"77":["recon",80],"78":["armor",60],"79":[null,30],"80":[null,100],"81":[null,80],"82":["armor",40],"84":[null,65],"86":["heli",110],"87":["heli",75],"89":["armor",65],"90":["armor",35],"91":["arty",80],"92":["arty",100],"93":["arty",275],"94":["aa",110],"95":[null,85],"96":["armor",45],"97":["arty",200],"98":["arty",140],"99":["recon",45],"100":["heli",95],"102":["heli",55],"103":["recon",100],"105":["heli",65],"106":["heli",25],"107":["heli",70],"108":["inf",60],"109":["aa",70],"110":["inf",90],"111":["inf",80],"112":["inf",50],"114":["recon",70],"115":["recon",85],"116":["recon",70],"117":["inf",70],"118":["inf",40],"119":["inf",45],"120":["aa",80],"121":["inf",50],"122":["inf",50],"123":["recon",65],"124":["recon",75],"125":["recon",100],"126":["inf",75],"127":["inf",70],"128":["inf",45],"129":["inf",60],"130":["inf",95],"131":["inf",115],"132":["inf",60],"133":["inf",75],"134":["aa",75],"135":["recon",30],"136":["recon",80],"137":["recon",100],"138":["recon",65],"139":[null,100],"140":[null,50],"141":["armor",35],"142":["armor",55],"143":[null,115],"144":["armor",80],"145":[null,90],"146":["inf",60],"147":["inf",100],"148":["inf",40],"149":["inf",50],"150":["inf",105],"151":["armor",100],"152":["recon",40],"153":[null,105],"154":["arty",60],"155":["arty",40],"156":["aa",175],"157":["armor",180],"158":["armor",155],"159":[null,80],"160":["jet",60],"162":["arty",270],"163":["aa",145],"164":[null,40],"166":[null,40],"167":["recon",40],"168":["jet",145],"169":["jet",155],"170":["recon",75],"171":[null,9],"172":["armor",50],"173":["recon",45],"176":["inf",40],"177":["recon",65],"180":["armor",55],"182":["armor",75],"183":["armor",90],"184":["recon",45],"185":["armor",30],"186":["recon",60],"187":["armor",50],"188":["aa",80],"189":["arty",75],"190":["arty",300],"191":["armor",280],"194":["armor",35],"195":["recon",45],"196":["aa",75],"197":["armor",95],"198":["arty",200],"199":[null,40],"200":["armor",40],"201":["armor",45],"202":["aa",80],"203":["arty",55],"204":["armor",35],"205":["arty",80],"206":["armor",50],"207":["arty",90],"208":["armor",65],"209":["recon",70],"210":["arty",100],"211":["aa",130],"212":["armor",55],"213":["armor",60],"214":["armor",50],"215":["recon",60],"216":["armor",50],"217":["recon",55],"218":["arty",65],"219":["armor",45],"220":["aa",90],"221":["aa",60],"222":["aa",45],"223":["arty",275],"224":["arty",300],"225":["aa",230],"226":["arty",250],"227":["aa",325],"228":[null,65],"229":[null,80],"230":["armor",30],"231":["aa",150],"232":["arty",260],"233":["aa",175],"234":["arty",80],"235":["armor",60],"236":["armor",170],"237":["recon",250],"238":["armor",250],"239":["armor",200],"240":["armor",160],"241":[null,40],"242":[null,75],"243":["armor",250],"244":["armor",240],"245":["armor",215],"246":[null,30],"247":["arty",130],"249":["recon",40],"250":["aa",80],"251":["aa",180],"252":["armor",55],"253":["armor",45],"254":["armor",45],"255":["armor",250],"256":["heli",85],"257":[null,65],"258":[null,30],"259":[null,100],"260":[null,110],"261":[null,110],"262":[null,105],"263":["heli",75],"264":["recon",150],"266":[null,70],"267":["heli",55],"268":[null,90],"269":["heli",85],"270":["heli",115],"271":["heli",135],"272":["heli",115],"273":[null,80],"274":[null,120],"275":[null,120],"276":["recon",70],"277":["recon",60],"278":["recon",85],"280":["jet",200],"281":[null,140],"282":["jet",95],"283":["jet",145],"284":["jet",135],"285":["jet",110],"286":["jet",205],"287":["jet",160],"288":["jet",60],"289":["jet",170],"291":["jet",175],"292":["jet",165],"293":["jet",200],"294":["jet",240],"295":["jet",240],"297":["jet",275],"298":["jet",140],"299":["jet",200],"300":["jet",100],"301":["jet",150],"302":[null,100],"303":[null,100],"304":[null,140],"305":[null,150],"306":["jet",150],"307":["jet",75],"308":["jet",185],"309":["jet",165],"310":["jet",150],"311":["jet",150],"312":["jet",130],"313":["jet",60],"314":["jet",60],"315":["jet",180],"316":[null,70],"317":["jet",200],"318":["jet",400],"319":["jet",130],"320":["inf",100],"321":[null,9],"322":[null,150],"323":[null,150],"324":[null,200],"325":[null,150],"326":[null,150],"327":[null,200],"328":["recon",50],"329":["recon",50],"330":[null,9],"331":["jet",100],"350":["recon",65],"351":["inf",80],"353":["inf",50],"360":[null,9],"361":[null,9],"362":["recon",75],"363":["recon",90],"364":["heli",150],"365":["armor",35],"366":["recon",70],"367":["recon",80],"369":["inf",50],"370":["inf",65],"371":["aa",70],"372":["inf",110],"373":["arty",150],"374":["jet",65],"375":[null,25],"376":["arty",250],"377":["jet",100],"379":["jet",100],"380":["heli",115],"381":[null,50],"382":["arty",140],"383":["recon",70],"384":["recon",45],"386":["armor",45],"387":["recon",75],"388":["arty",200],"389":["aa",100],"390":[null,55],"391":["arty",125],"392":["armor",40],"393":["aa",110],"394":["aa",200],"395":["recon",200],"396":["armor",50],"397":[null,100],"398":["inf",60],"399":["inf",65],"401":["inf",50],"402":["inf",70],"403":["recon",80],"404":["aa",70],"407":["inf",80],"413":["aa",75],"414":["inf",65],"419":["inf",65],"420":[null,9],"421":["armor",35],"422":["arty",220],"423":[null,45],"425":["armor",45],"426":["arty",200],"427":[null,50],"428":[null,80],"429":["arty",140],"430":["armor",30],"431":["arty",100],"432":["armor",35],"433":["armor",40],"434":["inf",70],"435":["inf",75],"436":["inf",50],"437":["recon",60],"438":["inf",75],"439":["inf",75],"440":["aa",75],"441":["inf",40],"442":["inf",75],"443":["armor",70],"444":["armor",75],"445":["armor",70],"447":["recon",50],"448":["aa",160],"449":["inf",80],"450":["armor",40],"451":[null,9],"452":["arty",110],"453":["armor",140],"455":["recon",45],"456":[null,9],"457":["armor",200],"458":["recon",50],"459":["inf",70],"461":[null,5],"462":[null,200],"463":[null,125],"465":["jet",130],"466":["aa",225],"467":["recon",50],"468":["recon",80],"469":["inf",70],"471":["armor",90],"472":[null,200],"473":["inf",100],"474":["armor",5],"475":["heli",5],"476":[null,30],"477":[null,65],"478":[null,40],"479":[null,170],"480":[null,75],"481":["armor",210],"482":["inf",50],"483":["inf",50],"484":[null,5],"485":[null,45],"486":[null,200],"487":[null,50],"488":[null,210],"489":[null,9],"490":[null,40],"491":[null,40],"492":[null,40],"493":[null,40],"494":[null,40],"495":[null,40],"496":["inf",40],"497":["inf",40],"498":["armor",70],"499":["recon",40],"500":["armor",85],"501":["armor",40],"502":["armor",35],"503":["armor",260],"504":[null,45],"505":["recon",45],"508":["aa",110],"509":["recon",45],"510":["arty",80],"511":["arty",90],"512":["jet",60],"513":["inf",65],"515":["inf",35],"517":["inf",100],"519":["inf",80],"522":["aa",70],"525":["recon",70],"528":["recon",75],"531":[null,80],"532":[null,65],"533":["inf",40],"535":["armor",40],"536":[null,80],"537":[null,45],"538":["aa",45],"539":["arty",230],"540":["arty",250],"541":["armor",30],"542":["armor",50],"543":["recon",65],"545":["aa",110],"602":["armor",100],"604":["inf",35],"612":["inf",75],"615":["armor",110],"624":["inf",40],"627":["armor",40],"628":["armor",45],"632":["recon",50],"633":["recon",180],"635":["arty",90],"636":["arty",210],"702":["jet",1500],"703":["armor",240]},"norm":{"career":{"kd":{"mu":{"armor":-0.3196,"inf":-1.2321,"recon":-1.3268,"arty":1.4975,"aa":1.782,"heli":-1.2978,"jet":0.8931},"elo":-0.0095,"gap":0.51,"sigma":{"armor":0.6919,"inf":0.6862,"recon":0.6796,"arty":0.6946,"aa":0.6927,"heli":0.6936,"jet":0.682},"lambda":1,"q":[-4.036,-2.487,-2.032,-1.844,-1.715,-1.566,-1.475,-1.389,-1.324,-1.242,-1.181,-1.138,-1.078,-1.043,-1.004,-0.967,-0.924,-0.891,-0.858,-0.83,-0.791,-0.755,-0.72,-0.693,-0.666,-0.64,-0.61,-0.586,-0.561,-0.535,-0.505,-0.475,-0.448,-0.421,-0.391,-0.365,-0.337,-0.312,-0.288,-0.265,-0.242,-0.219,-0.192,-0.168,-0.146,-0.127,-0.108,-0.091,-0.06,-0.03,-0.009,0.013,0.033,0.054,0.081,0.104,0.12,0.147,0.177,0.202,0.224,0.242,0.269,0.294,0.317,0.343,0.37,0.391,0.416,0.441,0.466,0.494,0.522,0.55,0.577,0.608,0.637,0.665,0.697,0.729,0.767,0.797,0.836,0.873,0.912,0.947,0.992,1.049,1.104,1.15,1.205,1.249,1.322,1.413,1.507,1.629,1.757,1.909,2.14,2.619,6.665]},"con":{"mu":{"armor":0.2048,"inf":-0.6317,"recon":-0.6904,"arty":-0.5807,"aa":0.2152,"heli":-0.2517,"jet":0.7624},"elo":0.0173,"gap":0.1663,"sigma":{"armor":0.4764,"inf":0.4809,"recon":0.4639,"arty":0.4775,"aa":0.4669,"heli":0.4771,"jet":0.4459},"lambda":3,"q":[-7.407,-3.174,-2.469,-2.131,-1.843,-1.68,-1.544,-1.444,-1.334,-1.257,-1.171,-1.119,-1.063,-1.003,-0.959,-0.912,-0.866,-0.82,-0.775,-0.727,-0.691,-0.648,-0.615,-0.571,-0.535,-0.508,-0.474,-0.443,-0.413,-0.383,-0.361,-0.335,-0.311,-0.288,-0.268,-0.237,-0.218,-0.196,-0.174,-0.145,-0.122,-0.097,-0.073,-0.048,-0.025,-0.004,0.015,0.033,0.053,0.076,0.094,0.12,0.138,0.16,0.18,0.204,0.221,0.239,0.261,0.284,0.314,0.337,0.36,0.38,0.397,0.422,0.448,0.471,0.492,0.513,0.531,0.556,0.574,0.595,0.612,0.641,0.668,0.697,0.727,0.753,0.776,0.8,0.829,0.864,0.894,0.925,0.961,0.989,1.024,1.068,1.107,1.149,1.204,1.264,1.332,1.4,1.471,1.582,1.724,1.933,3.323]},"obj":{"mu":{"armor":0.2223,"inf":0.095,"recon":0.2026,"arty":-0.4083,"aa":-0.4643,"heli":-0.4827,"jet":-0.421},"elo":0.021,"gap":0.0535,"sigma":{"armor":0.5151,"inf":0.3268,"recon":0.3268,"arty":0.6746,"aa":0.772,"heli":1.0949,"jet":0.7373},"lambda":10,"q":[-3.628,-2.568,-2.36,-2.174,-2.002,-1.881,-1.774,-1.668,-1.565,-1.468,-1.362,-1.283,-1.179,-1.108,-1.045,-0.986,-0.928,-0.881,-0.838,-0.794,-0.755,-0.719,-0.681,-0.64,-0.589,-0.544,-0.512,-0.476,-0.444,-0.409,-0.383,-0.354,-0.331,-0.305,-0.264,-0.24,-0.213,-0.189,-0.161,-0.135,-0.115,-0.091,-0.065,-0.047,-0.026,0.002,0.029,0.047,0.072,0.093,0.118,0.139,0.163,0.181,0.201,0.226,0.245,0.275,0.295,0.323,0.343,0.361,0.384,0.408,0.43,0.452,0.475,0.494,0.519,0.539,0.56,0.586,0.615,0.639,0.661,0.685,0.71,0.733,0.759,0.784,0.82,0.848,0.869,0.896,0.927,0.959,0.989,1.037,1.071,1.109,1.144,1.193,1.239,1.302,1.36,1.4,1.459,1.556,1.662,1.824,2.573]}}},"matchPct":{"career":[-8.795,-3.102,-2.542,-2.258,-2.058,-1.92,-1.796,-1.693,-1.605,-1.528,-1.46,-1.395,-1.336,-1.28,-1.231,-1.179,-1.133,-1.085,-1.039,-0.992,-0.949,-0.909,-0.869,-0.83,-0.794,-0.758,-0.724,-0.691,-0.661,-0.63,-0.598,-0.568,-0.535,-0.505,-0.475,-0.449,-0.422,-0.395,-0.366,-0.334,-0.304,-0.275,-0.246,-0.216,-0.184,-0.153,-0.123,-0.097,-0.069,-0.042,-0.013,0.014,0.042,0.073,0.099,0.13,0.162,0.189,0.221,0.248,0.281,0.312,0.337,0.367,0.394,0.421,0.447,0.479,0.506,0.537,0.566,0.595,0.625,0.658,0.692,0.727,0.761,0.794,0.826,0.856,0.89,0.928,0.965,1.002,1.045,1.083,1.122,1.166,1.207,1.256,1.314,1.366,1.425,1.489,1.558,1.647,1.743,1.87,2.031,2.31,4.246]},"source":{"repository":"https://github.com/AlexanderHYu/ba-dragon","commit":"072dc9bc2d73ffc87000c1d3db4c0f9b4dcab549","files":["src/shared/dragon/score.ts","src/shared/dragon/roles.ts","src/shared/dragon/model.ts","src/shared/dragon/model.json","src/shared/types/batrace.ts"],"license":"MIT","licenseText":"MIT License\n\nCopyright (c) 2026 AlexanderHYu\nCopyright (c) 2025-2026 Zola (Zawinzala) — 从 https://github.com/Zawinzala/brokenarrow-log-maggot\n沿用的部分(录像、玩家追踪、卡组工具、日志解析规则)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","adaptation":"Python per-match career scoring and base-price composition; units retain role and base price only. No titles, Kalman aggregation, timeline or effective ELO."}} +{"version":2,"fittedAt":"2026-11-12","expect":{"scale":400,"afkPenalty":500},"catSplit":{"recon":{"recon":1},"infantry":{"inf":0.86,"aa":0.14},"vehicles":{"armor":1},"support":{"arty":0.365,"aa":0.435},"logistic":{},"helicopters":{"heli":0.557},"aircrafts":{"jet":0.973}},"avgRoles":{"armor":0.256,"inf":0.164,"recon":0.133,"arty":0.095,"aa":0.139,"heli":0.047,"jet":0.165},"weights":{"kd":0.5,"con":0.5,"obj":0,"out":0.5},"outSd":0.4541,"marks":{"dragon":0.8,"qu":0.2},"units":{"1":["armor",55],"2":["recon",260],"3":["armor",65],"4":["arty",140],"5":["arty",75],"6":["armor",45],"7":[null,70],"8":["heli",110],"9":["armor",130],"10":["aa",90],"11":["arty",200],"12":["aa",170],"13":["armor",390],"14":["armor",80],"15":["armor",55],"16":["armor",70],"17":[null,110],"19":["heli",90],"20":["aa",110],"21":["recon",70],"22":["armor",45],"23":["recon",35],"24":["armor",85],"25":["armor",70],"26":["armor",50],"27":["aa",110],"28":["recon",70],"29":["recon",50],"30":["armor",60],"31":["aa",150],"33":["armor",45],"34":["aa",140],"35":["recon",45],"37":["recon",90],"40":["arty",90],"41":["armor",50],"44":["jet",225],"46":["heli",135],"47":["armor",20],"48":["recon",40],"49":["recon",45],"50":["arty",80],"51":["recon",55],"52":[null,40],"53":["armor",205],"54":["armor",260],"57":["inf",60],"60":["inf",65],"61":["recon",70],"62":["inf",70],"63":["inf",80],"65":["recon",85],"66":["inf",125],"68":["recon",75],"69":["aa",90],"70":["inf",110],"72":["inf",90],"73":["aa",100],"74":["inf",60],"75":["inf",60],"76":["recon",90],"77":["recon",80],"78":["armor",60],"79":[null,30],"80":[null,100],"81":[null,80],"82":["armor",40],"84":[null,65],"86":["heli",110],"87":["heli",75],"89":["armor",65],"90":["armor",35],"91":["arty",80],"92":["arty",100],"93":["arty",275],"94":["aa",110],"95":[null,85],"96":["armor",45],"97":["arty",200],"98":["arty",140],"99":["recon",45],"100":["heli",95],"102":["heli",55],"103":["recon",100],"105":["heli",65],"106":["heli",25],"107":["heli",70],"108":["inf",60],"109":["aa",70],"110":["inf",90],"111":["inf",80],"112":["inf",50],"114":["recon",70],"115":["recon",85],"116":["recon",70],"117":["inf",70],"118":["inf",40],"119":["inf",45],"120":["aa",80],"121":["inf",50],"122":["inf",50],"123":["recon",65],"124":["recon",75],"125":["recon",100],"126":["inf",75],"127":["inf",70],"128":["inf",45],"129":["inf",60],"130":["inf",95],"131":["inf",115],"132":["inf",60],"133":["inf",75],"134":["aa",75],"135":["recon",30],"136":["recon",80],"137":["recon",100],"138":["recon",65],"139":[null,100],"140":[null,50],"141":["armor",35],"142":["armor",55],"143":[null,115],"144":["armor",80],"145":[null,90],"146":["inf",60],"147":["inf",100],"148":["inf",40],"149":["inf",50],"150":["inf",105],"151":["armor",100],"152":["recon",40],"153":[null,105],"154":["arty",60],"155":["arty",40],"156":["aa",175],"157":["armor",180],"158":["armor",155],"159":[null,80],"160":["jet",60],"162":["arty",270],"163":["aa",145],"164":[null,40],"166":[null,40],"167":["recon",40],"168":["jet",145],"169":["jet",155],"170":["recon",75],"171":[null,9],"172":["armor",50],"173":["recon",45],"176":["inf",40],"177":["recon",65],"180":["armor",55],"182":["armor",75],"183":["armor",90],"184":["recon",45],"185":["armor",30],"186":["recon",60],"187":["armor",50],"188":["aa",80],"189":["arty",75],"190":["arty",300],"191":["armor",280],"194":["armor",35],"195":["recon",45],"196":["aa",75],"197":["armor",95],"198":["arty",200],"199":[null,40],"200":["armor",40],"201":["armor",45],"202":["aa",80],"203":["arty",55],"204":["armor",35],"205":["arty",80],"206":["armor",50],"207":["arty",90],"208":["armor",65],"209":["recon",70],"210":["arty",100],"211":["aa",130],"212":["armor",55],"213":["armor",60],"214":["armor",50],"215":["recon",60],"216":["armor",50],"217":["recon",55],"218":["arty",65],"219":["armor",45],"220":["aa",90],"221":["aa",60],"222":["aa",45],"223":["arty",275],"224":["arty",300],"225":["aa",230],"226":["arty",250],"227":["aa",325],"228":[null,65],"229":[null,80],"230":["armor",30],"231":["aa",150],"232":["arty",260],"233":["aa",175],"234":["arty",80],"235":["armor",60],"236":["armor",170],"237":["recon",250],"238":["armor",250],"239":["armor",200],"240":["armor",160],"241":[null,40],"242":[null,75],"243":["armor",250],"244":["armor",240],"245":["armor",215],"246":[null,30],"247":["arty",130],"249":["recon",40],"250":["aa",80],"251":["aa",180],"252":["armor",55],"253":["armor",45],"254":["armor",45],"255":["armor",250],"256":["heli",85],"257":[null,65],"258":[null,30],"259":[null,100],"260":[null,110],"261":[null,110],"262":[null,105],"263":["heli",75],"264":["recon",150],"266":[null,70],"267":["heli",55],"268":[null,90],"269":["heli",85],"270":["heli",115],"271":["heli",135],"272":["heli",115],"273":[null,80],"274":[null,120],"275":[null,120],"276":["recon",70],"277":["recon",60],"278":["recon",85],"280":["jet",200],"281":[null,140],"282":["jet",95],"283":["jet",145],"284":["jet",135],"285":["jet",110],"286":["jet",205],"287":["jet",160],"288":["jet",60],"289":["jet",170],"291":["jet",175],"292":["jet",165],"293":["jet",200],"294":["jet",240],"295":["jet",240],"297":["jet",275],"298":["jet",140],"299":["jet",200],"300":["jet",100],"301":["jet",150],"302":[null,100],"303":[null,100],"304":[null,140],"305":[null,150],"306":["jet",150],"307":["jet",75],"308":["jet",185],"309":["jet",165],"310":["jet",150],"311":["jet",150],"312":["jet",130],"313":["jet",60],"314":["jet",60],"315":["jet",180],"316":[null,70],"317":["jet",200],"318":["jet",400],"319":["jet",130],"320":["inf",100],"321":[null,9],"322":[null,150],"323":[null,150],"324":[null,200],"325":[null,150],"326":[null,150],"327":[null,200],"328":["recon",50],"329":["recon",50],"330":[null,9],"331":["jet",100],"350":["recon",65],"351":["inf",80],"353":["inf",50],"360":[null,9],"361":[null,9],"362":["recon",75],"363":["recon",90],"364":["heli",150],"365":["armor",35],"366":["recon",70],"367":["recon",80],"369":["inf",50],"370":["inf",65],"371":["aa",70],"372":["inf",110],"373":["arty",150],"374":["jet",65],"375":[null,25],"376":["arty",250],"377":["jet",100],"379":["jet",100],"380":["heli",115],"381":[null,50],"382":["arty",140],"383":["recon",70],"384":["recon",45],"386":["armor",45],"387":["recon",75],"388":["arty",200],"389":["aa",100],"390":[null,55],"391":["arty",125],"392":["armor",40],"393":["aa",110],"394":["aa",200],"395":["recon",200],"396":["armor",50],"397":[null,100],"398":["inf",60],"399":["inf",65],"401":["inf",50],"402":["inf",70],"403":["recon",80],"404":["aa",70],"407":["inf",80],"413":["aa",75],"414":["inf",65],"419":["inf",65],"420":[null,9],"421":["armor",35],"422":["arty",220],"423":[null,45],"425":["armor",45],"426":["arty",200],"427":[null,50],"428":[null,80],"429":["arty",140],"430":["armor",30],"431":["arty",100],"432":["armor",35],"433":["armor",40],"434":["inf",70],"435":["inf",75],"436":["inf",50],"437":["recon",60],"438":["inf",75],"439":["inf",75],"440":["aa",75],"441":["inf",40],"442":["inf",75],"443":["armor",70],"444":["armor",75],"445":["armor",70],"447":["recon",50],"448":["aa",160],"449":["inf",80],"450":["armor",40],"451":[null,9],"452":["arty",110],"453":["armor",140],"455":["recon",45],"456":[null,9],"457":["armor",200],"458":["recon",50],"459":["inf",70],"461":[null,5],"462":[null,200],"463":[null,125],"465":["jet",130],"466":["aa",225],"467":["recon",50],"468":["recon",80],"469":["inf",70],"471":["armor",90],"472":[null,200],"473":["inf",100],"474":["armor",5],"475":["heli",5],"476":[null,30],"477":[null,65],"478":[null,40],"479":[null,170],"480":[null,75],"481":["armor",210],"482":["inf",50],"483":["inf",50],"484":[null,5],"485":[null,45],"486":[null,200],"487":[null,50],"488":[null,210],"489":[null,9],"490":[null,40],"491":[null,40],"492":[null,40],"493":[null,40],"494":[null,40],"495":[null,40],"496":["inf",40],"497":["inf",40],"498":["armor",70],"499":["recon",40],"500":["armor",85],"501":["armor",40],"502":["armor",35],"503":["armor",260],"504":[null,45],"505":["recon",45],"508":["aa",110],"509":["recon",45],"510":["arty",80],"511":["arty",90],"512":["jet",60],"513":["inf",65],"515":["inf",35],"517":["inf",100],"519":["inf",80],"522":["aa",70],"525":["recon",70],"528":["recon",75],"531":[null,80],"532":[null,65],"533":["inf",40],"535":["armor",40],"536":[null,80],"537":[null,45],"538":["aa",45],"539":["arty",230],"540":["arty",250],"541":["armor",30],"542":["armor",50],"543":["recon",65],"545":["aa",110],"602":["armor",100],"604":["inf",35],"612":["inf",75],"615":["armor",110],"624":["inf",40],"627":["armor",40],"628":["armor",45],"632":["recon",50],"633":["recon",180],"635":["arty",90],"636":["arty",210],"702":["jet",1500],"703":["armor",240]},"norm":{"career":{"kd":{"mu":{"armor":-0.3196,"inf":-1.2321,"recon":-1.3268,"arty":1.4975,"aa":1.782,"heli":-1.2978,"jet":0.8931},"elo":-0.0095,"gap":0.51,"sigma":{"armor":0.6919,"inf":0.6862,"recon":0.6796,"arty":0.6946,"aa":0.6927,"heli":0.6936,"jet":0.682},"lambda":1,"q":[-4.036,-2.487,-2.032,-1.844,-1.715,-1.566,-1.475,-1.389,-1.324,-1.242,-1.181,-1.138,-1.078,-1.043,-1.004,-0.967,-0.924,-0.891,-0.858,-0.83,-0.791,-0.755,-0.72,-0.693,-0.666,-0.64,-0.61,-0.586,-0.561,-0.535,-0.505,-0.475,-0.448,-0.421,-0.391,-0.365,-0.337,-0.312,-0.288,-0.265,-0.242,-0.219,-0.192,-0.168,-0.146,-0.127,-0.108,-0.091,-0.06,-0.03,-0.009,0.013,0.033,0.054,0.081,0.104,0.12,0.147,0.177,0.202,0.224,0.242,0.269,0.294,0.317,0.343,0.37,0.391,0.416,0.441,0.466,0.494,0.522,0.55,0.577,0.608,0.637,0.665,0.697,0.729,0.767,0.797,0.836,0.873,0.912,0.947,0.992,1.049,1.104,1.15,1.205,1.249,1.322,1.413,1.507,1.629,1.757,1.909,2.14,2.619,6.665]},"con":{"mu":{"armor":0.2048,"inf":-0.6317,"recon":-0.6904,"arty":-0.5807,"aa":0.2152,"heli":-0.2517,"jet":0.7624},"elo":0.0173,"gap":0.1663,"sigma":{"armor":0.4764,"inf":0.4809,"recon":0.4639,"arty":0.4775,"aa":0.4669,"heli":0.4771,"jet":0.4459},"lambda":3,"q":[-7.407,-3.174,-2.469,-2.131,-1.843,-1.68,-1.544,-1.444,-1.334,-1.257,-1.171,-1.119,-1.063,-1.003,-0.959,-0.912,-0.866,-0.82,-0.775,-0.727,-0.691,-0.648,-0.615,-0.571,-0.535,-0.508,-0.474,-0.443,-0.413,-0.383,-0.361,-0.335,-0.311,-0.288,-0.268,-0.237,-0.218,-0.196,-0.174,-0.145,-0.122,-0.097,-0.073,-0.048,-0.025,-0.004,0.015,0.033,0.053,0.076,0.094,0.12,0.138,0.16,0.18,0.204,0.221,0.239,0.261,0.284,0.314,0.337,0.36,0.38,0.397,0.422,0.448,0.471,0.492,0.513,0.531,0.556,0.574,0.595,0.612,0.641,0.668,0.697,0.727,0.753,0.776,0.8,0.829,0.864,0.894,0.925,0.961,0.989,1.024,1.068,1.107,1.149,1.204,1.264,1.332,1.4,1.471,1.582,1.724,1.933,3.323]},"obj":{"mu":{"armor":0.2223,"inf":0.095,"recon":0.2026,"arty":-0.4083,"aa":-0.4643,"heli":-0.4827,"jet":-0.421},"elo":0.021,"gap":0.0535,"sigma":{"armor":0.5151,"inf":0.3268,"recon":0.3268,"arty":0.6746,"aa":0.772,"heli":1.0949,"jet":0.7373},"lambda":10,"q":[-3.628,-2.568,-2.36,-2.174,-2.002,-1.881,-1.774,-1.668,-1.565,-1.468,-1.362,-1.283,-1.179,-1.108,-1.045,-0.986,-0.928,-0.881,-0.838,-0.794,-0.755,-0.719,-0.681,-0.64,-0.589,-0.544,-0.512,-0.476,-0.444,-0.409,-0.383,-0.354,-0.331,-0.305,-0.264,-0.24,-0.213,-0.189,-0.161,-0.135,-0.115,-0.091,-0.065,-0.047,-0.026,0.002,0.029,0.047,0.072,0.093,0.118,0.139,0.163,0.181,0.201,0.226,0.245,0.275,0.295,0.323,0.343,0.361,0.384,0.408,0.43,0.452,0.475,0.494,0.519,0.539,0.56,0.586,0.615,0.639,0.661,0.685,0.71,0.733,0.759,0.784,0.82,0.848,0.869,0.896,0.927,0.959,0.989,1.037,1.071,1.109,1.144,1.193,1.239,1.302,1.36,1.4,1.459,1.556,1.662,1.824,2.573]}}},"matchPct":{"career":[-8.795,-3.102,-2.542,-2.258,-2.058,-1.92,-1.796,-1.693,-1.605,-1.528,-1.46,-1.395,-1.336,-1.28,-1.231,-1.179,-1.133,-1.085,-1.039,-0.992,-0.949,-0.909,-0.869,-0.83,-0.794,-0.758,-0.724,-0.691,-0.661,-0.63,-0.598,-0.568,-0.535,-0.505,-0.475,-0.449,-0.422,-0.395,-0.366,-0.334,-0.304,-0.275,-0.246,-0.216,-0.184,-0.153,-0.123,-0.097,-0.069,-0.042,-0.013,0.014,0.042,0.073,0.099,0.13,0.162,0.189,0.221,0.248,0.281,0.312,0.337,0.367,0.394,0.421,0.447,0.479,0.506,0.537,0.566,0.595,0.625,0.658,0.692,0.727,0.761,0.794,0.826,0.856,0.89,0.928,0.965,1.002,1.045,1.083,1.122,1.166,1.207,1.256,1.314,1.366,1.425,1.489,1.558,1.647,1.743,1.87,2.031,2.31,4.246]},"source":{"repository":"https://github.com/AlexanderHYu/ba-dragon","commit":"072dc9bc2d73ffc87000c1d3db4c0f9b4dcab549","files":["src/shared/dragon/score.ts","src/shared/dragon/roles.ts","src/shared/dragon/model.ts","src/shared/dragon/model.json","src/shared/types/batrace.ts","src/renderer/src/features/players/PlayerDetail.tsx"],"license":"MIT","licenseText":"MIT License\n\nCopyright (c) 2026 AlexanderHYu\nCopyright (c) 2025-2026 Zola (Zawinzala) — 从 https://github.com/Zawinzala/brokenarrow-log-maggot\n沿用的部分(录像、玩家追踪、卡组工具、日志解析规则)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","adaptation":"Python career-row and player aggregate scoring, profile tiers and base-price composition; no match awards, timeline or effective ELO."},"kalman":{"P0":0.153,"q":0,"r":1.1221,"shortMin":16},"tiers":[[0.9,"dragon"],[0.7,"solid"],[0.3,"average"],[0.1,"weak"],[0,"qu"]],"playerPct":[-1.0956,-0.7659,-0.7119,-0.6391,-0.6033,-0.5718,-0.5484,-0.5344,-0.4859,-0.4618,-0.439,-0.4185,-0.3947,-0.3823,-0.3586,-0.3426,-0.338,-0.3272,-0.3182,-0.3072,-0.2904,-0.2854,-0.2817,-0.2704,-0.2592,-0.2438,-0.233,-0.2251,-0.2196,-0.2151,-0.2052,-0.1927,-0.1837,-0.1769,-0.1733,-0.1698,-0.1647,-0.1553,-0.1481,-0.1428,-0.1369,-0.1282,-0.1201,-0.1138,-0.1077,-0.1014,-0.092,-0.0862,-0.0834,-0.0755,-0.0701,-0.0648,-0.0548,-0.0446,-0.0336,-0.0309,-0.0171,-0.0108,0.0017,0.0041,0.0135,0.0252,0.0373,0.0525,0.0594,0.0698,0.0788,0.0839,0.0889,0.1005,0.1125,0.1236,0.1273,0.1378,0.1455,0.1592,0.1692,0.1739,0.1886,0.1934,0.2018,0.2076,0.2118,0.2243,0.2274,0.2395,0.2522,0.2636,0.2727,0.2878,0.3099,0.3264,0.3474,0.3641,0.3842,0.4182,0.4882,0.5253,0.5871,0.6303,0.8701]} diff --git a/docs/API_NOTES.md b/docs/API_NOTES.md index 6a95780..f577282 100644 --- a/docs/API_NOTES.md +++ b/docs/API_NOTES.md @@ -83,7 +83,11 @@ SteamID64 与 STB ID 均保持字符串;**未找到可靠的 Steam→STB 映 ## 评分、预测与战报展示 -`scoring.py` 使用 `assets/scoring-model.json`,移植 ba-dragon 固定提交的逐局评分逻辑与参数。近期战绩首列统一命名「评分」,按分数段着色,不显示称号。缺少必要数据时返回 `None` 并显示「暂无」,不补零。它与来源 ELO 分别展示,不是完整生涯评价,也不引入时间线或 Kalman 聚合算法。 +`scoring.py` 使用 `assets/scoring-model.json`,移植 ba-dragon 固定提交的 `computeDragonScore`。近期战绩使用逐局分,不显示称号;玩家概览接收按时间从新到旧排列的对局,先跳过无效局,再取最多 20 场,将逐局标准分从旧到新输入 Kalman 滤波器,短局权重较低。再查 `playerPct` 得到 1–10 综合分,按显示分数及 `tiers` 给出称号;它不是单局显示分的平均值。1 场有效对局也可评分,`sample_size` 保留实际场数;0 场时综合分、称号和前四维均为 `None`。 + +五个雷达值均为 0–100。分值 K/D、摧毁贡献、占点贡献分别表示相对同条件玩家的表现百分位;占点不计入综合分。「胜负预期」是逐局 `phi((S-E)/outSd)` 的平均表现:`S` 采用上游模型内部的排位 ELO 涨跌,`E` 由双方赛前 ELO 和其他挂机者修正得出。前四项均按可用分项取平均后四舍五入为百分制整数。与上游缺失值回退不同,插件在缺少本人或在线队友占点时跳过该局的占点轴,缺少任何参战者所需的 ELO 或摧毁/损失价值时跳过整局。已归一化的真实零仍参与计算。 + +第五维 `win_rate` 由服务层传入,仅统计近期样本中目标玩家有明确布尔 `won` 的对局。没有已知赛果时为 `None`,已知赛果全部为负时为 `0`;即使没有有效评分局,也可独立提供该轴。两种胜负指标不互相填补,评分本身不触发网络请求。 `ba last` 的单局图片顶部展示基于双方赛前 ELO 的赛前预测及双队摘要;中部左侧兵种构成、右侧双方对比;底部展示队伍玩家数据。摘要区分赛前平均 ELO(`OldRating`)与赛后平均 ELO(`NewRating`)。预测是模型估算,不表示实际赛果。兵种构成按模型的单位角色与基础价格估算出动花费,缺少单位价格或记录时保留不完整说明,不冒充实际结算。 @@ -194,4 +198,4 @@ AstrBot 适配器从事件的 `get_platform_id()/get_sender_id()/get_group_id()` 该提交的 ba-dragon 主源码为 MIT,LICENSE 载明 AlexanderHYu 与沿用部分的 Zola 版权;其 README 另外说明可选录像使用 GPL FFmpeg。 Python 请求调度、数据模型和业务适配由本插件实现;`scoring.py` 的移植部分与 `assets/scoring-model.json` 使用 ba-dragon 的 MIT 评分逻辑和模型参数,并保留其来源与版权。未引入录像工具或 FFmpeg。 -完整上游许可原样保留于 [BA_DRAGON_LICENSE.txt](BA_DRAGON_LICENSE.txt),安装、源码与 Gemini 包均随附。本仓库根 `LICENSE` 继续为 Apache-2.0;具体第三方来源与移植范围见 [THIRD_PARTY.md](THIRD_PARTY.md)。 +完整上游许可原样保留于 [BA_DRAGON_LICENSE.txt](BA_DRAGON_LICENSE.txt) 和模型的 `source.licenseText`。本仓库根 `LICENSE` 继续为 Apache-2.0;分发时的许可保留要求、具体来源与移植范围见 [THIRD_PARTY.md](THIRD_PARTY.md)。 diff --git a/docs/THIRD_PARTY.md b/docs/THIRD_PARTY.md index 3866f57..fa9b723 100644 --- a/docs/THIRD_PARTY.md +++ b/docs/THIRD_PARTY.md @@ -6,7 +6,7 @@ | --- | --- | --- | | [AstrBot](https://github.com/astrbotdevs/astrbot) | 原生插件 API、ZIP 格式与配置 Schema 核对 | v4.29.4,`61335414433db721b3f7ecc93f90deafe0a59d78` | | [AstrBot T2I](https://github.com/AstrBotDevs/astrbot-t2i-service) | 核对 `viewport_width`、像素比及 JPEG 质量参数 | `bcc08e47274c69e5ace19bbf738b95260ce17ca7` | -| [ba-dragon](https://github.com/AlexanderHYu/ba-dragon) | BATrace 接口参考;逐局评分、赛前 ELO 预测及兵种构成估算的 MIT 移植 | `072dc9bc2d73ffc87000c1d3db4c0f9b4dcab549`,详见下文及 API_NOTES.md | +| [ba-dragon](https://github.com/AlexanderHYu/ba-dragon) | BATrace 接口参考;逐局评分、玩家综合评分、赛前 ELO 预测及兵种构成估算的 MIT 移植 | `072dc9bc2d73ffc87000c1d3db4c0f9b4dcab549`,详见下文及 API_NOTES.md | | [wows-stats-bot](https://github.com/benx1n/wows-stats-bot) | README 中绑定与 @ 查询的交互研究,未移植 HoshinoBot 实现 | master,`80c86970685887578054e61e1a76d1589ea1dc31` | | [BATrace](https://dash.batrace.top/) | 预期战绩数据来源 | 自身接入许可、配额及真实字段待确认 | | [astrbot_plugin_openai_native](https://github.com/timeance/astrbot_plugin_openai_native) | 参考用户跨群累计、群共享额度、配置提示与额度查询;按本任务要求统一私聊用户计数和北京时间日界 | main,`98bd76784bb2a35df0aea968138f87fd4d9ee207`;核对 README、配置 Schema、事件身份提取 | @@ -15,11 +15,11 @@ ## ba-dragon 评分与模型 -`scoring.py` 将固定提交中的 `src/shared/dragon/score.ts`、`roles.ts`、`model.ts` 相关逻辑移植为 Python;`assets/scoring-model.json` 使用同一提交的 `src/shared/dragon/model.json` 参数,以及评分和兵种构成所需的单位角色与基础价格信息。模型内的 `source` 记录仓库、提交、来源文件和 MIT 文本。 +`scoring.py` 将固定提交中的 `src/shared/dragon/score.ts`、`roles.ts`、`model.ts` 相关逻辑移植为 Python;`assets/scoring-model.json` 从同一提交的 `src/shared/dragon/model.json` 提取评分参数,单位表仅保留角色和基础价格。模型内的 `source` 记录仓库、提交、来源文件和完整 MIT 文本。 -移植范围是逐局评分、基于赛前 ELO 的预测及按基础花费估算的兵种构成。展示统一称「评分」,按分数着色;不包含称号、时间线或 Kalman 生涯聚合。模型结果是估算,不代表官方评价。 +玩家概览使用 `computeDragonScore` 的 Kalman 聚合、玩家分位表、分档和四个表现分项;分档称号取自 `src/renderer/src/features/players/PlayerDetail.tsx`。第五项「实际胜率」由插件服务根据明确的 `won` 计算并传入评分模块。近期战绩保持逐局评分。未移植单局奖项、时间线或实力 ELO;这些模型分数不代表官方评价。 -完整上游版权与 MIT 许可原样保留于 [BA_DRAGON_LICENSE.txt](BA_DRAGON_LICENSE.txt),包括 `Copyright (c) 2026 AlexanderHYu` 及 `Copyright (c) 2025-2026 Zola (Zawinzala)` 与原文件的沿用部分说明。安装包、源码包及 Gemini 文案包均保留该文本;文案润色不修改许可证。 +[BA_DRAGON_LICENSE.txt](BA_DRAGON_LICENSE.txt) 和模型的 `source.licenseText` 均原样保留固定提交的 `LICENSE`,包括 `Copyright (c) 2026 AlexanderHYu` 及 `Copyright (c) 2025-2026 Zola (Zawinzala)` 与原文件的沿用部分说明。分发这些移植代码或模型时,安装包、源码和 Gemini 文案包均应保留完整上游版权及 MIT 许可;文案润色不修改该文本。 未移植参考项目的录像工具或 FFmpeg。其 README 提到的可选 GPL FFmpeg 不随本插件分发。 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index d56981c..5e9190e 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,15 +1,15 @@ # 验证记录 -验证日期:2026-11-18(Asia/Hong_Kong)。版本:v0.1.4。 +验证日期:2026-11-18(Asia/Hong_Kong)。版本:v0.1.5。 ## 本次结果 | 项目 | 结果 | | --- | --- | -| 完整离线测试 | **723 passed,31.67 秒** | -| 评分与固定上游 TypeScript 对照 | **320 个合成样本一致**;中间值误差小于 1e-12 | -| 三类战报本地渲染 | 18 组 HTML/文字、36 张 PNG;无布局越界或外部请求 | -| 设置中心本地交互 | 深色 390px、浅色 1100px 两组通过;4 张预览;验证浅色默认值及已保存深色配置 | +| 完整离线测试 | **740 项通过** | +| 综合评分与固定上游 TypeScript 对照 | **483 组合成输入通过**,涵盖单局、多局、时间缺失、零场与真实零值 | +| 三类战报本地渲染 | 深浅色、长名称和缺失样本共 36 张截图通过布局检查,另生成 12 张按 390px 聊天气泡等比缩放的概览与近期战绩预览 | +| 设置中心本地交互 | 设置页面未变;沿用 v0.1.4 的两组浏览器验证,覆盖浅色默认值及已保存深色配置 | | 依赖兼容性 | 依赖未变;沿用 v0.1.3 的 `uv pip check` 结果:30 个已安装包兼容 | | 完整 AstrBot 服务、真实渲染服务 | 未启动;按 v4.29.4 固定源码核对 API,使用事件与桥接桩验证 | | BATrace / QQ 实际联调 | 开发环境未调用;用户已提供候选结果和图片超时日志 | @@ -21,11 +21,12 @@ - 分值 K/D 使用摧毁分与损失分;击杀/阵亡是单位数量,伤害/承伤是另一组数据。出兵花费、补给消耗保留有效小数,不被整数格式误判为缺失。 - 分析接口只以明确布尔 `won` 及相同对局 ID 提供目标玩家胜负;不将 ELO 涨跌当成展示的权威胜负。单局页保留已知目标胜负。 - 分析样本与近期样本分别标明;重复和相互矛盾的分析结果不重复计入分母。地图、单位按来源 ID 关联。 -- 「评分」移植固定 ba-dragon 模型的逐局 career 计算,按分数着色,不展示称号。保留 MIT 来源与完整许可。 -- Oracle 包含原始 160 个样本,以及逐个删除 `StartTime` 的 160 个边界样本。开始/结束时间分别保留;不以结束时间减时长反推开始时间。近期列表按真实结束时间、缺少时按真实开始时间排序,两者都缺少才放最后。 +- 近期「评分」移植固定 ba-dragon 模型的逐局 career 计算,按分数着色,不展示称号;玩家概览展示综合评分和称号。保留 MIT 来源与完整许可。 +- 端到端样例对照:同一场的逐局分为 9.3,玩家综合分为 7.9(有龙样)。雷达的分值 K/D、摧毁贡献、占点贡献、胜负预期分别为 91、53、53、92;该玩家实际一战一胜,所以第五轴是 100%。无胜负记录时,第五轴留空。 +- 上游对照包含 160 组单局、160 组缺少开始时间、160 组多局和 3 组边界输入。近期列表按真实结束时间、缺少时按真实开始时间排序,不反推开始时间。 - 赛前预测使用 A/B 队全部必要赛前 ELO;兵种构成按已收录单位基础价格估算。缺少成员单位数据或存在未知价格时,不把已识别部分重新归一化为完整构成。 - 队伍摘要的赛前平均 ELO 使用传递到展示层的赛前值;本局 `NewRating` 标明为赛后平均 ELO,不将历史对局的赛后值称为当前值。 -- 单局图片按 900 CSS 像素渲染:顶部预测及 A/B 队伍摘要,中部左侧兵种构成、右侧双方对比,底部玩家。其他卡片为 390 CSS 像素;运行仍使用 JPEG 85、ultra 像素比。 +- 玩家概览、近期战绩、单局战报分别使用 640、800、900 CSS 像素。单局保持顶部预测及 A/B 队伍摘要、中部左侧兵种构成与右侧双方对比、底部玩家的布局;运行仍使用 JPEG 85、ultra 像素比。 - 双方对比与逐兵种构成都共用左 A、右 B 的横条;兵种使用对应类别的同色系深浅色(A 深、B 浅)。构成数值保持双方各自占比,横条按这两个占比划分;缺失值与 0/0 不生成虚假的比例。 - 所有图片页脚为本地内嵌 GitHub Logo、`timeance/astrbot_plugin_BA_stats` 和「数据来源 BATracer」。深浅主题分别使用官方白色与黑色 Logo,不在运行时请求素材。 - 图片默认浅色;原生配置、独立设置中心和渲染器默认值一致,已保存的深色选择保持有效。图片缓存摘要包含完整 HTML,样式、主题和 Logo 变更会生成新缓存。 @@ -55,7 +56,16 @@ v0.1.3 共用图片下载与验证流程:检查 HTTP 状态,限制下载大 这些结果证明离线流程与坏缓存处理通过测试,**不代表已完成真实 QQ 收发验收**。仍需在用户实例安装后验证;不能将旧日志中的所有 QQ 超时都归因为相同原因。 -## 执行与证据 +## v0.1.5 验证方式 + +```powershell +& ../.venv/Scripts/python.exe -X utf8 -m pytest -q +& ../.venv/Scripts/python.exe -X utf8 -B tools/render_previews.py --screenshots --output ../tmp/overview-v015/previews +``` + +另用 20 场合成对局走通解析、服务和两种宽度的玩家概览渲染:胜负预期 83、实际胜率 65%。已查看 640px 和 390px 截图;伤害值 `11,682.87` 均在同一行,长单位名能换行。 + +## 历史验证:v0.1.4 ```powershell & ../.venv/Scripts/python.exe -X utf8 -m pytest -q --basetemp=../tmp/pytest-v014-reviewed --junitxml=../validation/pytest-v0.1.4.xml @@ -72,7 +82,7 @@ v0.1.3 共用图片下载与验证流程:检查 HTTP 状态,限制下载大 主代理目视检查了单局深浅两色宽图、单局缺失数据手机卡、近期浅色手机卡、玩家概览深色手机卡和常用设置浅色桌面页。卡片矩阵含正常、长昵称、缺失数据三组,深浅两色,900/390px;预览均标明合成样本。浏览器拦截外部请求,只使用本地生成内容,没有使用外部账号或登录态。 -本轮战报预览保存在会话目录的 `tmp/report-visual-v014/previews/`;设置中心预览位于 `previews/settings-*.png`。本地预览不随插件发布。 +v0.1.4 战报预览保存在会话目录的 `tmp/report-visual-v014/previews/`;设置中心预览位于 `previews/settings-*.png`。本地预览不随插件发布。 会话目录:`H:/Codex/01a1e923-f766-7562-b804-35854a994fc4`。Python 3.11.4;Playwright 1.65.2,本地 Chromium 159.0.8154.6。主测试使用 httpx.MockTransport、临时 SQLite 和 AstrBot 桩;没有访问真实战绩、QQ 账号、数据库或运行配置。 diff --git a/main.py b/main.py index 548f0e0..1f8dae5 100644 --- a/main.py +++ b/main.py @@ -155,7 +155,7 @@ async def initialize(self): await self.storage.open() self._images.mkdir(parents=True, exist_ok=True) self._prune_images() - self.diagnostics.record("plugin_start", status="0.1.4") + self.diagnostics.record("plugin_start", status="0.1.5") async def _run(self, awaitable, *, timed=True): if self._closed: @@ -227,8 +227,13 @@ async def _prepare_image(self, view, umo, mode, progress): progress["stage"] = "generate" source = await self.html_render( "{{ body | safe }}", {"body": html}, return_url=True, - options={"type": "jpeg", "quality": 85, "full_page": True, - "viewport_width": 900 if view.get("kind") == "match" else 390, "device_scale_factor_level": "ultra"}, umo=umo) + options={ + "type": "jpeg", "quality": 85, "full_page": True, + "viewport_width": Renderer.WIDTHS[view.get("kind", "overview")], + "device_scale_factor_level": "ultra", + }, + umo=umo, + ) url = source if is_image_url(source) else None content_type = "" if url: @@ -304,7 +309,7 @@ async def _status(self): "schema": "响应结构变化", "identity_mismatch": "身份校验失败", "no_data": "暂无收录", "upstream": "上游暂不可用", "queue_full": "队列已满", "not_configured": "接入未配置", "closed": "客户端已关闭", "daily_quota": "每日额度已用完"} - return (f"断箭战报 v0.1.4\n在线查询:{'已启用' if status['configured'] else '未启用或 API 地址无效'}\n" + return (f"断箭战报 v0.1.5\n在线查询:{'已启用' if status['configured'] else '未启用或 API 地址无效'}\n" f"今日总请求:{usage['global']}/{GLOBAL_DAILY_LIMIT}(固定上限);北京时间 0 点重置\n" f"本次运行请求:{status['requests']};进行中:{status['inflight']}\n" f"API 缓存:{await self.storage.cache_count()} 条;命中:{status['cache_hits']};旧缓存:{status['stale_hits']}\n" diff --git a/metadata.yaml b/metadata.yaml index 3469028..53f67b0 100644 --- a/metadata.yaml +++ b/metadata.yaml @@ -1,8 +1,8 @@ name: astrbot_plugin_ba_stats display_name: 断箭战报 -short_desc: "《断箭》战绩查询,支持逐局评分、赛前预测与图片战报。" -desc: "查询《断箭》(Broken Arrow)玩家概览、近期战绩和单局战报,展示逐局评分、赛前预测、双方对比与兵种构成,支持账号绑定、群友查询及图片或文字展示。在设置中心或原生插件配置中开启在线查询后使用。" -version: "0.1.4" +short_desc: "《断箭》战绩查询,支持玩家评分、五维雷达图与图片战报。" +desc: "查询《断箭》(Broken Arrow)玩家概览、近期战绩和单局战报,展示玩家评分、五维雷达图、逐局评分、赛前预测与双方对比,支持账号绑定、群友查询及图片或文字展示。在设置中心或原生插件配置中开启在线查询后使用。" +version: "0.1.5" author: timeance repo: https://github.com/timeance/astrbot_plugin_BA_stats astrbot_version: ">=4.29.4" diff --git a/render.py b/render.py index b12a3a5..7eacd1f 100644 --- a/render.py +++ b/render.py @@ -15,6 +15,10 @@ losses, destroyed_value, lost_value, unit_exchange, value_exchange}]}]. Team sizes are unrestricted; never pad absent players with dummy rows. common_units (overview, optional): [{name: str, count?: int}]. + profile_rating (overview): {score: 1..10 | None, title, tone, sample_size, + dimensions: [{key: kd|contrib|obj|outcome|win_rate, label, value: 0..100 | None}]}. + The last axis is actual win rate. Missing axes never become zero points. + style_scope (overview): actual analysis sample label, e.g. 近100场风格. scope: str describing actual sample / mode / coverage (never inferred). fetched_at, source_updated_at: aware datetime or ISO 8601 with timezone. stale: bool; source_url: optional public http(s) link; notes?: list[str]. @@ -45,6 +49,7 @@ from copy import deepcopy from datetime import datetime from decimal import Decimal, InvalidOperation +from math import cos, pi, sin from pathlib import Path from urllib.parse import urlsplit from zoneinfo import ZoneInfo @@ -57,6 +62,8 @@ _MODES = {"ranked": "排位", "custom": "自定义", "unknown": "暂无"} _ROLES = {"装甲": "armor", "步兵": "infantry", "侦察": "recon", "炮兵": "artillery", "防空": "air-defense", "直升机": "helicopter", "固定翼": "aircraft", "后勤/运输": "logistics"} +_PROFILE_AXES = (("kd", "分值 K/D"), ("contrib", "摧毁贡献"), ("obj", "占点贡献"), + ("outcome", "胜负预期"), ("win_rate", "实际胜率")) def _plain(value, default=MISSING) -> str: @@ -77,15 +84,17 @@ def _number(value) -> Decimal | None: return None -def _numeric(value, style="decimal") -> str: +def _numeric(value, style="decimal", *, compact=False) -> str: parsed = _number(value) if parsed is None: return MISSING if style == "integer": - return str(int(parsed)) if parsed == parsed.to_integral_value() else MISSING + return format(int(parsed), ",d" if compact else "d") if parsed == parsed.to_integral_value() else MISSING if style == "decimal" and parsed == parsed.to_integral_value(): - return str(int(parsed)) - return format(parsed, "+.2f" if style == "signed" else ".2f") + return format(int(parsed), ",d" if compact else "d") + sign = "+" if style == "signed" else "" + result = format(parsed, sign + ("," if compact else "") + ".2f") + return result.rstrip("0").rstrip(".") if compact else result def _split_width(values) -> float | None: @@ -132,6 +141,8 @@ def _outcome(value) -> dict: class Renderer: """Render self-contained cards without network access or model imports.""" + WIDTHS = {"overview": 640, "recent": 800, "match": 900} + def __init__(self, theme: str = "light", timezone: str = "Asia/Shanghai"): if theme not in {"dark", "light"}: raise ValueError("theme must be dark or light") @@ -191,12 +202,12 @@ def _duration(value) -> str: return f"{hours}时{minutes:02d}分{seconds:02d}秒" if hours else f"{minutes}分{seconds:02d}秒" @staticmethod - def _metric(metric: Mapping) -> dict: + def _metric(metric: Mapping, *, compact=False) -> dict: value = metric.get("value") style = metric.get("format", "decimal") if style not in {"integer", "decimal", "percent", "signed"}: style = "decimal" - formatted = _plain(value) if isinstance(value, str) else _numeric(value, style) + formatted = _plain(value) if isinstance(value, str) else _numeric(value, style, compact=compact) unit = _plain(metric.get("unit"), "") if style == "percent" and not unit: unit = "%" @@ -215,7 +226,7 @@ def _exchange(self, item: Mapping, *, elo: bool = False) -> list[dict]: """Pair comparable values, preserving zero and unknown independently.""" def value(key, style="decimal"): raw = item.get(key) - return _plain(raw) if isinstance(raw, str) else _numeric(raw, style) + return _plain(raw) if isinstance(raw, str) else _numeric(raw, style, compact=not elo) def pair(first, second, style="decimal"): return f"{value(first, style)} / {value(second, style)}" @@ -230,6 +241,8 @@ def pair(first, second, style="decimal"): {"label": "摧毁 / 损失", "value": pair("destroyed_value", "lost_value")}, {"label": "击杀 / 阵亡", "value": pair("kills", "losses", "integer")}, ]) + if not elo: + metrics[-2], metrics[-1] = metrics[-1], metrics[-2] if elo: if any(item.get(key) is not None for key in ("damage_dealt", "damage_received")): metrics.append({"label": "伤害 / 承伤", "value": pair("damage_dealt", "damage_received")}) @@ -240,6 +253,48 @@ def pair(first, second, style="decimal"): metrics.append({"label": label, "value": value(key, style)}) return [self._metric(metric) for metric in metrics] + @staticmethod + def _profile(value) -> dict: + rating = _mapping(value) + score = _number(rating.get("score")) + if score is not None and not 1 <= score <= 10: + score = None + tone = _plain(rating.get("tone"), "") + supplied = {item.get("key"): item for item in _records(rating.get("dimensions")) + if isinstance(item.get("key"), str)} + + center = (180, 114) + radius = 66 + + def point(index, radius): + angle = -pi / 2 + index * 2 * pi / 5 + return (center[0] + radius * cos(angle), center[1] + radius * sin(angle)) + + def coordinates(points): + return " ".join(f"{x:.2f},{y:.2f}" for x, y in points) + + axes = [] + for index, (key, label) in enumerate(_PROFILE_AXES): + number = _number(supplied.get(key, {}).get("value")) + if number is not None and not 0 <= number <= 100: + number = None + x, y = point(index, 88) + xy = point(index, float(number) * radius / 100) if number is not None else None + axes.append({"key": key, "label": label, + "display": _numeric(number, compact=True) + ("%" if key == "win_rate" and number is not None else ""), + "x": f"{x:.2f}", "y": f"{y - 4:.2f}", + "anchor": "middle" if index == 0 else "start" if index in (1, 2) else "end", + "line": coordinates([center, point(index, radius)]), + "point": xy}) + complete = all(axis["point"] is not None for axis in axes) + return {"score": format(score, ".1f") if score is not None else MISSING, + "title": _plain(rating.get("title"), "") if score is not None else "", + "tone": tone if score is not None and tone in {"low", "medium", "high"} else "medium", + "axes": axes, + "rings": [coordinates([point(index, radius * step / 4) for index in range(5)]) for step in range(1, 5)], + "polygon": coordinates([axis["point"] for axis in axes]) if complete else "", + } + def _prepare(self, view: dict) -> dict: kind = view.get("kind", "overview") if kind not in _TITLES: @@ -248,6 +303,7 @@ def _prepare(self, view: dict) -> dict: match = _mapping(view.get("match")) prepared = { "kind": kind, + "width": self.WIDTHS[kind], "github_logo": self._github_logo, "title": _plain(view.get("title"), _TITLES[kind]), "theme": self.theme, @@ -256,7 +312,7 @@ def _prepare(self, view: dict) -> dict: "id": _plain(player.get("id")), "source_url": _safe_url(player.get("source_url")), }, - "metrics": [self._metric(item) for item in _records(view.get("metrics"))], + "metrics": [self._metric(item, compact=kind != "match") for item in _records(view.get("metrics"))], "scope": _plain(view.get("scope")), "fetched_at": self._time(view.get("fetched_at")), "source_updated_at": self._time(view.get("source_updated_at")), @@ -265,20 +321,23 @@ def _prepare(self, view: dict) -> dict: "synthetic": view.get("synthetic") is True, "notes": [_plain(note) for note in view.get("notes", [])] if isinstance(view.get("notes"), (list, tuple)) else [], "common_units": [ - {"name": _plain(item.get("name")), "count": _numeric(item.get("count"), "integer"), - "damage": _numeric(item.get("damage")), "roi": _numeric(item.get("roi"))} + {"name": _plain(item.get("name")), "count": _numeric(item.get("count"), "integer", compact=True), + "damage": _numeric(item.get("damage"), compact=True), "roi": _numeric(item.get("roi"), compact=True)} for item in _records(view.get("common_units")) ], - "analysis_scope": _plain(view.get("analysis_scope"), ""), - "categories": [{"name": _plain(item.get("name")), "percentage": _numeric(item.get("percentage"))} + "style_scope": _plain(view.get("style_scope"), ""), + "categories": [{"name": _plain(item.get("name")), "percentage": self._metric( + {"value": item.get("percentage"), "format": "percent"}, compact=True)["display"]} for item in _records(view.get("categories"))], - "map_stats": [{"name": _plain(item.get("name")), "count": _numeric(item.get("count"), "integer"), - "win_rate": _numeric(item.get("win_rate"))} + "map_stats": [{"name": _plain(item.get("name")), "count": _numeric(item.get("count"), "integer", compact=True), + "win_rate": _numeric(item.get("win_rate"), compact=True)} for item in _records(view.get("map_stats"))], "rows": [], "teams": [], "pagination": "", } + if kind == "overview": + prepared["profile_rating"] = self._profile(view.get("profile_rating")) for item in _records(view.get("rows")): score = _number(item.get("score")) prepared["rows"].append({ @@ -290,7 +349,7 @@ def _prepare(self, view: dict) -> dict: "mode": _MODES.get(_plain(item.get("mode")), _plain(item.get("mode"))), "outcome": _outcome(item.get("outcome")), "duration": self._duration(item.get("duration_seconds")), - "elo_delta": _numeric(item.get("elo_delta"), "signed"), + "elo_delta": _numeric(item.get("elo_delta"), "signed", compact=True), "exchange": self._exchange(item), "source_url": _safe_url(item.get("source_url")), }) @@ -403,14 +462,17 @@ def metrics(items): return " · ".join(f"{m['label']}:{m['display']}" + (f"({m['note']})" if m["note"] else "") for m in items) if data["kind"] == "overview": + profile = data["profile_rating"] + lines.append("综合评分 " + profile["score"] + (" · " + profile["title"] if profile["title"] else "")) for offset in range(0, len(data["metrics"]), 2): lines.append(metrics(data["metrics"][offset:offset + 2])) if not data["metrics"]: lines.append("统计指标:暂无") - if data["analysis_scope"]: - lines.append(data["analysis_scope"]) + lines.append("五维表现:" + " · ".join(f"{axis['label']} {axis['display']}" for axis in profile["axes"])) + if data["style_scope"]: + lines.append(data["style_scope"] + (":暂无" if not data["categories"] else "")) if data["categories"]: - lines.append("兵种:" + " · ".join(f"{c['name']} {c['percentage']}%" for c in data["categories"])) + lines.append("兵种:" + " · ".join(f"{c['name']} {c['percentage']}" for c in data["categories"])) if data["common_units"]: lines.append("常用单位") for unit in data["common_units"]: diff --git a/scoring.py b/scoring.py index 83c655b..6be20f3 100644 --- a/scoring.py +++ b/scoring.py @@ -1,11 +1,10 @@ -"""Per-match scoring adapted from ba-dragon, under the MIT license. +"""Match and player scoring adapted from ba-dragon, under the MIT license. Copyright (c) 2026 AlexanderHYu Copyright (c) 2025-2026 Zola (Zawinzala) Full original copyright, license and pinned source paths are bundled in -assets/scoring-model.json. Only computeDragonScore's individual career rows -are reproduced: no player aggregate, titles, or timeline. Missing career -composition uses the upstream avgRoles fallback; missing match inputs do not. +assets/scoring-model.json. Both reports use computeDragonScore's career +observations; only the player overview aggregates them into a score and tier. """ from __future__ import annotations @@ -25,6 +24,10 @@ MODEL = json.loads((Path(__file__).parent / "assets" / "scoring-model.json").read_text(encoding="utf-8")) ROLE_KEYS = ("armor", "inf", "recon", "arty", "aa", "heli", "jet") CAT_KEYS = ("recon", "infantry", "vehicles", "support", "logistic", "helicopters", "aircrafts") +_PROFILE_AXES = (("kd", "分值 K/D"), ("contrib", "摧毁贡献"), ("obj", "占点贡献"), + ("outcome", "胜负预期"), ("win_rate", "实际胜率")) +_PROFILE_TIERS = {"dragon": ("真龙", "high"), "solid": ("有龙样", "high"), + "average": ("泯然众人", "medium"), "weak": ("有点蛆", "low"), "qu": ("纯蛆", "low")} ROLE_NAMES = {"armor": "装甲", "inf": "步兵", "recon": "侦察", "arty": "炮兵", "aa": "防空", "heli": "直升机", "jet": "固定翼", "_": "后勤/运输"} # score.ts TRADE and TRADE_NORM, unchanged from the pinned source. @@ -177,17 +180,17 @@ def _match_features(match: Match, me: Participant, trade: tuple[float, float]) - dw, lw = me.destroyed_value * kill, me.lost_value * loss avg_dw = sum(p.destroyed_value * (kill if p.player_id == me.player_id else 1) for p in active_team) / len(active_team) - # The pinned model gives objectives zero weight; retain upstream zero - # handling without treating a missing displayed objective as an observation. - if MODEL["weights"]["obj"] and any(not _nonnegative(p.objectives) for p in players): + obj = None + if all(_nonnegative(p.objectives) for p in active_team): + avg_obj = sum(p.objectives for p in active_team) / len(active_team) + obj = math.log2((me.objectives + 1) / (avg_obj + 1)) + elif MODEL["weights"]["obj"]: return None - objectives = me.objectives or 0 - avg_objectives = sum(p.objectives or 0 for p in active_team) / len(active_team) return {"eloN": (old - 2100) / 400, "gapN": (old - average(players)) / 400, "S": 1 if me.elo > old else 0, "E": expected, "x": {"kd": math.log2((dw + 200) / (lw + 200)), "con": math.log2((dw + 200) / (avg_dw + 200)), - "obj": math.log2((objectives + 1) / (avg_objectives + 1))}} + "obj": obj}} def _percentile(value: float, quantiles: list[float]) -> float: @@ -213,42 +216,100 @@ def _to10(percentile: float) -> float: return math.floor((1 + 9 * percentile) * 10 + 0.5) / 10 -def recent_score(match: Match, participant: Participant, analysis: Mapping | None) -> float | None: - """Return the exact individual computeDragonScore career-row score, 1..10. +def _phi(z: float) -> float: + """score.ts uses this normal CDF approximation for the outcome percentile.""" + t = 1 / (1 + 0.2316419 * abs(z)) + d = 0.3989423 * math.exp(-z * z / 2) + p = d * t * (0.3193815 + t * (-0.3565638 + t * (1.781478 + t * (-1.821256 + t * 1.330274)))) + return 1 - p if z > 0 else p - Career categories with missing spend or highlight category/cost return None. - Empty career composition uses MODEL.avgRoles, exactly as upstream does. - UnitData affects the upstream AFK detector but never replaces career roles - or supplies per-unit trade multipliers here. Teammates use multiplier 1. - """ - me = next((p for p in match.players if p.player_id == participant.player_id), None) - if me is None or (analysis is not None and not isinstance(analysis, Mapping)): - return None - roles = _career_roles(analysis) - if roles is None: - return None - features = _match_features(match, me, _career_trade(roles)) - if features is None: - return None + +def _career_performance(features: dict, roles: Mapping) -> tuple[float, dict]: norms, weights = MODEL["norm"]["career"], MODEL["weights"] z = {} - for metric in ("kd", "con", "obj"): + for metric, observation in features["x"].items(): + if observation is None: + continue norm = norms[metric] mu = norm["elo"] * features["eloN"] + norm["gap"] * features["gapN"] variance = 0.0 for role in ROLE_KEYS: mu += roles[role] * norm["mu"][role] variance += roles[role] * norm["sigma"][role] ** 2 - z[metric] = (features["x"][metric] - mu) / math.sqrt(variance or 1) + z[metric] = (observation - mu) / math.sqrt(variance or 1) obj_factor = sum(roles[r] for r in ("armor", "inf", "recon")) obj_factor += 0.2 * sum(roles[r] for r in ("arty", "aa", "heli", "jet")) - stat = (weights["kd"] * z["kd"] + weights["con"] * z["con"] - + weights["obj"] * obj_factor * z["obj"]) + stat = weights["kd"] * z["kd"] + weights["con"] * z["con"] + if weights["obj"]: + stat += weights["obj"] * obj_factor * z["obj"] stat /= weights["kd"] + weights["con"] + weights["obj"] * obj_factor - combined = stat + weights["out"] * (features["S"] - features["E"]) / MODEL["outSd"] + out = (features["S"] - features["E"]) / MODEL["outSd"] + parts = {key: _percentile(z[k], norms[k]["q"]) for k, key in + (("kd", "kd"), ("con", "contrib"), ("obj", "obj")) if k in z} + if weights["out"]: + parts["outcome"] = _phi(out) + return stat + weights["out"] * out, parts + + +def recent_score(match: Match, participant: Participant, analysis: Mapping | None) -> float | None: + """Return the individual computeDragonScore career-row score, 1..10.""" + me = next((p for p in match.players if p.player_id == participant.player_id), None) + if me is None or (analysis is not None and not isinstance(analysis, Mapping)): + return None + roles = _career_roles(analysis) + if roles is None: + return None + features = _match_features(match, me, _career_trade(roles)) + if features is None: + return None + combined, _ = _career_performance(features, roles) return _to10(_percentile(combined, MODEL["matchPct"]["career"])) +def profile_rating(matches: list[Match], player_id: str, analysis: Mapping | None, + win_rate: float | None) -> dict: + """Aggregate up to 20 valid recent rows. Input matches are newest first. + + The caller supplies the independent observed win percentage from explicit + analysis won records. The model's Elo-derived S never supplies this axis. + """ + roles = _career_roles(analysis) if analysis is None or isinstance(analysis, Mapping) else None + observations = [] + if roles is not None: + trade = _career_trade(roles) + for match in matches: + me = next((p for p in match.players if p.player_id == player_id), None) + features = _match_features(match, me, trade) if me is not None else None + if features is None: + continue + combined, parts = _career_performance(features, roles) + observations.append((combined, (match.duration_seconds or 0) / 60, parts)) + if len(observations) == 20: + break + + score = title = tone = None + axes = {"win_rate": win_rate if _finite(win_rate) and 0 <= win_rate <= 100 else None} + if observations: + k = MODEL["kalman"] + mean, variance = 0.0, k["P0"] + for combined, minutes, _ in reversed(observations): + variance += k["q"] + noise = k["r"] / min(1, max(0.3, minutes / k["shortMin"])) + gain = variance / (variance + noise) + mean += gain * (combined - mean) + variance *= 1 - gain + score = _to10(_percentile(mean, MODEL["playerPct"])) + tier = next(t for threshold, t in MODEL["tiers"] if score >= _to10(threshold)) + title, tone = _PROFILE_TIERS[tier] + for key, _ in _PROFILE_AXES[:-1]: + values = [parts[key] for _, _, parts in observations if key in parts] + if values: + axes[key] = math.floor(sum(values) / len(values) * 100 + 0.5) + return {"score": score, "title": title, "tone": tone, "sample_size": len(observations), + "dimensions": [{"key": key, "label": label, "value": axes.get(key)} + for key, label in _PROFILE_AXES]} + + def score_band(score: float | None) -> Literal["low", "medium", "high"] | None: """Color bands only, using the displayed-score thresholds in markOf.""" if not _finite(score) or not 1 <= score <= 10: diff --git a/service.py b/service.py index 4a0e59b..c8da816 100644 --- a/service.py +++ b/service.py @@ -12,10 +12,14 @@ from .commands import Request, Target from .models import FetchResult, Match, Participant, Player from .pending import PendingManager -from .scoring import match_prediction, recent_score, score_band, team_composition +from .scoring import match_prediction, profile_rating, recent_score, score_band, team_composition from .storage import Binding +CATEGORY_NAMES = {"recon": "侦察", "infantry": "步兵", "vehicles": "载具", "support": "支援", + "logistic": "后勤", "helicopters": "直升机", "aircrafts": "固定翼"} + + @dataclass(frozen=True) class Caller: platform: str @@ -82,7 +86,7 @@ def map_name(match, player=None): return match.map_name -def recent_rows(matches, player_id, player=None): +def recent_rows(matches, player_id, player=None, *, with_scores=True): rows = [] outcomes = analysis_outcomes(player) if player is not None and player.id == player_id else {} for match in matches: @@ -90,13 +94,14 @@ def recent_rows(matches, player_id, player=None): if person is None: continue row = participant_view(person) - score = recent_score(match, person, player.analysis if player is not None and player.id == player_id else None) + if with_scores: + score = recent_score(match, person, player.analysis if player is not None and player.id == player_id else None) + row.update(score=score, score_band=score_band(score)) outcome = outcomes.get(match.id, person.outcome) row.update(id=match.id, started_at=match.started_at, ended_at=match.ended_at, map_name=map_name(match, player), mode=match.mode, outcome=outcome, outcome_source="analysis" if outcomes.get(match.id) in {"win", "loss"} else None, - score=score, score_band=score_band(score), duration_seconds=match.duration_seconds, source_url=match.source_url) rows.append(row) return rows @@ -200,17 +205,13 @@ def overview_metrics(player, rows): known = [point["won"] for point in points if isinstance(point.get("won"), bool)] dated = [point for point in points if point.get("endTime") is not None and point.get("dmr") is not None] latest = max(dated, key=lambda point: point["endTime"]) if dated else None - dmr_note = "分析单局" - if latest is not None: - dmr_note += f" · #{latest['matchId']}" if latest.get("matchId") is not None else "" return [ {"label": "ELO", "value": player.elo}, {"label": "近期分值 K/D", "value": ratio(sum(row["destroyed_value"] for row in pairs), - sum(row["lost_value"] for row in pairs)) if pairs else None, - "note": f"近期 {len(pairs)} 场摧毁分 ÷ 损失分"}, + sum(row["lost_value"] for row in pairs)) if pairs else None}, {"label": "分析样本胜率", "value": 100 * sum(known) / len(known) if known else None, - "format": "percent", "note": f"{sum(known)} 胜 / {len(known)} 场已知结果"}, - {"label": "伤害交换比", "value": latest["dmr"] if latest else None, "note": dmr_note}, + "format": "percent"}, + {"label": "单局伤害交换比", "value": latest["dmr"] if latest else None}, ] @@ -390,15 +391,11 @@ async def _report(self, request, player_id): view.update(freshness(player_result, result, detail)) return Response(view=view) return Response(f"{player.name} · STB ID:{player.id}\n当前返回样本中暂无可用单局战报。\n{player.source_url or ''}") - rows = recent_rows(matches, player.id, player) + rows = recent_rows(matches, player.id, player, with_scores=request.action == "recent") times = [m.started_at for m in matches if m.started_at and any(p.player_id == player.id for p in m.players)] scope = f"近期{len(rows)}场" - analysis_count = player.analysis.get("matchCount") - if analysis_count is None: - analysis_count = len(player.analysis.get("trend", {}).get("points", [])) view = {"kind": "recent" if request.action == "recent" else "overview", "player": asdict(player), "rows": rows, "scope": scope, - "analysis_scope": f"分析样本{analysis_count}场 · 与近期样本独立" if player.analysis else "", "source_url": player.source_url, **freshness(player_result, result)} if times: from zoneinfo import ZoneInfo @@ -407,12 +404,21 @@ async def _report(self, request, player_id): if len(times) != len(rows): view["scope"] += f"({len(times)}/{len(rows)} 场有开始时间)" if view["kind"] == "overview": + # The profile uses recent matches; the metric grid retains the full analysis sample. + results = [r["outcome"] for r in rows[:20] if r["outcome_source"] == "analysis"] + win_rate = 100 * results.count("win") / len(results) if results else None + view["profile_rating"] = profile_rating(matches, player.id, player.analysis, win_rate) view["metrics"] = overview_metrics(player, rows) view["common_units"] = common_units(player, matches) view["map_stats"] = [{"name": m["mapName"] or f"地图#{m['mapId']}", "count": m["matchCount"], "win_rate": m["winRate"]} for m in player.analysis.get("mapPerformance", [])[:5]] - view["categories"] = [{"name": c["categoryKey"], "percentage": c["percentage"]} + analysis_count = player.analysis.get("matchCount") + if analysis_count is None: + analysis_count = len(player.analysis.get("trend", {}).get("points", [])) + view["style_scope"] = f"近{analysis_count}场风格" if player.analysis else "" + view["categories"] = [{"name": CATEGORY_NAMES.get(c["categoryKey"], c["categoryKey"]), + "percentage": c["percentage"]} for c in player.analysis.get("categoryPreferences", [])] return Response(view=view) diff --git a/templates/base.html b/templates/base.html index f9e64aa..8f57717 100644 --- a/templates/base.html +++ b/templates/base.html @@ -32,7 +32,7 @@ } a { color: var(--accent); text-decoration: none; overflow-wrap: anywhere; } a:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } - .report { width: 100%; max-width: 980px; margin: 0 auto; padding: 24px; } + .report { width: 100%; max-width: {{ view.width }}px; margin: 0 auto; padding: 24px; } .brandline { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: baseline; gap: 8px 20px; margin-bottom: 24px; color: var(--muted); font-size: 14px; } .brand { color: var(--accent); font-size: 17px; font-weight: 700; letter-spacing: 2px; } .identity { border-left: 4px solid var(--accent); padding-left: 18px; margin-bottom: 22px; } @@ -47,7 +47,7 @@ .metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 1px; background: var(--line); border: 1px solid var(--line); margin-bottom: 26px; } .metric { min-width: 0; padding: 18px 18px 16px; background: var(--panel); } .metric-label { color: var(--muted); font-size: 14px; overflow-wrap: anywhere; } - .metric-number { font-size: 36px; line-height: 1.25; margin-top: 5px; font-weight: 700; overflow-wrap: anywhere; } + .metric-number { font-size: 36px; line-height: 1.25; margin-top: 5px; font-weight: 700; white-space: nowrap; } .metric-unit { font-size: 16px; font-weight: 400; margin-left: 3px; } .metric-note { font-size: 13px; color: var(--muted); margin-top: 7px; overflow-wrap: anywhere; } .section-heading { margin: 24px 0 12px; } @@ -84,10 +84,55 @@ .compact-line { display: flex; flex-wrap: wrap; gap: 4px 14px; margin-top: 7px; overflow-wrap: anywhere; } .compact-line span { min-width: 0; } .compact-line b { font-weight: 600; } - .report-table { width: 100%; border-collapse: collapse; table-layout: fixed; } + .report-table { width: 100%; border-collapse: collapse; table-layout: auto; } .report-table th, .report-table td { padding: 9px 5px; text-align: right; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; } .report-table th { color: var(--muted); font-size: 13px; font-weight: 400; } .report-table th:first-child, .report-table td:first-child { text-align: left; width: 38%; } + .report-table th:not(:first-child), .report-table td:not(:first-child) { white-space: nowrap; overflow-wrap: normal; } + .report-overview, .report-recent { padding: 16px 20px; } + :is(.report-overview, .report-recent) .brand { letter-spacing: 0; } + .report-overview .brandline, .report-recent .brandline { margin-bottom: 14px; } + .report-overview .identity, .report-recent .identity { margin-bottom: 14px; padding-left: 12px; } + .report-overview h1, .report-recent h1 { font-size: 28px; } + .report-overview .identity-meta, .report-recent .identity-meta, + .report-overview .scope, .report-recent .scope { margin-top: 4px; } + .report-overview .synthetic, .report-recent .synthetic { padding: 5px 10px; margin-bottom: 12px; } + .report-overview .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); margin-bottom: 15px; } + .report-overview .metric { padding: 8px 10px; } + .report-overview .metric-number { font-size: 24px; margin-top: 2px; } + .report-overview .metric-unit { margin-left: 0; } + .report-overview .scope { font-size: 14px; } + .report-overview .identity { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 25%); column-gap: 10px; } + .report-overview .identity .scope { grid-column: 1; } + .profile-grade { grid-column: 2; grid-row: 1 / span 2; align-self: start; text-align: right; } + .profile-grade .score { display: block; margin: 2px 0; font-size: 30px; } + .profile-grade .score.is-missing { font-size: 22px; color: var(--muted); } + .grade-title { font-size: 14px; font-weight: 600; overflow-wrap: anywhere; } + .radar-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 6px; } + .radar { display: block; width: 100%; max-width: 452px; margin: 5px auto 0; } + .radar-grid { fill: none; stroke: var(--muted); stroke-opacity: .45; } + .radar-area { fill: var(--accent); fill-opacity: .17; stroke: var(--accent); stroke-width: 2; } + .radar-dot { fill: var(--accent); stroke: var(--canvas); stroke-width: 1.5; } + .radar-label { fill: var(--muted); font-size: 17px; } + .radar-value { fill: var(--ink); font-size: 20px; font-weight: 700; } + .report-overview .section-heading { margin: 13px 0 5px; } + .report-overview .report-table :is(th, td) { padding-block: 5px; } + .style-list { display: flex; flex-wrap: wrap; gap: 3px 14px; list-style: none; padding: 0; margin: 0; overflow-wrap: anywhere; } + .style-list b { white-space: nowrap; } + .report-recent .pagination { margin-bottom: 8px; } + .report-recent .recent-card { padding: 9px 12px; margin-bottom: 7px; } + .report-recent .row-heading h3 { flex: 1; min-width: 0; } + .report-recent .row-heading .score { display: inline-flex; flex-direction: row; align-items: baseline; gap: 4px; min-width: 78px; white-space: nowrap; } + .report-recent .row-heading .score small { margin: 0; font-size: 13px; } + .report-recent .row-heading .score.is-missing { font-size: 18px; color: var(--muted); } + .report-recent .row-meta { margin-top: 4px; gap: 2px 12px; } + .report-recent .row-meta .numeric { white-space: nowrap; } + .recent-metrics { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 4px 10px; margin: 6px 0 0; } + .recent-metrics > :last-child { grid-column: 1 / -1; } + .recent-metrics dt { color: var(--muted); font-size: 14px; } + .recent-metrics dd { margin: 0; font-weight: 650; } + .recent-metrics .number { display: inline-block; white-space: nowrap; } + .report-overview footer, .report-recent footer { margin-top: 14px; padding-top: 8px; } .compact-team { font-size: 14px; color: var(--muted); } .score { display: inline-flex; flex-direction: column; font-size: 25px; font-weight: 700; line-height: 1.1; flex-shrink: 0; } .score small { font-size: 11px; color: var(--muted); font-weight: 400; margin-bottom: 4px; } @@ -171,10 +216,41 @@ .summary-metrics dd { font-size: 20px; } .prediction-values { font-size: 20px; } } + @media (max-width: 520px) { + .report-overview, .report-recent { padding-inline: 14px; } + .report-overview h1, .report-recent h1 { font-size: 24px; } + .report-recent .row-heading { gap: 8px; } + .report-recent .row-heading h3 { font-size: 18px; } + } + @media (min-width: 600px) { + .report-overview { font-size: 21px; line-height: 1.4; } + .report-overview h1 { font-size: 32px; } + .report-overview h2 { font-size: 23px; } + .report-overview :is(.brandline, .identity-meta, .scope, .metric-label, .grade-title, + .report-table th, .synthetic, footer, .attribution a) { font-size: 19px; } + .report-overview .brand { font-size: 22px; } + .report-overview .metric { padding: 6px 12px; } + .report-overview .metric-number, .profile-grade .score { font-size: 32px; } + .report-overview .metric-unit { font-size: 21px; } + } + @media (min-width: 760px) { + .report-recent { font-size: 24px; line-height: 1.3; } + .report-recent h1 { font-size: 36px; } + .report-recent :is(.brandline, .identity-meta, .scope, .pagination, .row-meta, + .row-heading .score small, .recent-metrics dt, .synthetic, + footer, .attribution a) { font-size: 23px; } + .report-recent .brand { font-size: 26px; } + .report-recent .row-heading h3, .report-recent .row-heading .score { font-size: 32px; } + .report-recent .row-heading .score { min-width: 116px; gap: 6px; } + .report-recent .row-heading .score.is-missing, .report-recent .outcome { font-size: 25px; } + .recent-metrics { grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr) minmax(0, 1.95fr); } + .recent-metrics > :last-child { grid-column: auto; } + .recent-metrics dd { font-size: 27px; } + } -
+
断箭战报{{ view.title }}
{% if view.synthetic %}

合成样本 · 非真实玩家战绩

{% endif %}
diff --git a/templates/overview.html b/templates/overview.html index d6ce5d2..c80c6d2 100644 --- a/templates/overview.html +++ b/templates/overview.html @@ -1,7 +1,34 @@ {% extends "base.html" %} +{% block identity %} +

{{ view.player.name }}

+

玩家 ID:{{ view.player.id }}

+
+ 综合评分 + {{ view.profile_rating.score }} + {% if view.profile_rating.title %}{{ view.profile_rating.title }}{% endif %} +
+{% endblock %} {% block content %} -{% if view.analysis_scope %}

{{ view.analysis_scope }}

{% endif %} -{% if view.categories %}

{% for c in view.categories %}{{ c.name }} {{ c.percentage }}%{% endfor %}

{% endif %} +{% set rating = view.profile_rating %} +
+

五维表现

刻度 0–100
+ + 玩家五维表现 + {% for axis in rating.axes %}{{ axis.label }} {{ axis.display }}{% if not loop.last %},{% endif %}{% endfor %} + {% for ring in rating.rings %}{% endfor %} + {% for axis in rating.axes %}{% endfor %} + {% if rating.polygon %}{% endif %} + {% for axis in rating.axes %} + {% if axis.point is not none %}{% endif %} + {{ axis.label }}{{ axis.display }} + {% endfor %} + +
+{% if view.categories or view.style_scope %} +

{{ view.style_scope or '兵种风格' }}

+ {% if view.categories %}
    {% for c in view.categories %}
  • {{ c.name }} {{ c.percentage }}
  • {% endfor %}
+ {% else %}

暂无

{% endif %} +
{% endif %} {% if view.common_units %}

常用单位

diff --git a/templates/recent.html b/templates/recent.html index beb0e52..5d19af7 100644 --- a/templates/recent.html +++ b/templates/recent.html @@ -1,13 +1,17 @@ {% extends "base.html" %} -{% from "_macros.html" import exchange, outcome %} +{% from "_macros.html" import outcome %} {% block content %} {% if view.rows %}
    {% for row in view.rows %}
  1. -
    评分{{ row.score }}

    {{ row.map_name }}

    {{ outcome(row.outcome) }}
    -
    #{{ row.id }}{% if row.duration != '暂无' %}{{ row.duration }}{% endif %}{% if row.elo_delta != '暂无' %}ELO {{ row.elo_delta }}{% endif %}
    -
    {% for metric in row.exchange %}{{ metric.label }} {{ metric.display }}{% endfor %}
    +
    评分{{ row.score }}

    {{ row.map_name }}

    {{ outcome(row.outcome) }}
    +
    #{{ row.id }}{% if row.duration != '暂无' %}{{ row.duration }}{% endif %}{% if row.elo_delta != '暂无' %}ELO {{ row.elo_delta }}{% endif %}
    +
    + {% for metric in row.exchange %} +
    {{ metric.label }}
    {% for part in metric.display.split(' / ') %}{% if not loop.first %} {% endif %}{% if not loop.first %}/ {% endif %}{{ part }}{% endfor %}
    + {% endfor %} +
  2. {% endfor %}
diff --git a/tests/test_main.py b/tests/test_main.py index b43aa5d..0feb7df 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -727,16 +727,19 @@ async def test_cancelled_image_send_is_not_converted_to_fallback(app, monkeypatc event.send.assert_awaited_once() -async def test_image_render_uses_mobile_jpeg_contract_and_fixed_outer_template(app, monkeypatch, tmp_path): +@pytest.mark.parametrize(("kind", "width"), [("overview", 640), ("recent", 800), ("match", 900), (None, 640)]) +async def test_image_render_uses_card_width_and_fixed_outer_template(app, monkeypatch, tmp_path, kind, width): plugin = await app.make(images=True) source = tmp_path / "synthetic-render.jpg" source.write_bytes(image_bytes()) render = AsyncMock(return_value=str(source)) monkeypatch.setattr(plugin, "html_render", render) view = { - "kind": "overview", "player": {"id": "001", "name": "Synthetic {{ 7 * 7 }} a b"}, + "player": {"id": "001", "name": "Synthetic {{ 7 * 7 }} a b"}, "scope": "合成测试样本", "fetched_at": datetime(2026, 11, 17, tzinfo=timezone.utc), } + if kind is not None: + view["kind"] = kind first = await plugin._image(view, "onebot:test:group:one") assert first.path.suffix == ".jpg" assert first.path.read_bytes() == source.read_bytes() @@ -749,7 +752,7 @@ async def test_image_render_uses_mobile_jpeg_contract_and_fixed_outer_template(a assert options["umo"] == "onebot:test:group:one" assert options["options"] == { "type": "jpeg", "quality": 85, "full_page": True, - "viewport_width": 390, "device_scale_factor_level": "ultra", + "viewport_width": width, "device_scale_factor_level": "ultra", } second = await plugin._image(view, "onebot:test:group:two") assert second != first diff --git a/tests/test_render.py b/tests/test_render.py index 9f4431a..4ed0910 100644 --- a/tests/test_render.py +++ b/tests/test_render.py @@ -71,7 +71,7 @@ def test_identity_scope_precision_and_same_text_values(view, theme): text = renderer.text(view) for value in [ "00076561198012345678", "合成样本玩家", view["scope"], - "62.50%", "8场", "1.23", "2.79", "合成样本", + "62.5%", "8场", "1.23", "2.79", "合成样本", ]: assert compact(value) in compact(visible) assert compact(value) in compact(text) @@ -142,9 +142,8 @@ def test_safe_http_links_are_escaped_not_loaded(view): def test_missing_metric_is_unknown_without_fake_zero_or_unit(view, value): view["metrics"] = [{"label": "ELO", "value": value, "unit": "分"}] renderer = Renderer() - assert "ELO:暂无" in renderer.text(view) - assert "暂无分" not in compact(VisibleHTML(renderer.template(view)).text) - assert "0.00" not in renderer.text(view) + assert "ELO:暂无" in renderer.text(view).splitlines() + assert re.findall(r'

(.*?)

', renderer.template(view), re.S) == ["暂无"] def test_real_zero_and_unknown_stay_distinct(view): @@ -159,7 +158,7 @@ def test_real_zero_and_unknown_stay_distinct(view): assert "分值 K/D 暂无" in text assert "胜负暂无" in text assert "0分00秒" in text - assert "ELO +0.00" in text + assert "ELO +0" in text def test_exchange_values_are_separate_and_not_recalculated(view): @@ -170,7 +169,7 @@ def test_exchange_values_are_separate_and_not_recalculated(view): renderer = Renderer() html_text = compact(VisibleHTML(renderer.template(view)).text) text = renderer.text(view) - for expected in ["击杀 / 阵亡 8 / 2", "摧毁 / 损失 2500.50 / 2000.75", "分值 K/D 1.25"]: + for expected in ["击杀 / 阵亡 8 / 2", "摧毁 / 损失 2,500.5 / 2,000.75", "分值 K/D 1.25"]: assert expected in text assert compact(expected.replace(":", "")) in html_text @@ -265,13 +264,53 @@ def test_fresh_report_omits_empty_sections_and_repeated_provenance(view): def test_analysis_units_maps_and_categories_share_values(view): - view.update(analysis_scope="分析样本 100 场", categories=[{"name": "固定翼", "percentage": 31}], + view.update(style_scope="近83场风格", categories=[{"name": "固定翼", "percentage": 31}, + {"name": "防空", "percentage": None}], common_units=[{"name": "Tu-95", "count": 72, "damage": 11683, "roi": 1.62}], - map_stats=[{"name": "Coast", "count": 8, "win_rate": 50}]) + map_stats=[{"name": "Coast", "count": 8, "win_rate": 50}, + {"name": "Other", "count": 0, "win_rate": None}]) + view["metrics"].append({"label": "单局伤害交换比", "value": 1.3}) renderer = Renderer() for output in (renderer.text(view), VisibleHTML(renderer.template(view)).text): - for value in ("分析样本 100 场", "固定翼", "31%", "Tu-95", "72", "11683", "1.62", "Coast", "50%"): + for value in ("近83场风格", "固定翼 31%", "防空 暂无", "Tu-95", "72", "11,683", "1.62", "Coast", "50%", + "Other", "单局伤害交换比"): assert compact(value) in compact(output) + assert "暂无%" not in compact(output) + + +@pytest.fixture +def profile(): + return {"score": 5.8, "title": "泯然众人", "tone": "medium", "sample_size": 4, + "dimensions": [{"key": key, "value": value} + for key, value in (("win_rate", 0), ("outcome", 71), ("obj", 16), + ("contrib", 59), ("kd", 37))]} + + +@pytest.mark.parametrize("kind", ["overview", "recent", "match"]) +def test_title_and_five_distinct_axes_belong_only_to_overview(view, profile, kind): + view.update(kind=kind, profile_rating=profile, rows=[{"id": "42", "title": profile["title"], "score": 5.8}]) + renderer = Renderer() + parsed = VisibleHTML(renderer.template(view)) + for output in (parsed.text, renderer.text(view)): + for value in ("泯然众人", "五维表现", "分值 K/D 37", "摧毁贡献 59", "占点贡献 16", "胜负预期 71", "实际胜率 0%"): + assert (compact(value) in compact(output)) == (kind == "overview") + assert sum(attrs.get("class") == "radar-area" for _, attrs in parsed.tags) == (kind == "overview") + assert sum(attrs.get("class") == "radar-dot" for _, attrs in parsed.tags) == (5 if kind == "overview" else 0) + + +@pytest.mark.parametrize("value", [None, float("nan"), -1, 101]) +def test_missing_radar_axis_keeps_real_zero_without_filling_polygon(view, profile, value): + profile["dimensions"][1]["value"] = value + profile["score"] = None + view["profile_rating"] = profile + renderer = Renderer() + parsed = VisibleHTML(renderer.template(view)) + for output in (parsed.text, renderer.text(view)): + assert "综合评分暂无" in compact(output) + assert "胜负预期暂无" in compact(output) and "实际胜率0%" in compact(output) + assert profile["title"] not in output + assert not any(attrs.get("class") == "radar-area" for _, attrs in parsed.tags) + assert sum(attrs.get("class") == "radar-dot" for _, attrs in parsed.tags) == 4 def test_recent_score_precedes_match_and_has_color_without_title(view): diff --git a/tests/test_report_data.py b/tests/test_report_data.py index 8f6eb27..6695148 100644 --- a/tests/test_report_data.py +++ b/tests/test_report_data.py @@ -77,12 +77,12 @@ async def test_overview_separates_analysis_denominator_recent_values_and_single_ data = metrics(view) assert data["ELO"]["value"] == 1000 assert data["近期分值 K/D"]["value"] == 3 # (100 + 200) / (25 + 75) - assert "2 场" in data["近期分值 K/D"]["note"] assert data["分析样本胜率"]["value"] == pytest.approx(200 / 3) - assert data["分析样本胜率"]["note"] == "2 胜 / 3 场已知结果" - assert data["伤害交换比"]["value"] == 2.5 - assert data["伤害交换比"]["note"] == "分析单局 · #win" - assert view["analysis_scope"] == "分析样本80场 · 与近期样本独立" + dims = {axis["key"]: axis["value"] for axis in view["profile_rating"]["dimensions"]} + assert dims["win_rate"] == 50 # Only the win and loss are in the recent sample. + assert dims["outcome"] is None # Team ELO is missing, but the actual outcomes are known. + assert data["单局伤害交换比"]["value"] == 2.5 + assert view["style_scope"] == "近80场风格" assert view["scope"] == "近期3场 · 11-17—11-17" assert [row["outcome"] for row in view["rows"]] == ["win", "loss", "unknown"] assert player == original_player and matches == original_matches @@ -100,8 +100,7 @@ async def test_won_requires_boolean_and_an_exact_target_match_id(report, won, ex assert [row["outcome"] for row in view["rows"]] == [expected, "unknown", "unknown"] assert view["rows"][0]["outcome_source"] == ("analysis" if won is not None else None) assert metrics(view)["分析样本胜率"]["value"] == percentage - if won is None: - assert "0 场已知结果" in metrics(view)["分析样本胜率"]["note"] + assert view["profile_rating"]["dimensions"][-1]["value"] == percentage async def test_duplicate_results_conflict_stays_unknown_and_does_not_inflate_win_rate(report): @@ -113,7 +112,7 @@ async def test_duplicate_results_conflict_stays_unknown_and_does_not_inflate_win view = await report.run(player, [recent(report, "42"), recent(report, "ok")]) assert [row["outcome"] for row in view["rows"]] == ["unknown", "loss"] assert metrics(view)["分析样本胜率"]["value"] == 0 - assert metrics(view)["分析样本胜率"]["note"] == "0 胜 / 1 场已知结果" + assert view["profile_rating"]["dimensions"][-1]["value"] == 0 async def test_overview_units_maps_and_categories_use_analysis_and_preserve_same_name_ids(report): @@ -123,7 +122,7 @@ async def test_overview_units_maps_and_categories_use_analysis_and_preserve_same {"unitId": "b", "unitName": "Same", "spawnCount": 3}, {"unitId": "c"}, {"unitId": "d", "unitName": "Fourth"}, ], - "categoryPreferences": [{"categoryKey": "tank", "percentage": 0}, + "categoryPreferences": [{"categoryKey": "support", "percentage": 0}, {"categoryKey": "infantry", "percentage": 75}], "mapPerformance": [{"mapId": 20 + i, "mapName": f"Map {i}", "matchCount": i, "winRate": 0 if i == 0 else 50} for i in range(6)], @@ -136,7 +135,7 @@ async def test_overview_units_maps_and_categories_use_analysis_and_preserve_same {"id": "b", "name": "Same(ID:b)", "count": 3, "damage": None, "roi": None}, {"id": "c", "name": "单位#c", "count": None, "damage": None, "roi": None}, ] - assert view["categories"] == [{"name": "tank", "percentage": 0}, {"name": "infantry", "percentage": 75}] + assert view["categories"] == [{"name": "支援", "percentage": 0}, {"name": "步兵", "percentage": 75}] assert len(view["map_stats"]) == 5 assert view["map_stats"][0] == {"name": "Map 0", "count": 0, "win_rate": 0} assert view["rows"][0]["map_name"] == "Map 0" @@ -150,8 +149,8 @@ async def test_analysis_empty_lists_remain_empty_without_inventing_statistics(re assert view["common_units"] == view["map_stats"] == view["categories"] == [] assert metrics(view)["近期分值 K/D"]["value"] is None assert metrics(view)["分析样本胜率"]["value"] is None - assert metrics(view)["伤害交换比"]["value"] is None - assert view["analysis_scope"] == "分析样本0场 · 与近期样本独立" + assert metrics(view)["单局伤害交换比"]["value"] is None + assert view["style_scope"] == "近0场风格" assert view["rows"][0]["map_name"] == "地图#20" @@ -256,6 +255,23 @@ async def test_recent_scores_flow_to_html_and_text_without_changing_result_autho assert "评分 暂无" in renderer.text(view) +async def test_overview_renders_aggregate_and_separate_observed_win_rate(report): + from render import Renderer + + player = report.player({"trend": {"points": [{"matchId": "score-fixture", "won": True}]}}) + match = scoring_report_match(report) + for participant in match.players: + participant.objectives = 0 + view = await report.run(player, [match]) + rating = view["profile_rating"] + # Pinned computeDragonScore gives 7.9 for the profile and 9.3 for the single match. + assert (rating["score"], rating["title"]) == (7.9, "有龙样") + assert [axis["value"] for axis in rating["dimensions"]] == [91, 53, 53, 92, 100] + for output in (Renderer().template(view), Renderer().text(view)): + assert all(term in output for term in ("7.9", "有龙样", "胜负预期", "胜率", "100%")) + report.client.match.assert_not_awaited() + + def test_match_prediction_composition_and_a_b_order_reach_both_renderers(report): from render import Renderer diff --git a/tests/test_scoring.py b/tests/test_scoring.py index 48c3824..ecb6cd6 100644 --- a/tests/test_scoring.py +++ b/tests/test_scoring.py @@ -7,11 +7,12 @@ """ from copy import deepcopy +from pathlib import Path import pytest -from models import Match, Participant, parse_match -from scoring import MODEL, match_prediction, recent_score, score_band, team_composition +from models import Match, Participant, parse_match, parse_recent +from scoring import MODEL, match_prediction, profile_rating, recent_score, score_band, team_composition def raw_match(): @@ -265,11 +266,103 @@ def test_color_bands_use_upstream_displayed_score_marks(score, band): assert score_band(score) == band -def test_bundled_model_has_pinned_source_and_complete_mit_notice_without_titles(): +def profile_sample(): + # Newest first: short strong win, full-length loss, and a win with an AFK ally. + short, loss, afk = (raw_match() for _ in range(3)) + short["TotalPlayTimeInSec"] = 210 + short["Data"]["a"].update(DestructionScore=6100, LossesScore=800) + short["Data"]["c"]["ObjectivesCaptured"] = 1 + loss["Data"]["a"].update(NewRating=1880, DestructionScore=350, LossesScore=6500, ObjectivesCaptured=0) + loss["Data"]["c"]["ObjectivesCaptured"] = 5 + afk["Data"]["a"].update(DestructionScore=2300, LossesScore=2000, ObjectivesCaptured=1) + afk["Data"]["c"].update(DestructionScore=0, LossesScore=0) + return [short, loss, afk] + + +@pytest.mark.parametrize("indices,analysis,expected", [ + ([0, 1, 2], SUPPORT_ANALYSIS, (1.8, "纯蛆", "low", [30, 49, 56, 75])), + ([0], FRONT_ANALYSIS, (7.8, "有龙样", "high", [100, 98, 72, 95])), + ([1], {}, (2.0, "有点蛆", "low", [0, 10, 1, 30])), +]) +def test_profile_matches_pinned_compute_dragon_score(indices, analysis, expected): + # In the mixed TS fixture the individual scores are 9.9, 1.1, 5.1, but + # the player score is 1.8. Averaging their displayed scores would give 5.4. + raws = profile_sample() + matches = [parse_match({"matchInfo": raws[i]}, str(i)) for i in indices] + before = deepcopy(matches) + profile = profile_rating(matches, "a", analysis, 0) + score, title, tone, parts = expected + assert profile == { + "score": score, "title": title, "tone": tone, "sample_size": len(matches), + "dimensions": [dict(key=key, label=label, value=value) for key, label, value in zip( + ("kd", "contrib", "obj", "outcome", "win_rate"), + ("分值 K/D", "摧毁贡献", "占点贡献", "胜负预期", "实际胜率"), [*parts, 0])], + } + assert matches == before + + +def test_profile_caps_newest_valid_rows_after_normalizing_match_order(): + short, loss, _ = profile_sample() + unrated = deepcopy(short) + unrated["Data"]["a"]["NewRating"] = unrated["Data"]["a"]["OldRating"] + raws = [] + for i, raw in enumerate([loss, *([short] * 20), unrated]): + start = 1700000000 + i * 3600 + raws.append({"matchId": str(i), "data": { + **raw, "StartTime": start, "EndTime": start + raw["TotalPlayTimeInSec"], + }}) + matches = parse_recent({"matches": raws[::2] + raws[1::2]}) + assert [m.id for m in matches] == [str(i) for i in range(21, -1, -1)] + profile = profile_rating(matches, "a", {}, None) + assert (profile["score"], profile["title"], profile["sample_size"]) == (10, "真龙", 20) + assert [d["value"] for d in profile["dimensions"]] == [99, 99, 83, 95, None] + + +def test_missing_objectives_omit_only_unobserved_parts_and_never_supply_a_win(): + short, _, afk = profile_sample() + short["Data"]["c"].pop("ObjectivesCaptured") + latest = parse_match({"matchInfo": short}, "latest") + earlier = parse_match({"matchInfo": afk}, "earlier") + single = profile_rating([latest], "a", FRONT_ANALYSIS, None) + assert single["score"] == 7.8 + assert [d["value"] for d in single["dimensions"]] == [100, 98, None, 95, None] + # Missing objectives for an inactive ally do not affect the active-team comparison. + earlier_obj = profile_rating([earlier], "a", FRONT_ANALYSIS, None)["dimensions"][2]["value"] + assert earlier_obj is not None + both = profile_rating([latest, earlier], "a", FRONT_ANALYSIS, None) + assert both["sample_size"] == 2 and both["dimensions"][2]["value"] == earlier_obj + empty = profile_rating([latest], "absent", {}, 100) + assert (empty["sample_size"], empty["score"], empty["title"], empty["tone"]) == (0, None, None, None) + assert [d["value"] for d in empty["dimensions"]] == [None, None, None, None, 100] + + +def test_profile_distinguishes_explicit_zero_from_unknown_values(): + raw = raw_match() + for player in raw["Data"].values(): + player.update(DestructionScore=0, LossesScore=0, ObjectivesCaptured=0) + zero = profile_rating([normalized(raw)], "a", {}, 0) + # The TS oracle still scores the explicit zeros and returns an objective percentile. + assert (zero["score"], zero["title"], zero["sample_size"]) == (7.2, "泯然众人", 1) + assert [d["value"] for d in zero["dimensions"]] == [61, 58, 54, 86, 0] + raw["Data"]["a"].pop("DestructionScore") # Protobuf omits zero counters. + assert profile_rating([normalized(raw)], "a", {}, 0) == zero + raw["Data"]["a"].pop("ObjectivesCaptured") + missing = profile_rating([normalized(raw)], "a", {}, None) + assert missing["score"] == zero["score"] + assert [d["value"] for d in missing["dimensions"]] == [61, 58, None, 86, None] + raw["Data"]["a"]["DestructionScore"] = None + incomplete = profile_rating([normalized(raw)], "a", {}, 0) + assert incomplete["score"] is None and incomplete["sample_size"] == 0 + assert [d["value"] for d in incomplete["dimensions"]] == [None, None, None, None, 0] + + +def test_bundled_model_has_pinned_source_and_complete_mit_notice_without_match_awards(): source = MODEL["source"] assert source["commit"] == "072dc9bc2d73ffc87000c1d3db4c0f9b4dcab549" assert source["license"] == "MIT" + notice = Path(__file__).resolve().parents[1] / "docs" / "BA_DRAGON_LICENSE.txt" + assert source["licenseText"].encode("utf-8") == notice.read_bytes() assert "Copyright (c) 2026 AlexanderHYu" in source["licenseText"] assert "Copyright (c) 2025-2026 Zola (Zawinzala)" in source["licenseText"] assert 'THE SOFTWARE IS PROVIDED "AS IS"' in source["licenseText"] - assert not set(MODEL).intersection({"titles", "titleDist", "titleFreq", "tiers", "playerPct", "kalman", "effElo"}) + assert not set(MODEL).intersection({"titles", "titleDist", "titleFreq", "effElo"}) diff --git a/tests/test_service.py b/tests/test_service.py index 3f58abf..bbb0bc3 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -473,9 +473,8 @@ async def test_overview_uses_actual_sample_and_known_outcomes_only(h): assert len(view["rows"]) == 3 assert [row["outcome"] for row in view["rows"]] == ["win", "loss", "unknown"] assert metrics["分析样本胜率"]["value"] == 50 - assert "2 场已知结果" in metrics["分析样本胜率"]["note"] assert view["scope"] == "近期3场" - assert view["analysis_scope"] == "分析样本30场 · 与近期样本独立" + assert view["style_scope"] == "近30场风格" assert view["stale"] is True diff --git a/tools/render_previews.py b/tools/render_previews.py index 848a4ee..5e25412 100644 --- a/tools/render_previews.py +++ b/tools/render_previews.py @@ -2,13 +2,13 @@ Run from the repository using the session's .venv/Scripts/python.exe -B: tools/render_previews.py # HTML + matching text only - tools/render_previews.py --screenshots # desktop + 390px mobile PNGs + tools/render_previews.py --screenshots # production, 390px reflow, and 390px chat previews Chromium must already be installed under the session's .playwright directory. No installation, server, external page, account, or live API is used. Browser contexts are offline and all requests are aborted as an additional boundary. All outputs, browser temporary profiles and the manifest stay under the -session root's previews/. Images show synthetic samples, never real players. +selected output directory. Images show synthetic samples, never real players. """ from __future__ import annotations @@ -25,17 +25,19 @@ sys.dont_write_bytecode = True REPOSITORY = Path(__file__).resolve().parents[1] SESSION = REPOSITORY.parent -OUTPUT = SESSION / "previews" +OUTPUT = SESSION / "tmp" / "overview-v015" / "previews" sys.path.insert(0, str(REPOSITORY)) from render import Renderer +PHONE_WIDTH = 390 + def sample_views() -> dict[str, dict]: """Deterministic synthetic data, including long names and missing fields.""" base = { - "player": {"id": "sample-000001", "name": "蓝线观察员 · 合成样本"}, - "scope": "最近取得 5 场 · 其中排位样本 4 场 · 非完整历史", + "player": {"id": "sample-000001", "name": "蓝线观察员"}, + "scope": "近期5场 · 11-13—11-17", "fetched_at": "2026-11-17T04:10:00Z", "source_updated_at": "2026-11-17T04:00:00Z", "source_url": "https://example.invalid/synthetic-preview", @@ -45,14 +47,22 @@ def sample_views() -> dict[str, dict]: overview.update( kind="overview", metrics=[ - {"label": "ELO", "value": 1834.25, "note": "来源更新时点"}, - {"label": "分析样本胜率", "value": 75, "format": "percent", "note": "75 胜 / 100 场已知结果"}, - {"label": "近期分值 K/D", "value": 150 / 96, "note": "近期 5 场摧毁分 ÷ 损失分"}, - {"label": "伤害交换比", "value": 39602 / 26081, "note": "分析单局 · #sample-match-001"}, + {"label": "ELO", "value": 1854.02}, + {"label": "近期分值 K/D", "value": 1.42}, + {"label": "分析样本胜率", "value": 40, "format": "percent"}, + {"label": "单局伤害交换比", "value": 1.3}, ], - common_units=[{"name": "合成装甲单位 A", "count": 12,"damage":5200,"roi":1.6}, {"name": "合成支援兵种 B", "count": 8,"damage":2100,"roi":1.2}], - analysis_scope="分析样本 100 场", - map_stats=[{"name":"合成港区","count":8,"win_rate":50}], + profile_rating={"score": 5.8, "title": "泯然众人", "tone": "medium", "sample_size": 4, + "dimensions": [{"key": key, "label": label, "value": value} for key, label, value in + (("kd", "分值 K/D", 37), ("contrib", "摧毁贡献", 59), ("obj", "占点贡献", 30), + ("outcome", "胜负预期", 51), ("win_rate", "实际胜率", 60))]}, + common_units=[{"name": "Tu-95", "count": 72, "damage": 11682.87, "roi": 1.62}, + {"name": "Mi-8AMTSh-VN Sapsan", "count": 165, "damage": 7074.14, "roi": .37}], + style_scope="近83场风格", categories=[{"name": name, "percentage": value} for name, value in + (("支援", 31.4), ("固定翼", 30.7), ("步兵", 10.7), ("车辆", 10.1), + ("侦察", 9.6), ("直升机", 7.5))], + map_stats=[{"name": "合成港区", "count": 8, "win_rate": 50}, + {"name": "合成山区", "count": 6, "win_rate": 100 / 3}], ) recent = deepcopy(base) recent.update(kind="recent", rows=[ @@ -68,6 +78,7 @@ def sample_views() -> dict[str, dict]: for index in range(5) ]) match = deepcopy(base) + match["player"]["name"] += " · 合成样本" match.update( kind="match", scope="单场记录 · 排位 · 5 对 5 人", match={"id": "sample-match-001", "map_name": "合成港区", "mode": "ranked", @@ -86,7 +97,7 @@ def sample_views() -> dict[str, dict]: ("固定翼", (24, 20)), ("后勤/运输", (1, 1))]], "composition_note":"合成样本", "players": [ {"id": base["player"]["id"] if side == 0 and index == 1 else f"sample-{side}-{index}", - "name": base["player"]["name"] if side == 0 and index == 1 else f"合成队员 {side + 1}-{index + 1}", + "name": match["player"]["name"] if side == 0 and index == 1 else f"合成队员 {side + 1}-{index + 1}", "elo_before": 1800 + index * 12.5, "elo": 1800 + index * 12.5 + (8.25 if side == 0 else -8.25), "elo_delta": 8.25 if side == 0 else -8.25, "damage_dealt": 1253, "damage_received": 964, "objectives": 3, @@ -102,12 +113,18 @@ def sample_views() -> dict[str, dict]: for kind, normal in [("overview", overview), ("recent", recent), ("match", match)]: samples[f"{kind}-normal"] = normal long = deepcopy(normal) - long["player"]["name"] = "合成长昵称_中文MixedPlayer_" * 7 + '{{7*7}} <昵称>&' + long["player"]["name"] = "合成长昵称_中文MixedPlayer_" * (7 if kind == "match" else 3) + '{{7*7}} <昵称>&' long["player"]["id"] = "sample-long-id-" + "0123456789" * 8 if kind == "overview": - long["common_units"][0]["name"] = "合成长单位名称_" * 8 + long["metrics"][0]["value"] = 12345.67 + long["profile_rating"]["dimensions"][0]["value"] = 100 + long["common_units"][0]["name"] = "合成长单位名称_" * 3 + long["common_units"][1].update(name="LongUnitDesignationWithoutSpaces" * 2, damage=1234567.89) + long["map_stats"][0].update(name="合成长地图名称_" * 3, win_rate=0) elif kind == "recent": - long["rows"][0]["map_name"] = "合成长地图名称_" * 6 + long["rows"][0].update(map_name="合成长地图名称_" * 3, id=long["player"]["id"], + destroyed_value=9876543.21, lost_value=1234567.89, + value_exchange=9876543.21 / 1234567.89) else: long["teams"][0]["name"] = "合成长分队名称_" * 7 long["teams"][0]["players"][0]["name"] = long["player"]["name"] @@ -116,11 +133,14 @@ def sample_views() -> dict[str, dict]: missing.update(kind=kind, player={"id": "sample-missing", "name": None}, source_url=None, source_updated_at=None, stale=True, scope="已取得样本 · 覆盖范围暂无") if kind == "overview": - missing["metrics"] = [ - {"label": "ELO", "value": None}, {"label": "样本胜率", "value": None, "format": "percent"}, - {"label": "实际样本", "value": 0, "format": "integer", "unit": "场"}, - {"label": "价值交换比", "value": None}, - ] + missing["metrics"] = [dict(metric, value=None) for metric in overview["metrics"]] + missing["profile_rating"] = deepcopy(overview["profile_rating"]) + missing["profile_rating"].update(score=None, title=None, tone=None, sample_size=0) + for axis in missing["profile_rating"]["dimensions"]: + axis["value"] = 0 if axis["key"] == "win_rate" else None + missing["style_scope"] = "近0场风格" + missing["common_units"] = [{"name": "合成未完整单位", "count": 0, "roi": 0}] + missing["map_stats"] = [{"name": "合成未完整地图", "count": 2}] elif kind == "recent": missing["rows"] = [{"id": "sample-partial", "kills": 0, "duration_seconds": 0}] else: @@ -132,9 +152,10 @@ def sample_views() -> dict[str, dict]: async def screenshots(artifacts: list[dict]) -> list[dict]: + from PIL import Image from playwright.async_api import async_playwright - os.environ.setdefault("PLAYWRIGHT_BROWSERS_PATH", str(SESSION / ".playwright")) + os.environ["PLAYWRIGHT_BROWSERS_PATH"] = str(SESSION / ".playwright") temporary = OUTPUT / ".tmp" temporary.mkdir(exist_ok=True) os.environ["TMP"] = str(temporary) @@ -144,7 +165,7 @@ async def screenshots(artifacts: list[dict]) -> list[dict]: async with async_playwright() as playwright: browser = await playwright.chromium.launch(headless=True) try: - for label, width in [("desktop", 900), ("mobile", 390)]: + for width in [*Renderer.WIDTHS.values(), PHONE_WIDTH]: context = await browser.new_context(viewport={"width": width, "height": 900}, device_scale_factor=1, offline=True) await context.route("**/*", lambda route: route.abort()) @@ -153,23 +174,64 @@ async def screenshots(artifacts: list[dict]) -> list[dict]: requests = [] page.on("request", lambda request: requests.append(request.url)) for item in artifacts: + if width not in (Renderer.WIDTHS[item["kind"]], PHONE_WIDTH): + continue requests.clear() await page.set_content((OUTPUT / item["html"]).read_text(encoding="utf-8"), wait_until="load") await page.evaluate("document.fonts.ready") - dimensions = await page.evaluate("""() => ({ - width: innerWidth, - documentWidth: document.documentElement.scrollWidth, - height: document.documentElement.scrollHeight, - reportHeight: document.querySelector('.report').getBoundingClientRect().height, - synthetic: document.querySelector('.synthetic')?.textContent, - font: getComputedStyle(document.body).fontFamily - })""") - name = f"{item['name']}-{label}.png" + dimensions = await page.evaluate(r"""() => { + const report = document.querySelector('.report'); + const bounds = report.getBoundingClientRect(); + const numbers = report.querySelectorAll( + '.metric-number, .report-table td:not(:first-child), .score, .style-list b, ' + + '.compact-line b, .recent-metrics dd, .row-meta .numeric, .summary-metrics dd, ' + + '.comparison-values b, .prediction-values b' + ); + const overflowingNumbers = [...numbers].filter(el => { + if (el.clientWidth && el.scrollWidth > el.clientWidth + 1) return true; + const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + for (const token of node.data.matchAll(/[+-]?\d[\d,.]*%?/g)) { + const range = document.createRange(); + range.setStart(node, token.index); + range.setEnd(node, token.index + token[0].length); + const rects = [...range.getClientRects()]; + if (rects.length !== 1 || rects.some(r => r.left < bounds.left - 1 || + r.right > bounds.right + 1)) return true; + } + } + return false; + }).map(el => el.textContent.trim()); + const radar = report.querySelector('.radar'); + const frame = radar?.getBoundingClientRect(); + const clippedRadarLabels = [...(radar?.querySelectorAll('.radar-label') ?? [])] + .filter(el => { + const box = el.getBoundingClientRect(); + return box.left < frame.left || box.right > frame.right || + box.top < frame.top || box.bottom > frame.bottom; + }).map(el => el.textContent.trim()); + return { + width: innerWidth, documentWidth: document.documentElement.scrollWidth, + height: document.documentElement.scrollHeight, + reportWidth: bounds.width, reportHeight: bounds.height, + synthetic: report.querySelector('.synthetic')?.textContent, + font: getComputedStyle(document.body).fontFamily, + overflowingNumbers, clippedRadarLabels + }; + }""") + name = f"{item['name']}-{width}.png" await page.locator(".report").screenshot(path=str(OUTPUT / name), animations="disabled") - check = {"image": name, "viewport": label, **dimensions, + check = {"image": name, "viewport": width, **dimensions, "external_requests": list(requests), - "passed": dimensions["documentWidth"] <= width and not requests - and bool(dimensions["synthetic"])} + "passed": dimensions["reportWidth"] == width and dimensions["documentWidth"] == width + and not requests and not dimensions["overflowingNumbers"] + and not dimensions["clippedRadarLabels"] and bool(dimensions["synthetic"])} + if width != PHONE_WIDTH and item["kind"] in {"overview", "recent"}: + chat_image = f"{item['name']}-{width}-chat-{PHONE_WIDTH}.png" + with Image.open(OUTPUT / name) as image: + height = round(image.height * PHONE_WIDTH / image.width) + image.resize((PHONE_WIDTH, height), Image.Resampling.LANCZOS).save(OUTPUT / chat_image) + check["chat_preview"] = chat_image checks.append(check) finally: await context.close() @@ -199,7 +261,7 @@ def main() -> int: html_name, text_name = name + ".html", name + ".txt" (OUTPUT / html_name).write_text(renderer.template(page), encoding="utf-8") (OUTPUT / text_name).write_text(renderer.text(page), encoding="utf-8") - artifacts.append({"name": name, "html": html_name, "text": text_name}) + artifacts.append({"name": name, "kind": view["kind"], "html": html_name, "text": text_name}) checks = asyncio.run(screenshots(artifacts)) if args.screenshots else [] manifest = { "synthetic": True, "live_api_used": False, @@ -209,7 +271,9 @@ def main() -> int: } (OUTPUT / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8") failures = [check["image"] for check in checks if not check["passed"]] - print(f"Synthetic previews: {len(artifacts)} HTML/text pairs; {len(checks)} screenshots; {len(failures)} layout/network failures.") + chat_count = sum("chat_preview" in check for check in checks) + print(f"Synthetic previews: {len(artifacts)} HTML/text pairs; {len(checks)} screenshots; " + f"{chat_count} chat-scale previews; {len(failures)} layout/network failures.") print(f"Output: {OUTPUT}") if failures: print("Failed: " + ", ".join(failures))