Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Improve conflicts docs and notebook; align conflicts APIs

KaifAhmad1b091c870bcf2
diff --git a/README.md b/README.md
index e8fa88bd..a2fb4f8c 100644
--- a/README.md
+++ b/README.md
@@ -399,13 +399,14 @@ result = ExecutionEngine().execute_pipeline(pipeline, parallel=True)
from semantica.deduplication import DuplicateDetector
from semantica.conflicts import ConflictDetector
-conflicts = ConflictDetector().detect_conflicts(kg)
-duplicates = DuplicateDetector().find_duplicates(entities=kg.entities, similarity_threshold=0.85)
+entities = kg.get("entities", [])
+conflicts = ConflictDetector().detect_conflicts(entities)
+duplicates = DuplicateDetector(similarity_threshold=0.85).detect_duplicates(entities)
print(f"Conflicts: {len(conflicts)} | Duplicates: {len(duplicates)}")
```
-[**Cookbook: Conflict Detection**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/17_Conflict_Detection.ipynb) • [**Deduplication**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/18_Deduplication.ipynb) • [**Conflict Resolution**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/advanced/04_Conflict_Resolution_Strategies.ipynb)
+[**Cookbook: Conflict Detection & Resolution**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb) • [**Deduplication**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction/18_Deduplication.ipynb)
### Export & Integration
diff --git a/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb b/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb
index 3b05c505..7bf1352d 100644
--- a/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb
+++ b/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb
@@ -12,6 +12,22 @@
"\n",
"The **Semantica Conflict Resolution Module** (`semantica.conflicts`) provides a robust framework for managing these data inconsistencies. It is designed to ensure that your downstream applications consume only high-quality, reconciled data.\n",
"\n",
+ "### What counts as a \"conflict\"?\n",
+ "\n",
+ "- A conflict happens when **multiple records for the same entity** disagree on a field.\n",
+ "- Semantica typically assumes each record is a dictionary with:\n",
+ " - `id` (or `entity_id`): stable identifier for the entity being described\n",
+ " - one or more attributes (e.g., `name`, `birth_date`, `department`)\n",
+ " - `source`: where the value came from (db, scrape, api, file)\n",
+ " - optional `timestamp`: when the value was observed\n",
+ "- The module is source-aware: it can record **which sources contributed which values**, then resolve using strategies like voting or credibility.\n",
+ "\n",
+ "### Practical API notes (to avoid common mismatches)\n",
+ "\n",
+ "- Use `ConflictDetector.detect_value_conflicts(entities, property_name=...)` when you want to check one field.\n",
+ "- Use `ConflictDetector.detect_conflicts(entities)` when you want a broader scan (value/type/temporal/etc.).\n",
+ "- If you're starting from a `KnowledgeGraph`, pull entities via `kg.get(\"entities\", [])` (not `kg.entities`).\n",
+ "\n",
"### Key Capabilities\n",
"\n",
"1. **Multi-Dimensional Conflict Detection**\n",
@@ -39,13 +55,42 @@
"\n",
"```bash\n",
"pip install semantica\n",
- "```"
+ "```\n",
+ "\n",
+ "- If you're running this notebook inside the Semantica repo, prefer an editable install (so changes in code are reflected immediately):\n",
+ " - `pip install -e .`\n",
+ "- If you're using a hosted notebook environment, `%pip install semantica` is often more reliable than `!pip install ...` because it installs into the active kernel."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n"
+ ]
+ }
+ ],
+ "source": [
+ "!pip install -q semantica "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
"outputs": [],
"source": [
"import json\n",
@@ -62,9 +107,16 @@
"\n",
"**The Scenario:**\n",
"We have received records for **Employee 001** from three distinct sources:\n",
- "1. **HR Database**: Highly trusted internal source.\n",
- "2. **LinkedIn Scrape**: Less reliable external source.\n",
- "3. **Public Directory**: Outdated public API.\n",
+ "\n",
+ "- **HR Database**: Highly trusted internal source.\n",
+ "- **LinkedIn Scrape**: Less reliable external source.\n",
+ "- **Public Directory**: Outdated public API.\n",
+ "\n",
+ "**The record shape (what Semantica expects):**\n",
+ "\n",
+ "- Each record is a dictionary describing the same entity (`id`: `emp_001`).\n",
+ "- Each record includes a `source` key so conflicts can be attributed.\n",
+ "- A `timestamp` lets you apply time-based resolution strategies (e.g., most recent wins).\n",
"\n",
"**The Conflicts:**\n",
"* **`birth_date`**: The Public Directory lists a different year.\n",
@@ -73,7 +125,7 @@
},
{
"cell_type": "code",
- "execution_count": 2,
+ "execution_count": 3,
"metadata": {},
"outputs": [
{
@@ -132,19 +184,38 @@
"Before we can effectively resolve conflicts based on trust, we must register our sources with the `SourceTracker`.\n",
"\n",
"The `SourceTracker` acts as a central registry for:\n",
- "* **Credibility Scores**: How much we trust the source.\n",
- "* **Metadata**: Source type, location, and update frequency.\n",
+ "\n",
+ "- **Credibility Scores**: How much you trust the source.\n",
+ "- **Metadata**: Helpful context (e.g., source type, system of record vs scrape).\n",
+ "\n",
+ "**How to think about credibility scores:**\n",
+ "\n",
+ "- Use scores as a *relative ordering* (the exact decimals matter less than the ranking).\n",
+ "- Start simple: `internal_db > vendor_api > web_scrape`.\n",
+ "- Revisit scores later using analytics (e.g., \"which sources are frequently wrong?\").\n",
"\n",
"We iterate through our simulated sources and register them."
]
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": 4,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Registering sources...\n",
+ " - Registered 'hr_db' with credibility 0.95\n",
+ " - Registered 'linkedin_scrape' with credibility 0.6\n",
+ " - Registered 'public_dir' with credibility 0.4\n"
+ ]
+ }
+ ],
"source": [
- "from semantica.conflicts import SourceTracker\n\n",
+ "from semantica.conflicts import SourceTracker\n",
+ "\n",
"source_tracker = SourceTracker()\n",
"\n",
"print(\"Registering sources...\")\n",
@@ -166,17 +237,47 @@
"We use the `ConflictDetector` to scan our records for discrepancies. \n",
"\n",
"The detector is flexible and can be configured to check:\n",
- "* **Specific Properties**: Check only critical fields like `birth_date`.\n",
- "* **Entire Entities**: Scan all properties for an entity.\n",
+ "\n",
+ "- **Specific properties**: Check only critical fields like `birth_date`.\n",
+ "- **Entity-wide scans**: Scan many properties (or all) for an entity.\n",
+ "\n",
+ "**What you get back:**\n",
+ "\n",
+ "- A list of `Conflict` objects.\n",
+ "- Useful fields you’ll typically inspect:\n",
+ " - `conflict_type` (e.g., `value_conflict`)\n",
+ " - `entity_id`, `property_name`\n",
+ " - `conflicting_values` and `sources`\n",
+ " - `severity` and `confidence`\n",
"\n",
"Here, we explicitly check `birth_date` and `department`."
]
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": 5,
"metadata": {},
"outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<div style='font-family: monospace;'><h4>🧠 Semantica - 📊 Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>✅</td><td>Semantica is resolving</td><td>⚠️ conflicts</td><td>ConflictDetector</td><td>-</td><td>0.00s</td></tr><tr><td>✅</td><td>Semantica is resolving</td><td>⚠️ conflicts</td><td>ConflictAnalyzer</td><td>-</td><td>0.00s</td></tr></table></div>"
+ ],
+ "text/plain": [
+ "<IPython.core.display.HTML object>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Value conflict detected: emp_001.birth_date has conflicting values: ['1980-05-15', '1982-05-15']\n",
+ "Value conflict detected: emp_001.department has conflicting values: ['Engineering', 'Software Engineering']\n"
+ ]
+ },
{
"name": "stdout",
"output_type": "stream",
@@ -194,7 +295,8 @@
}
],
"source": [
- "from semantica.conflicts import ConflictDetector\n\n",
+ "from semantica.conflicts import ConflictDetector\n",
+ "\n",
"# Initialize detector with our populated source tracker\n",
"detector = ConflictDetector(source_tracker=source_tracker)\n",
"\n",
@@ -223,14 +325,21 @@
"## Step 4: Analyzing Conflict Patterns\n",
"\n",
"When dealing with large datasets, individual conflicts are less important than systemic patterns. The `ConflictAnalyzer` helps answer questions like:\n",
- "* \"Is one specific source responsible for most conflicts?\"\n",
- "* \"Are conflicts concentrated in a specific entity type?\"\n",
- "* \"What is the distribution of conflict severity?\""
+ "\n",
+ "- \"Is one specific source responsible for most conflicts?\"\n",
+ "- \"Are conflicts concentrated in a specific entity type or property?\"\n",
+ "- \"What is the distribution of conflict severity and conflict types?\"\n",
+ "\n",
+ "**How to use this in a pipeline:**\n",
+ "\n",
+ "- Run analysis to identify noisy sources.\n",
+ "- Use results to adjust credibility scores (Step 2) or refine ingestion/cleaning rules.\n",
+ "- Track trends over time to catch regressions in upstream systems."
]
},
{
"cell_type": "code",
- "execution_count": 5,
+ "execution_count": 6,
"metadata": {},
"outputs": [
{
@@ -239,13 +348,14 @@
"text": [
"Conflict Analysis Summary:\n",
"Total Conflicts: 2\n",
- "By Type: {'counts': {'value_conflict': 2}, 'details': {'value_conflict': [{'conflict_id': 'emp_001_birth_date_conflict', 'entity_id': 'emp_001', 'severity': 'medium'}, {'conflict_id': 'emp_001_department_conflict', 'entity_id': 'emp_001', 'severity': 'medium'}]}}\n",
- "By Severity: {'counts': {'medium': 2}, 'details': {'medium': [{'conflict_id': 'emp_001_birth_date_conflict', 'type': 'value_conflict', 'entity_id': 'emp_001', 'property_name': 'birth_date'}, {'conflict_id': 'emp_001_department_conflict', 'type': 'value_conflict', 'entity_id': 'emp_001', 'property_name': 'department'}]}}\n"
+ "By Type: {'value_conflict': 2}\n",
+ "By Severity: {'medium': 2}\n"
]
}
],
"source": [
- "from semantica.conflicts import ConflictAnalyzer\n\n",
+ "from semantica.conflicts import ConflictAnalyzer\n",
+ "\n",
"analyzer = ConflictAnalyzer()\n",
"analysis = analyzer.analyze_conflicts(conflicts)\n",
"\n",
@@ -261,11 +371,14 @@
"source": [
"## Step 5: Resolving Conflicts\n",
"\n",
- "This is the critical step where we decide which value to trust. Semantica offers flexible `ResolutionStrategies`.\n",
+ "This is the critical step where we decide which value to trust. Semantica offers flexible resolution strategies.\n",
"\n",
"### Strategy A: Voting (Majority Rules)\n",
"This strategy selects the value that appears most frequently. It is simple but treats all sources as equal.\n",
"\n",
+ "- Best when you have many independent sources of similar quality.\n",
+ "- Less suitable if you have a single system-of-record that should always dominate.\n",
+ "\n",
"### Strategy B: Credibility Weighted\n",
"This strategy calculates a weighted score for each value based on the `credibility` of its source. \n",
"\n",
@@ -273,16 +386,27 @@
"* `hr_db` (0.95) says \"1980-05-15\"\n",
"* `public_dir` (0.40) says \"1982-05-15\"\n",
"\n",
- "Even if multiple low-quality sources agreed on the wrong date, the high-credibility source would likely win."
+ "Even if multiple low-quality sources agreed on the wrong date, the high-credibility source would likely win.\n",
+ "\n",
+ "**What the resolver returns:**\n",
+ "\n",
+ "- A list of resolution results where each item typically includes:\n",
+ " - whether it was resolved\n",
+ " - the chosen value (`resolved_value`)\n",
+ " - a confidence score\n",
+ " - metadata (like the property name) to support audit trails\n",
+ "\n",
+ "Run the next cell to compare voting vs credibility-weighted outcomes."
]
},
{
"cell_type": "code",
- "execution_count": 6,
+ "execution_count": null,
"metadata": {},
"outputs": [],
"source": [
- "from semantica.conflicts import ConflictResolver, ResolutionStrategy\n\n",
+ "from semantica.conflicts import ConflictResolver\n",
+ "\n",
"resolver = ConflictResolver()\n",
"\n",
"# CRITICAL: Link the source tracker to the resolver.\n",
@@ -290,13 +414,13 @@
"resolver.set_source_tracker(source_tracker)\n",
"\n",
"print(\"--- Resolution: Voting ---\")\n",
- "voting_results = resolver.resolve_conflicts(conflicts, strategy=ResolutionStrategy.VOTING)\n",
+ "voting_results = resolver.resolve_conflicts(conflicts, strategy=\"voting\")\n",
"for res in voting_results:\n",
" print(f\"Property: {res.metadata.get('property_name'):<15} | Resolved Value: {res.resolved_value}\")\n",
"\n",
"print(\"\\n--- Resolution: Credibility Weighted ---\")\n",
"# Notice how the HR DB's value is preferred due to higher credibility\n",
- "credibility_results = resolver.resolve_conflicts(conflicts, strategy=ResolutionStrategy.CREDIBILITY_WEIGHTED)\n",
+ "credibility_results = resolver.resolve_conflicts(conflicts, strategy=\"credibility_weighted\")\n",
"for res in credibility_results:\n",
" print(f\"Property: {res.metadata.get('property_name'):<15} | Resolved Value: {res.resolved_value} (Confidence: {res.confidence:.2f})\")"
]
@@ -310,9 +434,16 @@
"Not all conflicts can be resolved automatically. High-stakes or low-confidence resolutions require human review.\n",
"\n",
"The `InvestigationGuideGenerator` produces a structured \"flight plan\" for an analyst, detailing:\n",
- "1. **What** is in conflict.\n",
- "2. **Who** (which sources) are involved.\n",
- "3. **How** to verify the correct data (actionable steps)."
+ "\n",
+ "- **What** is in conflict (entity + field + competing values).\n",
+ "- **Who** is involved (which sources produced which values).\n",
+ "- **How** to verify the correct data (actionable steps an analyst can follow).\n",
+ "\n",
+ "**When to generate guides:**\n",
+ "\n",
+ "- Low-confidence resolutions.\n",
+ "- Conflicts on critical fields (identity, legal names, compliance attributes).\n",
+ "- Any time you want a human-in-the-loop checkpoint before writing back to the graph."
]
},
{
@@ -321,7 +452,8 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.conflicts import InvestigationGuideGenerator\n\n",
+ "from semantica.conflicts import InvestigationGuideGenerator\n",
+ "\n",
"guide_generator = InvestigationGuideGenerator()\n",
"\n",
"# Generate a guide for the first conflict (birth_date)\n",
@@ -349,11 +481,19 @@
"You have successfully built a conflict resolution pipeline using Semantica! \n",
"\n",
"**Recap of what we achieved:**\n",
- "1. **Ingested** multi-source data with potential quality issues.\n",
- "2. **Registered** sources with credibility scores to establish a \"hierarchy of trust.\"\n",
- "3. **Detected** conflicts automatically across the dataset.\n",
- "4. **Resolved** conflicts using a credibility-weighted strategy, prioritizing trusted internal data.\n",
- "5. **Generated** actionable guides for human-in-the-loop review of difficult cases."
+ "\n",
+ "- **Simulated** multi-source entity records with realistic disagreements.\n",
+ "- **Registered** sources with credibility scores to create a trust hierarchy.\n",
+ "- **Detected** value conflicts for specific properties.\n",
+ "- **Analyzed** conflicts to understand distribution by type and severity.\n",
+ "- **Resolved** conflicts using voting and credibility-weighted strategies.\n",
+ "- **Generated** an investigation guide to support human review.\n",
+ "\n",
+ "**Suggested next steps in a real project:**\n",
+ "\n",
+ "- Integrate with your ingestion layer so each extracted value includes a `source` and (ideally) a `timestamp`.\n",
+ "- Expand detection beyond value conflicts using `ConflictDetector.detect_conflicts(...)`.\n",
+ "- Store resolutions and guide outputs to build an audit trail for downstream consumers."
]
}
],
@@ -378,4 +518,4 @@
},
"nbformat": 4,
"nbformat_minor": 4
-}
\ No newline at end of file
+}
diff --git a/docs/concepts.md b/docs/concepts.md
index 987c2b50..99a01e30 100644
--- a/docs/concepts.md
+++ b/docs/concepts.md
@@ -2286,24 +2286,25 @@ flowchart LR
Find conflicts in your knowledge graph:
```python
- from semantica.kg import ConflictDetector
- from semantica.conflicts import ConflictAnalyzer, detect_conflicts
+ from semantica.conflicts import ConflictAnalyzer, ConflictDetector
# Sample knowledge graph with conflicts
kg = {
"entities": [
{
- "id": "e1",
- "text": "Apple Inc.",
+ "id": "e1",
+ "text": "Apple Inc.",
"type": "Organization",
- "properties": {"founded": "1976", "employees": "160000"},
+ "founded": "1976",
+ "employees": "160000",
"source": "wikipedia"
},
{
- "id": "e2",
- "text": "Apple Inc.",
+ "id": "e1",
+ "text": "Apple Inc.",
"type": "Organization",
- "properties": {"founded": "1977", "employees": "164000"},
+ "founded": "1977",
+ "employees": "164000",
"source": "bloomberg"
},
],
@@ -2315,14 +2316,6 @@ flowchart LR
]
}
- # Method 1: Using convenience function
- conflicts = detect_conflicts(
- kg["entities"],
- method="value",
- property_name="founded"
- )
-
- # Method 2: Using ConflictDetector class
detector = ConflictDetector()
all_conflicts = detector.detect_value_conflicts(kg["entities"], "founded")
@@ -2331,17 +2324,17 @@ flowchart LR
print(f" Type: {conflict.conflict_type.value}")
print(f" Entity: {conflict.entity_id}")
print(f" Property: {conflict.property_name}")
- print(f" Values: {[v['value'] for v in conflict.values]}")
+ print(f" Values: {conflict.conflicting_values}")
print(f" Sources: {conflict.sources}")
# Analyze conflicts
analyzer = ConflictAnalyzer()
- analysis = analyzer.analyze(all_conflicts)
+ analysis = analyzer.analyze_conflicts(all_conflicts)
print(f"Conflict Analysis:")
print(f" Total conflicts: {analysis['total_conflicts']}")
- print(f" By type: {analysis['by_type']}")
- print(f" By severity: {analysis['by_severity']}")
+ print(f" By type: {analysis.get('by_type', {}).get('counts')}")
+ print(f" By severity: {analysis.get('by_severity', {}).get('counts')}")
```
=== "Resolution Strategies"
@@ -2350,7 +2343,6 @@ flowchart LR
```python
from semantica.conflicts import (
ConflictResolver,
- ResolutionStrategy,
Conflict,
ConflictType
)
@@ -2360,95 +2352,76 @@ flowchart LR
Conflict(
conflict_id="c1",
entity_id="e1",
- conflict_type=ConflictType.VALUE,
+ conflict_type=ConflictType.VALUE_CONFLICT,
property_name="founded",
- values=[
- {"value": "1976", "source": "wikipedia", "confidence": 0.95},
- {"value": "1976", "source": "sec_filing", "confidence": 0.99},
- {"value": "1977", "source": "news_article", "confidence": 0.70}
+ conflicting_values=["1976", "1976", "1977"],
+ sources=[
+ {"document": "wikipedia", "confidence": 0.95},
+ {"document": "sec_filing", "confidence": 0.99},
+ {"document": "news_article", "confidence": 0.70},
],
- sources=["wikipedia", "sec_filing", "news_article"]
)
]
# Strategy 1: Voting (most common value wins)
- resolver_voting = ConflictResolver(strategy=ResolutionStrategy.VOTING)
- resolved_voting = resolver_voting.resolve(conflicts)
+ resolver = ConflictResolver()
+ resolved_voting = resolver.resolve_conflicts(conflicts, strategy="voting")
print("Voting Resolution:")
for r in resolved_voting:
- print(f" {r.property_name}: {r.resolved_value}")
+ print(f" {r.conflict_id}: {r.resolved_value} (confidence: {r.confidence:.2f})")
# Strategy 2: Highest confidence
- resolver_conf = ConflictResolver(strategy=ResolutionStrategy.HIGHEST_CONFIDENCE)
- resolved_conf = resolver_conf.resolve(conflicts)
+ resolved_conf = resolver.resolve_conflicts(conflicts, strategy="highest_confidence")
print("Highest Confidence Resolution:")
for r in resolved_conf:
- print(f" {r.property_name}: {r.resolved_value} (confidence: {r.confidence:.2f})")
+ print(f" {r.conflict_id}: {r.resolved_value} (confidence: {r.confidence:.2f})")
- # Strategy 3: Source priority
- resolver_priority = ConflictResolver(
- strategy=ResolutionStrategy.SOURCE_PRIORITY,
- source_priority=["sec_filing", "wikipedia", "news_article"]
- )
- resolved_priority = resolver_priority.resolve(conflicts)
+ # Strategy 3: Credibility weighted
+ resolved_cred = resolver.resolve_conflicts(conflicts, strategy="credibility_weighted")
- print("Source Priority Resolution:")
- for r in resolved_priority:
- print(f" {r.property_name}: {r.resolved_value} (source: {r.selected_source})")
+ print("Credibility Weighted Resolution:")
+ for r in resolved_cred:
+ print(f" {r.conflict_id}: {r.resolved_value} (confidence: {r.confidence:.2f})")
```
=== "Custom Resolution Rules"
Define custom resolution rules per property:
```python
- from semantica.conflicts import (
- ConflictResolver,
- ResolutionStrategy,
- resolve_conflicts
- )
+ from semantica.conflicts import ConflictResolver
# Define property-specific resolution rules
resolution_config = {
"founded": {
- "strategy": ResolutionStrategy.SOURCE_PRIORITY,
- "source_priority": ["official_records", "sec_filing", "wikipedia"]
+ "strategy": "highest_confidence",
},
"revenue": {
- "strategy": ResolutionStrategy.MOST_RECENT,
+ "strategy": "most_recent",
},
"employees": {
- "strategy": ResolutionStrategy.VOTING,
+ "strategy": "voting",
},
"ceo": {
- "strategy": ResolutionStrategy.HIGHEST_CONFIDENCE,
+ "strategy": "highest_confidence",
}
}
- # Create resolver with custom config
- resolver = ConflictResolver(
- strategy=ResolutionStrategy.HIGHEST_CONFIDENCE,
- min_confidence=0.7
- )
+ resolver = ConflictResolver()
# Resolve conflicts for each property
resolved_values = {}
for property_name, config in resolution_config.items():
- property_resolver = ConflictResolver(
- strategy=config["strategy"],
- source_priority=config.get("source_priority")
- )
-
# Get conflicts for this property
property_conflicts = [c for c in conflicts if c.property_name == property_name]
if property_conflicts:
- results = property_resolver.resolve(property_conflicts)
+ results = resolver.resolve_conflicts(property_conflicts, strategy=config["strategy"])
for result in results:
resolved_values[property_name] = {
"value": result.resolved_value,
- "strategy": config["strategy"].value,
+ "strategy": config["strategy"],
"confidence": result.confidence
}
@@ -2462,54 +2435,45 @@ flowchart LR
```python
from semantica.conflicts import SourceTracker, SourceReference
+ from datetime import datetime
# Initialize source tracker
tracker = SourceTracker()
- # Add entities from different sources
- tracker.add_source(SourceReference(
- entity_id="e1",
- property_name="founded",
- value="1976",
- source="wikipedia",
- timestamp="2024-01-15",
- confidence=0.95
- ))
-
- tracker.add_source(SourceReference(
- entity_id="e1",
- property_name="founded",
- value="1976",
- source="sec_filing",
- timestamp="2024-03-01",
- confidence=0.99
- ))
-
- tracker.add_source(SourceReference(
- entity_id="e1",
- property_name="founded",
- value="1977",
- source="news_article",
- timestamp="2024-02-20",
- confidence=0.70
- ))
+ tracker.track_property_source(
+ "e1",
+ "founded",
+ "1976",
+ SourceReference(document="wikipedia", confidence=0.95, timestamp=datetime(2024, 1, 15)),
+ )
+ tracker.track_property_source(
+ "e1",
+ "founded",
+ "1976",
+ SourceReference(document="sec_filing", confidence=0.99, timestamp=datetime(2024, 3, 1)),
+ )
+ tracker.track_property_source(
+ "e1",
+ "founded",
+ "1977",
+ SourceReference(document="news_article", confidence=0.70, timestamp=datetime(2024, 2, 20)),
+ )
- # Get all sources for an entity
- sources = tracker.get_sources("e1")
+ sources = tracker.get_entity_sources("e1")
print("Entity Sources:")
for source in sources:
- print(f" Source: {source.source}")
- print(f" Property: {source.property_name}")
- print(f" Value: {source.value}")
+ print(f" Source: {source.document}")
print(f" Confidence: {source.confidence}")
# Get property-specific sources
property_sources = tracker.get_property_sources("e1", "founded")
print("Property Sources for 'founded':")
- for ps in property_sources:
- print(f" {ps.value} from {ps.source} ({ps.timestamp})")
+ if property_sources:
+ print(f" Value: {property_sources.value}")
+ for ps in property_sources.sources:
+ print(f" {ps.document} ({ps.timestamp})")
```
=== "Conflict Investigation"
@@ -2518,7 +2482,6 @@ flowchart LR
```python
from semantica.conflicts import (
InvestigationGuideGenerator,
- ConflictDetector,
Conflict,
ConflictType
)
@@ -2530,14 +2493,14 @@ flowchart LR
conflict = Conflict(
conflict_id="c1",
entity_id="e1",
- conflict_type=ConflictType.VALUE,
+ conflict_type=ConflictType.VALUE_CONFLICT,
property_name="founded",
- values=[
- {"value": "1976", "source": "wikipedia", "confidence": 0.95},
- {"value": "1977", "source": "news", "confidence": 0.70}
+ conflicting_values=["1976", "1977"],
+ sources=[
+ {"document": "wikipedia", "confidence": 0.95},
+ {"document": "news", "confidence": 0.70},
],
- sources=["wikipedia", "news"],
- severity=0.6
+ severity="medium"
)
# Generate investigation guide
@@ -2546,25 +2509,14 @@ flowchart LR
print("Conflict Investigation Guide:")
print(f" Conflict ID: {guide.conflict_id}")
print(f" Title: {guide.title}")
- print(f" Summary: {guide.summary}")
+ print(f" Summary: {guide.conflict_summary}")
print("Investigation Steps:")
- for i, step in enumerate(guide.steps, 1):
+ for i, step in enumerate(guide.investigation_steps, 1):
print(f" {i}. {step.description}")
- print(f" Priority: {step.priority}")
if step.expected_outcome:
print(f" Expected: {step.expected_outcome}")
-
- print("Checklist:")
- for item in guide.checklist:
- print(f" [ ] {item}")
-
- # Get context for the conflict
- context = guide_generator.get_conflict_context(conflict)
- print(f"Context:")
- print(f" Entity: {context.get('entity_text', 'Unknown')}")
- print(f" Property: {context.get('property', 'Unknown')}")
- print(f" Value count: {len(conflict.values)}")
+ print(f" Value count: {len(conflict.conflicting_values)}")
```
diff --git a/docs/cookbook.md b/docs/cookbook.md
index 1c2c1a82..99ed22dc 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -220,7 +220,7 @@ Deep dive into advanced features, customization, and complex workflows.
**Difficulty**: Advanced
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/04_Conflict_Resolution_Strategies.ipynb)
+ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb)
- :material-export: **Multi-Format Export**
---
diff --git a/docs/examples.md b/docs/examples.md
index 9d74840d..e27cef44 100644
--- a/docs/examples.md
+++ b/docs/examples.md
@@ -112,13 +112,15 @@ Resolve conflicts in data from multiple sources.
```python
from semantica.core import Semantica
-from semantica.conflicts import ConflictResolver
+from semantica.conflicts import ConflictDetector, ConflictResolver
semantica = Semantica()
result = semantica.build_knowledge_base(["source1.pdf", "source2.pdf"])
# Detect and resolve conflicts
-conflicts = semantica.kg.detect_conflicts(result["knowledge_graph"])
+kg = result["knowledge_graph"]
+detector = ConflictDetector()
+conflicts = detector.detect_conflicts(kg["entities"])
resolver = ConflictResolver(default_strategy="voting")
resolved = resolver.resolve_conflicts(conflicts)
```
diff --git a/docs/modules.md b/docs/modules.md
index cac17c89..c8b55d5d 100644
--- a/docs/modules.md
+++ b/docs/modules.md
@@ -727,18 +727,13 @@ print(f"Reduced from {len(entities)} to {len(merged_entities)} entities")
**Quick Example:**
```python
-from semantica.conflicts import detect_and_resolve, ConflictDetector
+from semantica.conflicts import ConflictDetector, ConflictResolver
-# Using convenience function
-conflicts, results = detect_and_resolve(
- entities,
- property_name="name",
- resolution_strategy="voting"
-)
-
-# Using classes directly
detector = ConflictDetector()
conflicts = detector.detect_value_conflicts(entities, "name")
+
+resolver = ConflictResolver()
+results = resolver.resolve_conflicts(conflicts, strategy="voting")
```
---
diff --git a/docs/reference/conflicts.md b/docs/reference/conflicts.md
index eeb9eab8..a1f09284 100644
--- a/docs/reference/conflicts.md
+++ b/docs/reference/conflicts.md
@@ -255,22 +255,20 @@ conflicts:
```python
from semantica.conflicts import ConflictDetector, ConflictResolver
-from semantica.ingest import Ingestor
+from semantica.core import Semantica
-# 1. Ingest from multiple sources
-ingestor = Ingestor()
-data1 = ingestor.ingest("source1.pdf")
-data2 = ingestor.ingest("source2.html")
-
-# 2. Combine entities (assuming same IDs)
-combined_entities = data1.entities + data2.entities
+# 1. Build knowledge base from multiple sources
+semantica = Semantica()
+result = semantica.build_knowledge_base(["source1.pdf", "source2.html"])
+kg = result["knowledge_graph"]
+entities = kg.get("entities", [])
# 3. Detect conflicts
detector = ConflictDetector()
-conflicts = detector.detect_value_conflicts(combined_entities, "revenue")
+conflicts = detector.detect_value_conflicts(entities, "revenue")
# 4. Resolve conflicts
-resolver = ConflictResolver()
+resolver = ConflictResolver(default_strategy="credibility_weighted")
resolutions = resolver.resolve_conflicts(
conflicts,
strategy="credibility_weighted"
@@ -322,5 +320,4 @@ tracker.set_source_credibility("bad_source", 0.1)
## Cookbook
-- [Conflict Detection](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/17_Conflict_Detection.ipynb)
-- [Conflict Resolution Strategies](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/04_Conflict_Resolution_Strategies.ipynb)
+- [Conflict Detection & Resolution](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb)
diff --git a/docs/reference/deduplication.md b/docs/reference/deduplication.md
index c51f86ee..43caf8a4 100644
--- a/docs/reference/deduplication.md
+++ b/docs/reference/deduplication.md
@@ -676,13 +676,14 @@ Configuration is loaded in the following priority order:
### Ingestion Pipeline
```python
-from semantica.ingest import Ingestor
+from semantica.core import Semantica
from semantica.deduplication import DuplicateDetector, EntityMerger, MergeStrategy
-from semantica.kg import KnowledgeGraph
-# 1. Ingest
-ingestor = Ingestor()
-raw_entities = ingestor.ingest_batch(files)
+# 1. Build knowledge base
+semantica = Semantica()
+result = semantica.build_knowledge_base(files)
+kg = result["knowledge_graph"]
+raw_entities = kg.get("entities", [])
# 2. Deduplicate
detector = DuplicateDetector(similarity_threshold=0.85)
@@ -696,10 +697,6 @@ merge_operations = merger.merge_duplicates(
# Extract merged entities
merged_entities = [op.merged_entity for op in merge_operations]
-
-# 3. Load to KG
-kg = KnowledgeGraph()
-kg.add_entities(merged_entities)
```
---
diff --git a/pyproject.toml b/pyproject.toml
index 0aea5c77..07e0da52 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -237,7 +237,7 @@ known_first_party = ["semantica"]
known_third_party = ["numpy", "pandas", "scikit-learn", "spacy", "transformers", "torch"]
[tool.mypy]
-python_version = "3.8"
+python_version = "3.9"
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
diff --git a/semantica/conflicts/__init__.py b/semantica/conflicts/__init__.py
index 81745d2c..880c7558 100644
--- a/semantica/conflicts/__init__.py
+++ b/semantica/conflicts/__init__.py
@@ -11,11 +11,14 @@ Algorithms Used:
Conflict Detection:
- Value Comparison: Property value comparison across sources with equality checking
- Type Mismatch Detection: Entity type comparison and mismatch identification
- - Relationship Consistency: Relationship property comparison and inconsistency detection
+ - Relationship Consistency: Relationship property comparison and inconsistency
+ detection
- Temporal Analysis: Time-based conflict detection using timestamp comparison
- Logical Consistency: Logical rule validation and inconsistency detection
- - Severity Calculation: Multi-factor severity scoring (property importance, value difference, source count)
- - Confidence Scoring: Confidence calculation based on source credibility and value diversity
+ - Severity Calculation: Multi-factor severity scoring (property importance,
+ value difference, source count)
+ - Confidence Scoring: Confidence calculation based on source credibility and
+ value diversity
Conflict Resolution:
- Voting Algorithm: Majority value selection using Counter-based frequency counting
@@ -25,7 +28,8 @@ Conflict Resolution:
- Manual Flagging: Conflict flagging for human review workflow
Conflict Analysis:
- - Pattern Identification: Frequency-based pattern detection using Counter and defaultdict
+ - Pattern Identification: Frequency-based pattern detection using Counter and
+ defaultdict
- Type Classification: Conflict type categorization and grouping
- Severity Analysis: Severity-based grouping and analysis
- Source Analysis: Source-based conflict aggregation and analysis
@@ -97,6 +101,14 @@ from .methods import (
from .registry import MethodRegistry, method_registry
from .source_tracker import PropertySource, SourceReference, SourceTracker
+voting = ResolutionStrategy.VOTING
+credibility_weighted = ResolutionStrategy.CREDIBILITY_WEIGHTED
+most_recent = ResolutionStrategy.MOST_RECENT
+first_seen = ResolutionStrategy.FIRST_SEEN
+highest_confidence = ResolutionStrategy.HIGHEST_CONFIDENCE
+manual_review = ResolutionStrategy.MANUAL_REVIEW
+expert_review = ResolutionStrategy.EXPERT_REVIEW
+
__all__ = [
# Core Classes
@@ -109,6 +121,13 @@ __all__ = [
"ConflictResolver",
"ResolutionResult",
"ResolutionStrategy",
+ "voting",
+ "credibility_weighted",
+ "most_recent",
+ "first_seen",
+ "highest_confidence",
+ "manual_review",
+ "expert_review",
"InvestigationGuideGenerator",
"InvestigationGuide",
"InvestigationStep",
diff --git a/semantica/conflicts/config.py b/semantica/conflicts/config.py
index d58bb343..c258a7c5 100644
--- a/semantica/conflicts/config.py
+++ b/semantica/conflicts/config.py
@@ -6,7 +6,8 @@ resolution operations, supporting multiple configuration sources including envir
variables, config files, and programmatic configuration.
Supported Configuration Sources:
- - Environment variables: CONFLICT_CONFIDENCE_THRESHOLD, CONFLICT_DEFAULT_STRATEGY, etc.
+ - Environment variables: CONFLICT_CONFIDENCE_THRESHOLD,
+ CONFLICT_DEFAULT_STRATEGY, etc.
- Config files: YAML, JSON, TOML formats
- Programmatic: Python API for setting conflict configurations
@@ -47,7 +48,11 @@ from ..utils.logging import get_logger
class ConflictsConfig:
- """Configuration manager for conflicts module - supports .env files, environment variables, and programmatic config."""
+ """
+ Configuration manager for conflicts module.
+
+ Supports .env files, environment variables, and programmatic config.
+ """
def __init__(self, config_file: Optional[str] = None):
"""Initialize configuration manager."""
diff --git a/semantica/conflicts/conflict_analyzer.py b/semantica/conflicts/conflict_analyzer.py
index d2830142..8e0de3c4 100644
--- a/semantica/conflicts/conflict_analyzer.py
+++ b/semantica/conflicts/conflict_analyzer.py
@@ -19,9 +19,11 @@ Type Classification:
- Type Distribution Analysis: Analyzes distribution of conflict types
Severity Analysis:
- - Severity-based Grouping: Groups conflicts by severity level (low, medium, high, critical)
+ - Severity-based Grouping: Groups conflicts by severity level (low, medium,
+ high, critical)
- Severity Distribution: Calculates distribution of severities
- - Critical Conflict Identification: Identifies critical conflicts requiring immediate attention
+ - Critical Conflict Identification: Identifies critical conflicts requiring
+ immediate attention
Source Analysis:
- Source-based Aggregation: Aggregates conflicts by source document
@@ -63,14 +65,14 @@ Author: Semantica Contributors
License: MIT
"""
-from collections import Counter, defaultdict
+from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Dict, List, Optional
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
-from .conflict_detector import Conflict, ConflictType
+from .conflict_detector import Conflict
@dataclass
@@ -304,7 +306,10 @@ class ConflictAnalyzer:
affected_properties=[prop],
affected_entities=list(entities),
metadata={
- "description": f"Property '{prop}' has conflicts across {len(entities)} entities"
+ "description": (
+ f"Property '{prop}' has conflicts across "
+ f"{len(entities)} entities"
+ )
},
)
)
@@ -341,7 +346,9 @@ class ConflictAnalyzer:
pattern_type="critical_conflict_cluster",
frequency=len(critical_conflicts),
metadata={
- "description": f"{len(critical_conflicts)} critical conflicts detected"
+ "description": (
+ f"{len(critical_conflicts)} critical conflicts detected"
+ )
},
)
)
@@ -365,8 +372,9 @@ class ConflictAnalyzer:
if top_properties:
top_prop = top_properties[0]
recommendations.append(
- f"Property '{top_prop['property_name']}' has {top_prop['conflict_count']} conflicts. "
- f"Consider implementing stricter validation or source verification."
+ f"Property '{top_prop['property_name']}' has "
+ f"{top_prop['conflict_count']} conflicts. Consider implementing "
+ f"stricter validation or source verification."
)
# Recommendation 2: Problematic sources
@@ -376,8 +384,8 @@ class ConflictAnalyzer:
if problematic_source_patterns:
for pattern in problematic_source_patterns:
recommendations.append(
- f"Source '{pattern.common_sources[0]}' appears in multiple conflicts. "
- f"Review source quality and credibility."
+ f"Source '{pattern.common_sources[0]}' appears in multiple "
+ f"conflicts. Review source quality and credibility."
)
# Recommendation 3: High-conflict entities
@@ -385,15 +393,17 @@ class ConflictAnalyzer:
if top_entities:
top_entity = top_entities[0]
recommendations.append(
- f"Entity '{top_entity['entity_id']}' has {top_entity['conflict_count']} conflicts. "
- f"Review entity data sources and merge strategy."
+ f"Entity '{top_entity['entity_id']}' has "
+ f"{top_entity['conflict_count']} conflicts. Review entity data sources "
+ f"and merge strategy."
)
# Recommendation 4: Critical conflicts
critical_count = len([c for c in conflicts if c.severity == "critical"])
if critical_count > 0:
recommendations.append(
- f"{critical_count} critical conflicts detected. Immediate review required."
+ f"{critical_count} critical conflicts detected. Immediate review "
+ f"required."
)
if not recommendations:
@@ -453,7 +463,7 @@ class ConflictAnalyzer:
# Group conflicts by time period
from collections import defaultdict
- from datetime import datetime, timedelta
+ from datetime import datetime
trends = []
conflict_by_period = defaultdict(list)
@@ -475,7 +485,9 @@ class ConflictAnalyzer:
if timestamp:
if isinstance(timestamp, str):
try:
- timestamp = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
+ timestamp = datetime.fromisoformat(
+ timestamp.replace("Z", "+00:00")
+ )
except (ValueError, AttributeError):
try:
timestamp = datetime.strptime(timestamp, "%Y-%m-%d")
@@ -524,8 +536,10 @@ class ConflictAnalyzer:
"trend": trend,
"trend_direction": "up"
if trend == "increasing"
- else "down" if trend == "decreasing" else "stable",
+ else "down"
+ if trend == "decreasing"
+ else "stable",
}
)
- return trends
\ No newline at end of file
+ return trends
diff --git a/semantica/conflicts/conflict_detector.py b/semantica/conflicts/conflict_detector.py
index cc1eafbd..9b65fbae 100644
--- a/semantica/conflicts/conflict_detector.py
+++ b/semantica/conflicts/conflict_detector.py
@@ -10,15 +10,19 @@ Algorithms Used:
Conflict Detection:
- Value Comparison: Property value comparison across sources with equality checking
- Type Mismatch Detection: Entity type comparison and mismatch identification
- - Relationship Consistency: Relationship property comparison and inconsistency detection
+ - Relationship Consistency: Relationship property comparison and inconsistency
+ detection
- Temporal Analysis: Time-based conflict detection using timestamp comparison
- Logical Consistency: Logical rule validation and inconsistency detection
Severity Calculation:
- - Multi-factor Severity Scoring: Combines property importance, value difference magnitude,
- and source count to calculate conflict severity (low, medium, high, critical)
- - Critical Field Detection: Identifies critical fields (id, name, type, etc.) for higher severity
- - Numeric Difference Analysis: Calculates severity based on numeric value differences
+ - Multi-factor Severity Scoring: Combines property importance, value difference
+ magnitude, and source count to calculate conflict severity (low, medium,
+ high, critical)
+ - Critical Field Detection: Identifies critical fields (id, name, type, etc.)
+ for higher severity
+ - Numeric Difference Analysis: Calculates severity based on numeric value
+ differences
Confidence Scoring:
- Source Credibility Weighting: Uses average confidence of sources
@@ -53,9 +57,8 @@ License: MIT
from dataclasses import dataclass, field
from enum import Enum
-from typing import Any, Dict, List, Optional, Set
+from typing import Any, Dict, List, Optional
-from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
from .source_tracker import SourceReference, SourceTracker
@@ -341,8 +344,8 @@ class ConflictDetector:
)
# Check each field
- for field in fields_to_check:
- conflicts = self.detect_value_conflicts(entities, field, entity_type)
+ for field_name in fields_to_check:
+ conflicts = self.detect_value_conflicts(entities, field_name, entity_type)
all_conflicts.extend(conflicts)
return all_conflicts
@@ -388,7 +391,8 @@ class ConflictDetector:
try:
if len(set(values)) == 2:
return (
- "Compare source documents and use most recent or authoritative source"
+ "Compare source documents and use most recent or authoritative "
+ "source"
)
except TypeError:
# Handle unhashable types (like dicts or lists)
@@ -396,7 +400,8 @@ class ConflictDetector:
str_values = [str(v) for v in values]
if len(set(str_values)) == 2:
return (
- "Compare source documents and use most recent or authoritative source"
+ "Compare source documents and use most recent or authoritative "
+ "source"
)
return "Multiple conflicting values detected. Manual review recommended."
@@ -442,9 +447,7 @@ class ConflictDetector:
return report
- def detect_type_conflicts(
- self, entities: List[Dict[str, Any]]
- ) -> List[Conflict]:
+ def detect_type_conflicts(self, entities: List[Dict[str, Any]]) -> List[Conflict]:
"""
Detect entity type conflicts.
@@ -521,13 +524,16 @@ class ConflictDetector:
sources=sources,
confidence=self._calculate_conflict_confidence(types, sources),
severity=self._calculate_severity("type", types),
- recommended_action="Review entity type definitions and classification",
+ recommended_action=(
+ "Review entity type definitions and classification"
+ ),
)
conflicts.append(conflict)
self.detected_conflicts[conflict.conflict_id] = conflict
self.logger.warning(
- f"Type conflict detected: {entity_id} has conflicting types: {unique_types}"
+ f"Type conflict detected: {entity_id} conflicting types: "
+ f"{unique_types}"
)
self.progress_tracker.stop_tracking(
@@ -636,7 +642,9 @@ class ConflictDetector:
year_match = re.search(r"\b(19|20)\d{2}\b", v)
if year_match:
- normalized_values.append(int(year_match.group()))
+ normalized_values.append(
+ int(year_match.group())
+ )
else:
normalized_values.append(v)
else:
@@ -649,8 +657,9 @@ class ConflictDetector:
)
if len(unique_values) > 1:
+ conflict_id = f"{entity_id}_{prop_name}_temporal_conflict"
conflict = Conflict(
- conflict_id=f"{entity_id}_{prop_name}_temporal_conflict",
+ conflict_id=conflict_id,
conflict_type=ConflictType.TEMPORAL_CONFLICT,
entity_id=entity_id,
property_name=prop_name,
@@ -660,7 +669,10 @@ class ConflictDetector:
values, sources
),
severity=self._calculate_severity(prop_name, values),
- recommended_action="Check temporal context and determine correct time period",
+ recommended_action=(
+ "Check temporal context and determine correct time "
+ "period"
+ ),
)
conflicts.append(conflict)
self.detected_conflicts[conflict.conflict_id] = conflict
@@ -771,9 +783,12 @@ class ConflictDetector:
property_name="type",
conflicting_values=[type1, type2],
sources=sources,
- confidence=1.0, # High confidence for logical conflicts
+ confidence=1.0,
severity="critical",
- recommended_action=f"Entity cannot be both {type1_str} and {type2_str}. Review classification.",
+ recommended_action=(
+ f"Entity cannot be both {type1_str} and "
+ f"{type2_str}. Review classification."
+ ),
)
conflicts.append(conflict)
self.detected_conflicts[
@@ -781,7 +796,7 @@ class ConflictDetector:
] = conflict
self.logger.warning(
- f"Logical conflict detected: {entity_id} cannot be both "
+ f"Logical conflict: {entity_id} cannot be both "
f"{type1_str} and {type2_str}"
)
break
@@ -838,9 +853,9 @@ class ConflictDetector:
if self.conflict_fields:
for entity_type_key, fields in self.conflict_fields.items():
if not entity_type or entity_type_key == entity_type:
- for field in fields:
+ for field_name in fields:
conflicts = self.detect_value_conflicts(
- filtered_entities, field, entity_type
+ filtered_entities, field_name, entity_type
)
all_conflicts.extend(conflicts)
else:
@@ -913,7 +928,7 @@ class ConflictDetector:
return {
"resolved_count": resolved_count,
"unresolved_count": unresolved_count,
- "total_conflicts": len(conflicts)
+ "total_conflicts": len(conflicts),
}
def clear_conflicts(self) -> None:
diff --git a/semantica/conflicts/conflict_resolver.py b/semantica/conflicts/conflict_resolver.py
index fd7d57e6..a50b8cb8 100644
--- a/semantica/conflicts/conflict_resolver.py
+++ b/semantica/conflicts/conflict_resolver.py
@@ -58,12 +58,11 @@ License: MIT
from collections import Counter
from dataclasses import dataclass, field
from enum import Enum
-from typing import Any, Callable, Dict, List, Optional, Union
+from typing import Any, Dict, List, Optional, Union
-from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
-from .conflict_detector import Conflict, ConflictType
+from .conflict_detector import Conflict
from .source_tracker import SourceTracker
@@ -218,7 +217,10 @@ class ConflictResolver:
strategy = normalized_strategy
self.logger.info(
- f"Resolving conflict {conflict.conflict_id} using strategy: {strategy.value}"
+ (
+ f"Resolving conflict {conflict.conflict_id} using strategy: "
+ f"{strategy.value}"
+ )
)
if strategy == ResolutionStrategy.VOTING:
@@ -310,7 +312,9 @@ class ConflictResolver:
resolved_value=most_common_value,
confidence=confidence,
sources_used=sources_used,
- resolution_notes=f"Resolved by voting: {count}/{total_votes} votes for this value",
+ resolution_notes=(
+ f"Resolved by voting: {count}/{total_votes} votes for this value"
+ ),
)
def _resolve_by_credibility(self, conflict: Conflict) -> ResolutionResult:
@@ -359,7 +363,10 @@ class ConflictResolver:
resolved_value=resolved_value,
confidence=confidence,
sources_used=sources_used,
- resolution_notes=f"Resolved by credibility-weighted voting (weight: {value_weights[resolved_value]:.2f})",
+ resolution_notes=(
+ "Resolved by credibility-weighted voting "
+ f"(weight: {value_weights[resolved_value]:.2f})"
+ ),
)
def _resolve_by_recency(self, conflict: Conflict) -> ResolutionResult:
diff --git a/semantica/conflicts/conflicts_usage.md b/semantica/conflicts/conflicts_usage.md
index b0d3d71b..b05b5ff1 100644
--- a/semantica/conflicts/conflicts_usage.md
+++ b/semantica/conflicts/conflicts_usage.md
@@ -150,45 +150,20 @@ print(f"Resolved {resolution_result.get('resolved_count')} conflicts")
### Using Detection Methods
```python
-from semantica.conflicts.methods import detect_conflicts
-
-# Value conflict detection
-conflicts = detect_conflicts(
- entities,
- method="value",
- property_name="name"
-)
-
-# Type conflict detection
-conflicts = detect_conflicts(
- entities,
- method="type"
-)
+from semantica.conflicts import ConflictDetector
-# Relationship conflict detection
-conflicts = detect_conflicts(
- entities,
- method="relationship",
- relationships=relationships
-)
+detector = ConflictDetector()
-# Temporal conflict detection
-conflicts = detect_conflicts(
- entities,
- method="temporal"
-)
+value_conflicts = detector.detect_value_conflicts(entities, property_name="name")
+type_conflicts = detector.detect_type_conflicts(entities)
+relationship_conflicts = detector.detect_relationship_conflicts(relationships)
+temporal_conflicts = detector.detect_temporal_conflicts(entities)
-# Logical conflict detection
-conflicts = detect_conflicts(
- entities,
- method="logical"
-)
-
-# Entity-wide conflict detection
-conflicts = detect_conflicts(
- entities,
- method="entity",
- entity_type="Company"
+conflicts = (
+ value_conflicts
+ + type_conflicts
+ + relationship_conflicts
+ + temporal_conflicts
)
```
@@ -291,28 +266,10 @@ for result in results:
### Using Resolution Methods
```python
-from semantica.conflicts.methods import resolve_conflicts
-
-# Voting resolution
-results = resolve_conflicts(conflicts, method="voting")
-
-# Credibility weighted resolution
-results = resolve_conflicts(conflicts, method="credibility_weighted")
-
-# Most recent resolution
-results = resolve_conflicts(conflicts, method="most_recent")
-
-# First seen resolution
-results = resolve_conflicts(conflicts, method="first_seen")
-
-# Highest confidence resolution
-results = resolve_conflicts(conflicts, method="highest_confidence")
-
-# Manual review
-results = resolve_conflicts(conflicts, method="manual_review")
+from semantica.conflicts import ConflictResolver
-# Expert review
-results = resolve_conflicts(conflicts, method="expert_review")
+resolver = ConflictResolver()
+results = resolver.resolve_conflicts(conflicts, strategy="voting")
```
## Conflict Analysis
@@ -327,7 +284,7 @@ analyzer = ConflictAnalyzer()
# Analyze conflict patterns
analysis = analyzer.analyze_conflicts(conflicts)
-print(f"Total conflicts: {analysis['statistics']['total_conflicts']}")
+print(f"Total conflicts: {analysis['total_conflicts']}")
print(f"Patterns found: {len(analysis['patterns'])}")
for pattern in analysis['patterns']:
@@ -346,7 +303,7 @@ analyzer = ConflictAnalyzer()
analysis = analyzer.analyze_conflicts(conflicts)
print("Conflicts by type:")
-for conflict_type, count in analysis['by_type'].items():
+for conflict_type, count in analysis['by_type']['counts'].items():
print(f" {conflict_type}: {count}")
```
@@ -361,8 +318,8 @@ analyzer = ConflictAnalyzer()
analysis = analyzer.analyze_conflicts(conflicts)
print("Conflicts by severity:")
-for severity, conflicts_list in analysis['by_severity'].items():
- print(f" {severity}: {len(conflicts_list)} conflicts")
+for severity, count in analysis['by_severity']['counts'].items():
+ print(f" {severity}: {count} conflicts")
```
### Source Analysis
@@ -376,8 +333,8 @@ analyzer = ConflictAnalyzer()
analysis = analyzer.analyze_conflicts(conflicts)
print("Conflicts by source:")
-for source, conflicts_list in analysis['by_source'].items():
- print(f" {source}: {len(conflicts_list)} conflicts")
+for source, count in analysis['by_source']['counts'].items():
+ print(f" {source}: {count} conflicts")
```
### Trend Analysis
@@ -399,22 +356,10 @@ for trend in trends:
### Using Analysis Methods
```python
-from semantica.conflicts.methods import analyze_conflicts
-
-# Pattern analysis
-analysis = analyze_conflicts(conflicts, method="pattern")
-
-# Type analysis
-analysis = analyze_conflicts(conflicts, method="type")
-
-# Severity analysis
-analysis = analyze_conflicts(conflicts, method="severity")
-
-# Source analysis
-analysis = analyze_conflicts(conflicts, method="source")
+from semantica.conflicts import ConflictAnalyzer
-# Trend analysis
-analysis = analyze_conflicts(conflicts, method="trend")
+analyzer = ConflictAnalyzer()
+analysis = analyzer.analyze_conflicts(conflicts)
```
## Source Tracking
@@ -446,8 +391,8 @@ tracker.track_property_source(
)
# Get property sources
-sources = tracker.get_property_sources("entity_1", "name")
-for prop_source in sources:
+prop_source = tracker.get_property_sources("entity_1", "name")
+if prop_source:
print(f"Value: {prop_source.value}")
print(f"Sources: {len(prop_source.sources)}")
```
@@ -517,40 +462,22 @@ chain = tracker.generate_traceability_chain("entity_1", "name")
print("Traceability chain:")
for step in chain:
- print(f" {step['type']}: {step['identifier']}")
- print(f" Sources: {step['sources']}")
+ print(f" {step['type']}: {step['entity_id']}.{step.get('property_name')}")
+ print(f" Source: {step.get('source', {}).get('document')}")
```
### Using Tracking Methods
```python
-from semantica.conflicts.methods import track_sources
-from semantica.conflicts import SourceReference
+from semantica.conflicts import SourceTracker, SourceReference
-# Property tracking
source = SourceReference(document="doc1", confidence=0.9)
-track_sources(
- "entity_1",
- method="property",
- property_name="name",
- value="Apple Inc.",
- source=source
-)
+tracker = SourceTracker()
+tracker.track_property_source("entity_1", "name", "Apple Inc.", source)
-# Entity tracking
-track_sources(
- "entity_1",
- method="entity",
- source=source
-)
+tracker.track_entity_source("entity_1", source)
-# Relationship tracking
-track_sources(
- "entity_1",
- method="relationship",
- relationship_id="rel_1",
- source=source
-)
+tracker.track_relationship_source("rel_1", source)
```
## Investigation Guides
@@ -613,16 +540,14 @@ print(checklist_md)
### Using Investigation Methods
```python
-from semantica.conflicts.methods import generate_investigation_guide
+from semantica.conflicts import InvestigationGuideGenerator
-# Generate guide
-guide = generate_investigation_guide(conflict, method="guide")
+generator = InvestigationGuideGenerator()
+guide = generator.generate_guide(conflict)
-# Generate checklist
-checklist = generate_investigation_guide(conflict, method="checklist")
+checklist = generator.export_investigation_checklist(guide, format="text")
-# Extract context
-context = generate_investigation_guide(conflict, method="context")
+context = guide.context
```
## Using Methods
@@ -630,26 +555,37 @@ context = generate_investigation_guide(conflict, method="context")
### List Available Methods
```python
-from semantica.conflicts.methods import list_available_methods
+from semantica.conflicts import MethodRegistry
# List all available methods
-all_methods = list_available_methods()
-print("Available methods:")
+all_methods = MethodRegistry.list_all()
+print("Registered methods:")
for task, methods in all_methods.items():
print(f" {task}: {methods}")
# List methods for specific task
-detection_methods = list_available_methods("detection")
+detection_methods = MethodRegistry.list_all("detection")
print(f"Detection methods: {detection_methods}")
```
### Get Conflict Method
```python
-from semantica.conflicts.methods import get_conflict_method
+from semantica.conflicts import MethodRegistry, ResolutionResult
-# Get a specific method
-method = get_conflict_method("resolution", "voting")
+def custom_resolution_method(conflicts, **kwargs):
+ results = []
+ for conflict in conflicts:
+ result = ResolutionResult(
+ conflict_id=conflict.conflict_id,
+ resolved=True,
+ resolved_value="custom_value"
+ )
+ results.append(result)
+ return results
+
+MethodRegistry.register("resolution", "custom_method", custom_resolution_method)
+method = MethodRegistry.get("resolution", "custom_method")
if method:
results = method(conflicts)
```
@@ -659,7 +595,7 @@ if method:
### Register Custom Method
```python
-from semantica.conflicts import method_registry
+from semantica.conflicts import MethodRegistry, ResolutionResult
def custom_resolution_method(conflicts, **kwargs):
"""Custom resolution method."""
@@ -676,36 +612,36 @@ def custom_resolution_method(conflicts, **kwargs):
return results
# Register custom method
-method_registry.register("resolution", "custom_method", custom_resolution_method)
+MethodRegistry.register("resolution", "custom_method", custom_resolution_method)
# Use custom method
-from semantica.conflicts.methods import resolve_conflicts
-results = resolve_conflicts(conflicts, method="custom_method")
+method = MethodRegistry.get("resolution", "custom_method")
+results = method(conflicts) if method else []
```
### List Registered Methods
```python
-from semantica.conflicts import method_registry
+from semantica.conflicts import MethodRegistry
# List all registered methods
-all_methods = method_registry.list_all()
+all_methods = MethodRegistry.list_all()
print("Registered methods:")
for task, methods in all_methods.items():
- print(f" {task}: {list(methods.keys())}")
+ print(f" {task}: {methods}")
# List methods for specific task
-resolution_methods = method_registry.list_all("resolution")
+resolution_methods = MethodRegistry.list_all("resolution")
print(f"Resolution methods: {resolution_methods}")
```
### Unregister Method
```python
-from semantica.conflicts import method_registry
+from semantica.conflicts import MethodRegistry
# Unregister a method
-method_registry.unregister("resolution", "custom_method")
+MethodRegistry.unregister("resolution", "custom_method")
```
## Configuration
diff --git a/semantica/conflicts/investigation_guide.py b/semantica/conflicts/investigation_guide.py
index e7cdedf8..a12828db 100644
--- a/semantica/conflicts/investigation_guide.py
+++ b/semantica/conflicts/investigation_guide.py
@@ -8,13 +8,17 @@ conflicts to help domain experts investigate and resolve discrepancies.
Algorithms Used:
Guide Generation:
- - Template-based Generation: Uses conflict type and severity to select appropriate templates
- - Context Extraction: Extracts conflict context from Conflict object and SourceTracker
+ - Template-based Generation: Uses conflict type and severity to select appropriate
+ templates
+ - Context Extraction: Extracts conflict context from Conflict object and
+ SourceTracker
- Step Generation: Generates investigation steps based on conflict characteristics
- - Severity-based Recommendations: Provides recommendations based on conflict severity
+ - Severity-based Recommendations: Provides recommendations based on conflict
+ severity
Checklist Generation:
- - Step-by-step Checklist Creation: Converts investigation steps into checklist format
+ - Step-by-step Checklist Creation: Converts investigation steps into checklist
+ format
- Action Item Extraction: Extracts actionable items from investigation steps
- Priority Ordering: Orders checklist items by priority and severity
@@ -25,7 +29,8 @@ Context Extraction:
- Related Conflicts: Identifies related conflicts for context
Step Generation:
- - Type-based Steps: Generates steps specific to conflict type (value, type, relationship, etc.)
+ - Type-based Steps: Generates steps specific to conflict type (value, type,
+ relationship, etc.)
- Severity-based Steps: Adjusts steps based on conflict severity
- Source Investigation Steps: Includes steps for investigating conflicting sources
- Resolution Steps: Suggests resolution steps based on conflict characteristics
@@ -233,8 +238,12 @@ class InvestigationGuideGenerator:
InvestigationStep(
step_number=1,
description="Review conflict details and context",
- action="Examine the conflict summary and identify the conflicting values",
- expected_outcome="Understanding of the nature and scope of the conflict",
+ action=(
+ "Examine the conflict summary and identify the conflicting values"
+ ),
+ expected_outcome=(
+ "Understanding of the nature and scope of the conflict"
+ ),
)
)
@@ -247,7 +256,10 @@ class InvestigationGuideGenerator:
InvestigationStep(
step_number=2,
description="Identify all source documents",
- action=f"Locate and review the following source documents: {source_list}",
+ action=(
+ "Locate and review the following source documents: "
+ f"{source_list}"
+ ),
expected_outcome="All source documents identified and accessible",
)
)
@@ -258,7 +270,10 @@ class InvestigationGuideGenerator:
InvestigationStep(
step_number=3,
description="Compare conflicting information across sources",
- action="Review each source document and note the specific value and context for each",
+ action=(
+ "Review each source document and note the specific value and "
+ "context for each"
+ ),
expected_outcome="List of values and their sources with context",
)
)
@@ -279,7 +294,10 @@ class InvestigationGuideGenerator:
InvestigationStep(
step_number=5,
description="Determine resolution approach",
- action="Choose resolution strategy based on source credibility, recency, and business rules",
+ action=(
+ "Choose resolution strategy based on source credibility, "
+ "recency, and business rules"
+ ),
expected_outcome="Resolution approach selected",
)
)
diff --git a/semantica/conflicts/methods.py b/semantica/conflicts/methods.py
index 74b662fd..e8350f8c 100644
--- a/semantica/conflicts/methods.py
+++ b/semantica/conflicts/methods.py
@@ -48,11 +48,14 @@ Algorithms Used:
Conflict Detection:
- Value Comparison: Property value comparison across sources with equality checking
- Type Mismatch Detection: Entity type comparison and mismatch identification
- - Relationship Consistency: Relationship property comparison and inconsistency detection
+ - Relationship Consistency: Relationship property comparison and inconsistency
+ detection
- Temporal Analysis: Time-based conflict detection using timestamp comparison
- Logical Consistency: Logical rule validation and inconsistency detection
- - Severity Calculation: Multi-factor severity scoring (property importance, value difference, source count)
- - Confidence Scoring: Confidence calculation based on source credibility and value diversity
+ - Severity Calculation: Multi-factor severity scoring (property importance,
+ value difference, source count)
+ - Confidence Scoring: Confidence calculation based on source credibility and
+ value diversity
Conflict Resolution:
- Voting Algorithm: Majority value selection using Counter-based frequency counting
@@ -62,7 +65,8 @@ Conflict Resolution:
- Manual Flagging: Conflict flagging for human review workflow
Conflict Analysis:
- - Pattern Identification: Frequency-based pattern detection using Counter and defaultdict
+ - Pattern Identification: Frequency-based pattern detection using Counter and
+ defaultdict
- Type Classification: Conflict type categorization and grouping
- Severity Analysis: Severity-based grouping and analysis
- Source Analysis: Source-based conflict aggregation and analysis
@@ -112,18 +116,13 @@ License: MIT
from typing import Any, Callable, Dict, List, Optional, Union
-from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
-from .conflict_analyzer import ConflictAnalyzer, ConflictPattern
-from .conflict_detector import Conflict, ConflictDetector, ConflictType
+from .conflict_analyzer import ConflictAnalyzer
+from .conflict_detector import Conflict, ConflictDetector
from .conflict_resolver import ConflictResolver, ResolutionResult, ResolutionStrategy
-from .investigation_guide import (
- InvestigationGuide,
- InvestigationGuideGenerator,
- InvestigationStep,
-)
+from .investigation_guide import InvestigationGuide, InvestigationGuideGenerator
from .registry import method_registry
-from .source_tracker import PropertySource, SourceReference, SourceTracker
+from .source_tracker import SourceReference, SourceTracker
logger = get_logger("conflicts_methods")
@@ -323,7 +322,8 @@ def track_sources(
"""
Track source information (convenience function).
- This is a user-friendly wrapper that tracks source information using the specified method.
+ This is a user-friendly wrapper that tracks source information using the
+ specified method.
Args:
entity_id: Entity identifier
@@ -344,13 +344,20 @@ def track_sources(
>>> from semantica.conflicts.methods import track_sources
>>> from semantica.conflicts import SourceReference
>>> source = SourceReference(document="doc1", page=1, confidence=0.9)
- >>> track_sources("entity_1", property_name="name", value="Apple", source=source)
+ >>> track_sources(
+ ... "entity_1", property_name="name", value="Apple", source=source
+ ... )
"""
# Check for custom method in registry
custom_method = method_registry.get("tracking", method)
if custom_method:
return custom_method(
- entity_id, property_name=property_name, value=value, source=source, tracker=tracker, **kwargs
+ entity_id,
+ property_name=property_name,
+ value=value,
+ source=source,
+ tracker=tracker,
+ **kwargs,
)
# Use provided tracker or create new one
@@ -376,7 +383,9 @@ def track_sources(
raise ValueError(
"relationship_id and source are required for relationship tracking"
)
- return actual_tracker.track_relationship_source(relationship_id, source, **kwargs)
+ return actual_tracker.track_relationship_source(
+ relationship_id, source, **kwargs
+ )
else:
# Default to property tracking
if property_name and value and source:
@@ -393,7 +402,8 @@ def generate_investigation_guide(
"""
Generate investigation guide (convenience function).
- This is a user-friendly wrapper that generates investigation guides using the specified method.
+ This is a user-friendly wrapper that generates investigation guides using the
+ specified method.
Args:
conflict: Single conflict or list of conflicts
@@ -467,7 +477,8 @@ def get_conflict_method(task: str, name: str) -> Optional[Callable]:
or returns a built-in method if available.
Args:
- task: Task type ("detection", "resolution", "analysis", "tracking", "investigation")
+ task: Task type ("detection", "resolution", "analysis", "tracking",
+ "investigation")
name: Method name
Returns:
@@ -626,6 +637,3 @@ def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:
result[t] = list(set(registered.get(t, []) + builtin_methods.get(t, [])))
return result
-
-
-
diff --git a/semantica/conflicts/registry.py b/semantica/conflicts/registry.py
index 953f4434..18f7f3cf 100644
--- a/semantica/conflicts/registry.py
+++ b/semantica/conflicts/registry.py
@@ -22,7 +22,8 @@ Algorithms Used:
Key Features:
- Method registry for custom conflict methods
- - Task-based method organization (detection, resolution, analysis, tracking, investigation)
+ - Task-based method organization (detection, resolution, analysis, tracking,
+ investigation)
- Dynamic registration and unregistration
- Easy discovery of available methods
- Support for community-contributed extensions
@@ -35,14 +36,16 @@ Global Instances:
Example Usage:
>>> from semantica.conflicts.registry import method_registry
- >>> method_registry.register("resolution", "custom_method", custom_resolution_function)
+ >>> method_registry.register(
+ ... "resolution", "custom_method", custom_resolution_function
+ ... )
>>> available = method_registry.list_all("resolution")
Author: Semantica Contributors
License: MIT
"""
-from typing import Any, Callable, Dict, List, Optional
+from typing import Callable, Dict, List, Optional
class MethodRegistry:
@@ -62,7 +65,8 @@ class MethodRegistry:
Register a custom conflict method.
Args:
- task: Task type ("detection", "resolution", "analysis", "tracking", "investigation")
+ task: Task type ("detection", "resolution", "analysis", "tracking",
+ "investigation")
name: Method name
method_func: Method function
"""
@@ -76,7 +80,8 @@ class MethodRegistry:
Get method by task and name.
Args:
- task: Task type ("detection", "resolution", "analysis", "tracking", "investigation")
+ task: Task type ("detection", "resolution", "analysis", "tracking",
+ "investigation")
name: Method name
Returns:
@@ -105,7 +110,8 @@ class MethodRegistry:
Unregister a method.
Args:
- task: Task type ("detection", "resolution", "analysis", "tracking", "investigation")
+ task: Task type ("detection", "resolution", "analysis", "tracking",
+ "investigation")
name: Method name
"""
if task in cls._methods and name in cls._methods[task]:
diff --git a/semantica/conflicts/source_tracker.py b/semantica/conflicts/source_tracker.py
index 3ef58b88..a25eb841 100644
--- a/semantica/conflicts/source_tracker.py
+++ b/semantica/conflicts/source_tracker.py
@@ -8,7 +8,8 @@ conflict investigation and source disagreement analysis.
Algorithms Used:
Property Source Tracking:
- - Dictionary-based Mapping: Uses nested dictionaries (entity -> property -> PropertySource)
+ - Dictionary-based Mapping: Uses nested dictionaries (entity -> property ->
+ PropertySource)
for efficient property-to-source mapping
- Source Aggregation: Aggregates multiple sources for the same property value
- Source Deduplication: Prevents duplicate source entries
@@ -23,12 +24,14 @@ Relationship Source Tracking:
- Relationship Source Aggregation: Aggregates sources for relationship properties
Credibility Scoring:
- - Source Credibility Calculation: Calculates source credibility based on historical accuracy
+ - Source Credibility Calculation: Calculates source credibility based on
+ historical accuracy
- Credibility Weighting: Uses credibility scores for weighted conflict resolution
- Credibility Updates: Updates credibility based on conflict resolution outcomes
Traceability Chain:
- - Graph-based Traceability: Builds traceability graph connecting entities, properties, and sources
+ - Graph-based Traceability: Builds traceability graph connecting entities,
+ properties, and sources
- Chain Generation: Generates traceability chains from entity to source documents
- Path Finding: Finds paths through the traceability graph
@@ -61,7 +64,7 @@ License: MIT
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime
-from typing import Any, Dict, List, Optional, Set
+from typing import Any, Dict, List, Optional
from ..utils.exceptions import ValidationError
from ..utils.logging import get_logger
@@ -535,7 +538,8 @@ class SourceTracker:
self, entity_id: str, property_name: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
- Generate traceability chain for an entity or property (alias for get_traceability_chain).
+ Generate traceability chain for an entity or property (alias for
+ get_traceability_chain).
Args:
entity_id: Entity identifier
@@ -544,4 +548,4 @@ class SourceTracker:
Returns:
List of traceability records
"""
- return self.get_traceability_chain(entity_id, property_name)
\ No newline at end of file
+ return self.get_traceability_chain(entity_id, property_name)
diff --git a/tests/conflicts/test_conflicts.py b/tests/conflicts/test_conflicts.py
index 37a95a88..bee5c828 100644
--- a/tests/conflicts/test_conflicts.py
+++ b/tests/conflicts/test_conflicts.py
@@ -1,21 +1,28 @@
import unittest
from datetime import datetime
from unittest.mock import MagicMock, patch
-from semantica.conflicts.source_tracker import SourceTracker, SourceReference
-from semantica.conflicts.conflict_detector import ConflictDetector, ConflictType, Conflict
-from semantica.conflicts.conflict_resolver import ConflictResolver, ResolutionStrategy
+
from semantica.conflicts.conflict_analyzer import ConflictAnalyzer
+from semantica.conflicts.conflict_detector import (
+ Conflict,
+ ConflictDetector,
+ ConflictType,
+)
+from semantica.conflicts.conflict_resolver import ConflictResolver
from semantica.conflicts.investigation_guide import InvestigationGuideGenerator
+from semantica.conflicts.source_tracker import SourceReference, SourceTracker
-class TestConflictsModule(unittest.TestCase):
+class TestConflictsModule(unittest.TestCase):
def setUp(self):
# Mock progress tracker
- self.mock_tracker_patcher = patch("semantica.utils.progress_tracker.get_progress_tracker")
+ self.mock_tracker_patcher = patch(
+ "semantica.utils.progress_tracker.get_progress_tracker"
+ )
self.mock_get_tracker = self.mock_tracker_patcher.start()
self.mock_tracker = MagicMock()
self.mock_get_tracker.return_value = self.mock_tracker
-
+
self.setUp_data()
def tearDown(self):
@@ -32,7 +39,7 @@ class TestConflictsModule(unittest.TestCase):
"source": "source1",
"page": 1,
"confidence": 0.9,
- "metadata": {"timestamp": "2023-01-01T10:00:00"}
+ "metadata": {"timestamp": "2023-01-01T10:00:00"},
},
{
"id": "e1",
@@ -42,42 +49,36 @@ class TestConflictsModule(unittest.TestCase):
"source": "source2",
"page": 5,
"confidence": 0.8,
- "metadata": {"timestamp": "2023-06-01T10:00:00"}
- }
+ "metadata": {"timestamp": "2023-06-01T10:00:00"},
+ },
]
-
+
self.source1 = SourceReference(
- document="doc1",
- page=1,
- confidence=0.9,
- timestamp=datetime(2023, 1, 1)
+ document="doc1", page=1, confidence=0.9, timestamp=datetime(2023, 1, 1)
)
self.source2 = SourceReference(
- document="doc2",
- page=2,
- confidence=0.8,
- timestamp=datetime(2023, 6, 1)
+ document="doc2", page=2, confidence=0.8, timestamp=datetime(2023, 6, 1)
)
def test_source_tracker(self):
tracker = SourceTracker()
-
+
# Test tracking property source
tracker.track_property_source("e1", "age", 30, self.source1)
tracker.track_property_source("e1", "age", 32, self.source2)
-
+
# Test getting property sources
prop_source = tracker.get_property_sources("e1", "age")
self.assertIsNotNone(prop_source)
self.assertEqual(len(prop_source.sources), 2)
- self.assertEqual(prop_source.value, 32) # Should store latest value
-
+ self.assertEqual(prop_source.value, 32) # Should store latest value
+
# Test finding disagreements
disagreements = tracker.find_source_disagreements("e1", "age")
- # Since we tracked different sources for the same property, there might be disagreements
- # based on how find_source_disagreements works (it checks for diff document or confidence)
+ # Since we tracked different sources for the same property, there might be
+ # disagreements based on how find_source_disagreements works.
self.assertTrue(len(disagreements) > 0)
-
+
# Test tracking entity source
tracker.track_entity_source("e1", self.source1)
sources = tracker.get_entity_sources("e1")
@@ -85,18 +86,17 @@ class TestConflictsModule(unittest.TestCase):
def test_conflict_detector(self):
detector = ConflictDetector()
-
- # We need to flatten the entities structure for detect_value_conflicts as it expects
- # list of entity dicts where properties are at top level or we need to adjust input
- # Looking at code: value = entity[property_name]
-
+
+ # We need to flatten the entities structure for detect_value_conflicts since it
+ # expects properties at top-level (value = entity[property_name]).
+
flat_entities = [
{"id": "e1", "age": 30, "source": "source1", "confidence": 0.9},
- {"id": "e1", "age": 32, "source": "source2", "confidence": 0.8}
+ {"id": "e1", "age": 32, "source": "source2", "confidence": 0.8},
]
-
+
conflicts = detector.detect_value_conflicts(flat_entities, "age")
-
+
self.assertEqual(len(conflicts), 1)
conflict = conflicts[0]
self.assertEqual(conflict.entity_id, "e1")
@@ -105,11 +105,11 @@ class TestConflictsModule(unittest.TestCase):
self.assertEqual(len(conflict.conflicting_values), 2)
self.assertIn(30, conflict.conflicting_values)
self.assertIn(32, conflict.conflicting_values)
-
+
# Test type conflicts
type_entities = [
{"id": "e2", "type": "Person", "source": "s1"},
- {"id": "e2", "type": "Organization", "source": "s2"}
+ {"id": "e2", "type": "Organization", "source": "s2"},
]
type_conflicts = detector.detect_type_conflicts(type_entities)
self.assertEqual(len(type_conflicts), 1)
@@ -117,7 +117,7 @@ class TestConflictsModule(unittest.TestCase):
def test_conflict_resolver(self):
resolver = ConflictResolver()
-
+
conflict = Conflict(
conflict_id="c1",
conflict_type=ConflictType.VALUE_CONFLICT,
@@ -125,22 +125,34 @@ class TestConflictsModule(unittest.TestCase):
property_name="age",
conflicting_values=[30, 30, 32],
sources=[
- {"document": "doc1", "confidence": 0.9, "metadata": {"timestamp": datetime(2023, 1, 1)}},
- {"document": "doc3", "confidence": 0.9, "metadata": {"timestamp": datetime(2023, 1, 2)}},
- {"document": "doc2", "confidence": 0.8, "metadata": {"timestamp": datetime(2023, 6, 1)}}
- ]
+ {
+ "document": "doc1",
+ "confidence": 0.9,
+ "metadata": {"timestamp": datetime(2023, 1, 1)},
+ },
+ {
+ "document": "doc3",
+ "confidence": 0.9,
+ "metadata": {"timestamp": datetime(2023, 1, 2)},
+ },
+ {
+ "document": "doc2",
+ "confidence": 0.8,
+ "metadata": {"timestamp": datetime(2023, 6, 1)},
+ },
+ ],
)
-
+
# Test Voting
result_voting = resolver.resolve_conflict(conflict, strategy="voting")
self.assertTrue(result_voting.resolved)
- self.assertEqual(result_voting.resolved_value, 30) # 30 appears twice
-
+ self.assertEqual(result_voting.resolved_value, 30) # 30 appears twice
+
# Test Most Recent
result_recent = resolver.resolve_conflict(conflict, strategy="most_recent")
self.assertTrue(result_recent.resolved)
- self.assertEqual(result_recent.resolved_value, 32) # doc2 is most recent (June)
-
+ self.assertEqual(result_recent.resolved_value, 32) # doc2 is most recent (June)
+
# Test Highest Confidence
# doc1 and doc3 have 0.9, doc2 has 0.8. Should pick 30 (first max confidence)
result_conf = resolver.resolve_conflict(conflict, strategy="highest_confidence")
@@ -149,7 +161,7 @@ class TestConflictsModule(unittest.TestCase):
def test_conflict_analyzer(self):
analyzer = ConflictAnalyzer()
-
+
conflicts = [
Conflict(
conflict_id="c1",
@@ -158,7 +170,7 @@ class TestConflictsModule(unittest.TestCase):
property_name="age",
conflicting_values=[30, 32],
sources=[{"document": "doc1"}, {"document": "doc2"}],
- severity="medium"
+ severity="medium",
),
Conflict(
conflict_id="c2",
@@ -167,12 +179,12 @@ class TestConflictsModule(unittest.TestCase):
property_name="type",
conflicting_values=["Person", "Org"],
sources=[{"document": "doc1"}, {"document": "doc3"}],
- severity="critical"
- )
+ severity="critical",
+ ),
]
-
+
analysis = analyzer.analyze_conflicts(conflicts)
-
+
self.assertEqual(analysis["total_conflicts"], 2)
self.assertEqual(analysis["by_severity"]["counts"]["critical"], 1)
self.assertEqual(analysis["by_severity"]["counts"]["medium"], 1)
@@ -180,7 +192,7 @@ class TestConflictsModule(unittest.TestCase):
def test_investigation_guide(self):
generator = InvestigationGuideGenerator()
-
+
conflict = Conflict(
conflict_id="c1",
conflict_type=ConflictType.VALUE_CONFLICT,
@@ -188,19 +200,20 @@ class TestConflictsModule(unittest.TestCase):
property_name="age",
conflicting_values=[30, 32],
sources=[{"document": "doc1"}, {"document": "doc2"}],
- severity="medium"
+ severity="medium",
)
-
+
guide = generator.generate_guide(conflict)
-
+
self.assertEqual(guide.conflict_id, "c1")
self.assertEqual(guide.severity, "medium")
self.assertTrue(len(guide.investigation_steps) > 0)
self.assertTrue(len(guide.recommended_actions) > 0)
-
+
# Test checklist export
checklist = generator.export_investigation_checklist(guide, format="text")
self.assertIn("INVESTIGATION GUIDE: c1", checklist)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()