cs2df 3.0.4__tar.gz → 3.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cs2df
3
- Version: 3.0.4
3
+ Version: 3.1.0
4
4
  Summary: Reference exporter & validator CLI for cs2-demo-format v3 (CS2 demo → ZIP data package)
5
5
  Project-URL: Homepage, https://github.com/Starfie1d1272/cs2-demo-format
6
6
  Project-URL: Repository, https://github.com/Starfie1d1272/cs2-demo-format
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "cs2df"
3
- version = "3.0.4"
3
+ version = "3.1.0"
4
4
  description = "Reference exporter & validator CLI for cs2-demo-format v3 (CS2 demo → ZIP data package)"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -5,7 +5,7 @@ demoparser2 / pandas stack installed. Heavy imports are deferred into the
5
5
  submodules that need them.
6
6
  """
7
7
 
8
- __version__ = "3.0.4"
8
+ __version__ = "3.1.0"
9
9
 
10
10
  SCHEMA_VERSION = "cs2-demo-format/3.0"
11
11
  EXPORTER_NAME = "cs2df"
@@ -12,6 +12,7 @@ import argparse
12
12
  import builtins
13
13
  import json
14
14
  import os
15
+ import re
15
16
  import sys
16
17
  import time
17
18
  from concurrent.futures import ProcessPoolExecutor, as_completed
@@ -27,7 +28,9 @@ def main(argv: list[str] | None = None) -> int:
27
28
  sub = parser.add_subparsers(dest="command", required=True)
28
29
 
29
30
  p_exp = sub.add_parser("export", help="export a CS2 .dem to a v3 ZIP package")
30
- p_exp.add_argument("demo", help="path to the .dem file")
31
+ p_exp.add_argument("demo", nargs="+",
32
+ help="path to the .dem file; pass multiple split parts "
33
+ "(…-p1.dem …-p2.dem) of ONE match to merge them")
31
34
  p_exp.add_argument("-o", "--output", default=None,
32
35
  help="output zip path (default: <demo>.zip next to the input)")
33
36
  p_exp.add_argument("--research", action="store_true",
@@ -78,16 +81,20 @@ def main(argv: list[str] | None = None) -> int:
78
81
 
79
82
 
80
83
  def _cmd_export(args) -> int:
81
- from .package import export_demo
84
+ from .package import export_demo_merged
82
85
 
83
- dem = Path(args.demo)
84
- if not dem.exists():
85
- print(f"ERROR: demo not found: {dem}", file=sys.stderr)
86
+ dems = [Path(d) for d in args.demo]
87
+ missing = [str(d) for d in dems if not d.exists()]
88
+ if missing:
89
+ print(f"ERROR: demo not found: {', '.join(missing)}", file=sys.stderr)
86
90
  return 1
87
91
  if not _compress_level_ok(args.compress_level):
88
92
  print("ERROR: --compress-level must be between 0 and 9", file=sys.stderr)
89
93
  return 1
90
- out = Path(args.output) if args.output else dem.with_suffix(".zip")
94
+ # 多段合并时输出名去掉 -pN 后缀,落到第一段同目录。
95
+ first = dems[0]
96
+ default_stem = re.sub(r"-p\d+$", "", first.stem)
97
+ out = Path(args.output) if args.output else first.with_name(default_stem + ".zip")
91
98
 
92
99
  t0 = time.perf_counter()
93
100
  progress = None
@@ -95,12 +102,14 @@ def _cmd_export(args) -> int:
95
102
  def progress(stage: str, frac: float) -> None:
96
103
  print(f" [{frac * 100:5.1f}%] {stage}")
97
104
 
98
- data, _match_meta = export_demo(str(dem), research=args.research,
99
- sample_rate=args.sample_rate,
100
- window_before_ms=args.window_before,
101
- window_after_ms=args.window_after,
102
- compress_level=args.compress_level,
103
- progress=progress)
105
+ if len(dems) > 1:
106
+ print(f"合并 {len(dems)} 段 → {out.name}")
107
+ data, _match_meta = export_demo_merged([str(d) for d in dems], research=args.research,
108
+ sample_rate=args.sample_rate,
109
+ window_before_ms=args.window_before,
110
+ window_after_ms=args.window_after,
111
+ compress_level=args.compress_level,
112
+ progress=progress)
104
113
  out.write_bytes(data)
105
114
  dt = time.perf_counter() - t0
106
115
  print(f"wrote {out} ({len(data) / 1e6:.2f} MB) in {dt:.1f}s")
@@ -160,7 +160,13 @@ def build_players(raw: dict) -> PlayerDirectory:
160
160
  if not sid or sid in seen or not _is_valid_steamid(sid):
161
161
  continue
162
162
  seen.add(sid)
163
- team_key = team_num_to_key.get(int(r.get("team_num") or 0))
163
+ # team_num 可能为 NaN(polars float 缺失列)——典型是有合法 steamid 但无队伍的
164
+ # 教练/观察员。注意 NaN 在 Python 中为真值,`NaN or 0` 仍是 NaN,int(NaN) 会抛
165
+ # ValueError,必须显式判 None/NaN 后跳过(等价于无 teamKey)。
166
+ tn = r.get("team_num")
167
+ if tn is None or tn != tn:
168
+ continue
169
+ team_key = team_num_to_key.get(int(tn))
164
170
  if not team_key:
165
171
  continue
166
172
  out.append({"steamId64": sid, "name": str(r.get("name") or sid), "teamKey": team_key})
@@ -0,0 +1,189 @@
1
+ """Merge split GOTV recordings of ONE match into a single parse_demo() output.
2
+
3
+ HLTV occasionally splits one match's GOTV demo into parts (``…-p1.dem``,
4
+ ``…-p2.dem``). Across parts the round COUNTER is global (part 2 already starts at
5
+ round 3), but the TICK clock restarts from ~0 in every file. We therefore:
6
+
7
+ 1. parse each part with :func:`cs2df.parse.parse_demo`;
8
+ 2. shift every tick in each later part past the previous parts' span, so the
9
+ merged timeline is strictly monotonic (within-part tick deltas — and thus
10
+ reaction times, round spans, duel windows — are preserved by a constant shift);
11
+ 3. concatenate the event streams and per-frame DataFrames;
12
+ 4. keep match metadata / roster from the first part (the true match start).
13
+
14
+ The merged dict has the exact shape :func:`parse_demo` returns, so
15
+ :func:`cs2df.package.build_package` re-derives coherent per-match artifacts
16
+ (player-stats, clutches, …) over the union — no per-artifact merge logic needed.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Any
22
+
23
+ # Metadata / roster taken from the first part, never shifted or concatenated.
24
+ _META_FIRST = {
25
+ "_timings", "header", "tickrate", "sample_rate", "match_start_tick",
26
+ "team_a_name", "team_b_name", "player_info",
27
+ }
28
+ # Event lists: list[dict]; shift any of these tick-bearing keys present on a row.
29
+ _EVENT_LISTS = {
30
+ "round_starts", "round_freeze_ends", "round_ends",
31
+ "deaths", "hurts", "fires", "blinds",
32
+ "bomb_planted", "bomb_defused", "bomb_exploded", "bomb_beginplant",
33
+ "bomb_begindefuse", "bomb_dropped", "bomb_pickup",
34
+ "grenade_detonations", "inferno_expires", "smoke_expires",
35
+ "grenade_throws", "grenade_trajectories",
36
+ "round_side_samples", "economy_raw",
37
+ }
38
+ _ROW_TICK_KEYS = ("tick", "destroy_tick", "start_tick")
39
+ # Round-structure lists are ownership-filtered, never tick-trimmed; the rest are
40
+ # combat/effect events that get trimmed of a resumed part's pre-live residue.
41
+ _ROUND_LISTS = {"round_starts", "round_freeze_ends", "round_ends"}
42
+ _DF_KEYS = {"fire_velocity_df", "replay_df", "duel_df"}
43
+ _INT_TICK_LISTS = {"replay_ticks", "freeze_ticks"}
44
+ _WINDOW_LISTS = {"duel_windows"} # list[tuple[start, end]]
45
+
46
+ # Inter-part gap, in seconds, inserted between segments so spans never touch.
47
+ _GAP_SECONDS = 8
48
+
49
+
50
+ def _round_of(row: dict[str, Any], is_end: bool) -> int:
51
+ """Actual round number for a round_* event from its total_rounds_played.
52
+
53
+ total_rounds_played at round_end == that round's number; at round_start /
54
+ round_freeze_end it is N-1 for round N. Mirrors cs2df.rounds._rn semantics.
55
+ """
56
+ trp = int(row.get("total_rounds_played") or 0)
57
+ return trp if is_end else trp + 1
58
+
59
+
60
+ def _max_tick(raw: dict[str, Any]) -> int:
61
+ """Largest tick observed in a part (used to compute the next part's offset)."""
62
+ cands = [0]
63
+ for key in ("round_ends", "round_freeze_ends", "grenade_throws"):
64
+ for row in raw.get(key) or []:
65
+ for tk in ("tick", "destroy_tick"):
66
+ v = row.get(tk)
67
+ if isinstance(v, (int, float)) and v > 0:
68
+ cands.append(int(v))
69
+ for key in _INT_TICK_LISTS:
70
+ cands.extend(int(t) for t in (raw.get(key) or []) if t)
71
+ for key in _DF_KEYS:
72
+ df = raw.get(key)
73
+ if df is not None and hasattr(df, "columns") and "tick" in getattr(df, "columns", []) and len(df):
74
+ cands.append(int(df["tick"].max()))
75
+ return max(cands)
76
+
77
+
78
+ def _shift_part(raw: dict[str, Any], off: int) -> None:
79
+ """Add ``off`` to every tick in ``raw`` in place (off == 0 → no-op)."""
80
+ if off == 0:
81
+ return
82
+ for key in _EVENT_LISTS:
83
+ for row in raw.get(key) or []:
84
+ for tk in _ROW_TICK_KEYS:
85
+ v = row.get(tk)
86
+ if isinstance(v, (int, float)) and v > 0:
87
+ row[tk] = int(v) + off
88
+ for key in _DF_KEYS:
89
+ df = raw.get(key)
90
+ if df is not None and hasattr(df, "columns") and "tick" in getattr(df, "columns", []):
91
+ df = df.copy()
92
+ df["tick"] = df["tick"] + off
93
+ raw[key] = df
94
+ for key in _INT_TICK_LISTS:
95
+ lst = raw.get(key)
96
+ if lst:
97
+ raw[key] = [int(t) + off for t in lst]
98
+ for key in _WINDOW_LISTS:
99
+ lst = raw.get(key)
100
+ if lst:
101
+ raw[key] = [(int(s) + off, int(e) + off) for s, e in lst]
102
+
103
+
104
+ def merge_raw(parts: list[dict[str, Any]]) -> dict[str, Any]:
105
+ """Merge per-part parse_demo() outputs into one (parts in play order)."""
106
+ if not parts:
107
+ raise ValueError("merge_raw: no parts")
108
+ if len(parts) == 1:
109
+ return parts[0]
110
+
111
+ # 1. shift each part past the previous parts' span.
112
+ running = 0
113
+ for part in parts:
114
+ _shift_part(part, running)
115
+ running += _max_tick(part) + part.get("tickrate", 64) * _GAP_SECONDS
116
+
117
+ # 1b. round ownership: a part only owns rounds past the previous parts'. When a
118
+ # GOTV recording resumes it re-emits a few warmup/restart round_* events with low
119
+ # total_rounds_played; those would collide in build_rounds' per-round tick maps
120
+ # (e.g. overwriting an earlier part's freeze tick and getting the seam round
121
+ # dropped as bogus). Drop each later part's round_* events for already-owned rounds.
122
+ prev_max = 0
123
+ for idx, part in enumerate(parts):
124
+ if idx > 0:
125
+ for key, is_end in (("round_ends", True), ("round_starts", False),
126
+ ("round_freeze_ends", False)):
127
+ rows = part.get(key) or []
128
+ part[key] = [r for r in rows if _round_of(r, is_end) > prev_max]
129
+ # Trim combat/effect residue captured before this part's first live round
130
+ # (a resume starts mid-freeze and re-emits seam events the previous part
131
+ # already owns). Threshold = first owned round's freeze-end tick.
132
+ freezes = [int(r.get("tick") or 0) for r in part.get("round_freeze_ends") or []
133
+ if int(r.get("tick") or 0) > 0]
134
+ trim_before = min(freezes) if freezes else 0
135
+ if trim_before > 0:
136
+ for key in _EVENT_LISTS - _ROUND_LISTS:
137
+ rows = part.get(key) or []
138
+ part[key] = [r for r in rows
139
+ if not (0 < int(r.get("tick") or 0) < trim_before)]
140
+ ends = part.get("round_ends") or []
141
+ if ends:
142
+ prev_max = max([prev_max] + [_round_of(r, True) for r in ends])
143
+
144
+ # 2. assemble the merged dict.
145
+ merged: dict[str, Any] = {}
146
+ base = parts[0]
147
+ for key in _META_FIRST:
148
+ if key in base:
149
+ merged[key] = base[key]
150
+
151
+ for key in _EVENT_LISTS:
152
+ out: list[Any] = []
153
+ for part in parts:
154
+ out.extend(part.get(key) or [])
155
+ merged[key] = out
156
+
157
+ import pandas as pd # lazy: native dep
158
+ for key in _DF_KEYS:
159
+ frames = [part[key] for part in parts
160
+ if part.get(key) is not None and len(part[key])]
161
+ merged[key] = pd.concat(frames, ignore_index=True) if frames else base.get(key)
162
+
163
+ for key in _INT_TICK_LISTS:
164
+ seen: set[int] = set()
165
+ for part in parts:
166
+ seen.update(int(t) for t in (part.get(key) or []))
167
+ merged[key] = sorted(seen)
168
+
169
+ for key in _WINDOW_LISTS:
170
+ out_w: list[Any] = []
171
+ for part in parts:
172
+ out_w.extend(part.get(key) or [])
173
+ merged[key] = out_w
174
+
175
+ return merged
176
+
177
+
178
+ def parse_and_merge(dem_paths: list[str], **parse_kwargs: Any) -> dict[str, Any]:
179
+ """Parse each part with parse_demo() and merge into one raw dict."""
180
+ from .parse import parse_demo
181
+ progress = parse_kwargs.pop("progress", None)
182
+ n = len(dem_paths)
183
+ parts: list[dict[str, Any]] = []
184
+ for i, path in enumerate(dem_paths):
185
+ def _scaled(stage: str, frac: float, _i=i) -> None:
186
+ if progress is not None:
187
+ progress(f"[part {_i + 1}/{n}] {stage}", (_i + frac) / n)
188
+ parts.append(parse_demo(path, progress=_scaled if progress else None, **parse_kwargs))
189
+ return merge_raw(parts)
@@ -65,6 +65,42 @@ def export_demo(dem_path: str, *, research: bool = False, sample_rate: int = 8,
65
65
  compress_level=compress_level)
66
66
 
67
67
 
68
+ def export_demo_merged(dem_paths: list[str], *, research: bool = False, sample_rate: int = 8,
69
+ window_before_ms: int = 2000, window_after_ms: int = 1000,
70
+ compress_level: int = 3,
71
+ progress: ProgressFn | None = None) -> tuple[bytes, dict]:
72
+ """Parse several split GOTV parts of ONE match, merge, and build a single ZIP.
73
+
74
+ Use for HLTV demos split into ``…-p1.dem`` / ``…-p2.dem``: ticks are reconciled
75
+ onto a global timeline so the package's per-match derivations stay coherent.
76
+ """
77
+ if len(dem_paths) == 1:
78
+ return export_demo(dem_paths[0], research=research, sample_rate=sample_rate,
79
+ window_before_ms=window_before_ms, window_after_ms=window_after_ms,
80
+ compress_level=compress_level, progress=progress)
81
+ from .merge import parse_and_merge
82
+
83
+ # Combined hash over all parts, in order, so the merged package has a stable id.
84
+ try:
85
+ h = hashlib.sha256()
86
+ for part in dem_paths:
87
+ h.update(_sha256_hex(part).encode("ascii"))
88
+ demo_hash: str | None = h.hexdigest()
89
+ except Exception:
90
+ demo_hash = None
91
+
92
+ scaled = (lambda stage, frac: progress(stage, frac * 0.9)) if progress else None
93
+ raw = parse_and_merge(list(dem_paths), sample_rate=sample_rate, research=research,
94
+ window_before_ms=window_before_ms,
95
+ window_after_ms=window_after_ms, progress=scaled)
96
+ if progress:
97
+ progress("build package", 0.92)
98
+ return build_package(raw, dem_paths[0], demo_hash,
99
+ window_before_ms=window_before_ms,
100
+ window_after_ms=window_after_ms,
101
+ compress_level=compress_level)
102
+
103
+
68
104
  def build_package(raw: dict[str, Any], dem_path: str, demo_hash: str | None, *,
69
105
  window_before_ms: int = 2000, window_after_ms: int = 1000,
70
106
  compress_level: int = 3) -> tuple[bytes, dict]:
@@ -0,0 +1,68 @@
1
+ from __future__ import annotations
2
+
3
+ from cs2df.merge import merge_raw
4
+
5
+
6
+ def _part(tickrate, round_ends, round_starts, round_freeze_ends, hurts):
7
+ return {
8
+ "tickrate": tickrate,
9
+ "round_ends": round_ends,
10
+ "round_starts": round_starts,
11
+ "round_freeze_ends": round_freeze_ends,
12
+ "hurts": hurts,
13
+ "deaths": [],
14
+ }
15
+
16
+
17
+ def test_merge_two_parts_keeps_seam_round_shifts_ticks_and_trims_residue():
18
+ # Part 0 owns rounds 1-2 (total_rounds_played: end == round number).
19
+ part0 = _part(
20
+ 64,
21
+ round_ends=[{"total_rounds_played": 1, "tick": 200},
22
+ {"total_rounds_played": 2, "tick": 460}],
23
+ round_starts=[{"total_rounds_played": 0, "tick": 50},
24
+ {"total_rounds_played": 1, "tick": 300}],
25
+ round_freeze_ends=[{"total_rounds_played": 0, "tick": 100},
26
+ {"total_rounds_played": 1, "tick": 360}],
27
+ hurts=[{"tick": 150}, {"tick": 400}],
28
+ )
29
+ # Part 1 owns rounds 3-4 with a LOCAL tick clock (restarts near 0) and resume
30
+ # residue: spurious low-trp round_* events (actual round 2, already owned) plus a
31
+ # phantom hurt at the very first tick.
32
+ part1 = _part(
33
+ 64,
34
+ round_ends=[{"total_rounds_played": 2, "tick": 1}, # spurious (round 2)
35
+ {"total_rounds_played": 3, "tick": 200},
36
+ {"total_rounds_played": 4, "tick": 460}],
37
+ round_starts=[{"total_rounds_played": 1, "tick": 2}, # spurious (round 2)
38
+ {"total_rounds_played": 2, "tick": 5},
39
+ {"total_rounds_played": 3, "tick": 300}],
40
+ round_freeze_ends=[{"total_rounds_played": 1, "tick": 3}, # spurious
41
+ {"total_rounds_played": 2, "tick": 60},
42
+ {"total_rounds_played": 3, "tick": 360}],
43
+ hurts=[{"tick": 4}, {"tick": 120}, {"tick": 400}], # tick 4 == resume residue
44
+ )
45
+
46
+ merged = merge_raw([part0, part1])
47
+
48
+ # Seam round 2 survives; rounds are 1..4 with no gap/duplicate.
49
+ end_rounds = [int(r["total_rounds_played"]) for r in merged["round_ends"]]
50
+ assert end_rounds == [1, 2, 3, 4]
51
+
52
+ # Round ticks are strictly monotonic across the seam (part 1 shifted past part 0).
53
+ end_ticks = [r["tick"] for r in merged["round_ends"]]
54
+ assert end_ticks == sorted(end_ticks) and len(set(end_ticks)) == len(end_ticks)
55
+ assert end_ticks[1] < end_ticks[2] # part0's round 2 < part1's round 3
56
+
57
+ # Resume residue (the tick-4 phantom hurt) is trimmed; the 4 real hurts remain.
58
+ assert len(merged["hurts"]) == 4
59
+ # No hurt sits in the dead gap between part0's last tick and part1's first live round.
60
+ assert all(h["tick"] <= 460 or h["tick"] >= end_ticks[1] for h in merged["hurts"])
61
+
62
+
63
+ def test_single_part_passthrough():
64
+ part = _part(64, [{"total_rounds_played": 1, "tick": 200}],
65
+ [{"total_rounds_played": 0, "tick": 50}],
66
+ [{"total_rounds_played": 0, "tick": 100}],
67
+ [{"tick": 150}])
68
+ assert merge_raw([part]) is part
@@ -30,7 +30,7 @@ wheels = [
30
30
 
31
31
  [[package]]
32
32
  name = "cs2df"
33
- version = "3.0.4"
33
+ version = "3.1.0"
34
34
  source = { editable = "." }
35
35
  dependencies = [
36
36
  { name = "demoparser2" },
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes