-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.py
More file actions
562 lines (462 loc) · 18.6 KB
/
Copy pathscript.py
File metadata and controls
562 lines (462 loc) · 18.6 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
from datetime import datetime, timedelta
import json
import os
import shutil
import subprocess
import sys
import tempfile
from concurrent.futures import ThreadPoolExecutor, as_completed
# === АВТОУСТАНОВКА REQUESTS ===
try:
import requests
except ImportError:
print("[D2PT Grid] Installing 'requests'...")
subprocess.check_call([sys.executable, "-m", "pip", "install", "requests", "--quiet"])
import requests
print("[D2PT Grid] 'requests' installed!")
# === ПУТИ ===
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
MINIFY_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, "..", ".."))
STEAM_ROOT = r"C:\Program Files (x86)\Steam"
STEAM_ID = ""
# === ДЕФОЛТНЫЕ НАСТРОЙКИ (переопределяются config.json) ===
DEFAULTS = {
"grid_sources": ["matches_wr", "d2ptrating"],
"patch": "latest",
"max_per_role": None,
"all_heroes_width": None,
"role_width": 500,
"all_heroes_height": 420,
"all_heroes_x": 520,
"synergy_col_width": 220,
"synergy_gap": 10,
"synergy_start_x": 75,
"max_screen_width": 1080,
"backup_limit": 10,
"cache_ttl_hours": 1,
"dry_run": False,
"install_configs": ["All Roles", "Carry", "Mid", "Offlane", "Support", "Hard Support"],
"short_labels": {
"matches_wr": "WR",
"d2ptrating": "RT",
},
"combined_label": "CMB",
}
SETTINGS = dict(DEFAULTS)
D2PT_CONFIG_MARKER = "D2PT"
# === ЗАГРУЗКА КОНФИГОВ ===
LOCAL_CFG_PATH = os.path.join(SCRIPT_DIR, "config.json")
if os.path.exists(LOCAL_CFG_PATH):
try:
with open(LOCAL_CFG_PATH, "r", encoding="utf-8") as f:
user_cfg = json.load(f)
for k, v in user_cfg.items():
if k in SETTINGS:
SETTINGS[k] = v
if "steam_id" in user_cfg:
STEAM_ID = str(user_cfg["steam_id"]) if user_cfg["steam_id"] else ""
except Exception as e:
print(f"[D2PT Grid] WARNING: config.json error: {e}")
def log(msg):
print(f"[D2PT Grid] {msg}")
def warn(msg):
print(f"[D2PT Grid] WARNING: {msg}")
# === СЕТЕВЫЕ ЗАПРОСЫ С RETRY ===
def fetch_json(url, timeout=15, retries=3):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "en-US,en;q=0.9",
"Referer": "https://dota2protracker.com/meta-hero-grids",
}
import time
for attempt in range(retries):
try:
r = requests.get(url, headers=headers, timeout=timeout)
r.raise_for_status()
return r.json()
except Exception as e:
if attempt == retries - 1:
raise
wait = 2 ** attempt
log(f"Retry {attempt + 1}/{retries} after {wait}s: {url}")
time.sleep(wait)
def load_minify_config():
global STEAM_ROOT, STEAM_ID
cfg_path = os.path.join(MINIFY_ROOT, "minify_config.json")
if not os.path.exists(cfg_path):
return
try:
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
if "steam_root" in cfg:
STEAM_ROOT = cfg["steam_root"]
if "steam_id" in cfg and cfg["steam_id"]:
STEAM_ID = str(cfg["steam_id"])
mod_name = os.path.basename(SCRIPT_DIR)
modconf = cfg.get("modconf", {}).get(mod_name, {})
if "grid_sources" in modconf:
src = modconf["grid_sources"]
SETTINGS["grid_sources"] = src if isinstance(src, list) else [src]
except Exception as e:
warn(f"minify_config.json error: {e}")
def get_steam_accounts():
userdata_path = os.path.join(STEAM_ROOT, "userdata")
if not os.path.exists(userdata_path):
return []
accounts = []
for item in os.listdir(userdata_path):
account_path = os.path.join(userdata_path, item)
dota_cfg = os.path.join(account_path, "570", "remote", "cfg")
if os.path.isdir(account_path) and item.isdigit() and os.path.exists(dota_cfg):
accounts.append({"steam_id": item, "cfg_path": dota_cfg})
return accounts
# === КЭШИРОВАНИЕ ===
def atomic_write_json(path, data):
dir_name = os.path.dirname(path) or "."
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", suffix=".tmp", dir=dir_name, delete=False
) as f:
json.dump(data, f, indent=2, ensure_ascii=False)
tmp = f.name
shutil.move(tmp, path)
def get_cache_path(src):
return os.path.join(SCRIPT_DIR, f"cache_{src}_{SETTINGS['patch']}.json")
def load_cached(src):
path = get_cache_path(src)
if not os.path.exists(path):
return None
try:
mtime = datetime.fromtimestamp(os.path.getmtime(path))
ttl = timedelta(hours=SETTINGS.get("cache_ttl_hours", 1))
if datetime.now() - mtime > ttl:
return None
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return None
def save_cache(src, data):
path = get_cache_path(src)
try:
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False)
except Exception as e:
warn(f"Cache save failed: {e}")
# === СОКРАЩЕНИЕ ИМЁН ===
def clean_config_name(name):
if " - " in name:
return name.split(" - ", 1)[-1]
return name
def short_source_label(label):
mapping = SETTINGS.get("short_labels", {})
return mapping.get(label, label)
# === ОБЪЕДИНЕНИЕ СПИСКОВ ГЕРОЕВ ===
def merge_hero_lists(list_a, list_b):
positions = {}
for idx, hid in enumerate(list_a):
positions.setdefault(hid, []).append(idx)
for idx, hid in enumerate(list_b):
positions.setdefault(hid, []).append(idx)
def sort_key(hid):
pos = positions[hid]
in_both = len(pos) > 1
avg = sum(pos) / len(pos)
return (0 if in_both else 1, avg)
return sorted(positions.keys(), key=sort_key)
def merge_single_category(cat_a, cat_b):
if not cat_a and not cat_b:
return None
if not cat_a:
return dict(cat_b)
if not cat_b:
return dict(cat_a)
merged = dict(cat_a)
heroes_a = cat_a.get("hero_ids", [])
heroes_b = cat_b.get("hero_ids", [])
seen = set()
merged["hero_ids"] = [h for h in heroes_a + heroes_b if not (h in seen or seen.add(h))]
return merged
def merge_all_roles_config(cfg_a, cfg_b):
cats_a = {c["category_name"]: c for c in cfg_a.get("categories", [])}
cats_b = {c["category_name"]: c for c in cfg_b.get("categories", [])}
all_names = list(cats_a.keys())
for n in cats_b:
if n not in cats_a:
all_names.append(n)
role_names = {"Carry", "Mid", "Offlane", "Support", "Hard Support"}
max_per = SETTINGS.get("max_per_role")
merged_cats = []
for cat_name in all_names:
cat_a = cats_a.get(cat_name)
cat_b = cats_b.get(cat_name)
if not cat_a:
merged_cats.append(dict(cat_b))
continue
if not cat_b:
merged_cats.append(dict(cat_a))
continue
if cat_name in role_names:
# Используем тот же алгоритм смешивания источников (по средней позиции
# и приоритету героев, попавших в оба списка), что и для "Top Heroes Pos X",
# чтобы топ героев по ролям совпадал в обеих сетках.
merged_cat = dict(cat_a)
merged_cat["hero_ids"] = merge_hero_lists(
cat_a.get("hero_ids", []), cat_b.get("hero_ids", [])
)
if max_per:
merged_cat["hero_ids"] = merged_cat["hero_ids"][:max_per]
else:
merged_cat = merge_single_category(cat_a, cat_b)
merged_cats.append(merged_cat)
return {"config_name": cfg_a.get("config_name", ""), "categories": merged_cats}
def merge_position_config(cfg_a, cfg_b):
cats_a = cfg_a.get("categories", [])
cats_b = cfg_b.get("categories", [])
top_a = cats_a[0].get("hero_ids", []) if cats_a else []
top_b = cats_b[0].get("hero_ids", []) if cats_b else []
merged_top = merge_hero_lists(top_a, top_b)
max_per = SETTINGS.get("max_per_role")
if max_per:
merged_top = merged_top[:max_per]
merged_cats = [dict(cats_a[0])]
merged_cats[0]["hero_ids"] = merged_top
group_names = ["Best with", "Worst with", "Best against", "Worst against"]
for m_idx, hero in enumerate(merged_top):
idx_a = top_a.index(hero) if hero in top_a else -1
idx_b = top_b.index(hero) if hero in top_b else -1
for g_idx, g_name in enumerate(group_names):
cat_a = None
cat_b = None
if idx_a >= 0:
pos = 1 + idx_a * 4 + g_idx
if pos < len(cats_a):
cat_a = cats_a[pos]
if idx_b >= 0:
pos = 1 + idx_b * 4 + g_idx
if pos < len(cats_b):
cat_b = cats_b[pos]
merged_cat = merge_single_category(cat_a, cat_b)
if merged_cat:
merged_cat["y_position"] = 20 + m_idx * 75
merged_cats.append(merged_cat)
return {"config_name": cfg_a.get("config_name", ""), "categories": merged_cats}
def merge_two_configs(cfg_a, cfg_b):
name = cfg_a.get("config_name", "")
if "All Roles" in name:
return merge_all_roles_config(cfg_a, cfg_b)
return merge_position_config(cfg_a, cfg_b)
# === ФИЛЬТР КОНФИГОВ ===
def filter_configs(configs):
allowed = SETTINGS.get("install_configs", [])
if not allowed:
return configs
result = []
for cfg in configs:
name = cfg.get("config_name", "")
clean = clean_config_name(name)
if "All Roles" in name and "All Roles" in allowed:
result.append(cfg)
elif any(clean.startswith(a) for a in allowed if a != "All Roles"):
result.append(cfg)
return result
# === ФИКС РАЗМЕТКИ ===
def fix_layout(configs):
max_w = SETTINGS.get("max_screen_width", 1080)
role_w = SETTINGS.get("role_width", 500)
ah_x = SETTINGS.get("all_heroes_x", 520)
ah_h = SETTINGS.get("all_heroes_height", 420)
syn_w = SETTINGS.get("synergy_col_width", 220)
syn_gap = SETTINGS.get("synergy_gap", 10)
syn_start = SETTINGS.get("synergy_start_x", 75)
syn_names = {"Best with", "Worst with", "Best against", "Worst against"}
role_names = {"Carry", "Mid", "Offlane", "Support", "Hard Support"}
for cfg in configs:
cats = cfg.get("categories", [])
if not cats:
continue
first = cats[0].get("category_name", "")
cfg_name = cfg.get("config_name", "")
if "All Roles" in cfg_name:
for cat in cats:
name = cat.get("category_name", "")
if name in role_names:
cat["width"] = role_w
elif name == "All Heroes":
cat["x_position"] = ah_x
cat["height"] = ah_h
right = cat.get("x_position", 0) + cat.get("width", 0)
if right > max_w:
cat["width"] = max_w - cat["x_position"] - 20
elif "Top Heroes Pos" in first:
syn_cats = [c for c in cats if c.get("category_name") in syn_names]
if syn_cats:
rows = {}
for c in syn_cats:
rows.setdefault(c.get("y_position", 0), []).append(c)
for y, row in rows.items():
row.sort(key=lambda c: c.get("x_position", 0))
for i, c in enumerate(row):
c["width"] = syn_w
c["x_position"] = syn_start + i * (syn_w + syn_gap)
c["height"] = 55
top = cats[0]
n = len(top.get("hero_ids", []))
top["height"] = max(525, (n - 1) * 75 + 55 + 20)
return configs
# === ПРИМЕНЕНИЕ НАСТРОЕК ===
def apply_local_settings(configs):
ah_w = SETTINGS.get("all_heroes_width")
max_per = SETTINGS.get("max_per_role")
role_names = {"Carry", "Mid", "Offlane", "Support", "Hard Support",
"Top Heroes Pos 1", "Top Heroes Pos 2", "Top Heroes Pos 3",
"Top Heroes Pos 4", "Top Heroes Pos 5"}
for cfg in configs:
for cat in cfg.get("categories", []):
name = cat.get("category_name", "")
if name == "All Heroes" and ah_w:
cat["width"] = ah_w
if name in role_names and max_per:
heroes = cat.get("hero_ids", [])
if len(heroes) > max_per:
cat["hero_ids"] = heroes[:max_per]
return configs
# === БЭКАП С ЛИМИТОМ ===
def cleanup_backups(backup_dir, limit):
try:
files = [os.path.join(backup_dir, f) for f in os.listdir(backup_dir) if f.endswith(".json")]
if len(files) <= limit:
return
files.sort(key=lambda p: os.path.getmtime(p))
for old in files[:-limit]:
os.remove(old)
log(f"Removed old backup: {os.path.basename(old)}")
except Exception:
pass
# === МЕРЖ В STEAM ===
def merge_into_account(configs, dest_path, account_id, source_label):
original = os.path.join(dest_path, "hero_grid_config.json")
backup_dir = os.path.join(SCRIPT_DIR, "backup")
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
try:
if os.path.exists(original):
mtime = datetime.fromtimestamp(os.path.getmtime(original)).strftime("%Y-%m-%d_%H%M")
shutil.copy2(original, os.path.join(backup_dir, f"{account_id}_{mtime}.json"))
log(f"Backup: {account_id}_{mtime}.json")
cleanup_backups(backup_dir, SETTINGS.get("backup_limit", 10))
except Exception as e:
warn(f"Backup failed: {e}")
if SETTINGS.get("dry_run", False):
log(f"[DRY RUN] Would install {len(configs)} configs for {account_id} ({source_label})")
return
if not os.path.exists(original):
output = {"version": 3, "configs": []}
else:
with open(original, "r", encoding="utf-8") as f:
output = json.load(f)
configs_existing = output.get("configs", [])
marker = f"{D2PT_CONFIG_MARKER} "
configs_existing = [
c for c in configs_existing
if not c.get("config_name", "").startswith(marker)
]
for cfg in configs:
cfg_copy = dict(cfg)
cfg_copy["config_name"] = f"{D2PT_CONFIG_MARKER} {source_label} — {cfg_copy['config_name']}"
configs_existing.append(cfg_copy)
output["version"] = 3
output["configs"] = configs_existing
atomic_write_json(original, output)
log(f"Installed for account {account_id}: {len(configs)} configs ({source_label})")
# === ОСНОВНОЙ ЦИКЛ ===
def download_single(src):
cached = load_cached(src)
if cached:
log(f"Using cached: {src}")
return src, cached
url = f"https://dota2protracker.com/meta-hero-grids/download?mode={src}&patch={SETTINGS['patch']}"
log(f"Downloading: {url}")
data = fetch_json(url)
save_cache(src, data)
return src, data
def build_grid():
load_minify_config()
log(f"steam_id={STEAM_ID or 'ALL'}, patch={SETTINGS['patch']}, sources={SETTINGS['grid_sources']}")
if SETTINGS.get("dry_run"):
log("=== DRY RUN MODE ===")
# Параллельная загрузка
all_grids = {}
with ThreadPoolExecutor(max_workers=4) as ex:
futures = {ex.submit(download_single, src): src for src in SETTINGS["grid_sources"]}
for fut in as_completed(futures):
src = futures[fut]
try:
_, data = fut.result()
all_grids[src] = data
except Exception as e:
warn(f"Failed '{src}': {e}")
if not all_grids:
warn("No grids downloaded, aborting.")
return
# Собираем конфиги
configs_to_install = []
max_per = SETTINGS.get("max_per_role")
# Отдельные источники
for src, grid_data in all_grids.items():
configs = grid_data.get("configs", [])
if not configs:
continue
for cfg in configs:
cfg["config_name"] = clean_config_name(cfg["config_name"])
configs = filter_configs(configs)
configs = apply_local_settings(configs)
configs = fix_layout(configs)
label = short_source_label(src)
configs_to_install.append((label, configs))
# Объединённые
if len(all_grids) > 1:
sources = [s for s in SETTINGS["grid_sources"] if s in all_grids]
if not sources:
return
base_grid = all_grids[sources[0]]
other_grids = {s: all_grids[s] for s in sources[1:]}
combined = []
for cfg_base in base_grid.get("configs", []):
base_name = cfg_base.get("config_name", "")
merged = cfg_base
for other_src, other_grid in other_grids.items():
for cfg_other in other_grid.get("configs", []):
if cfg_other.get("config_name") == base_name:
merged = merge_two_configs(merged, cfg_other)
break
combined.append(merged)
if combined:
for cfg in combined:
cfg["config_name"] = clean_config_name(cfg["config_name"])
combined = filter_configs(combined)
combined = apply_local_settings(combined)
combined = fix_layout(combined)
configs_to_install.append((SETTINGS.get("combined_label", "CMB"), combined))
log("Built combined config")
# Установка
accounts = get_steam_accounts()
if not accounts:
warn(f"No accounts found in {STEAM_ROOT}\\userdata")
return
for label, configs in configs_to_install:
safe = label.replace(" ", "_").replace("+", "plus").replace("(", "").replace(")", "")
local_path = os.path.join(SCRIPT_DIR, f"d2pt_grid_{safe}.json")
atomic_write_json(local_path, {"version": 3, "configs": configs})
log(f"Saved local: {local_path}")
for acc in accounts:
if STEAM_ID and acc["steam_id"] != str(STEAM_ID):
continue
merge_into_account(configs, acc["cfg_path"], acc["steam_id"], label)
def main():
try:
build_grid()
except Exception as e:
warn(f"Failed: {e}")
raise
if __name__ == "__main__":
main()