mirror of
https://github.com/semantica-agi/semantica.git
synced 2026-08-29 04:26:20 +00:00
Add a Cite Us section to the README with BibTeX citation info, and align it with docs/citation.md (author/organization: Semantica, 2026). Update LICENSE and docs/project-license.md copyright holder to Semantica, and replace the stale Hawksight-AI GitHub org slug with semantica-agi across READMEs, plugin manifests, cookbook notebooks, and GitHub templates.
13 KiB
13 KiB
In [ ]:
# Install Semantica
!pip install -q semanticaIn [ ]:
entities = [
# Apple Variations
{
"id": "e1",
"name": "Apple Inc.",
"type": "Company",
"properties": {"industry": "Technology", "hq": "Cupertino", "founded": 1976},
"relationships": [{"predicate": "founded_by", "object": "Steve Jobs"}]
},
{
"id": "e2",
"name": "Apple Inc",
"type": "Company",
"properties": {"industry": "Tech", "hq": "Cupertino, CA"}, # Slightly different properties
"relationships": []
},
{
"id": "e3",
"name": "Apple",
"type": "Company",
"properties": {"industry": "Consumer Electronics"},
"relationships": [{"predicate": "ceo", "object": "Tim Cook"}]
},
# Microsoft Variations
{
"id": "e4",
"name": "Microsoft Corp",
"type": "Company",
"properties": {"industry": "Software", "hq": "Redmond"}
},
{
"id": "e5",
"name": "Microsoft",
"type": "Company",
"properties": {"industry": "Tech", "hq": "Redmond, WA"}
},
# Unique Entity
{
"id": "e6",
"name": "Google LLC",
"type": "Company",
"properties": {"industry": "Internet"}
}
]
print(f"Created {len(entities)} sample entities.")In [ ]:
from semantica.deduplication import SimilarityCalculator, SimilarityResult
# Initialize calculator with custom weights
calculator = SimilarityCalculator(
string_weight=0.5, # High importance on name
property_weight=0.3, # Medium importance on properties
relationship_weight=0.2 # Lower importance on relationships
)
# Compare "Apple Inc." (e1) vs "Apple Inc" (e2)
score_e1_e2 = calculator.calculate_similarity(entities[0], entities[1])
print(f"Similarity between '{entities[0]['name']}' and '{entities[1]['name']}':")
print(f" Total Score: {score_e1_e2.score:.4f}")
print(f" Breakdown: {score_e1_e2.components}")
# Compare "Apple Inc." (e1) vs "Microsoft" (e5)
score_e1_e5 = calculator.calculate_similarity(entities[0], entities[4])
print(f"\nSimilarity between '{entities[0]['name']}' and '{entities[4]['name']}':")
print(f" Total Score: {score_e1_e5.score:.4f}")In [ ]:
# Import specific classes for Duplicate Detection
from semantica.deduplication import DuplicateDetector, DuplicateCandidate, DuplicateGroup
from semantica.deduplication import DeduplicationConfig
detector = DuplicateDetector(
similarity_threshold=0.7,
confidence_threshold=0.6
)
# Detect pairs
candidates = detector.detect_duplicates(entities)
print(f"Found {len(candidates)} duplicate pairs:")
for c in candidates:
print(f" - {c.entity1['name']} <==> {c.entity2['name']} (Score: {c.similarity_score:.2f})")In [ ]:
existing_db = entities[:3] # The Apple entities
new_data = [entities[4]] # Microsoft
# Check if new data matches anything in existing DB
inc_candidates = detector.incremental_detect(new_data, existing_db)
print(f"New matches found: {len(inc_candidates)}")
# Expected: 0, because Microsoft is not Apple.In [ ]:
# Import specific classes for Clustering
from semantica.deduplication import ClusterBuilder, Cluster, ClusterResult
cluster_builder = ClusterBuilder(threshold=0.7)
result = cluster_builder.build_clusters(entities)
print(f"Found {len(result.clusters)} clusters:")
for i, cluster in enumerate(result.clusters):
names = [e['name'] for e in cluster.entities]
print(f" Cluster {i+1}: {names}")
cluster_builder = ClusterBuilder(threshold=0.7)
result = cluster_builder.build_clusters(entities)
print(f"Found {len(result.clusters)} clusters:")
for i, cluster in enumerate(result.clusters):
names = [e['name'] for e in cluster.entities]
print(f" Cluster {i+1}: {names}")In [ ]:
# Import specific classes for Entity Merging
from semantica.deduplication import EntityMerger, MergeStrategy, MergeStrategyManager, MergeOperation, MergeResultIn [ ]:
merger = EntityMerger()
# We will use the 'KEEP_MOST_COMPLETE' strategy
# This ensures we don't lose valuable information from richer entities
merge_ops = merger.merge_duplicates(
entities,
strategy=MergeStrategy.KEEP_MOST_COMPLETE
)
print(f"Performed {len(merge_ops)} merge operations.")
print("\n--- Merged Results ---")
for op in merge_ops:
final_ent = op.merged_entity
original_count = len(op.source_entities)
print(f"Merged {original_count} entities into: '{final_ent['name']}'")
print(f" - Final Properties: {final_ent['properties']}")
print(f" - Final Relationships: {len(final_ent.get('relationships', []))}")In [ ]:
def deduplicate_dataset(raw_entities):
print("1. Detecting duplicates...")
# Step 1: Detect
detector = DuplicateDetector(similarity_threshold=0.75)
# We can skip explicit detection calls if we just want to merge,
# as EntityMerger calls detection internally, but doing it manually allows inspection.
print("2. Merging entities...")
# Step 2: Merge
merger = EntityMerger()
ops = merger.merge_duplicates(raw_entities, strategy=MergeStrategy.KEEP_MOST_COMPLETE)
# Let's collect all final IDs to see what remains
merged_entities = [op.merged_entity for op in ops]
# Find entities that were NOT part of any merge (singletons)
merged_ids = set()
for op in ops:
for source in op.source_entities:
merged_ids.add(source['id'])
singletons = [e for e in raw_entities if e['id'] not in merged_ids]
final_dataset = merged_entities + singletons
return final_dataset
# Run the workflow
clean_data = deduplicate_dataset(entities)
print(f"\nOriginal Size: {len(entities)}")
print(f"Cleaned Size: {len(clean_data)}")
print("\nFinal Entity Names:")
for e in clean_data:
print(f" - {e['name']}")