Improved parser that handles math symbols and spaces correctly
(file_path: str)
| 3 | import os |
| 4 | |
| 5 | def parse_generation_history(file_path: str) -> Dict[int, List[str]]: |
| 6 | """Improved parser that handles math symbols and spaces correctly""" |
| 7 | history = {} |
| 8 | token_pattern = re.compile(r"\*([^&]*)&?") |
| 9 | |
| 10 | with open(file_path, 'r', encoding='utf-8') as f: |
| 11 | for line in f: |
| 12 | line = line.strip() |
| 13 | if not line: |
| 14 | continue |
| 15 | |
| 16 | try: |
| 17 | step_part, content_part = line.split(',', 1) |
| 18 | step = int(step_part.strip()) |
| 19 | except ValueError: |
| 20 | continue |
| 21 | |
| 22 | tokens = [] |
| 23 | for match in token_pattern.finditer(content_part): |
| 24 | raw_token = match.group(1).strip() |
| 25 | |
| 26 | if raw_token == "": |
| 27 | tokens.append(" ") |
| 28 | elif raw_token == "*": |
| 29 | tokens.append("*") |
| 30 | else: |
| 31 | tokens.append(raw_token) |
| 32 | |
| 33 | while len(tokens) < 64: |
| 34 | tokens.append(" ") |
| 35 | |
| 36 | if len(tokens) > 64: |
| 37 | print(f"Truncating extra tokens: Step {step} ({len(tokens)} tokens)") |
| 38 | tokens = tokens[:64] |
| 39 | elif len(tokens) < 64: |
| 40 | print(f"Padding missing tokens: Step {step} ({len(tokens)} tokens)") |
| 41 | tokens += [" "] * (64 - len(tokens)) |
| 42 | |
| 43 | history[step] = tokens |
| 44 | |
| 45 | return history |
| 46 | |
| 47 | def track_token_positions(history: Dict[int, List[str]]) -> List[int]: |
| 48 | """Track the first generation step for each token""" |