# SPDX-FileCopyrightText: 2025 Stanford University, ETH Zurich, and the project authors (see CONTRIBUTORS.md) # SPDX-FileCopyrightText: 2025 This source file is part of the OpenTSLM open-source project. # # SPDX-License-Identifier: MIT import re import sys import io import base64 from typing import Dict, Any import matplotlib.pyplot as plt import numpy as np from common_evaluator_plot import CommonEvaluatorPlot from opentslm.time_series_datasets.sleep.SleepEDFCoTQADataset import SleepEDFCoTQADataset def extract_label_from_text(text: str) -> str: """ Extract the label from a free-form rationale or prediction text. - If 'Answer:' is present (case-insensitive), take everything after the last 'Answer:' - Otherwise, take the last word - Strip whitespace and trailing punctuation - Lowercase for comparison """ if text is None: return "" pred = text.strip() matches = list(re.finditer(r"answer:\s*", pred, re.IGNORECASE)) if matches: start = matches[-1].end() label = pred[start:].strip() else: label = pred.split()[-1] if pred.split() else "" label = re.sub(r"[\.,;:!?]+$", "", label) return label.lower() def evaluate_sleep_stage( ground_truth_text: str, prediction_text: str ) -> Dict[str, Any]: """ Evaluate SleepEDFCoTQADataset predictions against ground truth. For SleepEDF, the dataset's "answer" is a rationale ending with 'Answer: