Skip to content

Engine

SyncEngine

A wrapper around an object type's synchronization process.

Given a list of SyncableContent, a SyncEngine synchronizes one pair of objects at a time (via SyncEngine.synchronize_pair()). The results of all pairs are then merged together and deduplicated. Each object type corresponds to a subclass of SyncEngine that overrides synchronize_pair() to define how pairs are synchronized in synchronize(), which contains wrapper logic for the entire process.

There are three distinct layers within SyncEngine.synchronize()'s wrapper logic:

  1. The aforementioned sync process that results in a data frame of synced identifiers.
  2. Collect remaining unsynced rows and run the sync process on those. Append any newly synced rows to the result dataframe from Layer 1.
  3. Append any remaining unsynced rows to the bottom of the result data frame.

This result dataframe is then deduplicated: by default, the result dataframe is grouped by the specific columns defined in SyncEngine and the first non-null result is selected for each data provider's identifier field.

This class should be subclassed for each new object type: see PlayerSyncEngine for an example.

NOTE: any SyncableContent objects provided to a SyncEngine will have their identifiers converted to strings for easier deduplication. Please see SyncableContent.normalize_ids and utils.string_stringify_object_id for more details.

Source code in src/glass_onion/engine.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
class SyncEngine:
    """
    A wrapper around an object type's synchronization process.

    Given a list of SyncableContent, a SyncEngine synchronizes one pair of objects at a time (via `SyncEngine.synchronize_pair()`). The results of all pairs are then merged together and deduplicated.
    Each object type corresponds to a subclass of SyncEngine that overrides `synchronize_pair()` to define how pairs are synchronized in `synchronize()`, which contains wrapper logic for the entire process.

    There are three distinct layers within `SyncEngine.synchronize()`'s wrapper logic:

    1. The aforementioned sync process that results in a data frame of synced identifiers.
    2. Collect remaining unsynced rows and run the sync process on those. Append any newly synced rows to the result dataframe from Layer 1.
    3. Append any remaining unsynced rows to the bottom of the result data frame.

    This result dataframe is then deduplicated: by default, the result dataframe is grouped by the specific columns defined in SyncEngine and the first non-null result is selected for each data provider's identifier field.

    This class should be subclassed for each new object type: see [PlayerSyncEngine][glass_onion.player.PlayerSyncEngine] for an example.

    NOTE: any `SyncableContent` objects provided to a `SyncEngine` will have their identifiers converted to strings for easier deduplication. Please see [SyncableContent.normalize_ids][glass_onion.engine.SyncableContent.normalize_ids] and [utils.string_stringify_object_id][glass_onion.utils.string_stringify_object_id] for more details.
    """

    def __init__(
        self,
        object_type: str,
        content: list[SyncableContent],
        join_columns: list[str],
        verbose: bool = False,
    ):
        """
        Create a new SyncEngine object.

        Args:
            object_type (str): the object type this SyncEngine is working with.
            content (list[SyncableContent]): a list of SyncableContent objects that correspond to `object_type`.
            join_columns (list[str]): a list of columns used to aggregate and deduplicate identifiers. In some subclasses, these columns are used to do an initial, naive synchronization pass before moving on to more complex checks.
            verbose (bool, optional): a flag to verbose logging. This will be `extremely` verbose, allowing new SyncEngine developers and those integrating SyncEngine into their workflows to see the interactions between different logical layers during synchronization.
        """
        assert isinstance(content, list), (
            "`content` must be a list of SyncableContent objects."
        )
        assert len(content) > 0, "`content` can not be empty"
        assert all([isinstance(c, SyncableContent) for c in content]), (
            "One or more objects in `content` are not `SyncableContent` objects."
        )

        assert object_type is not None, "`object_type` can not be NULL"
        assert len(object_type.strip()) > 0, (
            "`object_type` can not be empty or just whitespace"
        )

        assert all([c.object_type == object_type for c in content]), (
            "One or more `SyncableContent` objects in `content` do not match `SyncEngine.object_type`."
        )

        for c in content:
            # normalize all values
            c.normalize_ids()
            # check validity
            assert c.validate_data_schema(), (
                f"`data` for provider {c.provider} does not meet the schema requirements for its SyncableContent class."
            )

        self.content = content
        self.conflicts: list[Tuple[Tuple[str, Any], Tuple[str, Any]]] = []
        # apply_cosine_similarity() results keyed by its two inputs' values: its vectorizer is only fit on those values,
        # so the same inputs always produce the same result. Layers often re-run it on the same names.
        self.cosine_similarity_cache: dict[
            Tuple[Tuple[str, ...], Tuple[str, ...]], pd.DataFrame
        ] = {}
        # series_normalize() results keyed by raw string: normalization is per-string, so each string only needs it once
        self.normalized_strings: dict[str, str] = {}
        self.object_type = object_type
        self.verbose = verbose
        self.join_columns = join_columns

    def normalize(self, values: "pd.Series[str]") -> "pd.Series[str]":
        """
        Cached wrapper around [series_normalize][glass_onion.utils.series_normalize]: only strings this engine hasn't normalized yet are normalized (in one batch).

        Args:
            values (pd.Series[str]): a pandas.Series of non-null strings.

        Returns:
            A pandas.Series with normalized strings and the same index as `values`.
        """
        missing = pd.Series(
            list(dict.fromkeys(v for v in values if v not in self.normalized_strings)),
            dtype=object,
        )
        if len(missing) > 0:
            self.normalized_strings.update(zip(missing, series_normalize(missing)))
        return values.map(self.normalized_strings)

    def verbose_log(self, msg: Any):
        """
        Helper method to enable verbose logging via `print()`. These logs are sent to `stdout` (the default output location of `print()`). Logs are also prefixed with a timestamp for easy sorting.

        Args:
            msg (Any): any string-serializable object
        """
        if self.verbose:
            print(f"{datetime.now()}: {msg}")

    def synchronize_with_fuzzy_match(
        self,
        input1: SyncableContent,
        input2: SyncableContent,
        fields: Tuple[str, str],
        threshold: float = 0.90,
    ):
        """
        Synchronizes two SyncableContent objects using fuzzy matching similarity using the columns provided by the two-tuple `fields`.

        Index 0 of `fields` is the column to use for similarity in `input1`, while index 1 is the column to use in `input2`.

        NOTE: this approach uses a dictionary/map, so a string from `input1` can only be mapped to one string in `input2`.
        If there are duplicate instances of a string in `input1` under a different ID, the 2nd...Nth instances of that string will not get matched.

        See [thefuzz.process()](https://github.com/seatgeek/thefuzz/blob/master/thefuzz/process.py) for more details.

        Args:
            input1 (glass_onion.engine.SyncableContent): a SyncableContent object.
            input2 (glass_onion.engine.SyncableContent): a SyncableContent object.
            fields (Tuple[str, str]): a two-tuple containing the column names to use for player name similarity.
            threshold (float): the minimum similarity threshold that a match must be in order to be considered valid. Options: any float value from 0.0 to 1.0. Options outside this range will be clamped to the min or max value.

        Returns:
            (pandas.DataFrame): a pandas.DataFrame object that contains synchronized identifier pairs from `input1` and `input2`. The available columns are the `id_field` values of `input1` and `input2`.
        """

        assert len(fields) == 2, (
            "Must provide two columns (one from `input1` and one from `input2`) as `fields`."
        )
        assert fields[0] in input1.data.columns, (
            "First element of `fields` must exist in `input1.data`."
        )
        assert fields[1] in input2.data.columns, (
            "Second element of `fields` must exist in `input2.data`."
        )
        assert len(input1.data) > 0 and len(input2.data) > 0, (
            "Both SyncableContent objects must be non-empty."
        )

        name_population = input1.data[fields[0]]
        name_sample = input2.data[fields[1]]

        name_population = input1.data.loc[
            input1.data[fields[0]].notna(), [fields[0], input1.id_field]
        ]
        name_sample = input2.data.loc[
            input2.data[fields[1]].notna(), [fields[1], input2.id_field]
        ]

        # if one or both of the dataframes are now empty, just return an empty result
        # with both fields
        if not (len(name_population) > 0 and len(name_sample) > 0):
            return pd.DataFrame(
                {i: pd.Series(dtype=str) for i in [input1.id_field, input2.id_field]}
            )

        normalized_name_population = self.normalize(name_population[fields[0]])
        normalized_name_sample = self.normalize(name_sample[fields[1]])

        adjusted_threshold = max(min(threshold, 1.0), 0.0) * 100

        results = []
        name_map: dict[str, str] = {}
        for j in range(0, len(normalized_name_sample)):
            i2_raw = normalized_name_sample.loc[normalized_name_sample.index[j]]
            if i2_raw in name_map.values():
                continue

            result = process.extractOne(i2_raw, normalized_name_population)
            if result and result[1] >= adjusted_threshold:
                if result[0] in name_map.keys():
                    continue

                self.verbose_log(f"Logging match: {result[0]} -> {i2_raw}")
                name_map[result[0]] = i2_raw
                i = result[2]
                results.append(
                    {
                        f"{input1.id_field}": name_population.loc[i, input1.id_field],
                        f"{input2.id_field}": name_sample.loc[
                            name_sample.index[j], input2.id_field
                        ],
                    }
                )
            elif result and result[1] < adjusted_threshold:
                self.verbose_log(
                    f"not match: {result[0]} -/-> {i2_raw} (similarity: {result[1]} < ({adjusted_threshold}))"
                )

        if len(results) == 0:
            return pd.DataFrame(data=[], columns=[input1.id_field, input2.id_field])

        return pd.DataFrame(results)

    def synchronize_with_cosine_similarity(
        self,
        input1: SyncableContent,
        input2: SyncableContent,
        fields: Tuple[str, str],
        threshold: float = 0.75,
    ) -> pd.DataFrame:
        """
        Synchronizes two SyncableContent objects using cosine similarity and the columns provided by the two-tuple `fields`.

        Index 0 of `fields` is the column to use for similarity in `input1`, while index 1 is the column to use in `input2`.

        See [apply_cosine_similarity][glass_onion.utils.apply_cosine_similarity] for more details on implementation.

        Args:
            input1 (glass_onion.engine.SyncableContent): a SyncableContent object.
            input2 (glass_onion.engine.SyncableContent): a SyncableContent object.
            fields (Tuple[str, str]): a two-tuple containing the column names to use for player name similarity.
            threshold (float): the minimum similarity threshold that a match must be in order to be considered valid. Options: any float value from 0.0 to 1.0. Options outside this range will be clamped to the min or max value.

        Returns:
            pandas.DataFrame: contains unique synchronized identifier pairs from `input1` and `input2`. The available columns are the `id_field` values of `input1` and `input2`.
        """

        assert len(fields) == 2, (
            "Must provide two columns (one from `input1` and one from `input2`) as `fields`."
        )
        assert fields[0] in input1.data.columns, (
            "First element of `fields` must exist in `input1.data`."
        )
        assert fields[1] in input2.data.columns, (
            "Second element of `fields` must exist in `input2.data`."
        )
        assert len(input1.data) > 0 and len(input2.data) > 0, (
            "Both SyncableContent objects must be non-empty."
        )

        input1_fields = input1.data.loc[
            input1.data[fields[0]].notna(), fields[0]
        ].reset_index(drop=True)
        input2_fields = input2.data.loc[
            input2.data[fields[1]].notna(), fields[1]
        ].reset_index(drop=True)

        # if one or both of the dataframes are now empty, just return an empty result
        # with both fields
        if not (len(input1_fields) > 0 and len(input2_fields) > 0):
            return pd.DataFrame(
                {i: pd.Series(dtype=str) for i in [input1.id_field, input2.id_field]}
            )

        adjusted_threshold = max(min(threshold, 1.0), 0.0)

        # fast path: with one name on each side, the only possible pair can be scored without fitting a vectorizer
        if len(input1_fields) == 1 and len(input2_fields) == 1:
            normalized = self.normalize(pd.concat([input1_fields, input2_fields]))
            similarity = string_pair_cosine_similarity(
                normalized.iloc[0], normalized.iloc[1]
            )
            if similarity is not None:
                if similarity < adjusted_threshold:
                    return pd.DataFrame(
                        {
                            i: pd.Series(dtype=str)
                            for i in [input1.id_field, input2.id_field]
                        }
                    )
                return pd.DataFrame(
                    {
                        input1.id_field: input1.data.loc[
                            input1.data[fields[0]].notna(), input1.id_field
                        ].reset_index(drop=True),
                        input2.id_field: input2.data.loc[
                            input2.data[fields[1]].notna(), input2.id_field
                        ].reset_index(drop=True),
                    }
                )

        cache_key = (tuple(input1_fields), tuple(input2_fields))
        if cache_key not in self.cosine_similarity_cache:
            self.cosine_similarity_cache[cache_key] = apply_cosine_similarity(
                input1_fields, input2_fields
            )
        match_results = self.cosine_similarity_cache[cache_key]

        # sort_values() returns a copy, so the cached result isn't modified below
        result = match_results.sort_values(by="similarity", ascending=False)
        result = result[result.similarity >= adjusted_threshold]
        result["similarity_rank"] = result.groupby(["input1", "input2"])[
            "similarity"
        ].rank(method="dense", ascending=False)
        result = result[result.similarity_rank <= 1]

        composite = pd.merge(
            input1.data[[fields[0], input1.id_field]],
            result,
            left_on=fields[0],
            right_on="input1",
            how="inner",
        )

        composite = pd.merge(
            composite,
            input2.data[[fields[1], input2.id_field]],
            left_on="input2",
            right_on=fields[1],
            how="inner",
        )

        # deduplicate if there are duplicate name matches.
        # Must use rank(method="first") in case `similarity` is the same.
        composite["field_rank"] = composite.groupby(input1.id_field)["similarity"].rank(
            method="first", ascending=False
        )
        return composite.loc[
            composite["field_rank"] == 1, [input1.id_field, input2.id_field]
        ]

    def synchronize_with_naive_match(
        self, input1: SyncableContent, input2: SyncableContent, fields: Tuple[str, str]
    ) -> pd.DataFrame:
        """
        Synchronizes two SyncableContent objects using the `naive` similarity using the columns provided by the two-tuple `fields`.

        Index 0 of `fields` is the column to use for similarity in `input1`, while index 1 is the column to use in `input2`.

        NOTE: this is a _naive_ approach that uses a dictionary/map, so a string from `input1` can only be mapped to one string in `input2`.
        If there are duplicate instances of a string in `input1` under a different ID, the 2nd...Nth instances of that string will not get matched.

        Args:
            input1 (glass_onion.engine.SyncableContent): a SyncableContent object.
            input2 (glass_onion.engine.SyncableContent): a SyncableContent object.
            fields (Tuple[str, str]): a two-tuple containing the column names to use for player name similarity.

        Returns:
            pandas.DataFrame: contains synchronized identifier pairs from `input1` and `input2`. The available columns are the `id_field` values of `input1` and `input2`.
        """

        assert len(fields) == 2, (
            "Must provide two columns (one from `input1` and one from `input2`) as `fields`."
        )
        assert fields[0] in input1.data.columns, (
            "First element of `fields` must exist in `input1.data`."
        )
        assert fields[1] in input2.data.columns, (
            "Second element of `fields` must exist in `input2.data`."
        )

        assert len(input1.data) > 0 and len(input2.data) > 0, (
            "Both SyncableContent objects must be non-empty."
        )

        name_population = input1.data.loc[
            input1.data[fields[0]].notna(), [fields[0], input1.id_field]
        ]
        name_sample = input2.data.loc[
            input2.data[fields[1]].notna(), [fields[1], input2.id_field]
        ]

        # if one or both of the dataframes are now empty, just return an empty result
        # with both fields
        if not (len(name_population) > 0 and len(name_sample) > 0):
            return pd.DataFrame(
                {i: pd.Series(dtype=str) for i in [input1.id_field, input2.id_field]}
            )

        normalized_name_population = self.normalize(name_population[fields[0]])
        normalized_name_sample = self.normalize(name_sample[fields[1]])

        # only the first occurrence of each normalized string can ever be matched,
        # so collapse both sides to {string: id of first occurrence} (dicts keep insertion order).
        population_ids: dict[str, Any] = {}
        for name, id in zip(
            normalized_name_population.tolist(),
            name_population[input1.id_field].tolist(),
        ):
            population_ids.setdefault(name, id)

        sample_ids: dict[str, Any] = {}
        for name, id in zip(
            normalized_name_sample.tolist(), name_sample[input2.id_field].tolist()
        ):
            sample_ids.setdefault(name, id)

        results = []
        name_map: dict[str, str] = {}
        matched_sample: set[str] = set()

        # first pass to encapsulate exact matches
        for i1_raw, i1_id in population_ids.items():
            if i1_raw in sample_ids:
                self.verbose_log(f"Logging match: {i1_raw} -> {i1_raw}")
                name_map[i1_raw] = i1_raw
                matched_sample.add(i1_raw)
                results.append(
                    {
                        f"{input1.id_field}": i1_id,
                        f"{input2.id_field}": sample_ids[i1_raw],
                    }
                )

        # second pass: match if either name's token set is a subset of the other's.
        # Any such pair shares at least one token, so an inverted index of
        # token -> sample positions limits the comparisons to plausible candidates.
        sample_names = [n for n in sample_ids.keys() if n not in matched_sample]
        sample_sets = [frozenset(re.split(r"\s+", n.strip())) for n in sample_names]
        token_index: dict[str, list[int]] = {}
        for j, i2_set in enumerate(sample_sets):
            for token in i2_set:
                token_index.setdefault(token, []).append(j)

        for i1_raw, i1_id in population_ids.items():
            if i1_raw in name_map:
                continue

            i1_set = frozenset(re.split(r"\s+", i1_raw))
            candidates = sorted(
                {j for token in i1_set for j in token_index.get(token, ())}
            )
            for j in candidates:
                i2_raw = sample_names[j]
                if i2_raw in matched_sample:
                    continue

                i2_set = sample_sets[j]
                if i2_set <= i1_set or i1_set <= i2_set:
                    # this is a match
                    self.verbose_log(f"Logging match: {i1_raw} -> {i2_raw}")
                    name_map[i1_raw] = i2_raw
                    matched_sample.add(i2_raw)
                    results.append(
                        {
                            f"{input1.id_field}": i1_id,
                            f"{input2.id_field}": sample_ids[i2_raw],
                        }
                    )
                    break

        if len(results) == 0:
            return pd.DataFrame(data=[], columns=[input1.id_field, input2.id_field])

        return pd.DataFrame(results)

    def synchronize_all_combinations(
        self, content: Optional[list[SyncableContent]] = None
    ) -> SyncableContent:
        """
        Internal wrapper around `synchronize_pair()` that generates all possible combinations of the elements in `content` to run `synchronize_pair` on.

        Pair results are combined by treating every synced identifier pair as a link and grouping linked identifiers into one row, so an object can be
        synced through a third provider even if two providers never matched it directly (IE: A <-> C and B <-> C yields A <-> B <-> C).
        Links are applied strongest first: by the `sync_rank` column of each pair result if present (lower is stronger), then by identifier, so the
        result doesn't depend on the order of `content`. A link is skipped if it would put two identifiers from the same provider in one row; skipped
        links are recorded in `SyncEngine.conflicts`.

        Args:
            content (list[SyncableContent]): a list of SyncableContent objects that correspond to `object_type`. If `None`, defaults to `self.content`.

        Returns:
            A SyncableContent object with one row per group of linked identifiers. Non-identifier columns are taken from the first object in `content` that has an identifier in the row.
        """
        if content is None:
            content = self.content

        results = []
        combos = list(combinations(content, 2))
        for x, y in combos:
            z = self.synchronize_pair(x, y)
            results.append(z)

        id_fields = [c.id_field for c in content]

        # union-find over (id_field, id) nodes. Each root tracks the id_fields in its group
        # so that a link can't merge two identifiers from the same provider.
        parent: dict[Tuple[str, Any], Tuple[str, Any]] = {}
        group_fields: dict[Tuple[str, Any], set[str]] = {}

        def find(node: Tuple[str, Any]) -> Tuple[str, Any]:
            parent.setdefault(node, node)
            group_fields.setdefault(node, {node[0]})
            while parent[node] != node:
                parent[node] = parent[parent[node]]
                node = parent[node]
            return node

        def node_key(node: Tuple[str, Any]) -> Tuple[str, str]:
            # identifiers can be of mixed types, so compare them as strings
            return (node[0], str(node[1]))

        # collect every link as (rank, left node, right node) so they can be applied strongest first, independent of
        # the order of `content`. Pair results without a `sync_rank` column treat every link as equally strong.
        links: list[Tuple[float, Tuple[str, Any], Tuple[str, Any]]] = []
        for r in results:
            pair_fields = [f for f in id_fields if f in r.data.columns]
            ranks = (
                r.data["sync_rank"].fillna(0)
                if "sync_rank" in r.data.columns
                else pd.Series(0, index=r.data.index)
            )
            for rank, row in zip(ranks, r.data[pair_fields].itertuples(index=False)):
                nodes = sorted(
                    [(f, v) for f, v in zip(pair_fields, row) if pd.notna(v)],
                    key=node_key,
                )
                links += [(rank, nodes[0], node) for node in nodes[1:]]

        for rank, left, right in sorted(
            links, key=lambda l: (l[0], node_key(l[1]), node_key(l[2]))
        ):
            root_x, root_y = find(left), find(right)
            if root_x == root_y:
                continue
            if group_fields[root_x] & group_fields[root_y]:
                self.verbose_log(
                    f"Skipping link {left} <-> {right}: would put two identifiers from the same provider in one row"
                )
                self.conflicts.append((left, right))
                continue
            parent[root_y] = root_x
            group_fields[root_x] |= group_fields.pop(root_y)

        groups: dict[Tuple[str, Any], dict[str, Any]] = {}
        for node in parent:
            groups.setdefault(find(node), {})[node[0]] = node[1]

        unified = pd.DataFrame(list(groups.values()), columns=id_fields)

        # re-attach non-identifier columns, preferring earlier objects in `content`
        metadata_columns = []
        for r in results:
            for col in r.data.columns:
                if (
                    col not in id_fields
                    and col not in metadata_columns
                    and not col.endswith(f"_{self.object_type}_id")
                    and any(col in c.data.columns for c in content)
                ):
                    metadata_columns.append(col)

        for c in content:
            lookup = c.data.drop_duplicates(subset=c.id_field).set_index(c.id_field)
            for col in metadata_columns:
                if col not in lookup.columns:
                    continue
                values = unified[c.id_field].map(lookup[col])
                unified[col] = (
                    unified[col].fillna(values) if col in unified.columns else values
                )

        return SyncableContent(
            object_type=self.object_type, provider=content[0].provider, data=unified
        )

    def synchronize_pair(
        self, input1: SyncableContent, input2: SyncableContent
    ) -> SyncableContent:
        """
        Synchronize two SyncableContent objects.

        This method should be overridden for each new object type: see [PlayerSyncEngine][glass_onion.player.PlayerSyncEngine] for an example.

        Args:
            input1 (glass_onion.SyncableContent): a SyncableContent object from `SyncEngine.content`
            input2 (glass_onion.SyncableContent): a SyncableContent object from `SyncEngine.content`

        Returns:
            If `input1`'s underlying `data` dataframe is empty, returns `input2` with a column in `input2.data` for `input1.id_field`.
            If `input2`'s underlying `data` dataframe is empty, returns `input1` with a column in `input1.data` for `input2.id_field`.
            If both dataframes are non-empty, returns a new PlayerSyncableContent object with synchronized identifiers from `input1` and `input2`.

        Raises:
            NotImplementedError: if this method is not overridden.
        """
        if len(input1.data) == 0 and len(input2.data) > 0:
            input2.data[input1.id_field] = pd.NA
            return input2

        if len(input1.data) > 0 and len(input2.data) == 0:
            input1.data[input2.id_field] = pd.NA
            return input1

        raise NotImplementedError()

    def synchronize(self) -> SyncableContent:
        """
        Synchronizes the full list of SyncableContent objects from `SyncEngine.content` using `SyncEngine.synchronize_pair()`.

        There are three distinct layers here:

        1. The sync process that results in a data frame of synced identifiers, defined in each `SyncEngine` subclass's `synchronize_pair()` implementation.
        2. Collect remaining unsynced rows and run the sync process on those. Append any newly synced rows to the result dataframe from Layer 1.
        3. Append any remaining unsynced rows to the bottom of the result data frame.

        This result dataframe is then deduplicated: by default, the result dataframe is grouped by `SyncEngine.join_columns` and the first non-null result is selected for each data provider's identifier field.

        The result dataframe is then wrapped in a SyncableContent object using the `provider` from the first SyncableContent object in `SyncEngine.content`.

        Returns:
            * If there are no elements in `SyncEngine.content`, returns a SyncableContent object with `SyncEngine.object_type` with `provider` unknown and an empty `pandas.DataFrame`.
            * If there's only one element in `SyncEngine.content`, returns that element.
            * If there are 2+ elements in `SyncEngine.content`, returns a new SyncableContent object with synchronized identifiers based on the SyncableContent objects in `SyncEngine.content`.
        """
        if len(self.content) == 0:
            return SyncableContent(self.object_type, "unknown", pd.DataFrame())

        if len(self.content) == 1:
            return self.content[0]

        # conflicts accumulate across every synchronize_all_combinations() pass below
        self.conflicts = []

        # first pass: straight matching - approach: agglomerative
        self.verbose_log(
            f"Starting {self.object_type} synchronization across {len(self.content)} datasets"
        )

        self.verbose_log(f"Layer 1: agglomeration")
        sync_result = self.synchronize_all_combinations()
        id_mask = list(map(lambda x: x.id_field, self.content))

        synced = SyncableContent(
            self.object_type, self.content[0].provider, sync_result.data
        )

        self.verbose_log(
            f"Layer 1: Using {self.content[0].provider} as sync basis, found {len(sync_result.data)} total rows and {len(synced.data)} fully synced rows."
        )

        ## second pass: relate remainders to each other
        remainders = []
        for c in self.content:
            missing = c.data[~(c.data[c.id_field].isin(synced.data[c.id_field]))]

            if len(missing) > 0:
                self.verbose_log(
                    f"Layer 2: Aggregating {len(missing)} identified unsynced rows for {c.provider}"
                )
                remainders.append(
                    SyncableContent(self.object_type, c.provider, missing)
                )

        if len(remainders) > 1:
            self.verbose_log(
                f"Layer 2: Agglomeration on remaining unsynced rows across {len(remainders)} datasets"
            )
            # self.verbose_log([d.data for d in rem_results])
            remainders_result = self.synchronize_all_combinations(remainders)
            rem_id_mask = list(map(lambda x: x.id_field, remainders))
            rem_id_mask = [
                x for x in rem_id_mask if x in remainders_result.data.columns
            ]
            remainders_result.data.dropna(subset=rem_id_mask, inplace=True)

            self.verbose_log(
                f"Layer 2: Using remainders as sync basis, found {len(remainders_result.data)} new fully synced rows."
            )
            if len(remainders_result.data) > 0:
                synced.append(remainders_result)

        ## third pass: add remainders to end
        remainder_dfs = []
        for c in self.content:
            r = c.data[~(c.data[c.id_field].isin(synced.data[c.id_field]))]
            if len(r) > 0:
                self.verbose_log(
                    f"Layer 3: Aggregating {len(r)} identified unsynced rows for {c.provider}"
                )
                applicable_columns = synced.data.columns[
                    synced.data.columns.isin(c.data.columns)
                ]
                missing_columns = synced.data.columns[
                    ~(synced.data.columns.isin(c.data.columns))
                ]
                r_appendable = r[applicable_columns]
                r_appendable[missing_columns] = pd.NA
                r_appendable["provider"] = c.provider
                remainder_dfs.append(r_appendable)

        if len(remainder_dfs) > 0:
            remainder_df = pd.concat(remainder_dfs, axis=0)
            self.verbose_log(f"Layer 3: Including {len(remainder_df)} unsynced rows")
            synced.append(remainder_df)

        self.verbose_log(
            f"Pre-deduplication: Found {len(synced.data)} total rows: {synced.data}"
        )

        # validation / dedupe step: final table should summarize on key matching columns to eliminate any duplicate rows
        dedupe_aggregation = {
            k: (lambda x: x[x.notna()].iloc[0] if len(x[x.notna()]) > 0 else pd.NA)
            for k in id_mask
        }
        synced.data = (
            synced.data.groupby(self.join_columns).agg(dedupe_aggregation).reset_index()
        )
        synced.data["provider"] = self.content[0].provider
        self.verbose_log(
            f"After deduplication: Found {len(synced.data)} total unique rows based on join_columns: {self.join_columns}"
        )
        return synced

__init__(object_type, content, join_columns, verbose=False)

Create a new SyncEngine object.

Parameters:

Name Type Description Default
object_type str

the object type this SyncEngine is working with.

required
content list[SyncableContent]

a list of SyncableContent objects that correspond to object_type.

required
join_columns list[str]

a list of columns used to aggregate and deduplicate identifiers. In some subclasses, these columns are used to do an initial, naive synchronization pass before moving on to more complex checks.

required
verbose bool

a flag to verbose logging. This will be extremely verbose, allowing new SyncEngine developers and those integrating SyncEngine into their workflows to see the interactions between different logical layers during synchronization.

False
Source code in src/glass_onion/engine.py
def __init__(
    self,
    object_type: str,
    content: list[SyncableContent],
    join_columns: list[str],
    verbose: bool = False,
):
    """
    Create a new SyncEngine object.

    Args:
        object_type (str): the object type this SyncEngine is working with.
        content (list[SyncableContent]): a list of SyncableContent objects that correspond to `object_type`.
        join_columns (list[str]): a list of columns used to aggregate and deduplicate identifiers. In some subclasses, these columns are used to do an initial, naive synchronization pass before moving on to more complex checks.
        verbose (bool, optional): a flag to verbose logging. This will be `extremely` verbose, allowing new SyncEngine developers and those integrating SyncEngine into their workflows to see the interactions between different logical layers during synchronization.
    """
    assert isinstance(content, list), (
        "`content` must be a list of SyncableContent objects."
    )
    assert len(content) > 0, "`content` can not be empty"
    assert all([isinstance(c, SyncableContent) for c in content]), (
        "One or more objects in `content` are not `SyncableContent` objects."
    )

    assert object_type is not None, "`object_type` can not be NULL"
    assert len(object_type.strip()) > 0, (
        "`object_type` can not be empty or just whitespace"
    )

    assert all([c.object_type == object_type for c in content]), (
        "One or more `SyncableContent` objects in `content` do not match `SyncEngine.object_type`."
    )

    for c in content:
        # normalize all values
        c.normalize_ids()
        # check validity
        assert c.validate_data_schema(), (
            f"`data` for provider {c.provider} does not meet the schema requirements for its SyncableContent class."
        )

    self.content = content
    self.conflicts: list[Tuple[Tuple[str, Any], Tuple[str, Any]]] = []
    # apply_cosine_similarity() results keyed by its two inputs' values: its vectorizer is only fit on those values,
    # so the same inputs always produce the same result. Layers often re-run it on the same names.
    self.cosine_similarity_cache: dict[
        Tuple[Tuple[str, ...], Tuple[str, ...]], pd.DataFrame
    ] = {}
    # series_normalize() results keyed by raw string: normalization is per-string, so each string only needs it once
    self.normalized_strings: dict[str, str] = {}
    self.object_type = object_type
    self.verbose = verbose
    self.join_columns = join_columns

normalize(values)

Cached wrapper around series_normalize: only strings this engine hasn't normalized yet are normalized (in one batch).

Parameters:

Name Type Description Default
values Series[str]

a pandas.Series of non-null strings.

required

Returns:

Type Description
Series[str]

A pandas.Series with normalized strings and the same index as values.

Source code in src/glass_onion/engine.py
def normalize(self, values: "pd.Series[str]") -> "pd.Series[str]":
    """
    Cached wrapper around [series_normalize][glass_onion.utils.series_normalize]: only strings this engine hasn't normalized yet are normalized (in one batch).

    Args:
        values (pd.Series[str]): a pandas.Series of non-null strings.

    Returns:
        A pandas.Series with normalized strings and the same index as `values`.
    """
    missing = pd.Series(
        list(dict.fromkeys(v for v in values if v not in self.normalized_strings)),
        dtype=object,
    )
    if len(missing) > 0:
        self.normalized_strings.update(zip(missing, series_normalize(missing)))
    return values.map(self.normalized_strings)

synchronize()

Synchronizes the full list of SyncableContent objects from SyncEngine.content using SyncEngine.synchronize_pair().

There are three distinct layers here:

  1. The sync process that results in a data frame of synced identifiers, defined in each SyncEngine subclass's synchronize_pair() implementation.
  2. Collect remaining unsynced rows and run the sync process on those. Append any newly synced rows to the result dataframe from Layer 1.
  3. Append any remaining unsynced rows to the bottom of the result data frame.

This result dataframe is then deduplicated: by default, the result dataframe is grouped by SyncEngine.join_columns and the first non-null result is selected for each data provider's identifier field.

The result dataframe is then wrapped in a SyncableContent object using the provider from the first SyncableContent object in SyncEngine.content.

Returns:

Type Description
SyncableContent
  • If there are no elements in SyncEngine.content, returns a SyncableContent object with SyncEngine.object_type with provider unknown and an empty pandas.DataFrame.
SyncableContent
  • If there's only one element in SyncEngine.content, returns that element.
SyncableContent
  • If there are 2+ elements in SyncEngine.content, returns a new SyncableContent object with synchronized identifiers based on the SyncableContent objects in SyncEngine.content.
Source code in src/glass_onion/engine.py
def synchronize(self) -> SyncableContent:
    """
    Synchronizes the full list of SyncableContent objects from `SyncEngine.content` using `SyncEngine.synchronize_pair()`.

    There are three distinct layers here:

    1. The sync process that results in a data frame of synced identifiers, defined in each `SyncEngine` subclass's `synchronize_pair()` implementation.
    2. Collect remaining unsynced rows and run the sync process on those. Append any newly synced rows to the result dataframe from Layer 1.
    3. Append any remaining unsynced rows to the bottom of the result data frame.

    This result dataframe is then deduplicated: by default, the result dataframe is grouped by `SyncEngine.join_columns` and the first non-null result is selected for each data provider's identifier field.

    The result dataframe is then wrapped in a SyncableContent object using the `provider` from the first SyncableContent object in `SyncEngine.content`.

    Returns:
        * If there are no elements in `SyncEngine.content`, returns a SyncableContent object with `SyncEngine.object_type` with `provider` unknown and an empty `pandas.DataFrame`.
        * If there's only one element in `SyncEngine.content`, returns that element.
        * If there are 2+ elements in `SyncEngine.content`, returns a new SyncableContent object with synchronized identifiers based on the SyncableContent objects in `SyncEngine.content`.
    """
    if len(self.content) == 0:
        return SyncableContent(self.object_type, "unknown", pd.DataFrame())

    if len(self.content) == 1:
        return self.content[0]

    # conflicts accumulate across every synchronize_all_combinations() pass below
    self.conflicts = []

    # first pass: straight matching - approach: agglomerative
    self.verbose_log(
        f"Starting {self.object_type} synchronization across {len(self.content)} datasets"
    )

    self.verbose_log(f"Layer 1: agglomeration")
    sync_result = self.synchronize_all_combinations()
    id_mask = list(map(lambda x: x.id_field, self.content))

    synced = SyncableContent(
        self.object_type, self.content[0].provider, sync_result.data
    )

    self.verbose_log(
        f"Layer 1: Using {self.content[0].provider} as sync basis, found {len(sync_result.data)} total rows and {len(synced.data)} fully synced rows."
    )

    ## second pass: relate remainders to each other
    remainders = []
    for c in self.content:
        missing = c.data[~(c.data[c.id_field].isin(synced.data[c.id_field]))]

        if len(missing) > 0:
            self.verbose_log(
                f"Layer 2: Aggregating {len(missing)} identified unsynced rows for {c.provider}"
            )
            remainders.append(
                SyncableContent(self.object_type, c.provider, missing)
            )

    if len(remainders) > 1:
        self.verbose_log(
            f"Layer 2: Agglomeration on remaining unsynced rows across {len(remainders)} datasets"
        )
        # self.verbose_log([d.data for d in rem_results])
        remainders_result = self.synchronize_all_combinations(remainders)
        rem_id_mask = list(map(lambda x: x.id_field, remainders))
        rem_id_mask = [
            x for x in rem_id_mask if x in remainders_result.data.columns
        ]
        remainders_result.data.dropna(subset=rem_id_mask, inplace=True)

        self.verbose_log(
            f"Layer 2: Using remainders as sync basis, found {len(remainders_result.data)} new fully synced rows."
        )
        if len(remainders_result.data) > 0:
            synced.append(remainders_result)

    ## third pass: add remainders to end
    remainder_dfs = []
    for c in self.content:
        r = c.data[~(c.data[c.id_field].isin(synced.data[c.id_field]))]
        if len(r) > 0:
            self.verbose_log(
                f"Layer 3: Aggregating {len(r)} identified unsynced rows for {c.provider}"
            )
            applicable_columns = synced.data.columns[
                synced.data.columns.isin(c.data.columns)
            ]
            missing_columns = synced.data.columns[
                ~(synced.data.columns.isin(c.data.columns))
            ]
            r_appendable = r[applicable_columns]
            r_appendable[missing_columns] = pd.NA
            r_appendable["provider"] = c.provider
            remainder_dfs.append(r_appendable)

    if len(remainder_dfs) > 0:
        remainder_df = pd.concat(remainder_dfs, axis=0)
        self.verbose_log(f"Layer 3: Including {len(remainder_df)} unsynced rows")
        synced.append(remainder_df)

    self.verbose_log(
        f"Pre-deduplication: Found {len(synced.data)} total rows: {synced.data}"
    )

    # validation / dedupe step: final table should summarize on key matching columns to eliminate any duplicate rows
    dedupe_aggregation = {
        k: (lambda x: x[x.notna()].iloc[0] if len(x[x.notna()]) > 0 else pd.NA)
        for k in id_mask
    }
    synced.data = (
        synced.data.groupby(self.join_columns).agg(dedupe_aggregation).reset_index()
    )
    synced.data["provider"] = self.content[0].provider
    self.verbose_log(
        f"After deduplication: Found {len(synced.data)} total unique rows based on join_columns: {self.join_columns}"
    )
    return synced

synchronize_all_combinations(content=None)

Internal wrapper around synchronize_pair() that generates all possible combinations of the elements in content to run synchronize_pair on.

Pair results are combined by treating every synced identifier pair as a link and grouping linked identifiers into one row, so an object can be synced through a third provider even if two providers never matched it directly (IE: A <-> C and B <-> C yields A <-> B <-> C). Links are applied strongest first: by the sync_rank column of each pair result if present (lower is stronger), then by identifier, so the result doesn't depend on the order of content. A link is skipped if it would put two identifiers from the same provider in one row; skipped links are recorded in SyncEngine.conflicts.

Parameters:

Name Type Description Default
content list[SyncableContent]

a list of SyncableContent objects that correspond to object_type. If None, defaults to self.content.

None

Returns:

Type Description
SyncableContent

A SyncableContent object with one row per group of linked identifiers. Non-identifier columns are taken from the first object in content that has an identifier in the row.

Source code in src/glass_onion/engine.py
def synchronize_all_combinations(
    self, content: Optional[list[SyncableContent]] = None
) -> SyncableContent:
    """
    Internal wrapper around `synchronize_pair()` that generates all possible combinations of the elements in `content` to run `synchronize_pair` on.

    Pair results are combined by treating every synced identifier pair as a link and grouping linked identifiers into one row, so an object can be
    synced through a third provider even if two providers never matched it directly (IE: A <-> C and B <-> C yields A <-> B <-> C).
    Links are applied strongest first: by the `sync_rank` column of each pair result if present (lower is stronger), then by identifier, so the
    result doesn't depend on the order of `content`. A link is skipped if it would put two identifiers from the same provider in one row; skipped
    links are recorded in `SyncEngine.conflicts`.

    Args:
        content (list[SyncableContent]): a list of SyncableContent objects that correspond to `object_type`. If `None`, defaults to `self.content`.

    Returns:
        A SyncableContent object with one row per group of linked identifiers. Non-identifier columns are taken from the first object in `content` that has an identifier in the row.
    """
    if content is None:
        content = self.content

    results = []
    combos = list(combinations(content, 2))
    for x, y in combos:
        z = self.synchronize_pair(x, y)
        results.append(z)

    id_fields = [c.id_field for c in content]

    # union-find over (id_field, id) nodes. Each root tracks the id_fields in its group
    # so that a link can't merge two identifiers from the same provider.
    parent: dict[Tuple[str, Any], Tuple[str, Any]] = {}
    group_fields: dict[Tuple[str, Any], set[str]] = {}

    def find(node: Tuple[str, Any]) -> Tuple[str, Any]:
        parent.setdefault(node, node)
        group_fields.setdefault(node, {node[0]})
        while parent[node] != node:
            parent[node] = parent[parent[node]]
            node = parent[node]
        return node

    def node_key(node: Tuple[str, Any]) -> Tuple[str, str]:
        # identifiers can be of mixed types, so compare them as strings
        return (node[0], str(node[1]))

    # collect every link as (rank, left node, right node) so they can be applied strongest first, independent of
    # the order of `content`. Pair results without a `sync_rank` column treat every link as equally strong.
    links: list[Tuple[float, Tuple[str, Any], Tuple[str, Any]]] = []
    for r in results:
        pair_fields = [f for f in id_fields if f in r.data.columns]
        ranks = (
            r.data["sync_rank"].fillna(0)
            if "sync_rank" in r.data.columns
            else pd.Series(0, index=r.data.index)
        )
        for rank, row in zip(ranks, r.data[pair_fields].itertuples(index=False)):
            nodes = sorted(
                [(f, v) for f, v in zip(pair_fields, row) if pd.notna(v)],
                key=node_key,
            )
            links += [(rank, nodes[0], node) for node in nodes[1:]]

    for rank, left, right in sorted(
        links, key=lambda l: (l[0], node_key(l[1]), node_key(l[2]))
    ):
        root_x, root_y = find(left), find(right)
        if root_x == root_y:
            continue
        if group_fields[root_x] & group_fields[root_y]:
            self.verbose_log(
                f"Skipping link {left} <-> {right}: would put two identifiers from the same provider in one row"
            )
            self.conflicts.append((left, right))
            continue
        parent[root_y] = root_x
        group_fields[root_x] |= group_fields.pop(root_y)

    groups: dict[Tuple[str, Any], dict[str, Any]] = {}
    for node in parent:
        groups.setdefault(find(node), {})[node[0]] = node[1]

    unified = pd.DataFrame(list(groups.values()), columns=id_fields)

    # re-attach non-identifier columns, preferring earlier objects in `content`
    metadata_columns = []
    for r in results:
        for col in r.data.columns:
            if (
                col not in id_fields
                and col not in metadata_columns
                and not col.endswith(f"_{self.object_type}_id")
                and any(col in c.data.columns for c in content)
            ):
                metadata_columns.append(col)

    for c in content:
        lookup = c.data.drop_duplicates(subset=c.id_field).set_index(c.id_field)
        for col in metadata_columns:
            if col not in lookup.columns:
                continue
            values = unified[c.id_field].map(lookup[col])
            unified[col] = (
                unified[col].fillna(values) if col in unified.columns else values
            )

    return SyncableContent(
        object_type=self.object_type, provider=content[0].provider, data=unified
    )

synchronize_pair(input1, input2)

Synchronize two SyncableContent objects.

This method should be overridden for each new object type: see PlayerSyncEngine for an example.

Parameters:

Name Type Description Default
input1 SyncableContent

a SyncableContent object from SyncEngine.content

required
input2 SyncableContent

a SyncableContent object from SyncEngine.content

required

Returns:

Type Description
SyncableContent

If input1's underlying data dataframe is empty, returns input2 with a column in input2.data for input1.id_field.

SyncableContent

If input2's underlying data dataframe is empty, returns input1 with a column in input1.data for input2.id_field.

SyncableContent

If both dataframes are non-empty, returns a new PlayerSyncableContent object with synchronized identifiers from input1 and input2.

Raises:

Type Description
NotImplementedError

if this method is not overridden.

Source code in src/glass_onion/engine.py
def synchronize_pair(
    self, input1: SyncableContent, input2: SyncableContent
) -> SyncableContent:
    """
    Synchronize two SyncableContent objects.

    This method should be overridden for each new object type: see [PlayerSyncEngine][glass_onion.player.PlayerSyncEngine] for an example.

    Args:
        input1 (glass_onion.SyncableContent): a SyncableContent object from `SyncEngine.content`
        input2 (glass_onion.SyncableContent): a SyncableContent object from `SyncEngine.content`

    Returns:
        If `input1`'s underlying `data` dataframe is empty, returns `input2` with a column in `input2.data` for `input1.id_field`.
        If `input2`'s underlying `data` dataframe is empty, returns `input1` with a column in `input1.data` for `input2.id_field`.
        If both dataframes are non-empty, returns a new PlayerSyncableContent object with synchronized identifiers from `input1` and `input2`.

    Raises:
        NotImplementedError: if this method is not overridden.
    """
    if len(input1.data) == 0 and len(input2.data) > 0:
        input2.data[input1.id_field] = pd.NA
        return input2

    if len(input1.data) > 0 and len(input2.data) == 0:
        input1.data[input2.id_field] = pd.NA
        return input1

    raise NotImplementedError()

synchronize_with_cosine_similarity(input1, input2, fields, threshold=0.75)

Synchronizes two SyncableContent objects using cosine similarity and the columns provided by the two-tuple fields.

Index 0 of fields is the column to use for similarity in input1, while index 1 is the column to use in input2.

See apply_cosine_similarity for more details on implementation.

Parameters:

Name Type Description Default
input1 SyncableContent

a SyncableContent object.

required
input2 SyncableContent

a SyncableContent object.

required
fields Tuple[str, str]

a two-tuple containing the column names to use for player name similarity.

required
threshold float

the minimum similarity threshold that a match must be in order to be considered valid. Options: any float value from 0.0 to 1.0. Options outside this range will be clamped to the min or max value.

0.75

Returns:

Type Description
DataFrame

pandas.DataFrame: contains unique synchronized identifier pairs from input1 and input2. The available columns are the id_field values of input1 and input2.

Source code in src/glass_onion/engine.py
def synchronize_with_cosine_similarity(
    self,
    input1: SyncableContent,
    input2: SyncableContent,
    fields: Tuple[str, str],
    threshold: float = 0.75,
) -> pd.DataFrame:
    """
    Synchronizes two SyncableContent objects using cosine similarity and the columns provided by the two-tuple `fields`.

    Index 0 of `fields` is the column to use for similarity in `input1`, while index 1 is the column to use in `input2`.

    See [apply_cosine_similarity][glass_onion.utils.apply_cosine_similarity] for more details on implementation.

    Args:
        input1 (glass_onion.engine.SyncableContent): a SyncableContent object.
        input2 (glass_onion.engine.SyncableContent): a SyncableContent object.
        fields (Tuple[str, str]): a two-tuple containing the column names to use for player name similarity.
        threshold (float): the minimum similarity threshold that a match must be in order to be considered valid. Options: any float value from 0.0 to 1.0. Options outside this range will be clamped to the min or max value.

    Returns:
        pandas.DataFrame: contains unique synchronized identifier pairs from `input1` and `input2`. The available columns are the `id_field` values of `input1` and `input2`.
    """

    assert len(fields) == 2, (
        "Must provide two columns (one from `input1` and one from `input2`) as `fields`."
    )
    assert fields[0] in input1.data.columns, (
        "First element of `fields` must exist in `input1.data`."
    )
    assert fields[1] in input2.data.columns, (
        "Second element of `fields` must exist in `input2.data`."
    )
    assert len(input1.data) > 0 and len(input2.data) > 0, (
        "Both SyncableContent objects must be non-empty."
    )

    input1_fields = input1.data.loc[
        input1.data[fields[0]].notna(), fields[0]
    ].reset_index(drop=True)
    input2_fields = input2.data.loc[
        input2.data[fields[1]].notna(), fields[1]
    ].reset_index(drop=True)

    # if one or both of the dataframes are now empty, just return an empty result
    # with both fields
    if not (len(input1_fields) > 0 and len(input2_fields) > 0):
        return pd.DataFrame(
            {i: pd.Series(dtype=str) for i in [input1.id_field, input2.id_field]}
        )

    adjusted_threshold = max(min(threshold, 1.0), 0.0)

    # fast path: with one name on each side, the only possible pair can be scored without fitting a vectorizer
    if len(input1_fields) == 1 and len(input2_fields) == 1:
        normalized = self.normalize(pd.concat([input1_fields, input2_fields]))
        similarity = string_pair_cosine_similarity(
            normalized.iloc[0], normalized.iloc[1]
        )
        if similarity is not None:
            if similarity < adjusted_threshold:
                return pd.DataFrame(
                    {
                        i: pd.Series(dtype=str)
                        for i in [input1.id_field, input2.id_field]
                    }
                )
            return pd.DataFrame(
                {
                    input1.id_field: input1.data.loc[
                        input1.data[fields[0]].notna(), input1.id_field
                    ].reset_index(drop=True),
                    input2.id_field: input2.data.loc[
                        input2.data[fields[1]].notna(), input2.id_field
                    ].reset_index(drop=True),
                }
            )

    cache_key = (tuple(input1_fields), tuple(input2_fields))
    if cache_key not in self.cosine_similarity_cache:
        self.cosine_similarity_cache[cache_key] = apply_cosine_similarity(
            input1_fields, input2_fields
        )
    match_results = self.cosine_similarity_cache[cache_key]

    # sort_values() returns a copy, so the cached result isn't modified below
    result = match_results.sort_values(by="similarity", ascending=False)
    result = result[result.similarity >= adjusted_threshold]
    result["similarity_rank"] = result.groupby(["input1", "input2"])[
        "similarity"
    ].rank(method="dense", ascending=False)
    result = result[result.similarity_rank <= 1]

    composite = pd.merge(
        input1.data[[fields[0], input1.id_field]],
        result,
        left_on=fields[0],
        right_on="input1",
        how="inner",
    )

    composite = pd.merge(
        composite,
        input2.data[[fields[1], input2.id_field]],
        left_on="input2",
        right_on=fields[1],
        how="inner",
    )

    # deduplicate if there are duplicate name matches.
    # Must use rank(method="first") in case `similarity` is the same.
    composite["field_rank"] = composite.groupby(input1.id_field)["similarity"].rank(
        method="first", ascending=False
    )
    return composite.loc[
        composite["field_rank"] == 1, [input1.id_field, input2.id_field]
    ]

synchronize_with_fuzzy_match(input1, input2, fields, threshold=0.9)

Synchronizes two SyncableContent objects using fuzzy matching similarity using the columns provided by the two-tuple fields.

Index 0 of fields is the column to use for similarity in input1, while index 1 is the column to use in input2.

NOTE: this approach uses a dictionary/map, so a string from input1 can only be mapped to one string in input2. If there are duplicate instances of a string in input1 under a different ID, the 2nd...Nth instances of that string will not get matched.

See thefuzz.process() for more details.

Parameters:

Name Type Description Default
input1 SyncableContent

a SyncableContent object.

required
input2 SyncableContent

a SyncableContent object.

required
fields Tuple[str, str]

a two-tuple containing the column names to use for player name similarity.

required
threshold float

the minimum similarity threshold that a match must be in order to be considered valid. Options: any float value from 0.0 to 1.0. Options outside this range will be clamped to the min or max value.

0.9

Returns:

Type Description
DataFrame

a pandas.DataFrame object that contains synchronized identifier pairs from input1 and input2. The available columns are the id_field values of input1 and input2.

Source code in src/glass_onion/engine.py
def synchronize_with_fuzzy_match(
    self,
    input1: SyncableContent,
    input2: SyncableContent,
    fields: Tuple[str, str],
    threshold: float = 0.90,
):
    """
    Synchronizes two SyncableContent objects using fuzzy matching similarity using the columns provided by the two-tuple `fields`.

    Index 0 of `fields` is the column to use for similarity in `input1`, while index 1 is the column to use in `input2`.

    NOTE: this approach uses a dictionary/map, so a string from `input1` can only be mapped to one string in `input2`.
    If there are duplicate instances of a string in `input1` under a different ID, the 2nd...Nth instances of that string will not get matched.

    See [thefuzz.process()](https://github.com/seatgeek/thefuzz/blob/master/thefuzz/process.py) for more details.

    Args:
        input1 (glass_onion.engine.SyncableContent): a SyncableContent object.
        input2 (glass_onion.engine.SyncableContent): a SyncableContent object.
        fields (Tuple[str, str]): a two-tuple containing the column names to use for player name similarity.
        threshold (float): the minimum similarity threshold that a match must be in order to be considered valid. Options: any float value from 0.0 to 1.0. Options outside this range will be clamped to the min or max value.

    Returns:
        (pandas.DataFrame): a pandas.DataFrame object that contains synchronized identifier pairs from `input1` and `input2`. The available columns are the `id_field` values of `input1` and `input2`.
    """

    assert len(fields) == 2, (
        "Must provide two columns (one from `input1` and one from `input2`) as `fields`."
    )
    assert fields[0] in input1.data.columns, (
        "First element of `fields` must exist in `input1.data`."
    )
    assert fields[1] in input2.data.columns, (
        "Second element of `fields` must exist in `input2.data`."
    )
    assert len(input1.data) > 0 and len(input2.data) > 0, (
        "Both SyncableContent objects must be non-empty."
    )

    name_population = input1.data[fields[0]]
    name_sample = input2.data[fields[1]]

    name_population = input1.data.loc[
        input1.data[fields[0]].notna(), [fields[0], input1.id_field]
    ]
    name_sample = input2.data.loc[
        input2.data[fields[1]].notna(), [fields[1], input2.id_field]
    ]

    # if one or both of the dataframes are now empty, just return an empty result
    # with both fields
    if not (len(name_population) > 0 and len(name_sample) > 0):
        return pd.DataFrame(
            {i: pd.Series(dtype=str) for i in [input1.id_field, input2.id_field]}
        )

    normalized_name_population = self.normalize(name_population[fields[0]])
    normalized_name_sample = self.normalize(name_sample[fields[1]])

    adjusted_threshold = max(min(threshold, 1.0), 0.0) * 100

    results = []
    name_map: dict[str, str] = {}
    for j in range(0, len(normalized_name_sample)):
        i2_raw = normalized_name_sample.loc[normalized_name_sample.index[j]]
        if i2_raw in name_map.values():
            continue

        result = process.extractOne(i2_raw, normalized_name_population)
        if result and result[1] >= adjusted_threshold:
            if result[0] in name_map.keys():
                continue

            self.verbose_log(f"Logging match: {result[0]} -> {i2_raw}")
            name_map[result[0]] = i2_raw
            i = result[2]
            results.append(
                {
                    f"{input1.id_field}": name_population.loc[i, input1.id_field],
                    f"{input2.id_field}": name_sample.loc[
                        name_sample.index[j], input2.id_field
                    ],
                }
            )
        elif result and result[1] < adjusted_threshold:
            self.verbose_log(
                f"not match: {result[0]} -/-> {i2_raw} (similarity: {result[1]} < ({adjusted_threshold}))"
            )

    if len(results) == 0:
        return pd.DataFrame(data=[], columns=[input1.id_field, input2.id_field])

    return pd.DataFrame(results)

synchronize_with_naive_match(input1, input2, fields)

Synchronizes two SyncableContent objects using the naive similarity using the columns provided by the two-tuple fields.

Index 0 of fields is the column to use for similarity in input1, while index 1 is the column to use in input2.

NOTE: this is a naive approach that uses a dictionary/map, so a string from input1 can only be mapped to one string in input2. If there are duplicate instances of a string in input1 under a different ID, the 2nd...Nth instances of that string will not get matched.

Parameters:

Name Type Description Default
input1 SyncableContent

a SyncableContent object.

required
input2 SyncableContent

a SyncableContent object.

required
fields Tuple[str, str]

a two-tuple containing the column names to use for player name similarity.

required

Returns:

Type Description
DataFrame

pandas.DataFrame: contains synchronized identifier pairs from input1 and input2. The available columns are the id_field values of input1 and input2.

Source code in src/glass_onion/engine.py
def synchronize_with_naive_match(
    self, input1: SyncableContent, input2: SyncableContent, fields: Tuple[str, str]
) -> pd.DataFrame:
    """
    Synchronizes two SyncableContent objects using the `naive` similarity using the columns provided by the two-tuple `fields`.

    Index 0 of `fields` is the column to use for similarity in `input1`, while index 1 is the column to use in `input2`.

    NOTE: this is a _naive_ approach that uses a dictionary/map, so a string from `input1` can only be mapped to one string in `input2`.
    If there are duplicate instances of a string in `input1` under a different ID, the 2nd...Nth instances of that string will not get matched.

    Args:
        input1 (glass_onion.engine.SyncableContent): a SyncableContent object.
        input2 (glass_onion.engine.SyncableContent): a SyncableContent object.
        fields (Tuple[str, str]): a two-tuple containing the column names to use for player name similarity.

    Returns:
        pandas.DataFrame: contains synchronized identifier pairs from `input1` and `input2`. The available columns are the `id_field` values of `input1` and `input2`.
    """

    assert len(fields) == 2, (
        "Must provide two columns (one from `input1` and one from `input2`) as `fields`."
    )
    assert fields[0] in input1.data.columns, (
        "First element of `fields` must exist in `input1.data`."
    )
    assert fields[1] in input2.data.columns, (
        "Second element of `fields` must exist in `input2.data`."
    )

    assert len(input1.data) > 0 and len(input2.data) > 0, (
        "Both SyncableContent objects must be non-empty."
    )

    name_population = input1.data.loc[
        input1.data[fields[0]].notna(), [fields[0], input1.id_field]
    ]
    name_sample = input2.data.loc[
        input2.data[fields[1]].notna(), [fields[1], input2.id_field]
    ]

    # if one or both of the dataframes are now empty, just return an empty result
    # with both fields
    if not (len(name_population) > 0 and len(name_sample) > 0):
        return pd.DataFrame(
            {i: pd.Series(dtype=str) for i in [input1.id_field, input2.id_field]}
        )

    normalized_name_population = self.normalize(name_population[fields[0]])
    normalized_name_sample = self.normalize(name_sample[fields[1]])

    # only the first occurrence of each normalized string can ever be matched,
    # so collapse both sides to {string: id of first occurrence} (dicts keep insertion order).
    population_ids: dict[str, Any] = {}
    for name, id in zip(
        normalized_name_population.tolist(),
        name_population[input1.id_field].tolist(),
    ):
        population_ids.setdefault(name, id)

    sample_ids: dict[str, Any] = {}
    for name, id in zip(
        normalized_name_sample.tolist(), name_sample[input2.id_field].tolist()
    ):
        sample_ids.setdefault(name, id)

    results = []
    name_map: dict[str, str] = {}
    matched_sample: set[str] = set()

    # first pass to encapsulate exact matches
    for i1_raw, i1_id in population_ids.items():
        if i1_raw in sample_ids:
            self.verbose_log(f"Logging match: {i1_raw} -> {i1_raw}")
            name_map[i1_raw] = i1_raw
            matched_sample.add(i1_raw)
            results.append(
                {
                    f"{input1.id_field}": i1_id,
                    f"{input2.id_field}": sample_ids[i1_raw],
                }
            )

    # second pass: match if either name's token set is a subset of the other's.
    # Any such pair shares at least one token, so an inverted index of
    # token -> sample positions limits the comparisons to plausible candidates.
    sample_names = [n for n in sample_ids.keys() if n not in matched_sample]
    sample_sets = [frozenset(re.split(r"\s+", n.strip())) for n in sample_names]
    token_index: dict[str, list[int]] = {}
    for j, i2_set in enumerate(sample_sets):
        for token in i2_set:
            token_index.setdefault(token, []).append(j)

    for i1_raw, i1_id in population_ids.items():
        if i1_raw in name_map:
            continue

        i1_set = frozenset(re.split(r"\s+", i1_raw))
        candidates = sorted(
            {j for token in i1_set for j in token_index.get(token, ())}
        )
        for j in candidates:
            i2_raw = sample_names[j]
            if i2_raw in matched_sample:
                continue

            i2_set = sample_sets[j]
            if i2_set <= i1_set or i1_set <= i2_set:
                # this is a match
                self.verbose_log(f"Logging match: {i1_raw} -> {i2_raw}")
                name_map[i1_raw] = i2_raw
                matched_sample.add(i2_raw)
                results.append(
                    {
                        f"{input1.id_field}": i1_id,
                        f"{input2.id_field}": sample_ids[i2_raw],
                    }
                )
                break

    if len(results) == 0:
        return pd.DataFrame(data=[], columns=[input1.id_field, input2.id_field])

    return pd.DataFrame(results)

verbose_log(msg)

Helper method to enable verbose logging via print(). These logs are sent to stdout (the default output location of print()). Logs are also prefixed with a timestamp for easy sorting.

Parameters:

Name Type Description Default
msg Any

any string-serializable object

required
Source code in src/glass_onion/engine.py
def verbose_log(self, msg: Any):
    """
    Helper method to enable verbose logging via `print()`. These logs are sent to `stdout` (the default output location of `print()`). Logs are also prefixed with a timestamp for easy sorting.

    Args:
        msg (Any): any string-serializable object
    """
    if self.verbose:
        print(f"{datetime.now()}: {msg}")

SyncableContent

The underlying unit of the synchronization logic. This class is just a wrapper for the dataframe being synchronized, providing some context on the object type (object_type) being synchronized and the provider from which the data is sourced.

This class should be subclassed for each new object type: see PlayerSyncableContent for an example.

Source code in src/glass_onion/engine.py
class SyncableContent:
    """
    The underlying unit of the synchronization logic. This class is just a wrapper for the dataframe being synchronized, providing some context on the object type (`object_type`) being synchronized and the provider from which the data is sourced.

    This class should be subclassed for each new object type: see [PlayerSyncableContent][glass_onion.player.PlayerSyncableContent] for an example.
    """

    def validate_data_schema(self) -> bool:
        """
        Checks if this object's `data` meets the schema requirements for this object type.

        This is not run when the object is created: [SyncEngine][glass_onion.engine.SyncEngine] runs it on each object in `content` when the engine is created, so objects built internally during synchronization aren't re-validated.

        This class should be subclassed for each new object type: see [PlayerDataSchema][glass_onion.player.PlayerDataSchema] for an example.
        """
        assert self.data is not None, f"Field `data` can not be null"
        assert isinstance(self.data, pd.DataFrame), (
            "Field `data` must be a pandas.DataFrame object"
        )

        assert self.id_field in self.data.columns, (
            f"Field `{self.id_field}` must be available as a column in `data`"
        )
        return True

    def __init__(self, object_type: str, provider: str, data: pd.DataFrame):
        self.object_type = object_type
        self.provider = provider
        self.id_field = f"{provider}_{object_type}_id"
        self.data = data

        # only run the base structural checks here: subclass schema validation is expensive, so SyncEngine runs it once per input
        assert SyncableContent.validate_data_schema(self), (
            "`data` does not meet the schema requirements for this SyncableContent class."
        )

    def merge(self, right: "SyncableContent") -> "SyncableContent":
        """
        Combine two SyncableContent objects into one by conducting a left-join on the underlying dataframes.

        Notes:

        * This operation is not in-place and produces a new SyncableContent object.
        * This operation is not permitted on SyncableContent objects that do not use the same `object_type`.
        * This operation only moves fields from `right` that are identifiers of the same `object_type` as `self`. Example: if `self` has `object_type` player, the only fields merged from right will be those that contain `_player_id`.
        * This operation's left-join is done using the `id_field` of `right`, which MUST exist in `self` for the operation to work.

        Args:
            right (glass_onion.SyncableContent): a SyncableContent object.

        Returns:
            a new object that contains the shared `object_type` of both parent objects, `self.provider`, and a combined `data` `pandas.DataFrame` that contains all columns from `right` that are identifiers of the same `object_type` as `self` + all columns from `self.data`.
        """
        if right is None:
            return self

        assert self.object_type == right.object_type, (
            f"Left `object_type` ({self.object_type}) does not match Right `object_type` ({right.object_type})."
        )
        assert right.id_field in self.data.columns, (
            f"Right `id_field` ({right.id_field}) not in Left `data` columns."
        )

        id_mask = right.data.columns[
            right.data.columns.str.contains(f"_{self.object_type}_id")
        ]

        overlapping_mask = right.data.columns[
            (right.data.columns.isin(self.data.columns))
            & (right.data.columns != right.id_field)
        ]

        overlapping_id_mask = right.data.columns[
            (right.data.columns.isin(overlapping_mask))
            & (right.data.columns.isin(id_mask))
        ]

        merged = pd.merge(self.data, right.data[id_mask], how="left", on=right.id_field)
        dataframe_coalesce(merged, overlapping_id_mask)

        return SyncableContent(
            object_type=self.object_type, provider=self.provider, data=merged
        )

    def append(
        self, right: Union["SyncableContent", pd.DataFrame]
    ) -> "SyncableContent":
        """
        Combine two SyncableContent objects into one by appending all rows from `right` to the end of `left`.

        Notes:

        * This operation is in-place and does NOT produce a new SyncableContent object. This method simply returns the adjusted `left` object.
        * If `right` is a SyncableContent object, the rows from its `data` dataframe are appended to the end of `left`'s `data` dataframe. If `right` is a `pandas.DataFrame` object, its own rows are appended to the end of `left`'s `data` dataframe.
        * This operation is not permitted on SyncableContent objects that do not use the same `object_type`.
        * If `right` is None, this method is a no-op.

        Args:
            right (glass_onion.SyncableContent OR `pandas.DataFrame`): a SyncableContent object or a pandas.DataFrame object.

        Returns:
            `self` but with a `data` pandas.DataFrame that contains all rows from `right` and `left`.
        """
        new_data = None
        if right is not None:
            if isinstance(right, SyncableContent):
                assert self.object_type == right.object_type, (
                    f"Left `object_type` ({self.object_type}) does not match Right `object_type` ({right.object_type})."
                )

                new_data = right.data

            elif isinstance(right, pd.DataFrame):
                new_data = right

        if new_data is not None:
            self.data = pd.concat([self.data, new_data], axis=0, ignore_index=True)

        return self

    def normalize_ids(self):
        """
        Converts all object identifiers in this instance into strings, accounting for NaN/None, float/int differences, etc.

        NOTE: This operation is in-place and directly modifies the underlying `data` pandas.DataFrame.
        """
        self.data[self.id_field] = series_stringify_object_id(self.data[self.id_field])

append(right)

Combine two SyncableContent objects into one by appending all rows from right to the end of left.

Notes:

  • This operation is in-place and does NOT produce a new SyncableContent object. This method simply returns the adjusted left object.
  • If right is a SyncableContent object, the rows from its data dataframe are appended to the end of left's data dataframe. If right is a pandas.DataFrame object, its own rows are appended to the end of left's data dataframe.
  • This operation is not permitted on SyncableContent objects that do not use the same object_type.
  • If right is None, this method is a no-op.

Parameters:

Name Type Description Default
right glass_onion.SyncableContent OR `pandas.DataFrame`

a SyncableContent object or a pandas.DataFrame object.

required

Returns:

Type Description
SyncableContent

self but with a data pandas.DataFrame that contains all rows from right and left.

Source code in src/glass_onion/engine.py
def append(
    self, right: Union["SyncableContent", pd.DataFrame]
) -> "SyncableContent":
    """
    Combine two SyncableContent objects into one by appending all rows from `right` to the end of `left`.

    Notes:

    * This operation is in-place and does NOT produce a new SyncableContent object. This method simply returns the adjusted `left` object.
    * If `right` is a SyncableContent object, the rows from its `data` dataframe are appended to the end of `left`'s `data` dataframe. If `right` is a `pandas.DataFrame` object, its own rows are appended to the end of `left`'s `data` dataframe.
    * This operation is not permitted on SyncableContent objects that do not use the same `object_type`.
    * If `right` is None, this method is a no-op.

    Args:
        right (glass_onion.SyncableContent OR `pandas.DataFrame`): a SyncableContent object or a pandas.DataFrame object.

    Returns:
        `self` but with a `data` pandas.DataFrame that contains all rows from `right` and `left`.
    """
    new_data = None
    if right is not None:
        if isinstance(right, SyncableContent):
            assert self.object_type == right.object_type, (
                f"Left `object_type` ({self.object_type}) does not match Right `object_type` ({right.object_type})."
            )

            new_data = right.data

        elif isinstance(right, pd.DataFrame):
            new_data = right

    if new_data is not None:
        self.data = pd.concat([self.data, new_data], axis=0, ignore_index=True)

    return self

merge(right)

Combine two SyncableContent objects into one by conducting a left-join on the underlying dataframes.

Notes:

  • This operation is not in-place and produces a new SyncableContent object.
  • This operation is not permitted on SyncableContent objects that do not use the same object_type.
  • This operation only moves fields from right that are identifiers of the same object_type as self. Example: if self has object_type player, the only fields merged from right will be those that contain _player_id.
  • This operation's left-join is done using the id_field of right, which MUST exist in self for the operation to work.

Parameters:

Name Type Description Default
right SyncableContent

a SyncableContent object.

required

Returns:

Type Description
SyncableContent

a new object that contains the shared object_type of both parent objects, self.provider, and a combined data pandas.DataFrame that contains all columns from right that are identifiers of the same object_type as self + all columns from self.data.

Source code in src/glass_onion/engine.py
def merge(self, right: "SyncableContent") -> "SyncableContent":
    """
    Combine two SyncableContent objects into one by conducting a left-join on the underlying dataframes.

    Notes:

    * This operation is not in-place and produces a new SyncableContent object.
    * This operation is not permitted on SyncableContent objects that do not use the same `object_type`.
    * This operation only moves fields from `right` that are identifiers of the same `object_type` as `self`. Example: if `self` has `object_type` player, the only fields merged from right will be those that contain `_player_id`.
    * This operation's left-join is done using the `id_field` of `right`, which MUST exist in `self` for the operation to work.

    Args:
        right (glass_onion.SyncableContent): a SyncableContent object.

    Returns:
        a new object that contains the shared `object_type` of both parent objects, `self.provider`, and a combined `data` `pandas.DataFrame` that contains all columns from `right` that are identifiers of the same `object_type` as `self` + all columns from `self.data`.
    """
    if right is None:
        return self

    assert self.object_type == right.object_type, (
        f"Left `object_type` ({self.object_type}) does not match Right `object_type` ({right.object_type})."
    )
    assert right.id_field in self.data.columns, (
        f"Right `id_field` ({right.id_field}) not in Left `data` columns."
    )

    id_mask = right.data.columns[
        right.data.columns.str.contains(f"_{self.object_type}_id")
    ]

    overlapping_mask = right.data.columns[
        (right.data.columns.isin(self.data.columns))
        & (right.data.columns != right.id_field)
    ]

    overlapping_id_mask = right.data.columns[
        (right.data.columns.isin(overlapping_mask))
        & (right.data.columns.isin(id_mask))
    ]

    merged = pd.merge(self.data, right.data[id_mask], how="left", on=right.id_field)
    dataframe_coalesce(merged, overlapping_id_mask)

    return SyncableContent(
        object_type=self.object_type, provider=self.provider, data=merged
    )

normalize_ids()

Converts all object identifiers in this instance into strings, accounting for NaN/None, float/int differences, etc.

NOTE: This operation is in-place and directly modifies the underlying data pandas.DataFrame.

Source code in src/glass_onion/engine.py
def normalize_ids(self):
    """
    Converts all object identifiers in this instance into strings, accounting for NaN/None, float/int differences, etc.

    NOTE: This operation is in-place and directly modifies the underlying `data` pandas.DataFrame.
    """
    self.data[self.id_field] = series_stringify_object_id(self.data[self.id_field])

validate_data_schema()

Checks if this object's data meets the schema requirements for this object type.

This is not run when the object is created: SyncEngine runs it on each object in content when the engine is created, so objects built internally during synchronization aren't re-validated.

This class should be subclassed for each new object type: see PlayerDataSchema for an example.

Source code in src/glass_onion/engine.py
def validate_data_schema(self) -> bool:
    """
    Checks if this object's `data` meets the schema requirements for this object type.

    This is not run when the object is created: [SyncEngine][glass_onion.engine.SyncEngine] runs it on each object in `content` when the engine is created, so objects built internally during synchronization aren't re-validated.

    This class should be subclassed for each new object type: see [PlayerDataSchema][glass_onion.player.PlayerDataSchema] for an example.
    """
    assert self.data is not None, f"Field `data` can not be null"
    assert isinstance(self.data, pd.DataFrame), (
        "Field `data` must be a pandas.DataFrame object"
    )

    assert self.id_field in self.data.columns, (
        f"Field `{self.id_field}` must be available as a column in `data`"
    )
    return True