Repository navigation
Expand file tree
/
Copy pathreport.py
More file actions
238 lines (223 loc) · 14.9 KB
/
Copy pathreport.py
File metadata and controls
238 lines (223 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env python3
"""report.py - self-contained out/report.html with EN/RU/ES switcher.
Country names come from CLDR (Babel) on the fly, so any country auto-translates."""
import os, json, math, calendar
from collections import Counter
from datetime import date, timedelta
PROJECT = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(PROJECT, "data", "days.json")
RULES = os.path.join(PROJECT, "rules.json")
OUTDIR = os.path.join(PROJECT, "out")
LANGS = ("en","ru","es")
SCHENGEN = {"AT","BE","CZ","DK","EE","FI","FR","DE","GR","HU","IS","IT","LV","LI","LT",
"LU","MT","NL","NO","PL","PT","SK","SI","ES","SE","CH","HR","RO","BG"}
PALETTE = ["#3fb950","#f0883e","#58a6ff","#db61a2","#d29922","#a371f7","#39c5cf","#ff7b72",
"#7ee787","#ffa657","#79c0ff","#f778ba"]
I18N = {
"en": {"limits":"limits by rule","by_country":"days by country","by_month":"recorded days by month",
"by_region":"days by region","calendar":"presence calendar","flagged":"flagged days","left":"left","over":"over by",
"none":"none","points":"points","days_recorded":"days recorded","recomputed":"recomputed"},
"ru": {"limits":"\u043b\u0438\u043c\u0438\u0442\u044b \u043f\u043e \u043f\u0440\u0430\u0432\u0438\u043b\u0430\u043c","by_country":"\u0434\u043d\u0438 \u043f\u043e \u0441\u0442\u0440\u0430\u043d\u0430\u043c","by_month":"\u0434\u043d\u0435\u0439 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043e \u043f\u043e \u043c\u0435\u0441\u044f\u0446\u0430\u043c",
"by_region":"\u0434\u043d\u0438 \u043f\u043e \u0440\u0435\u0433\u0438\u043e\u043d\u0430\u043c",
"calendar":"\u043a\u0430\u043b\u0435\u043d\u0434\u0430\u0440\u044c \u043f\u0440\u0438\u0441\u0443\u0442\u0441\u0442\u0432\u0438\u044f","flagged":"\u0434\u043d\u0438 \u0441 \u043f\u043e\u043c\u0435\u0442\u043a\u043e\u0439","left":"\u043e\u0441\u0442\u0430\u043b\u043e\u0441\u044c","over":"\u043f\u0440\u0435\u0432\u044b\u0448\u0435\u043d\u043e \u043d\u0430",
"none":"\u043d\u0435\u0442","points":"\u0442\u043e\u0447\u0435\u043a","days_recorded":"\u0434\u043d\u0435\u0439 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043e","recomputed":"\u043f\u0435\u0440\u0435\u0441\u0447\u0438\u0442\u0430\u043d\u043e"},
"es": {"limits":"l\u00edmites por regla","by_country":"d\u00edas por pa\u00eds","by_month":"d\u00edas registrados por mes",
"by_region":"d\u00edas por regi\u00f3n",
"calendar":"calendario de presencia","flagged":"d\u00edas marcados","left":"quedan","over":"excedido en",
"none":"ninguno","points":"puntos","days_recorded":"d\u00edas registrados","recomputed":"recalculado"},
}
# country names on the fly from CLDR (Babel); falls back to the ISO code if Babel is missing.
try:
from babel import Locale
_LOC = {l: Locale.parse(l) for l in LANGS}
def cname(cc, lang): return _LOC.get(lang, _LOC["en"]).territories.get(cc, cc)
except Exception:
def cname(cc, lang): return cc
def color_map(ccs):
m={"CY":"#3fb950","ES":"#f0883e"}; i=0
for cc in ccs:
if cc not in m:
while PALETTE[i%len(PALETTE)] in m.values(): i+=1
m[cc]=PALETTE[i%len(PALETTE)]; i+=1
return m
def svg_donut(slices):
total=sum(v for _,v,_ in slices) or 1; cx=cy=110; R=92; r=58; a=-math.pi/2; out=[]
for _,v,col in slices:
if v<=0: continue
a1=a+2*math.pi*v/total
x1,y1=cx+R*math.cos(a),cy+R*math.sin(a); x2,y2=cx+R*math.cos(a1),cy+R*math.sin(a1)
xi1,yi1=cx+r*math.cos(a),cy+r*math.sin(a); xi2,yi2=cx+r*math.cos(a1),cy+r*math.sin(a1)
lg=1 if (a1-a)>math.pi else 0
out.append('<path d="M%.1f %.1f A%d %d 0 %d 1 %.1f %.1f L%.1f %.1f A%d %d 0 %d 0 %.1f %.1f Z" fill="%s"/>'%(x1,y1,R,R,lg,x2,y2,xi2,yi2,r,r,lg,xi1,yi1,col))
a=a1
out.append('<text x="%d" y="%d" text-anchor="middle" fill="#e6edf3" font-size="34" font-weight="700">%d</text>'%(cx,cy+8,int(total)))
return '<svg viewBox="0 0 220 220" width="200" height="200">%s</svg>'%("".join(out))
def svg_months(md):
months=sorted(md)
if not months: return ""
W,H,pad,gap=520,150,26,8; n=len(months); bw=(W-2*pad-gap*(n-1))/n; mx=max(md.values()) or 1
out=['<svg viewBox="0 0 %d %d" width="100%%" height="%d">'%(W,H,H)]
for i,m in enumerate(months):
x=pad+i*(bw+gap); h=(H-40)*md[m]/mx; y=H-22-h
out.append('<rect x="%.1f" y="%.1f" width="%.1f" height="%.1f" rx="3" fill="#3fb950"/>'%(x,y,bw,h))
out.append('<text x="%.1f" y="%d" text-anchor="middle" fill="#8b949e" font-size="11">%02d</text>'%(x+bw/2,H-6,m))
out.append('<text x="%.1f" y="%.1f" text-anchor="middle" fill="#e6edf3" font-size="11">%d</text>'%(x+bw/2,y-4,md[m]))
out.append('</svg>'); return "".join(out)
def svg_calendar(year, day_cc, colmap, upto):
cell,gap,lblw,top=13,3,30,16; rows=[]
for m in range(1,upto+1):
nd=calendar.monthrange(year,m)[1]; y=top+(m-1)*(cell+gap+4)
row=['<text x="0" y="%d" fill="#8b949e" font-size="11">%02d</text>'%(y+cell-2,m)]
for d in range(1,nd+1):
iso="%04d-%02d-%02d"%(year,m,d); cc=day_cc.get(iso)
col=colmap.get(cc,"#21262d") if cc else "#21262d"; x=lblw+(d-1)*(cell+gap)
row.append('<rect x="%d" y="%d" width="%d" height="%d" rx="2" fill="%s"/>'%(x,y,cell,cell,col))
rows.append("".join(row))
W=lblw+31*(cell+gap); H=top+upto*(cell+gap+4)+4
return '<svg viewBox="0 0 %d %d" width="100%%" height="%d">%s</svg>'%(W,H,H,"".join(rows))
def scope_name(rule, lang):
sc=rule.get("scope",{})
if "country" in sc:
n=cname(sc["country"], lang)
if "admin1" in sc: n+=" \u00b7 "+sc["admin1"]
return n
if sc.get("zone")=="schengen": return "Schengen"
return "?"
def rule_labels(rule):
if "desc" in rule:
return {l: scope_name(rule,l)+" \u00b7 "+rule["desc"].get(l, rule["desc"].get("en","")) for l in LANGS}
lab=rule.get("label",""); return {l:lab for l in LANGS}
def eval_rule(rule, days, year, today):
sc=rule.get("scope",{})
def match(d):
if "country" in sc:
if d["cc"] != sc["country"]: return False
if "admin1" in sc: return d.get("admin1","") == sc["admin1"]
return True
if sc.get("zone")=="schengen": return d["schengen"]
return False
if rule["basis"]=="calendar_year":
used=sum(1 for d in days if int(d["date"][:4])==year and match(d)); window=str(year)
else:
start=today-timedelta(days=179)
used=sum(1 for d in days if start<=date.fromisoformat(d["date"])<=today and match(d))
window="%s -> %s"%(start.isoformat(),today.isoformat())
left=rule["limit"]-used; pct=min(100,round(used/rule["limit"]*100)) if rule["limit"] else 0
status="ok" if pct<75 else ("warn" if pct<100 else "over")
return {"used":used,"limit":rule["limit"],"left":left,"pct":pct,"status":status,"window":window}
def main():
os.makedirs(OUTDIR, exist_ok=True)
data=json.load(open(DATA,encoding="utf-8")); rules=json.load(open(RULES,encoding="utf-8"))["rules"]
days=data["days"]; today=date.today(); year=today.year
day_cc={d["date"]:d["cc"] for d in days}
yr=[d for d in days if int(d["date"][:4])==year]
by_country=Counter(d["cc"] for d in yr)
order=sorted(by_country, key=lambda c:-by_country[c]); colmap=color_map(order)
slices=[(cc,by_country[cc],colmap[cc]) for cc in order]
md=Counter(int(d["date"][5:7]) for d in yr)
SC={"ok":"#3fb950","warn":"#d29922","over":"#f85149"}
# every country code that could need a localized name -> build CN map from CLDR
ccs=set()
for d in days:
ccs.add(d["cc"]); ccs.update(d.get("countries_seen",[]))
for r in rules:
sc=r.get("scope",{})
if "country" in sc: ccs.add(sc["country"])
CN={l:{cc:cname(cc,l) for cc in sorted(ccs)} for l in LANGS}
legend="".join('<span class=lg><i style="background:%s"></i><span data-cc="%s">%s</span> %d</span>'%(colmap[cc],cc,cname(cc,"en"),by_country[cc]) for cc in order)
rules_html=""; RLBL={}
for idx,rule in enumerate(rules):
rid=rule.get("id","r%d"%idx); lab=rule_labels(rule); RLBL[rid]=lab
ev=eval_rule(rule,days,year,today)
word="left" if ev["left"]>=0 else "over"; val=ev["left"] if ev["left"]>=0 else -ev["left"]
disp="left" if word=="left" else "over by"
rules_html+=('<div class=rule><div class=rl><span data-rule="%s">%s</span><span class=win>%s</span></div>'
'<div class=num>%d<small> / %d · <span data-i18n="%s">%s</span> %d</small></div>'
'<div class=track><div class=fill style="width:%d%%;background:%s"></div></div></div>'
%(rid,lab["en"],ev["window"],ev["used"],ev["limit"],word,disp,val,ev["pct"],SC[ev["status"]]))
flagged=[d for d in days if d["flagged"]]
# region (US state / province) breakdown, current year; card appears only when useful
reg=Counter((d["cc"], d["admin1"]) for d in yr if d.get("admin1"))
rule_cc={r["scope"]["country"] for r in rules if "admin1" in r.get("scope",{}) and "country" in r.get("scope",{})}
show_cc=[cc for cc in order if cc in rule_cc]
regions_html=""
if show_cc:
rows=[]
for cc in show_cc:
items=sorted(((a,n) for (c,a),n in reg.items() if c==cc), key=lambda x:-x[1])
mx=items[0][1] if items else 1
rows.append('<div class=regc><span data-cc="%s">%s</span></div>'%(cc,cname(cc,"en")))
for a,n in items:
rows.append('<div class=reg><div class=rl><span>%s</span><span>%d</span></div>'
'<div class=track><div class=fill style="width:%d%%;background:%s"></div></div></div>'
%(a,n,round(n/mx*100),colmap[cc]))
regions_html=('<div class="card"><h2 data-i18n="by_region">days by region</h2>%s</div>'%"".join(rows))
def fc(cs): return ", ".join('<span data-cc="%s">%s</span>'%(c,cname(c,"en")) for c in cs)
flagged_html=("".join('<tr><td>%s</td><td>%s</td></tr>'%(d["date"],fc(d["countries_seen"])) for d in flagged[-40:])
or '<tr><td colspan=2 class=muted data-i18n="none">none</td></tr>')
html=(_TPL.replace("__PTS__",str(data.get("point_count",0)))
.replace("__NDAYS__",str(len(days)))
.replace("__GEN__",data.get("generated","")[:19].replace("T"," "))
.replace("__RULES__",rules_html).replace("__DONUT__",svg_donut(slices))
.replace("__LEGEND__",legend).replace("__MONTHS__",svg_months(md))
.replace("__CAL__",svg_calendar(year,day_cc,colmap,max([today.month]+list(md))))
.replace("__REGIONS__",regions_html)
.replace("__FLAGGED__",flagged_html)
.replace("__I18N__",json.dumps(I18N,ensure_ascii=False))
.replace("__CN__",json.dumps(CN,ensure_ascii=False))
.replace("__RLBL__",json.dumps(RLBL,ensure_ascii=False)))
open(os.path.join(OUTDIR,"report.html"),"w",encoding="utf-8").write(html)
print("wrote", os.path.join(OUTDIR,"report.html"))
_TPL = """<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><title>daco</title>
<style>
:root{--bg:#0d1117;--panel:#161b22;--line:#30363d;--fg:#e6edf3;--muted:#8b949e}
*{box-sizing:border-box;margin:0;padding:0}
body{background:var(--bg);color:var(--fg);font:14px/1.5 ui-monospace,Menlo,monospace;padding:20px;max-width:820px;margin:0 auto}
.head{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px}
h1{font-size:13px;letter-spacing:.2em;text-transform:uppercase;color:var(--muted);font-weight:600}
h2{font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:var(--muted);margin:0 0 12px}
.sub{color:var(--muted);font-size:11px;margin:4px 0 18px}
.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:18px 20px;margin-bottom:14px}
.top{display:flex;gap:20px;align-items:center;flex-wrap:wrap}
.lg{display:inline-flex;align-items:center;font-size:12px;margin:2px 14px 2px 0}
.lg i{width:10px;height:10px;border-radius:2px;display:inline-block;margin-right:6px}
.rule{padding:10px 0;border-bottom:1px solid var(--line)}.rule:last-child{border:0}
.rl{display:flex;justify-content:space-between;font-size:13px;margin-bottom:6px}.rl .win{color:var(--muted);font-size:11px}
.num{font-size:22px;font-weight:600}.num small{font-size:12px;color:var(--muted);font-weight:400}
.track{height:6px;background:#21262d;border-radius:99px;margin-top:8px;overflow:hidden}.fill{height:100%;border-radius:99px}
table{width:100%;border-collapse:collapse;font-size:13px}td{padding:5px 8px;border-bottom:1px solid var(--line)}
td:first-child{color:var(--muted);width:110px;white-space:nowrap}.muted{color:var(--muted)}
.langs{display:flex;gap:6px}
.langbtn{background:#21262d;color:var(--muted);border:1px solid var(--line);border-radius:6px;padding:4px 10px;font:inherit;font-size:12px;cursor:pointer}
.langbtn.on{background:#1f6feb;color:#fff;border-color:#1f6feb}
.regc{font-size:12px;color:var(--muted);margin:10px 0 4px;letter-spacing:.06em;text-transform:uppercase}.regc:first-child{margin-top:0}
.reg{padding:6px 0}.reg .rl{font-size:13px;margin-bottom:4px}
.foot{text-align:center;color:var(--muted);font-size:11px;margin-top:18px}.foot a{color:#58a6ff;text-decoration:none}
</style></head><body>
<div class="head"><h1>daco · days counter</h1>
<div class="langs">
<button class="langbtn on" data-l="en" onclick="setLang('en')">EN</button>
<button class="langbtn" data-l="ru" onclick="setLang('ru')">RU</button>
<button class="langbtn" data-l="es" onclick="setLang('es')">ES</button>
</div></div>
<div class="sub">__PTS__ <span data-i18n="points">points</span> · __NDAYS__ <span data-i18n="days_recorded">days recorded</span> · <span data-i18n="recomputed">recomputed</span> __GEN__ UTC</div>
<div class="card"><h2 data-i18n="limits">limits by rule</h2>__RULES__</div>
<div class="card"><h2 data-i18n="by_country">days by country</h2><div class="top"><div>__DONUT__</div><div>__LEGEND__</div></div></div>
__REGIONS__
<div class="card"><h2 data-i18n="by_month">recorded days by month</h2>__MONTHS__</div>
<div class="card"><h2 data-i18n="calendar">presence calendar</h2>__CAL__</div>
<div class="card"><h2 data-i18n="flagged">flagged days</h2><table>__FLAGGED__</table></div>
<div class="foot">daco v1.0.1 · <a href="https://www.bermana.net">www.bermana.net</a> · © 2026 Artem Berman</div>
<script>
const I18N=__I18N__, CN=__CN__, RLBL=__RLBL__;
function setLang(l){
document.documentElement.lang=l;
document.querySelectorAll('[data-i18n]').forEach(function(e){var v=I18N[l][e.dataset.i18n]; if(v)e.textContent=v;});
document.querySelectorAll('[data-cc]').forEach(function(e){var m=CN[l]||{}; if(m[e.dataset.cc])e.textContent=m[e.dataset.cc];});
document.querySelectorAll('[data-rule]').forEach(function(e){var m=RLBL[e.dataset.rule]; if(m&&m[l])e.textContent=m[l];});
document.querySelectorAll('.langbtn').forEach(function(b){b.classList.toggle('on', b.dataset.l===l);});
}
</script></body></html>"""
if __name__=="__main__":
main()