duplicate_checker.py aktualisiert
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
# duplicate_checker.py (v2.2 - Multi-Key Blocking & optimiertes Scoring)
|
# duplicate_checker.py (v1.1 - Lauf 1 Logik + Match-Grund)
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@@ -6,55 +6,50 @@ from thefuzz import fuzz
|
|||||||
from config import Config
|
from config import Config
|
||||||
from helpers import normalize_company_name, simple_normalize_url
|
from helpers import normalize_company_name, simple_normalize_url
|
||||||
from google_sheet_handler import GoogleSheetHandler
|
from google_sheet_handler import GoogleSheetHandler
|
||||||
from collections import defaultdict
|
import time
|
||||||
|
|
||||||
# --- Konfiguration ---
|
# --- Konfiguration ---
|
||||||
CRM_SHEET_NAME = "CRM_Accounts"
|
CRM_SHEET_NAME = "CRM_Accounts"
|
||||||
MATCHING_SHEET_NAME = "Matching_Accounts"
|
MATCHING_SHEET_NAME = "Matching_Accounts"
|
||||||
SCORE_THRESHOLD = 85 # Etwas höherer Schwellenwert für bessere Präzision
|
SCORE_THRESHOLD = 80 # Treffer unter diesem Wert werden nicht als "potenzieller Treffer" angezeigt
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||||
|
|
||||||
def calculate_similarity_details(record1, record2):
|
def calculate_similarity_with_details(record1, record2):
|
||||||
"""Berechnet einen gewichteten Ähnlichkeits-Score und gibt die Details zurück."""
|
"""
|
||||||
|
Berechnet einen gewichteten Ähnlichkeits-Score und gibt den Score und den Grund zurück.
|
||||||
|
Dies ist die originale Scoring-Logik von Lauf 1.
|
||||||
|
"""
|
||||||
scores = {'name': 0, 'location': 0, 'domain': 0}
|
scores = {'name': 0, 'location': 0, 'domain': 0}
|
||||||
|
|
||||||
|
# Domain-Match (100 Punkte)
|
||||||
if record1.get('normalized_domain') and record1['normalized_domain'] != 'k.a.' and record1['normalized_domain'] == record2.get('normalized_domain'):
|
if record1.get('normalized_domain') and record1['normalized_domain'] != 'k.a.' and record1['normalized_domain'] == record2.get('normalized_domain'):
|
||||||
scores['domain'] = 100
|
scores['domain'] = 100
|
||||||
|
|
||||||
# Höhere Gewichtung für den Namen, da die Website oft fehlt
|
# Namensähnlichkeit (70% Gewichtung)
|
||||||
if record1.get('normalized_name') and record2.get('normalized_name'):
|
if record1.get('normalized_name') and record2.get('normalized_name'):
|
||||||
scores['name'] = round(fuzz.token_set_ratio(record1['normalized_name'], record2['normalized_name']) * 0.85)
|
name_similarity = fuzz.token_set_ratio(record1['normalized_name'], record2['normalized_name'])
|
||||||
|
scores['name'] = round(name_similarity * 0.7)
|
||||||
|
|
||||||
|
# Standort-Bonus (20 Punkte)
|
||||||
if record1.get('CRM Ort') and record1['CRM Ort'] == record2.get('CRM Ort'):
|
if record1.get('CRM Ort') and record1['CRM Ort'] == record2.get('CRM Ort'):
|
||||||
if record1.get('CRM Land') and record1['CRM Land'] == record2.get('CRM Land'):
|
if record1.get('CRM Land') and record1['CRM Land'] == record2.get('CRM Land'):
|
||||||
scores['location'] = 20
|
scores['location'] = 20
|
||||||
|
|
||||||
total_score = sum(scores.values())
|
total_score = sum(scores.values())
|
||||||
return {'total': total_score, 'details': scores}
|
|
||||||
|
|
||||||
def create_blocking_keys(name):
|
# Erstelle den Begründungstext
|
||||||
"""Erstellt mehrere Blocking Keys für einen Namen, um die Sensitivität zu erhöhen."""
|
reasons = []
|
||||||
if not name:
|
if scores['domain'] > 0: reasons.append(f"Domain({scores['domain']})")
|
||||||
return []
|
if scores['name'] > 0: reasons.append(f"Name({scores['name']})")
|
||||||
|
if scores['location'] > 0: reasons.append(f"Ort({scores['location']})")
|
||||||
|
reason_text = " + ".join(reasons) if reasons else "Keine Übereinstimmung"
|
||||||
|
|
||||||
words = name.split()
|
return round(total_score), reason_text
|
||||||
keys = set()
|
|
||||||
|
|
||||||
# 1. Erstes Wort
|
|
||||||
if len(words) > 0:
|
|
||||||
keys.add(words[0])
|
|
||||||
# 2. Zweites Wort (falls vorhanden)
|
|
||||||
if len(words) > 1:
|
|
||||||
keys.add(words[1])
|
|
||||||
# 3. Erste 4 Buchstaben des ersten Wortes
|
|
||||||
if len(words) > 0 and len(words[0]) >= 4:
|
|
||||||
keys.add(words[0][:4])
|
|
||||||
|
|
||||||
return list(keys)
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
logging.info("Starte den Duplikats-Check (v2.2 mit Multi-Key Blocking)...")
|
start_time = time.time()
|
||||||
|
logging.info("Starte den Duplikats-Check (v1.1 - Brute-Force mit Match-Grund)...")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
sheet_handler = GoogleSheetHandler()
|
sheet_handler = GoogleSheetHandler()
|
||||||
@@ -77,43 +72,32 @@ def main():
|
|||||||
df['normalized_domain'] = df['CRM Website'].astype(str).apply(simple_normalize_url)
|
df['normalized_domain'] = df['CRM Website'].astype(str).apply(simple_normalize_url)
|
||||||
df['CRM Ort'] = df['CRM Ort'].astype(str).str.lower().str.strip()
|
df['CRM Ort'] = df['CRM Ort'].astype(str).str.lower().str.strip()
|
||||||
df['CRM Land'] = df['CRM Land'].astype(str).str.lower().str.strip()
|
df['CRM Land'] = df['CRM Land'].astype(str).str.lower().str.strip()
|
||||||
df['block_keys'] = df['normalized_name'].apply(create_blocking_keys)
|
|
||||||
|
|
||||||
logging.info("Erstelle Index für CRM-Daten zur Beschleunigung...")
|
crm_records = crm_df.to_dict('records')
|
||||||
crm_index = defaultdict(list)
|
matching_records = matching_df.to_dict('records')
|
||||||
for record in crm_df.to_dict('records'):
|
|
||||||
for key in record['block_keys']:
|
|
||||||
crm_index[key].append(record)
|
|
||||||
|
|
||||||
logging.info("Starte Matching-Prozess...")
|
logging.info(f"Starte Matching-Prozess: {len(matching_records)} Einträge werden mit {len(crm_records)} CRM-Einträgen verglichen...")
|
||||||
results = []
|
results = []
|
||||||
|
|
||||||
for match_record in matching_df.to_dict('records'):
|
for i, match_record in enumerate(matching_records):
|
||||||
best_score_info = {'total': 0, 'details': {'name': 0, 'location': 0, 'domain': 0}}
|
best_score = -1
|
||||||
best_match_name = ""
|
best_match_name = ""
|
||||||
|
best_reason = ""
|
||||||
|
|
||||||
logging.info(f"Prüfe: {match_record['CRM Name']}...")
|
logging.info(f"Prüfe {i + 1}/{len(matching_records)}: {match_record.get('CRM Name', 'N/A')}...")
|
||||||
|
|
||||||
candidate_pool = {}
|
# Brute-Force-Vergleich: Jede Zeile wird mit jeder CRM-Zeile verglichen
|
||||||
for key in match_record['block_keys']:
|
for crm_record in crm_records:
|
||||||
for crm_record in crm_index.get(key, []):
|
score, reason = calculate_similarity_with_details(match_record, crm_record)
|
||||||
candidate_pool[crm_record['CRM Name']] = crm_record
|
if score > best_score:
|
||||||
|
best_score = score
|
||||||
if not candidate_pool:
|
best_match_name = crm_record.get('CRM Name', 'N/A')
|
||||||
logging.debug(" -> Keine Kandidaten im Index gefunden.")
|
best_reason = reason
|
||||||
|
|
||||||
for crm_record in candidate_pool.values():
|
|
||||||
score_info = calculate_similarity_details(match_record, crm_record)
|
|
||||||
if score_info['total'] > best_score_info['total']:
|
|
||||||
best_score_info = score_info
|
|
||||||
best_match_name = crm_record['CRM Name']
|
|
||||||
|
|
||||||
results.append({
|
results.append({
|
||||||
'Potenzieller Treffer im CRM': best_match_name if best_score_info['total'] >= SCORE_THRESHOLD else "",
|
'Potenzieller Treffer im CRM': best_match_name if best_score >= SCORE_THRESHOLD else "",
|
||||||
'Score (Gesamt)': best_score_info['total'],
|
'Ähnlichkeits-Score': best_score,
|
||||||
'Score (Name)': best_score_info['details']['name'],
|
'Matching-Grund': best_reason
|
||||||
'Bonus (Standort)': best_score_info['details']['location'],
|
|
||||||
'Bonus (Domain)': best_score_info['details']['domain']
|
|
||||||
})
|
})
|
||||||
|
|
||||||
logging.info("Matching abgeschlossen. Schreibe Ergebnisse zurück ins Sheet...")
|
logging.info("Matching abgeschlossen. Schreibe Ergebnisse zurück ins Sheet...")
|
||||||
@@ -129,5 +113,8 @@ def main():
|
|||||||
else:
|
else:
|
||||||
logging.error("FEHLER beim Schreiben der Ergebnisse ins Google Sheet.")
|
logging.error("FEHLER beim Schreiben der Ergebnisse ins Google Sheet.")
|
||||||
|
|
||||||
|
end_time = time.time()
|
||||||
|
logging.info(f"Gesamtdauer des Duplikats-Checks: {end_time - start_time:.2f} Sekunden.")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
Reference in New Issue
Block a user