|
| 1 | +# Generated on 2025-09-09 for merging duplicate AlgorithmCategoryMaps |
| 2 | + |
| 3 | +from django.db import migrations |
| 4 | +from django.db.models import Count |
| 5 | +import logging |
| 6 | +import json |
| 7 | + |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +def merge_duplicate_category_maps(apps, schema_editor): |
| 13 | + """ |
| 14 | + Find duplicate AlgorithmCategoryMaps based on their `data` field, |
| 15 | + compare them (description, version, associated Algorithms, associated Classifications), |
| 16 | + choose a keeper, then reassign Classifications and Algorithms to use the keeper. |
| 17 | + Then delete the duplicates. |
| 18 | + """ |
| 19 | + AlgorithmCategoryMap = apps.get_model("ml", "AlgorithmCategoryMap") |
| 20 | + Algorithm = apps.get_model("ml", "Algorithm") |
| 21 | + Classification = apps.get_model("main", "Classification") |
| 22 | + |
| 23 | + # Group category maps by their data content (JSON field) |
| 24 | + # We'll use a dictionary to group by serialized data |
| 25 | + data_groups = {} |
| 26 | + |
| 27 | + for category_map in AlgorithmCategoryMap.objects.all(): |
| 28 | + # Normalize the data for comparison by converting to a sorted JSON string |
| 29 | + normalized_data = json.dumps(category_map.data, sort_keys=True) |
| 30 | + |
| 31 | + if normalized_data not in data_groups: |
| 32 | + data_groups[normalized_data] = [] |
| 33 | + data_groups[normalized_data].append(category_map) |
| 34 | + |
| 35 | + # Process each group that has duplicates |
| 36 | + duplicates_found = 0 |
| 37 | + maps_merged = 0 |
| 38 | + |
| 39 | + for normalized_data, category_maps in data_groups.items(): |
| 40 | + if len(category_maps) <= 1: |
| 41 | + continue # Skip groups with only one category map |
| 42 | + |
| 43 | + duplicates_found += len(category_maps) - 1 |
| 44 | + logger.info(f"Found {len(category_maps)} duplicate category maps with data hash") |
| 45 | + |
| 46 | + # Choose the keeper - prioritize by: |
| 47 | + # 1. Has description |
| 48 | + # 2. Has version |
| 49 | + # 3. Most associated algorithms |
| 50 | + # 4. Most associated classifications |
| 51 | + # 5. Earliest created (as tie-breaker) |
| 52 | + |
| 53 | + def score_category_map(cm): |
| 54 | + score = 0 |
| 55 | + |
| 56 | + # Has description |
| 57 | + if cm.description: |
| 58 | + score += 1000 |
| 59 | + |
| 60 | + # Has version |
| 61 | + if cm.version: |
| 62 | + score += 500 |
| 63 | + |
| 64 | + # Count associated algorithms |
| 65 | + algorithm_count = Algorithm.objects.filter(category_map=cm).count() |
| 66 | + score += algorithm_count * 100 |
| 67 | + |
| 68 | + # Count associated classifications |
| 69 | + classification_count = Classification.objects.filter(category_map=cm).count() |
| 70 | + score += classification_count * 10 |
| 71 | + |
| 72 | + # Prefer older records (negative timestamp for sorting) |
| 73 | + score -= cm.created_at.timestamp() / 1000000 # Small adjustment for tie-breaking |
| 74 | + |
| 75 | + return score |
| 76 | + |
| 77 | + # Sort by score (highest first) and pick the keeper |
| 78 | + sorted_maps = sorted(category_maps, key=score_category_map, reverse=True) |
| 79 | + keeper = sorted_maps[0] |
| 80 | + duplicates = sorted_maps[1:] |
| 81 | + |
| 82 | + logger.info(f"Keeping category map #{keeper.pk}, merging {len(duplicates)} duplicates") |
| 83 | + |
| 84 | + # Merge data from duplicates to keeper |
| 85 | + for duplicate in duplicates: |
| 86 | + # Update algorithms pointing to the duplicate |
| 87 | + algorithms_updated = Algorithm.objects.filter(category_map=duplicate).update(category_map=keeper) |
| 88 | + logger.info(f"Updated {algorithms_updated} algorithms from category map #{duplicate.pk} to #{keeper.pk}") |
| 89 | + |
| 90 | + # Update classifications pointing to the duplicate |
| 91 | + classifications_updated = Classification.objects.filter(category_map=duplicate).update(category_map=keeper) |
| 92 | + logger.info( |
| 93 | + f"Updated {classifications_updated} classifications from category map #{duplicate.pk} to #{keeper.pk}" |
| 94 | + ) |
| 95 | + |
| 96 | + # If duplicate has better description or version, update keeper |
| 97 | + if not keeper.description and duplicate.description: |
| 98 | + keeper.description = duplicate.description |
| 99 | + logger.info(f"Updated keeper description from duplicate #{duplicate.pk}") |
| 100 | + |
| 101 | + if not keeper.version and duplicate.version: |
| 102 | + keeper.version = duplicate.version |
| 103 | + logger.info(f"Updated keeper version from duplicate #{duplicate.pk}") |
| 104 | + |
| 105 | + if not keeper.uri and duplicate.uri: |
| 106 | + keeper.uri = duplicate.uri |
| 107 | + logger.info(f"Updated keeper URI from duplicate #{duplicate.pk}") |
| 108 | + |
| 109 | + # Save keeper with any merged data |
| 110 | + keeper.save() |
| 111 | + |
| 112 | + # Delete the duplicates |
| 113 | + for duplicate in duplicates: |
| 114 | + logger.info(f"Deleting duplicate category map #{duplicate.pk}") |
| 115 | + duplicate.delete() |
| 116 | + |
| 117 | + maps_merged += len(duplicates) |
| 118 | + |
| 119 | + logger.info( |
| 120 | + f"Migration completed: {duplicates_found} duplicates found, {maps_merged} category maps merged and deleted" |
| 121 | + ) |
| 122 | + |
| 123 | + |
| 124 | +def reverse_merge_duplicate_category_maps(apps, schema_editor): |
| 125 | + """ |
| 126 | + This migration cannot be easily reversed since we deleted duplicate data. |
| 127 | + The reverse operation would require restoring the deleted category maps |
| 128 | + and reassigning relationships, which is not feasible without backup data. |
| 129 | + """ |
| 130 | + raise NotImplementedError( |
| 131 | + "This migration cannot be reversed as it permanently deletes duplicate " |
| 132 | + "AlgorithmCategoryMap instances. If you need to reverse this, restore from a backup." |
| 133 | + ) |
| 134 | + |
| 135 | + |
| 136 | +class Migration(migrations.Migration): |
| 137 | + dependencies = [ |
| 138 | + ("ml", "0022_alter_pipeline_default_config"), |
| 139 | + ("main", "0053_alter_classification_algorithm"), # Ensure Classification model is available |
| 140 | + ] |
| 141 | + |
| 142 | + operations = [ |
| 143 | + migrations.RunPython( |
| 144 | + merge_duplicate_category_maps, |
| 145 | + reverse_merge_duplicate_category_maps, |
| 146 | + ), |
| 147 | + ] |
0 commit comments