173 lines
6.9 KiB
Python
173 lines
6.9 KiB
Python
# duplicate_checker.py (v2.0 + Transparenz)
|
|
|
|
import logging
|
|
import pandas as pd
|
|
from thefuzz import fuzz
|
|
from config import Config
|
|
from helpers import normalize_company_name, simple_normalize_url, create_log_filename
|
|
from google_sheet_handler import GoogleSheetHandler
|
|
import time
|
|
|
|
# --- Konfiguration ---
|
|
CRM_SHEET_NAME = "CRM_Accounts"
|
|
MATCHING_SHEET_NAME = "Matching_Accounts"
|
|
SCORE_THRESHOLD = 80
|
|
|
|
# --- VOLLSTÄNDIGES LOGGING SETUP ---
|
|
LOG_LEVEL = logging.DEBUG if Config.DEBUG else logging.INFO
|
|
LOG_FORMAT = '%(asctime)s - %(levelname)-8s - %(name)s - %(message)s'
|
|
|
|
root_logger = logging.getLogger()
|
|
root_logger.setLevel(LOG_LEVEL)
|
|
|
|
# Handler nur hinzufügen, wenn noch keine konfiguriert sind, um Dopplung zu vermeiden
|
|
if not root_logger.handlers:
|
|
stream_handler = logging.StreamHandler()
|
|
stream_handler.setFormatter(logging.Formatter(LOG_FORMAT))
|
|
root_logger.addHandler(stream_handler)
|
|
|
|
log_file_path = create_log_filename("duplicate_check_v2_final")
|
|
if log_file_path:
|
|
file_handler = logging.FileHandler(log_file_path, mode='a', encoding='utf-8')
|
|
file_handler.setFormatter(logging.Formatter(LOG_FORMAT))
|
|
root_logger.addHandler(file_handler)
|
|
else:
|
|
log_file_path = next((h.baseFilename for h in root_logger.handlers if isinstance(h, logging.FileHandler)), None)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def calculate_similarity_with_details(record1, record2):
|
|
"""
|
|
Berechnet einen gewichteten Ähnlichkeits-Score und gibt den Score und den Grund zurück.
|
|
Basierend auf der v2.0 Scoring-Logik.
|
|
"""
|
|
scores = {'name': 0, 'location': 0, 'domain': 0}
|
|
|
|
domain1 = record1.get('normalized_domain')
|
|
domain2 = record2.get('normalized_domain')
|
|
if domain1 and domain1 != 'k.a.' and domain1 == domain2:
|
|
scores['domain'] = 100
|
|
|
|
name1 = record1.get('normalized_name')
|
|
name2 = record2.get('normalized_name')
|
|
if name1 and name2:
|
|
name_similarity = fuzz.token_set_ratio(name1, name2)
|
|
scores['name'] = round(name_similarity * 0.7)
|
|
|
|
ort1 = record1.get('CRM Ort')
|
|
ort2 = record2.get('CRM Ort')
|
|
land1 = record1.get('CRM Land')
|
|
land2 = record2.get('CRM Land')
|
|
if ort1 and ort1 == ort2 and land1 and land1 == land2:
|
|
scores['location'] = 20
|
|
|
|
total_score = sum(scores.values())
|
|
|
|
reasons = []
|
|
if scores['domain'] > 0: reasons.append(f"Domain({scores['domain']})")
|
|
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"
|
|
|
|
return round(total_score), reason_text
|
|
|
|
def main():
|
|
"""Hauptfunktion zum Laden, Vergleichen und Schreiben der Daten."""
|
|
start_time = time.time()
|
|
logger.info("Starte den Duplikats-Check (v2.0 mit Blocking und Maximum Logging)...")
|
|
logger.info(f"Logdatei: {log_file_path}")
|
|
|
|
try:
|
|
sheet_handler = GoogleSheetHandler()
|
|
except Exception as e:
|
|
logger.critical(f"FEHLER bei Initialisierung des GoogleSheetHandler: {e}")
|
|
return
|
|
|
|
logger.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: return
|
|
|
|
logger.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: return
|
|
original_matching_df = matching_df.copy()
|
|
|
|
logger.info("Normalisiere Daten für den Vergleich...")
|
|
for df in [crm_df, matching_df]:
|
|
df['normalized_name'] = df['CRM Name'].astype(str).apply(normalize_company_name)
|
|
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()
|
|
df['block_key'] = df['normalized_name'].apply(lambda x: x.split()[0] if x and x.split() else None)
|
|
|
|
logger.info("Erstelle Index für CRM-Daten zur Beschleunigung...")
|
|
crm_index = {}
|
|
crm_records = crm_df.to_dict('records')
|
|
for record in crm_records:
|
|
key = record['block_key']
|
|
if key:
|
|
if key not in crm_index:
|
|
crm_index[key] = []
|
|
crm_index[key].append(record)
|
|
|
|
logger.info("Starte Matching-Prozess...")
|
|
results = []
|
|
|
|
for match_record in matching_df.to_dict('records'):
|
|
best_score = -1
|
|
best_match_name = ""
|
|
best_reason = ""
|
|
|
|
logger.info(f"--- Prüfe: '{match_record.get('CRM Name', 'N/A')}' ---")
|
|
logger.debug(f" [Normalisiert: '{match_record.get('normalized_name')}', Domain: '{match_record.get('normalized_domain')}', Key: '{match_record.get('block_key')}']")
|
|
|
|
block_key = match_record.get('block_key')
|
|
candidates = crm_index.get(block_key, [])
|
|
|
|
if not candidates:
|
|
logger.debug(" -> Keine Kandidaten im Index gefunden. Überspringe Vergleich.")
|
|
results.append({
|
|
'Potenzieller Treffer im CRM': "", 'Ähnlichkeits-Score': 0, 'Matching-Grund': "Keine Kandidaten"
|
|
})
|
|
continue
|
|
|
|
logger.debug(f" -> Vergleiche mit {len(candidates)} Kandidaten aus Block '{block_key}'.")
|
|
|
|
for crm_row in candidates:
|
|
score, reason = calculate_similarity_with_details(match_record, crm_row)
|
|
|
|
if score > 0:
|
|
logger.debug(f" - Kandidat: '{crm_row.get('CRM Name', 'N/A')}' -> Score: {score} (Grund: {reason})")
|
|
|
|
if score > best_score:
|
|
best_score = score
|
|
best_match_name = crm_row.get('CRM Name', 'N/A')
|
|
best_reason = reason
|
|
|
|
logger.info(f" --> Bester Treffer: '{best_match_name}' mit Score {best_score} (Grund: {best_reason})")
|
|
|
|
results.append({
|
|
'Potenzieller Treffer im CRM': best_match_name if best_score >= SCORE_THRESHOLD else "",
|
|
'Ähnlichkeits-Score': best_score,
|
|
'Matching-Grund': best_reason
|
|
})
|
|
|
|
logging.info("Matching abgeschlossen. Schreibe Ergebnisse zurück ins Sheet...")
|
|
result_df = pd.DataFrame(results)
|
|
|
|
output_df = pd.concat([original_matching_df.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:
|
|
logger.info(f"Ergebnisse erfolgreich in das Tabellenblatt '{MATCHING_SHEET_NAME}' geschrieben.")
|
|
else:
|
|
logger.error("FEHLER beim Schreiben der Ergebnisse ins Google Sheet.")
|
|
|
|
end_time = time.time()
|
|
logger.info(f"Gesamtdauer des Duplikats-Checks: {end_time - start_time:.2f} Sekunden.")
|
|
logger.info(f"===== Skript beendet =====")
|
|
|
|
if __name__ == "__main__":
|
|
main() |