duplicate_checker.py aktualisiert
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
# duplicate_checker.py (v2.0 - mit Blocking-Strategie)
|
||||
# duplicate_checker.py (v2.1 - mit Match-Basis-Anzeige)
|
||||
|
||||
import logging
|
||||
import pandas as pd
|
||||
@@ -10,26 +10,35 @@ from google_sheet_handler import GoogleSheetHandler
|
||||
# --- Konfiguration ---
|
||||
CRM_SHEET_NAME = "CRM_Accounts"
|
||||
MATCHING_SHEET_NAME = "Matching_Accounts"
|
||||
SCORE_THRESHOLD = 80
|
||||
SCORE_THRESHOLD = 80 # Wird jetzt nur noch zur Hervorhebung genutzt, angezeigt werden alle
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
|
||||
def calculate_similarity(record1, record2):
|
||||
"""Berechnet einen gewichteten Ähnlichkeits-Score zwischen zwei Datensätzen."""
|
||||
total_score = 0
|
||||
if record1['normalized_domain'] and record1['normalized_domain'] == record2['normalized_domain']:
|
||||
total_score += 100
|
||||
def calculate_similarity_details(record1, record2):
|
||||
"""
|
||||
Berechnet einen gewichteten Ähnlichkeits-Score und gibt die Details zurück.
|
||||
"""
|
||||
scores = {'name': 0, 'location': 0, 'domain': 0}
|
||||
|
||||
# 1. Website-Domain (stärkstes Signal)
|
||||
if record1['normalized_domain'] and record1['normalized_domain'] != 'k.a.' and record1['normalized_domain'] == record2['normalized_domain']:
|
||||
scores['domain'] = 100
|
||||
|
||||
# 2. Firmenname (Fuzzy-Signal)
|
||||
if record1['normalized_name'] and record2['normalized_name']:
|
||||
name_similarity = fuzz.token_set_ratio(record1['normalized_name'], record2['normalized_name'])
|
||||
total_score += name_similarity * 0.7
|
||||
scores['name'] = round(fuzz.token_set_ratio(record1['normalized_name'], record2['normalized_name']) * 0.7)
|
||||
|
||||
# 3. Standort (Bestätigungs-Signal)
|
||||
if record1['CRM Ort'] and record1['CRM Ort'] == record2['CRM Ort']:
|
||||
if record1['CRM Land'] and record1['CRM Land'] == record2['CRM Land']:
|
||||
total_score += 20
|
||||
return round(total_score)
|
||||
scores['location'] = 20
|
||||
|
||||
total_score = sum(scores.values())
|
||||
return {'total': total_score, 'details': scores}
|
||||
|
||||
def main():
|
||||
"""Hauptfunktion zum Laden, Vergleichen und Schreiben der Daten."""
|
||||
logging.info("Starte den Duplikats-Check (v2.0 mit Blocking)...")
|
||||
logging.info("Starte den Duplikats-Check (v2.1 mit Match-Basis)...")
|
||||
|
||||
try:
|
||||
sheet_handler = GoogleSheetHandler()
|
||||
@@ -39,15 +48,11 @@ def main():
|
||||
|
||||
logging.info(f"Lade Master-Daten aus '{CRM_SHEET_NAME}'...")
|
||||
crm_df = sheet_handler.get_sheet_as_dataframe(CRM_SHEET_NAME)
|
||||
if crm_df is None or crm_df.empty:
|
||||
logging.critical(f"Konnte keine Daten aus '{CRM_SHEET_NAME}' laden. Breche ab.")
|
||||
return
|
||||
if crm_df is None or crm_df.empty: return
|
||||
|
||||
logging.info(f"Lade zu prüfende Daten aus '{MATCHING_SHEET_NAME}'...")
|
||||
matching_df = sheet_handler.get_sheet_as_dataframe(MATCHING_SHEET_NAME)
|
||||
if matching_df is None or matching_df.empty:
|
||||
logging.critical(f"Konnte keine Daten aus '{MATCHING_SHEET_NAME}' laden. Breche ab.")
|
||||
return
|
||||
if matching_df is None or matching_df.empty: return
|
||||
|
||||
logging.info("Normalisiere Daten für den Vergleich...")
|
||||
for df in [crm_df, matching_df]:
|
||||
@@ -55,58 +60,49 @@ def main():
|
||||
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 Land'] = df['CRM Land'].astype(str).str.lower().str.strip()
|
||||
# Blocking Key: Das erste Wort des normalisierten Namens
|
||||
df['block_key'] = df['normalized_name'].apply(lambda x: x.split()[0] if x else None)
|
||||
|
||||
# --- NEUE, SCHNELLE BLOCKING-STRATEGIE ---
|
||||
logging.info("Erstelle Index für CRM-Daten zur Beschleunigung...")
|
||||
crm_index = {}
|
||||
for index, row in crm_df.iterrows():
|
||||
key = row['block_key']
|
||||
if key:
|
||||
if key not in crm_index:
|
||||
crm_index[key] = []
|
||||
crm_index[key].append(row)
|
||||
crm_index = crm_df.groupby('block_key').apply(lambda x: x.to_dict('records')).to_dict()
|
||||
|
||||
logging.info("Starte Matching-Prozess...")
|
||||
results = []
|
||||
total_matches = len(matching_df)
|
||||
|
||||
for index, match_row in matching_df.iterrows():
|
||||
best_score = 0
|
||||
best_score_info = {'total': 0, 'details': {'name': 0, 'location': 0, 'domain': 0}}
|
||||
best_match_name = ""
|
||||
|
||||
logging.info(f"Prüfe {index + 1}/{total_matches}: {match_row['CRM Name']}...")
|
||||
logging.info(f"Prüfe {index + 1}/{len(matching_df)}: {match_row['CRM Name']}...")
|
||||
|
||||
# Finde den Block von Kandidaten
|
||||
block_key = match_row['block_key']
|
||||
candidates = crm_index.get(block_key, [])
|
||||
|
||||
# Führe den teuren Vergleich nur für die Kandidaten in diesem Block durch
|
||||
for crm_row in candidates:
|
||||
score = calculate_similarity(match_row, crm_row)
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
score_info = calculate_similarity_details(match_row, crm_row)
|
||||
if score_info['total'] > best_score_info['total']:
|
||||
best_score_info = score_info
|
||||
best_match_name = crm_row['CRM Name']
|
||||
|
||||
if best_score >= SCORE_THRESHOLD:
|
||||
results.append({'Potenzieller Treffer im CRM': best_match_name, 'Ähnlichkeits-Score': best_score})
|
||||
else:
|
||||
# Wenn nichts im Block gefunden wurde, trotzdem den besten Treffer (kann 0 sein) anzeigen
|
||||
results.append({'Potenzieller Treffer im CRM': '' if not best_match_name else best_match_name, 'Ähnlichkeits-Score': best_score})
|
||||
results.append({
|
||||
'Potenzieller Treffer im CRM': best_match_name if best_score_info['total'] >= SCORE_THRESHOLD else "",
|
||||
'Score (Gesamt)': best_score_info['total'],
|
||||
'Score (Name)': best_score_info['details']['name'],
|
||||
'Bonus (Standort)': best_score_info['details']['location'],
|
||||
'Bonus (Domain)': best_score_info['details']['domain']
|
||||
})
|
||||
|
||||
logging.info("Matching abgeschlossen. Schreibe Ergebnisse zurück ins Sheet...")
|
||||
result_df = pd.DataFrame(results)
|
||||
|
||||
# Die ursprünglichen Spalten aus matching_df für die Ausgabe nehmen
|
||||
output_df = matching_df[['CRM Name', 'CRM Website', 'CRM Ort', 'CRM Land']].copy()
|
||||
output_df = pd.concat([output_df.reset_index(drop=True), result_df], axis=1)
|
||||
# Originale Spalten aus matching_df für die Ausgabe nehmen
|
||||
original_cols = [col for col in ['CRM Name', 'CRM Website', 'CRM Ort', 'CRM Land'] if col in matching_df.columns]
|
||||
output_df = pd.concat([matching_df[original_cols].reset_index(drop=True), result_df], axis=1)
|
||||
|
||||
data_to_write = [output_df.columns.values.tolist()] + output_df.values.tolist()
|
||||
|
||||
success = sheet_handler.clear_and_write_data(MATCHING_SHEET_NAME, data_to_write)
|
||||
if success:
|
||||
logging.info(f"Ergebnisse erfolgreich in das Tabellenblatt '{MATCHING_SHEET_NAME}' geschrieben.")
|
||||
logging.info(f"Ergebnisse erfolgreich in '{MATCHING_SHEET_NAME}' geschrieben.")
|
||||
else:
|
||||
logging.error("FEHLER beim Schreiben der Ergebnisse ins Google Sheet.")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user