File size: 149,711 Bytes
9f2fc5c
1
{"repo": "MinishLab/semhash", "n_pairs": 33, "version": "v3_compressed", "max_tokens": 6000, "contexts": {"tests/test_utils.py::14": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["make_hashable"], "enclosing_function": "test_make_hashable", "extracted_code": "# Source: semhash/utils.py\ndef make_hashable(value: Any) -> Any:\n    \"\"\"\n    Convert a value to a hashable representation for use as dict keys.\n\n    Strings and other hashable types are returned as-is.\n    Non-hashable types (like PIL images, numpy arrays) are hashed to a string.\n\n    :param value: The value to make hashable.\n    :return: A hashable representation of the value.\n    \"\"\"\n    # Fast path: most values are strings or already hashable\n    if isinstance(value, (str, int, float, bool, type(None))):\n        return value\n    # Handle objects with tobytes() (PIL Image, numpy array, etc.)\n    if hasattr(value, \"tobytes\"):\n        return hashlib.md5(value.tobytes()).hexdigest()\n    # Fallback: try to hash, otherwise stringify\n    try:\n        hash(value)\n        return value\n    except TypeError:\n        return str(value)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 837, "extracted_code_full": "# Source: semhash/utils.py\ndef make_hashable(value: Any) -> Any:\n    \"\"\"\n    Convert a value to a hashable representation for use as dict keys.\n\n    Strings and other hashable types are returned as-is.\n    Non-hashable types (like PIL images, numpy arrays) are hashed to a string.\n\n    :param value: The value to make hashable.\n    :return: A hashable representation of the value.\n    \"\"\"\n    # Fast path: most values are strings or already hashable\n    if isinstance(value, (str, int, float, bool, type(None))):\n        return value\n    # Handle objects with tobytes() (PIL Image, numpy array, etc.)\n    if hasattr(value, \"tobytes\"):\n        return hashlib.md5(value.tobytes()).hexdigest()\n    # Fallback: try to hash, otherwise stringify\n    try:\n        hash(value)\n        return value\n    except TypeError:\n        return str(value)", "n_chars_compressed": 837, "compression_ratio": 1.0}, "tests/test_utils.py::45": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["coerce_value"], "enclosing_function": "test_coerce_value", "extracted_code": "# Source: semhash/utils.py\ndef coerce_value(value: Any) -> Any:\n    \"\"\"\n    Coerce a value for encoding: stringify primitives, keep complex types raw.\n\n    This ensures primitives (int, float, bool) work with text encoders,\n    while complex types (PIL images, tensors, etc.) are passed through for multimodal encoders.\n\n    :param value: The value to coerce.\n    :return: The coerced value.\n    \"\"\"\n    if isinstance(value, (str, bytes)):\n        return value\n    if isinstance(value, (int, float, bool)):\n        return str(value)\n    return value", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 549, "extracted_code_full": "# Source: semhash/utils.py\ndef coerce_value(value: Any) -> Any:\n    \"\"\"\n    Coerce a value for encoding: stringify primitives, keep complex types raw.\n\n    This ensures primitives (int, float, bool) work with text encoders,\n    while complex types (PIL images, tensors, etc.) are passed through for multimodal encoders.\n\n    :param value: The value to coerce.\n    :return: The coerced value.\n    \"\"\"\n    if isinstance(value, (str, bytes)):\n        return value\n    if isinstance(value, (int, float, bool)):\n        return str(value)\n    return value", "n_chars_compressed": 549, "compression_ratio": 1.0}, "tests/test_utils.py::15": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["make_hashable"], "enclosing_function": "test_make_hashable", "extracted_code": "# Source: semhash/utils.py\ndef make_hashable(value: Any) -> Any:\n    \"\"\"\n    Convert a value to a hashable representation for use as dict keys.\n\n    Strings and other hashable types are returned as-is.\n    Non-hashable types (like PIL images, numpy arrays) are hashed to a string.\n\n    :param value: The value to make hashable.\n    :return: A hashable representation of the value.\n    \"\"\"\n    # Fast path: most values are strings or already hashable\n    if isinstance(value, (str, int, float, bool, type(None))):\n        return value\n    # Handle objects with tobytes() (PIL Image, numpy array, etc.)\n    if hasattr(value, \"tobytes\"):\n        return hashlib.md5(value.tobytes()).hexdigest()\n    # Fallback: try to hash, otherwise stringify\n    try:\n        hash(value)\n        return value\n    except TypeError:\n        return str(value)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 837, "extracted_code_full": "# Source: semhash/utils.py\ndef make_hashable(value: Any) -> Any:\n    \"\"\"\n    Convert a value to a hashable representation for use as dict keys.\n\n    Strings and other hashable types are returned as-is.\n    Non-hashable types (like PIL images, numpy arrays) are hashed to a string.\n\n    :param value: The value to make hashable.\n    :return: A hashable representation of the value.\n    \"\"\"\n    # Fast path: most values are strings or already hashable\n    if isinstance(value, (str, int, float, bool, type(None))):\n        return value\n    # Handle objects with tobytes() (PIL Image, numpy array, etc.)\n    if hasattr(value, \"tobytes\"):\n        return hashlib.md5(value.tobytes()).hexdigest()\n    # Fallback: try to hash, otherwise stringify\n    try:\n        hash(value)\n        return value\n    except TypeError:\n        return str(value)", "n_chars_compressed": 837, "compression_ratio": 1.0}, "tests/test_utils.py::117": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["remove_exact_duplicates"], "enclosing_function": "test_remove_exact_duplicates", "extracted_code": "# Source: semhash/records.py\ndef remove_exact_duplicates(\n    records: Sequence[dict[str, Any]],\n    columns: Sequence[str],\n    reference_records: list[list[dict[str, Any]]] | None = None,\n) -> tuple[list[dict[str, Any]], list[tuple[dict[str, Any], list[dict[str, Any]]]]]:\n    \"\"\"\n    Remove exact duplicates based on the hashable representation of each record.\n\n    If reference_records is None, the function will only check for duplicates within the records list.\n\n    :param records: A list of records to check for exact duplicates.\n    :param columns: Columns to unpack.\n    :param reference_records: A list of records to compare against. These are already unpacked\n    :return: A list of deduplicated records and a list of duplicates.\n    \"\"\"\n    deduplicated: list[dict[str, Any]] = []\n    duplicates: list[tuple[dict[str, Any], list[dict[str, Any]]]] = []\n\n    column_set = set(columns)\n\n    # Build seen set from reference_records (cross-dataset mode) or empty (single-dataset mode)\n    seen: defaultdict[frozendict[str, Any], list[dict[str, Any]]] = defaultdict(list)\n    if reference_records is not None:\n        for record_set in reference_records:\n            key = to_frozendict(record_set[0], column_set)\n            seen[key] = list(record_set)\n\n    for record in records:\n        frozen_record = to_frozendict(record, column_set)\n        if duplicated_records := seen.get(frozen_record):\n            duplicates.append((record, duplicated_records))\n        else:\n            deduplicated.append(record)\n            # Single-dataset mode: track this record for future comparisons\n            if reference_records is None:\n                seen[frozen_record].append(record)\n\n    return deduplicated, duplicates", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1725, "extracted_code_full": "# Source: semhash/records.py\ndef remove_exact_duplicates(\n    records: Sequence[dict[str, Any]],\n    columns: Sequence[str],\n    reference_records: list[list[dict[str, Any]]] | None = None,\n) -> tuple[list[dict[str, Any]], list[tuple[dict[str, Any], list[dict[str, Any]]]]]:\n    \"\"\"\n    Remove exact duplicates based on the hashable representation of each record.\n\n    If reference_records is None, the function will only check for duplicates within the records list.\n\n    :param records: A list of records to check for exact duplicates.\n    :param columns: Columns to unpack.\n    :param reference_records: A list of records to compare against. These are already unpacked\n    :return: A list of deduplicated records and a list of duplicates.\n    \"\"\"\n    deduplicated: list[dict[str, Any]] = []\n    duplicates: list[tuple[dict[str, Any], list[dict[str, Any]]]] = []\n\n    column_set = set(columns)\n\n    # Build seen set from reference_records (cross-dataset mode) or empty (single-dataset mode)\n    seen: defaultdict[frozendict[str, Any], list[dict[str, Any]]] = defaultdict(list)\n    if reference_records is not None:\n        for record_set in reference_records:\n            key = to_frozendict(record_set[0], column_set)\n            seen[key] = list(record_set)\n\n    for record in records:\n        frozen_record = to_frozendict(record, column_set)\n        if duplicated_records := seen.get(frozen_record):\n            duplicates.append((record, duplicated_records))\n        else:\n            deduplicated.append(record)\n            # Single-dataset mode: track this record for future comparisons\n            if reference_records is None:\n                seen[frozen_record].append(record)\n\n    return deduplicated, duplicates", "n_chars_compressed": 1725, "compression_ratio": 1.0}, "tests/test_datamodels.py::42": {"resolved_imports": ["semhash/datamodels.py"], "used_names": ["DuplicateRecord"], "enclosing_function": "test_rethreshold", "extracted_code": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 666, "extracted_code_full": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]", "n_chars_compressed": 666, "compression_ratio": 1.0}, "tests/test_utils.py::81": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["compute_candidate_limit"], "enclosing_function": "test_compute_candidate_limit", "extracted_code": "# Source: semhash/utils.py\ndef compute_candidate_limit(\n    total: int,\n    selection_size: int,\n    fraction: float = 0.1,\n    min_candidates: int = 100,\n    max_candidates: int = 1000,\n) -> int:\n    \"\"\"\n    Compute the 'auto' candidate limit based on the total number of records.\n\n    :param total: Total number of records.\n    :param selection_size: Number of representatives to select.\n    :param fraction: Fraction of total records to consider as candidates.\n    :param min_candidates: Minimum number of candidates.\n    :param max_candidates: Maximum number of candidates.\n    :return: Computed candidate limit.\n    \"\"\"\n    # 1) fraction of total\n    limit = int(total * fraction)\n    # 2) ensure enough to pick selection_size\n    limit = max(limit, selection_size)\n    # 3) enforce lower bound\n    limit = max(limit, min_candidates)\n    # 4) enforce upper bound (and never exceed the dataset)\n    limit = min(limit, max_candidates, total)\n    return limit", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 961, "extracted_code_full": "# Source: semhash/utils.py\ndef compute_candidate_limit(\n    total: int,\n    selection_size: int,\n    fraction: float = 0.1,\n    min_candidates: int = 100,\n    max_candidates: int = 1000,\n) -> int:\n    \"\"\"\n    Compute the 'auto' candidate limit based on the total number of records.\n\n    :param total: Total number of records.\n    :param selection_size: Number of representatives to select.\n    :param fraction: Fraction of total records to consider as candidates.\n    :param min_candidates: Minimum number of candidates.\n    :param max_candidates: Maximum number of candidates.\n    :return: Computed candidate limit.\n    \"\"\"\n    # 1) fraction of total\n    limit = int(total * fraction)\n    # 2) ensure enough to pick selection_size\n    limit = max(limit, selection_size)\n    # 3) enforce lower bound\n    limit = max(limit, min_candidates)\n    # 4) enforce upper bound (and never exceed the dataset)\n    limit = min(limit, max_candidates, total)\n    return limit", "n_chars_compressed": 961, "compression_ratio": 1.0}, "tests/test_datamodels.py::123": {"resolved_imports": ["semhash/datamodels.py"], "used_names": ["DeduplicationResult", "DuplicateRecord"], "enclosing_function": "test_selected_with_duplicates_dicts", "extracted_code": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4987, "extracted_code_full": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_chars_compressed": 4987, "compression_ratio": 1.0}, "tests/test_utils.py::44": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["coerce_value"], "enclosing_function": "test_coerce_value", "extracted_code": "# Source: semhash/utils.py\ndef coerce_value(value: Any) -> Any:\n    \"\"\"\n    Coerce a value for encoding: stringify primitives, keep complex types raw.\n\n    This ensures primitives (int, float, bool) work with text encoders,\n    while complex types (PIL images, tensors, etc.) are passed through for multimodal encoders.\n\n    :param value: The value to coerce.\n    :return: The coerced value.\n    \"\"\"\n    if isinstance(value, (str, bytes)):\n        return value\n    if isinstance(value, (int, float, bool)):\n        return str(value)\n    return value", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 549, "extracted_code_full": "# Source: semhash/utils.py\ndef coerce_value(value: Any) -> Any:\n    \"\"\"\n    Coerce a value for encoding: stringify primitives, keep complex types raw.\n\n    This ensures primitives (int, float, bool) work with text encoders,\n    while complex types (PIL images, tensors, etc.) are passed through for multimodal encoders.\n\n    :param value: The value to coerce.\n    :return: The coerced value.\n    \"\"\"\n    if isinstance(value, (str, bytes)):\n        return value\n    if isinstance(value, (int, float, bool)):\n        return str(value)\n    return value", "n_chars_compressed": 549, "compression_ratio": 1.0}, "tests/test_semhash.py::57": {"resolved_imports": ["semhash/__init__.py", "semhash/datamodels.py", "semhash/utils.py"], "used_names": ["Encoder", "SemHash"], "enclosing_function": "test_multi_dataset_deduplication", "extracted_code": "# Source: semhash/__init__.py\nfrom pyversity import Strategy\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\n\n# Source: semhash/utils.py\nclass Encoder(Protocol):\n    \"\"\"An encoder protocol for SemHash. Supports text, images, or any encodable data.\"\"\"\n\n    def encode(\n        self,\n        inputs: Sequence[Any] | Any,\n        **kwargs: Any,\n    ) -> np.ndarray:\n        \"\"\"\n        Encode a list of inputs into embeddings.\n\n        :param inputs: A list of inputs to encode (strings, images, etc.).\n        :param **kwargs: Additional keyword arguments.\n        :return: The embeddings of the inputs.\n        \"\"\"\n        ...", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 722, "extracted_code_full": "# Source: semhash/__init__.py\nfrom pyversity import Strategy\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\n\n# Source: semhash/utils.py\nclass Encoder(Protocol):\n    \"\"\"An encoder protocol for SemHash. Supports text, images, or any encodable data.\"\"\"\n\n    def encode(\n        self,\n        inputs: Sequence[Any] | Any,\n        **kwargs: Any,\n    ) -> np.ndarray:\n        \"\"\"\n        Encode a list of inputs into embeddings.\n\n        :param inputs: A list of inputs to encode (strings, images, etc.).\n        :param **kwargs: Additional keyword arguments.\n        :return: The embeddings of the inputs.\n        \"\"\"\n        ...", "n_chars_compressed": 722, "compression_ratio": 1.0}, "tests/test_utils.py::151": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["prepare_records", "pytest"], "enclosing_function": "test_prepare_records", "extracted_code": "# Source: semhash/records.py\ndef prepare_records(\n    records: Sequence[Record], columns: Sequence[str] | None\n) -> tuple[list[dict[str, Any]], Sequence[str], bool]:\n    \"\"\"\n    Validate and prepare records for processing.\n\n    :param records: A list of records (strings or dictionaries).\n    :param columns: Columns to use if records are dictionaries.\n    :return: Tuple of (dict_records, columns, was_string).\n    :raises ValueError: If records are empty.\n    :raises ValueError: If columns are not provided for dictionary records.\n    :raises ValueError: If dict record contains None values.\n    :raises ValueError: If records are not homogeneous (mixed strings and dicts).\n    \"\"\"\n    if len(records) == 0:\n        raise ValueError(\"records must not be empty\")\n\n    if columns is None and isinstance(records[0], dict):\n        raise ValueError(\"Columns must be specified when passing dictionaries.\")\n\n    # String path: convert to dicts with \"text\" column\n    if isinstance(records[0], str):\n        if not all(isinstance(r, str) for r in records):\n            raise ValueError(\"All records must be strings when the first record is a string.\")\n        columns = [\"text\"]\n        dict_records: list[dict[str, Any]] = [{\"text\": record} for record in records]\n        was_string = True\n    # Dict path: validate and coerce values\n    else:\n        if not all(isinstance(r, dict) for r in records):\n            raise ValueError(\"All records must be dicts when the first record is a dict.\")\n        assert columns is not None\n\n        # Coerce values: stringify primitives, keep complex types raw (for images, etc.)\n        dict_records_typed: list[dict[str, Any]] = list(records)\n        dict_records = []\n        for record in dict_records_typed:\n            # Start with a copy of the full record to preserve non-embedding fields\n            coerced: dict[str, Any] = dict(record)\n            # Then coerce only the embedding columns\n            for column in columns:\n                val = record.get(column)\n                if val is None:\n                    raise ValueError(f\"Column '{column}' has None value in record {record}\")\n                coerced[column] = coerce_value(val)\n            dict_records.append(coerced)\n        was_string = False\n\n    return dict_records, columns, was_string", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2302, "extracted_code_full": "# Source: semhash/records.py\ndef prepare_records(\n    records: Sequence[Record], columns: Sequence[str] | None\n) -> tuple[list[dict[str, Any]], Sequence[str], bool]:\n    \"\"\"\n    Validate and prepare records for processing.\n\n    :param records: A list of records (strings or dictionaries).\n    :param columns: Columns to use if records are dictionaries.\n    :return: Tuple of (dict_records, columns, was_string).\n    :raises ValueError: If records are empty.\n    :raises ValueError: If columns are not provided for dictionary records.\n    :raises ValueError: If dict record contains None values.\n    :raises ValueError: If records are not homogeneous (mixed strings and dicts).\n    \"\"\"\n    if len(records) == 0:\n        raise ValueError(\"records must not be empty\")\n\n    if columns is None and isinstance(records[0], dict):\n        raise ValueError(\"Columns must be specified when passing dictionaries.\")\n\n    # String path: convert to dicts with \"text\" column\n    if isinstance(records[0], str):\n        if not all(isinstance(r, str) for r in records):\n            raise ValueError(\"All records must be strings when the first record is a string.\")\n        columns = [\"text\"]\n        dict_records: list[dict[str, Any]] = [{\"text\": record} for record in records]\n        was_string = True\n    # Dict path: validate and coerce values\n    else:\n        if not all(isinstance(r, dict) for r in records):\n            raise ValueError(\"All records must be dicts when the first record is a dict.\")\n        assert columns is not None\n\n        # Coerce values: stringify primitives, keep complex types raw (for images, etc.)\n        dict_records_typed: list[dict[str, Any]] = list(records)\n        dict_records = []\n        for record in dict_records_typed:\n            # Start with a copy of the full record to preserve non-embedding fields\n            coerced: dict[str, Any] = dict(record)\n            # Then coerce only the embedding columns\n            for column in columns:\n                val = record.get(column)\n                if val is None:\n                    raise ValueError(f\"Column '{column}' has None value in record {record}\")\n                coerced[column] = coerce_value(val)\n            dict_records.append(coerced)\n        was_string = False\n\n    return dict_records, columns, was_string", "n_chars_compressed": 2302, "compression_ratio": 1.0}, "tests/test_datamodels.py::224": {"resolved_imports": ["semhash/datamodels.py"], "used_names": ["DeduplicationResult", "DuplicateRecord"], "enclosing_function": "test_selected_with_duplicates_cache_invalidation_on_rethreshold", "extracted_code": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4987, "extracted_code_full": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_chars_compressed": 4987, "compression_ratio": 1.0}, "tests/test_utils.py::53": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["coerce_value"], "enclosing_function": "test_coerce_value", "extracted_code": "# Source: semhash/utils.py\ndef coerce_value(value: Any) -> Any:\n    \"\"\"\n    Coerce a value for encoding: stringify primitives, keep complex types raw.\n\n    This ensures primitives (int, float, bool) work with text encoders,\n    while complex types (PIL images, tensors, etc.) are passed through for multimodal encoders.\n\n    :param value: The value to coerce.\n    :return: The coerced value.\n    \"\"\"\n    if isinstance(value, (str, bytes)):\n        return value\n    if isinstance(value, (int, float, bool)):\n        return str(value)\n    return value", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 549, "extracted_code_full": "# Source: semhash/utils.py\ndef coerce_value(value: Any) -> Any:\n    \"\"\"\n    Coerce a value for encoding: stringify primitives, keep complex types raw.\n\n    This ensures primitives (int, float, bool) work with text encoders,\n    while complex types (PIL images, tensors, etc.) are passed through for multimodal encoders.\n\n    :param value: The value to coerce.\n    :return: The coerced value.\n    \"\"\"\n    if isinstance(value, (str, bytes)):\n        return value\n    if isinstance(value, (int, float, bool)):\n        return str(value)\n    return value", "n_chars_compressed": 549, "compression_ratio": 1.0}, "tests/test_datamodels.py::29": {"resolved_imports": ["semhash/datamodels.py"], "used_names": ["DeduplicationResult"], "enclosing_function": "test_deduplication_scoring_empty", "extracted_code": "# Source: semhash/datamodels.py\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4351, "extracted_code_full": "# Source: semhash/datamodels.py\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_chars_compressed": 4351, "compression_ratio": 1.0}, "tests/test_utils.py::79": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["compute_candidate_limit"], "enclosing_function": "test_compute_candidate_limit", "extracted_code": "# Source: semhash/utils.py\ndef compute_candidate_limit(\n    total: int,\n    selection_size: int,\n    fraction: float = 0.1,\n    min_candidates: int = 100,\n    max_candidates: int = 1000,\n) -> int:\n    \"\"\"\n    Compute the 'auto' candidate limit based on the total number of records.\n\n    :param total: Total number of records.\n    :param selection_size: Number of representatives to select.\n    :param fraction: Fraction of total records to consider as candidates.\n    :param min_candidates: Minimum number of candidates.\n    :param max_candidates: Maximum number of candidates.\n    :return: Computed candidate limit.\n    \"\"\"\n    # 1) fraction of total\n    limit = int(total * fraction)\n    # 2) ensure enough to pick selection_size\n    limit = max(limit, selection_size)\n    # 3) enforce lower bound\n    limit = max(limit, min_candidates)\n    # 4) enforce upper bound (and never exceed the dataset)\n    limit = min(limit, max_candidates, total)\n    return limit", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 961, "extracted_code_full": "# Source: semhash/utils.py\ndef compute_candidate_limit(\n    total: int,\n    selection_size: int,\n    fraction: float = 0.1,\n    min_candidates: int = 100,\n    max_candidates: int = 1000,\n) -> int:\n    \"\"\"\n    Compute the 'auto' candidate limit based on the total number of records.\n\n    :param total: Total number of records.\n    :param selection_size: Number of representatives to select.\n    :param fraction: Fraction of total records to consider as candidates.\n    :param min_candidates: Minimum number of candidates.\n    :param max_candidates: Maximum number of candidates.\n    :return: Computed candidate limit.\n    \"\"\"\n    # 1) fraction of total\n    limit = int(total * fraction)\n    # 2) ensure enough to pick selection_size\n    limit = max(limit, selection_size)\n    # 3) enforce lower bound\n    limit = max(limit, min_candidates)\n    # 4) enforce upper bound (and never exceed the dataset)\n    limit = min(limit, max_candidates, total)\n    return limit", "n_chars_compressed": 961, "compression_ratio": 1.0}, "tests/test_utils.py::26": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["make_hashable"], "enclosing_function": "test_make_hashable", "extracted_code": "# Source: semhash/utils.py\ndef make_hashable(value: Any) -> Any:\n    \"\"\"\n    Convert a value to a hashable representation for use as dict keys.\n\n    Strings and other hashable types are returned as-is.\n    Non-hashable types (like PIL images, numpy arrays) are hashed to a string.\n\n    :param value: The value to make hashable.\n    :return: A hashable representation of the value.\n    \"\"\"\n    # Fast path: most values are strings or already hashable\n    if isinstance(value, (str, int, float, bool, type(None))):\n        return value\n    # Handle objects with tobytes() (PIL Image, numpy array, etc.)\n    if hasattr(value, \"tobytes\"):\n        return hashlib.md5(value.tobytes()).hexdigest()\n    # Fallback: try to hash, otherwise stringify\n    try:\n        hash(value)\n        return value\n    except TypeError:\n        return str(value)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 837, "extracted_code_full": "# Source: semhash/utils.py\ndef make_hashable(value: Any) -> Any:\n    \"\"\"\n    Convert a value to a hashable representation for use as dict keys.\n\n    Strings and other hashable types are returned as-is.\n    Non-hashable types (like PIL images, numpy arrays) are hashed to a string.\n\n    :param value: The value to make hashable.\n    :return: A hashable representation of the value.\n    \"\"\"\n    # Fast path: most values are strings or already hashable\n    if isinstance(value, (str, int, float, bool, type(None))):\n        return value\n    # Handle objects with tobytes() (PIL Image, numpy array, etc.)\n    if hasattr(value, \"tobytes\"):\n        return hashlib.md5(value.tobytes()).hexdigest()\n    # Fallback: try to hash, otherwise stringify\n    try:\n        hash(value)\n        return value\n    except TypeError:\n        return str(value)", "n_chars_compressed": 837, "compression_ratio": 1.0}, "tests/test_utils.py::46": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["coerce_value"], "enclosing_function": "test_coerce_value", "extracted_code": "# Source: semhash/utils.py\ndef coerce_value(value: Any) -> Any:\n    \"\"\"\n    Coerce a value for encoding: stringify primitives, keep complex types raw.\n\n    This ensures primitives (int, float, bool) work with text encoders,\n    while complex types (PIL images, tensors, etc.) are passed through for multimodal encoders.\n\n    :param value: The value to coerce.\n    :return: The coerced value.\n    \"\"\"\n    if isinstance(value, (str, bytes)):\n        return value\n    if isinstance(value, (int, float, bool)):\n        return str(value)\n    return value", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 549, "extracted_code_full": "# Source: semhash/utils.py\ndef coerce_value(value: Any) -> Any:\n    \"\"\"\n    Coerce a value for encoding: stringify primitives, keep complex types raw.\n\n    This ensures primitives (int, float, bool) work with text encoders,\n    while complex types (PIL images, tensors, etc.) are passed through for multimodal encoders.\n\n    :param value: The value to coerce.\n    :return: The coerced value.\n    \"\"\"\n    if isinstance(value, (str, bytes)):\n        return value\n    if isinstance(value, (int, float, bool)):\n        return str(value)\n    return value", "n_chars_compressed": 549, "compression_ratio": 1.0}, "tests/test_utils.py::63": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["frozendict", "pytest", "to_frozendict"], "enclosing_function": "test_to_frozendict", "extracted_code": "# Source: semhash/utils.py\ndef to_frozendict(record: dict[str, Any], columns: Sequence[str] | set[str]) -> frozendict[str, Any]:\n    \"\"\"\n    Convert a record to a frozendict with hashable values.\n\n    :param record: The record to convert.\n    :param columns: The columns to include.\n    :return: A frozendict with only the specified columns (values made hashable).\n    :raises ValueError: If a column is missing from the record.\n    \"\"\"\n    try:\n        return frozendict({k: make_hashable(record[k]) for k in columns})\n    except KeyError as e:\n        missing = e.args[0]\n        raise ValueError(f\"Missing column '{missing}' in record {record}\") from e", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 655, "extracted_code_full": "# Source: semhash/utils.py\ndef to_frozendict(record: dict[str, Any], columns: Sequence[str] | set[str]) -> frozendict[str, Any]:\n    \"\"\"\n    Convert a record to a frozendict with hashable values.\n\n    :param record: The record to convert.\n    :param columns: The columns to include.\n    :return: A frozendict with only the specified columns (values made hashable).\n    :raises ValueError: If a column is missing from the record.\n    \"\"\"\n    try:\n        return frozendict({k: make_hashable(record[k]) for k in columns})\n    except KeyError as e:\n        missing = e.args[0]\n        raise ValueError(f\"Missing column '{missing}' in record {record}\") from e", "n_chars_compressed": 655, "compression_ratio": 1.0}, "tests/test_utils.py::77": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["compute_candidate_limit"], "enclosing_function": "test_compute_candidate_limit", "extracted_code": "# Source: semhash/utils.py\ndef compute_candidate_limit(\n    total: int,\n    selection_size: int,\n    fraction: float = 0.1,\n    min_candidates: int = 100,\n    max_candidates: int = 1000,\n) -> int:\n    \"\"\"\n    Compute the 'auto' candidate limit based on the total number of records.\n\n    :param total: Total number of records.\n    :param selection_size: Number of representatives to select.\n    :param fraction: Fraction of total records to consider as candidates.\n    :param min_candidates: Minimum number of candidates.\n    :param max_candidates: Maximum number of candidates.\n    :return: Computed candidate limit.\n    \"\"\"\n    # 1) fraction of total\n    limit = int(total * fraction)\n    # 2) ensure enough to pick selection_size\n    limit = max(limit, selection_size)\n    # 3) enforce lower bound\n    limit = max(limit, min_candidates)\n    # 4) enforce upper bound (and never exceed the dataset)\n    limit = min(limit, max_candidates, total)\n    return limit", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 961, "extracted_code_full": "# Source: semhash/utils.py\ndef compute_candidate_limit(\n    total: int,\n    selection_size: int,\n    fraction: float = 0.1,\n    min_candidates: int = 100,\n    max_candidates: int = 1000,\n) -> int:\n    \"\"\"\n    Compute the 'auto' candidate limit based on the total number of records.\n\n    :param total: Total number of records.\n    :param selection_size: Number of representatives to select.\n    :param fraction: Fraction of total records to consider as candidates.\n    :param min_candidates: Minimum number of candidates.\n    :param max_candidates: Maximum number of candidates.\n    :return: Computed candidate limit.\n    \"\"\"\n    # 1) fraction of total\n    limit = int(total * fraction)\n    # 2) ensure enough to pick selection_size\n    limit = max(limit, selection_size)\n    # 3) enforce lower bound\n    limit = max(limit, min_candidates)\n    # 4) enforce upper bound (and never exceed the dataset)\n    limit = min(limit, max_candidates, total)\n    return limit", "n_chars_compressed": 961, "compression_ratio": 1.0}, "tests/test_utils.py::13": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["make_hashable"], "enclosing_function": "test_make_hashable", "extracted_code": "# Source: semhash/utils.py\ndef make_hashable(value: Any) -> Any:\n    \"\"\"\n    Convert a value to a hashable representation for use as dict keys.\n\n    Strings and other hashable types are returned as-is.\n    Non-hashable types (like PIL images, numpy arrays) are hashed to a string.\n\n    :param value: The value to make hashable.\n    :return: A hashable representation of the value.\n    \"\"\"\n    # Fast path: most values are strings or already hashable\n    if isinstance(value, (str, int, float, bool, type(None))):\n        return value\n    # Handle objects with tobytes() (PIL Image, numpy array, etc.)\n    if hasattr(value, \"tobytes\"):\n        return hashlib.md5(value.tobytes()).hexdigest()\n    # Fallback: try to hash, otherwise stringify\n    try:\n        hash(value)\n        return value\n    except TypeError:\n        return str(value)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 837, "extracted_code_full": "# Source: semhash/utils.py\ndef make_hashable(value: Any) -> Any:\n    \"\"\"\n    Convert a value to a hashable representation for use as dict keys.\n\n    Strings and other hashable types are returned as-is.\n    Non-hashable types (like PIL images, numpy arrays) are hashed to a string.\n\n    :param value: The value to make hashable.\n    :return: A hashable representation of the value.\n    \"\"\"\n    # Fast path: most values are strings or already hashable\n    if isinstance(value, (str, int, float, bool, type(None))):\n        return value\n    # Handle objects with tobytes() (PIL Image, numpy array, etc.)\n    if hasattr(value, \"tobytes\"):\n        return hashlib.md5(value.tobytes()).hexdigest()\n    # Fallback: try to hash, otherwise stringify\n    try:\n        hash(value)\n        return value\n    except TypeError:\n        return str(value)", "n_chars_compressed": 837, "compression_ratio": 1.0}, "tests/test_datamodels.py::207": {"resolved_imports": ["semhash/datamodels.py"], "used_names": ["DeduplicationResult", "DuplicateRecord"], "enclosing_function": "test_selected_with_duplicates_caching", "extracted_code": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4987, "extracted_code_full": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_chars_compressed": 4987, "compression_ratio": 1.0}, "tests/test_semhash.py::331": {"resolved_imports": ["semhash/__init__.py", "semhash/datamodels.py", "semhash/utils.py"], "used_names": ["Encoder", "SemHash"], "enclosing_function": "test_preserve_non_embedding_fields", "extracted_code": "# Source: semhash/__init__.py\nfrom pyversity import Strategy\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\n\n# Source: semhash/utils.py\nclass Encoder(Protocol):\n    \"\"\"An encoder protocol for SemHash. Supports text, images, or any encodable data.\"\"\"\n\n    def encode(\n        self,\n        inputs: Sequence[Any] | Any,\n        **kwargs: Any,\n    ) -> np.ndarray:\n        \"\"\"\n        Encode a list of inputs into embeddings.\n\n        :param inputs: A list of inputs to encode (strings, images, etc.).\n        :param **kwargs: Additional keyword arguments.\n        :return: The embeddings of the inputs.\n        \"\"\"\n        ...", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 722, "extracted_code_full": "# Source: semhash/__init__.py\nfrom pyversity import Strategy\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\n\n# Source: semhash/utils.py\nclass Encoder(Protocol):\n    \"\"\"An encoder protocol for SemHash. Supports text, images, or any encodable data.\"\"\"\n\n    def encode(\n        self,\n        inputs: Sequence[Any] | Any,\n        **kwargs: Any,\n    ) -> np.ndarray:\n        \"\"\"\n        Encode a list of inputs into embeddings.\n\n        :param inputs: A list of inputs to encode (strings, images, etc.).\n        :param **kwargs: Additional keyword arguments.\n        :return: The embeddings of the inputs.\n        \"\"\"\n        ...", "n_chars_compressed": 722, "compression_ratio": 1.0}, "tests/test_semhash.py::183": {"resolved_imports": ["semhash/__init__.py", "semhash/datamodels.py", "semhash/utils.py"], "used_names": ["Encoder", "SemHash", "pytest"], "enclosing_function": "test_filter_outliers", "extracted_code": "# Source: semhash/__init__.py\nfrom pyversity import Strategy\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\n\n# Source: semhash/utils.py\nclass Encoder(Protocol):\n    \"\"\"An encoder protocol for SemHash. Supports text, images, or any encodable data.\"\"\"\n\n    def encode(\n        self,\n        inputs: Sequence[Any] | Any,\n        **kwargs: Any,\n    ) -> np.ndarray:\n        \"\"\"\n        Encode a list of inputs into embeddings.\n\n        :param inputs: A list of inputs to encode (strings, images, etc.).\n        :param **kwargs: Additional keyword arguments.\n        :return: The embeddings of the inputs.\n        \"\"\"\n        ...", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 722, "extracted_code_full": "# Source: semhash/__init__.py\nfrom pyversity import Strategy\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\n\n# Source: semhash/utils.py\nclass Encoder(Protocol):\n    \"\"\"An encoder protocol for SemHash. Supports text, images, or any encodable data.\"\"\"\n\n    def encode(\n        self,\n        inputs: Sequence[Any] | Any,\n        **kwargs: Any,\n    ) -> np.ndarray:\n        \"\"\"\n        Encode a list of inputs into embeddings.\n\n        :param inputs: A list of inputs to encode (strings, images, etc.).\n        :param **kwargs: Additional keyword arguments.\n        :return: The embeddings of the inputs.\n        \"\"\"\n        ...", "n_chars_compressed": 722, "compression_ratio": 1.0}, "tests/test_semhash.py::333": {"resolved_imports": ["semhash/__init__.py", "semhash/datamodels.py", "semhash/utils.py"], "used_names": ["Encoder", "SemHash"], "enclosing_function": "test_preserve_non_embedding_fields", "extracted_code": "# Source: semhash/__init__.py\nfrom pyversity import Strategy\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\n\n# Source: semhash/utils.py\nclass Encoder(Protocol):\n    \"\"\"An encoder protocol for SemHash. Supports text, images, or any encodable data.\"\"\"\n\n    def encode(\n        self,\n        inputs: Sequence[Any] | Any,\n        **kwargs: Any,\n    ) -> np.ndarray:\n        \"\"\"\n        Encode a list of inputs into embeddings.\n\n        :param inputs: A list of inputs to encode (strings, images, etc.).\n        :param **kwargs: Additional keyword arguments.\n        :return: The embeddings of the inputs.\n        \"\"\"\n        ...", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 722, "extracted_code_full": "# Source: semhash/__init__.py\nfrom pyversity import Strategy\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\n\n# Source: semhash/utils.py\nclass Encoder(Protocol):\n    \"\"\"An encoder protocol for SemHash. Supports text, images, or any encodable data.\"\"\"\n\n    def encode(\n        self,\n        inputs: Sequence[Any] | Any,\n        **kwargs: Any,\n    ) -> np.ndarray:\n        \"\"\"\n        Encode a list of inputs into embeddings.\n\n        :param inputs: A list of inputs to encode (strings, images, etc.).\n        :param **kwargs: Additional keyword arguments.\n        :return: The embeddings of the inputs.\n        \"\"\"\n        ...", "n_chars_compressed": 722, "compression_ratio": 1.0}, "tests/test_datamodels.py::127": {"resolved_imports": ["semhash/datamodels.py"], "used_names": ["DeduplicationResult", "DuplicateRecord"], "enclosing_function": "test_selected_with_duplicates_dicts", "extracted_code": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4987, "extracted_code_full": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_chars_compressed": 4987, "compression_ratio": 1.0}, "tests/test_semhash.py::147": {"resolved_imports": ["semhash/__init__.py", "semhash/datamodels.py", "semhash/utils.py"], "used_names": ["Encoder", "SemHash"], "enclosing_function": "test_self_find_representative", "extracted_code": "# Source: semhash/__init__.py\nfrom pyversity import Strategy\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\n\n# Source: semhash/utils.py\nclass Encoder(Protocol):\n    \"\"\"An encoder protocol for SemHash. Supports text, images, or any encodable data.\"\"\"\n\n    def encode(\n        self,\n        inputs: Sequence[Any] | Any,\n        **kwargs: Any,\n    ) -> np.ndarray:\n        \"\"\"\n        Encode a list of inputs into embeddings.\n\n        :param inputs: A list of inputs to encode (strings, images, etc.).\n        :param **kwargs: Additional keyword arguments.\n        :return: The embeddings of the inputs.\n        \"\"\"\n        ...", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 722, "extracted_code_full": "# Source: semhash/__init__.py\nfrom pyversity import Strategy\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\n\n# Source: semhash/utils.py\nclass Encoder(Protocol):\n    \"\"\"An encoder protocol for SemHash. Supports text, images, or any encodable data.\"\"\"\n\n    def encode(\n        self,\n        inputs: Sequence[Any] | Any,\n        **kwargs: Any,\n    ) -> np.ndarray:\n        \"\"\"\n        Encode a list of inputs into embeddings.\n\n        :param inputs: A list of inputs to encode (strings, images, etc.).\n        :param **kwargs: Additional keyword arguments.\n        :return: The embeddings of the inputs.\n        \"\"\"\n        ...", "n_chars_compressed": 722, "compression_ratio": 1.0}, "tests/test_utils.py::118": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["remove_exact_duplicates"], "enclosing_function": "test_remove_exact_duplicates", "extracted_code": "# Source: semhash/records.py\ndef remove_exact_duplicates(\n    records: Sequence[dict[str, Any]],\n    columns: Sequence[str],\n    reference_records: list[list[dict[str, Any]]] | None = None,\n) -> tuple[list[dict[str, Any]], list[tuple[dict[str, Any], list[dict[str, Any]]]]]:\n    \"\"\"\n    Remove exact duplicates based on the hashable representation of each record.\n\n    If reference_records is None, the function will only check for duplicates within the records list.\n\n    :param records: A list of records to check for exact duplicates.\n    :param columns: Columns to unpack.\n    :param reference_records: A list of records to compare against. These are already unpacked\n    :return: A list of deduplicated records and a list of duplicates.\n    \"\"\"\n    deduplicated: list[dict[str, Any]] = []\n    duplicates: list[tuple[dict[str, Any], list[dict[str, Any]]]] = []\n\n    column_set = set(columns)\n\n    # Build seen set from reference_records (cross-dataset mode) or empty (single-dataset mode)\n    seen: defaultdict[frozendict[str, Any], list[dict[str, Any]]] = defaultdict(list)\n    if reference_records is not None:\n        for record_set in reference_records:\n            key = to_frozendict(record_set[0], column_set)\n            seen[key] = list(record_set)\n\n    for record in records:\n        frozen_record = to_frozendict(record, column_set)\n        if duplicated_records := seen.get(frozen_record):\n            duplicates.append((record, duplicated_records))\n        else:\n            deduplicated.append(record)\n            # Single-dataset mode: track this record for future comparisons\n            if reference_records is None:\n                seen[frozen_record].append(record)\n\n    return deduplicated, duplicates", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1725, "extracted_code_full": "# Source: semhash/records.py\ndef remove_exact_duplicates(\n    records: Sequence[dict[str, Any]],\n    columns: Sequence[str],\n    reference_records: list[list[dict[str, Any]]] | None = None,\n) -> tuple[list[dict[str, Any]], list[tuple[dict[str, Any], list[dict[str, Any]]]]]:\n    \"\"\"\n    Remove exact duplicates based on the hashable representation of each record.\n\n    If reference_records is None, the function will only check for duplicates within the records list.\n\n    :param records: A list of records to check for exact duplicates.\n    :param columns: Columns to unpack.\n    :param reference_records: A list of records to compare against. These are already unpacked\n    :return: A list of deduplicated records and a list of duplicates.\n    \"\"\"\n    deduplicated: list[dict[str, Any]] = []\n    duplicates: list[tuple[dict[str, Any], list[dict[str, Any]]]] = []\n\n    column_set = set(columns)\n\n    # Build seen set from reference_records (cross-dataset mode) or empty (single-dataset mode)\n    seen: defaultdict[frozendict[str, Any], list[dict[str, Any]]] = defaultdict(list)\n    if reference_records is not None:\n        for record_set in reference_records:\n            key = to_frozendict(record_set[0], column_set)\n            seen[key] = list(record_set)\n\n    for record in records:\n        frozen_record = to_frozendict(record, column_set)\n        if duplicated_records := seen.get(frozen_record):\n            duplicates.append((record, duplicated_records))\n        else:\n            deduplicated.append(record)\n            # Single-dataset mode: track this record for future comparisons\n            if reference_records is None:\n                seen[frozen_record].append(record)\n\n    return deduplicated, duplicates", "n_chars_compressed": 1725, "compression_ratio": 1.0}, "tests/test_datamodels.py::106": {"resolved_imports": ["semhash/datamodels.py"], "used_names": ["DeduplicationResult", "DuplicateRecord", "SelectedWithDuplicates"], "enclosing_function": "test_selected_with_duplicates_strings", "extracted_code": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass SelectedWithDuplicates(Generic[Record]):\n    \"\"\"\n    A record that has been selected along with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being selected.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    duplicates: DuplicateList = field(default_factory=list)\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 5374, "extracted_code_full": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass SelectedWithDuplicates(Generic[Record]):\n    \"\"\"\n    A record that has been selected along with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being selected.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    duplicates: DuplicateList = field(default_factory=list)\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_chars_compressed": 5374, "compression_ratio": 1.0}, "tests/test_semhash.py::175": {"resolved_imports": ["semhash/__init__.py", "semhash/datamodels.py", "semhash/utils.py"], "used_names": ["Encoder", "SemHash", "pytest"], "enclosing_function": "test_filter_outliers", "extracted_code": "# Source: semhash/__init__.py\nfrom pyversity import Strategy\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\n\n# Source: semhash/utils.py\nclass Encoder(Protocol):\n    \"\"\"An encoder protocol for SemHash. Supports text, images, or any encodable data.\"\"\"\n\n    def encode(\n        self,\n        inputs: Sequence[Any] | Any,\n        **kwargs: Any,\n    ) -> np.ndarray:\n        \"\"\"\n        Encode a list of inputs into embeddings.\n\n        :param inputs: A list of inputs to encode (strings, images, etc.).\n        :param **kwargs: Additional keyword arguments.\n        :return: The embeddings of the inputs.\n        \"\"\"\n        ...", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 722, "extracted_code_full": "# Source: semhash/__init__.py\nfrom pyversity import Strategy\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\nfrom semhash.semhash import SemHash\n\n__all__ = [\"SemHash\", \"Strategy\"]\n\n\n# Source: semhash/utils.py\nclass Encoder(Protocol):\n    \"\"\"An encoder protocol for SemHash. Supports text, images, or any encodable data.\"\"\"\n\n    def encode(\n        self,\n        inputs: Sequence[Any] | Any,\n        **kwargs: Any,\n    ) -> np.ndarray:\n        \"\"\"\n        Encode a list of inputs into embeddings.\n\n        :param inputs: A list of inputs to encode (strings, images, etc.).\n        :param **kwargs: Additional keyword arguments.\n        :return: The embeddings of the inputs.\n        \"\"\"\n        ...", "n_chars_compressed": 722, "compression_ratio": 1.0}, "tests/test_datamodels.py::241": {"resolved_imports": ["semhash/datamodels.py"], "used_names": ["FilterResult"], "enclosing_function": "test_filter_result_empty", "extracted_code": "# Source: semhash/datamodels.py\nclass FilterResult(Generic[Record]):\n    \"\"\"\n    Result of filtering operations.\n\n    Attributes\n    ----------\n        selected: List of records that passed the filter criteria.\n        filtered: List of records that were filtered out.\n        scores_selected: List of scores for the selected records.\n        scores_filtered: List of scores for the filtered records.\n\n    \"\"\"\n\n    selected: list[Record]\n    filtered: list[Record]\n    scores_selected: list[float] = field(default_factory=list)\n    scores_filtered: list[float] = field(default_factory=list)\n\n    @property\n    def filter_ratio(self) -> float:\n        \"\"\"Return the percentage of records filtered out.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len(self.filtered) / denom\n        return 0.0\n\n    @property\n    def selected_ratio(self) -> float:\n        \"\"\"Return the percentage of records selected.\"\"\"\n        return 1 - self.filter_ratio", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 977, "extracted_code_full": "# Source: semhash/datamodels.py\nclass FilterResult(Generic[Record]):\n    \"\"\"\n    Result of filtering operations.\n\n    Attributes\n    ----------\n        selected: List of records that passed the filter criteria.\n        filtered: List of records that were filtered out.\n        scores_selected: List of scores for the selected records.\n        scores_filtered: List of scores for the filtered records.\n\n    \"\"\"\n\n    selected: list[Record]\n    filtered: list[Record]\n    scores_selected: list[float] = field(default_factory=list)\n    scores_filtered: list[float] = field(default_factory=list)\n\n    @property\n    def filter_ratio(self) -> float:\n        \"\"\"Return the percentage of records filtered out.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len(self.filtered) / denom\n        return 0.0\n\n    @property\n    def selected_ratio(self) -> float:\n        \"\"\"Return the percentage of records selected.\"\"\"\n        return 1 - self.filter_ratio", "n_chars_compressed": 977, "compression_ratio": 1.0}, "tests/test_datamodels.py::126": {"resolved_imports": ["semhash/datamodels.py"], "used_names": ["DeduplicationResult", "DuplicateRecord"], "enclosing_function": "test_selected_with_duplicates_dicts", "extracted_code": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4987, "extracted_code_full": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_chars_compressed": 4987, "compression_ratio": 1.0}, "tests/test_datamodels.py::23": {"resolved_imports": ["semhash/datamodels.py"], "used_names": ["DeduplicationResult", "DuplicateRecord"], "enclosing_function": "test_deduplication_scoring_exact", "extracted_code": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4987, "extracted_code_full": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_chars_compressed": 4987, "compression_ratio": 1.0}, "tests/test_utils.py::16": {"resolved_imports": ["semhash/records.py", "semhash/utils.py"], "used_names": ["make_hashable"], "enclosing_function": "test_make_hashable", "extracted_code": "# Source: semhash/utils.py\ndef make_hashable(value: Any) -> Any:\n    \"\"\"\n    Convert a value to a hashable representation for use as dict keys.\n\n    Strings and other hashable types are returned as-is.\n    Non-hashable types (like PIL images, numpy arrays) are hashed to a string.\n\n    :param value: The value to make hashable.\n    :return: A hashable representation of the value.\n    \"\"\"\n    # Fast path: most values are strings or already hashable\n    if isinstance(value, (str, int, float, bool, type(None))):\n        return value\n    # Handle objects with tobytes() (PIL Image, numpy array, etc.)\n    if hasattr(value, \"tobytes\"):\n        return hashlib.md5(value.tobytes()).hexdigest()\n    # Fallback: try to hash, otherwise stringify\n    try:\n        hash(value)\n        return value\n    except TypeError:\n        return str(value)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 837, "extracted_code_full": "# Source: semhash/utils.py\ndef make_hashable(value: Any) -> Any:\n    \"\"\"\n    Convert a value to a hashable representation for use as dict keys.\n\n    Strings and other hashable types are returned as-is.\n    Non-hashable types (like PIL images, numpy arrays) are hashed to a string.\n\n    :param value: The value to make hashable.\n    :return: A hashable representation of the value.\n    \"\"\"\n    # Fast path: most values are strings or already hashable\n    if isinstance(value, (str, int, float, bool, type(None))):\n        return value\n    # Handle objects with tobytes() (PIL Image, numpy array, etc.)\n    if hasattr(value, \"tobytes\"):\n        return hashlib.md5(value.tobytes()).hexdigest()\n    # Fallback: try to hash, otherwise stringify\n    try:\n        hash(value)\n        return value\n    except TypeError:\n        return str(value)", "n_chars_compressed": 837, "compression_ratio": 1.0}, "tests/test_datamodels.py::13": {"resolved_imports": ["semhash/datamodels.py"], "used_names": ["DeduplicationResult", "DuplicateRecord"], "enclosing_function": "test_deduplication_scoring", "extracted_code": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4987, "extracted_code_full": "# Source: semhash/datamodels.py\nclass DuplicateRecord(Generic[Record]):\n    \"\"\"\n    A single record with its duplicates.\n\n    Attributes\n    ----------\n        record: The original record being deduplicated.\n        exact: Whether the record was identified as an exact match.\n        duplicates: List of tuples consisting of duplicate records and their associated scores.\n\n    \"\"\"\n\n    record: Record\n    exact: bool\n    duplicates: DuplicateList = field(default_factory=list)\n\n    def _rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]\n\nclass DeduplicationResult(Generic[Record]):\n    \"\"\"\n    Deduplication result.\n\n    Attributes\n    ----------\n        selected: List of deduplicated records after removing duplicates.\n        filtered: List of DuplicateRecord objects containing details about duplicates of an original record.\n        threshold: The similarity threshold used for deduplication.\n        columns: Columns used for deduplication.\n\n    \"\"\"\n\n    selected: list[Record] = field(default_factory=list)\n    filtered: list[DuplicateRecord] = field(default_factory=list)\n    threshold: float = field(default=0.9)\n    columns: Sequence[str] | None = field(default=None)\n\n    @property\n    def duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return 1.0 - len(self.selected) / denom\n        return 0.0\n\n    @property\n    def exact_duplicate_ratio(self) -> float:\n        \"\"\"Return the percentage of records dropped due to an exact match.\"\"\"\n        if denom := len(self.selected) + len(self.filtered):\n            return len([dup for dup in self.filtered if dup.exact]) / denom\n        return 0.0\n\n    def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:\n        \"\"\"\n        Return the N least similar duplicate pairs.\n\n        :param n: The number of least similar pairs to return.\n        :return: A list of tuples consisting of (original_record, duplicate_record, score).\n        \"\"\"\n        all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]\n        sorted_pairs = sorted(all_pairs, key=lambda x: x[2])  # Sort by score\n        return sorted_pairs[:n]\n\n    def rethreshold(self, threshold: float) -> None:\n        \"\"\"Rethreshold the duplicates.\"\"\"\n        if self.threshold > threshold:\n            raise ValueError(\"Threshold is smaller than the given value.\")\n        # Invalidate cached property before modifying data\n        self.__dict__.pop(\"selected_with_duplicates\", None)\n        # Rethreshold duplicates and move records without duplicates to selected\n        for dup in list(self.filtered):\n            dup._rethreshold(threshold)\n            if not dup.duplicates:\n                self.filtered.remove(dup)\n                self.selected.append(dup.record)\n        self.threshold = threshold\n\n    @cached_property\n    def selected_with_duplicates(self) -> list[SelectedWithDuplicates[Record]]:\n        \"\"\"\n        For every kept record, return the duplicates that were removed along with their similarity scores.\n\n        :return: A list of tuples where each tuple contains a kept record\n                and a list of its duplicates with their similarity scores.\n        \"\"\"\n\n        def _to_hashable(record: Record) -> frozendict[str, str] | str:\n            \"\"\"Convert a record to a hashable representation.\"\"\"\n            if isinstance(record, dict) and self.columns is not None:\n                # Convert dict to frozendict for immutability and hashability\n                return to_frozendict(record, set(self.columns))\n            return str(record)\n\n        # Build a mapping from original-record  to  [(duplicate, score), …]\n        buckets: defaultdict[Hashable, DuplicateList] = defaultdict(list)\n        for duplicate_record in self.filtered:\n            for original_record, score in duplicate_record.duplicates:\n                buckets[_to_hashable(original_record)].append((duplicate_record.record, float(score)))\n\n        result: list[SelectedWithDuplicates[Record]] = []\n        for selected in self.selected:\n            # Get the list of duplicates for the selected record\n            raw_list = buckets.get(_to_hashable(selected), [])\n            # Ensure we don't have duplicates in the list\n            # Use full-record canonical JSON for dicts so that unhashable values are handled correctly\n            deduped = {\n                (\n                    json.dumps(rec, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n                    if isinstance(rec, dict)\n                    else rec\n                ): (rec, score)\n                for rec, score in raw_list\n            }\n            result.append(SelectedWithDuplicates(record=selected, duplicates=list(deduped.values())))\n\n        return result", "n_chars_compressed": 4987, "compression_ratio": 1.0}}}