duplicate_checker.py aktualisiert
This commit is contained in:
@@ -16,10 +16,8 @@ WEIGHTS = {
|
||||
}
|
||||
|
||||
# --- Logging Setup ---
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG,
|
||||
format='%(asctime)s - %(levelname)-8s - %(message)s'
|
||||
)
|
||||
LOG_FORMAT = '%(asctime)s - %(levelname)-8s - %(name)s - %(message)s'
|
||||
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# --- Hilfsfunktionen ---
|
||||
@@ -43,20 +41,37 @@ def normalize_domain(url: str) -> str:
|
||||
|
||||
|
||||
def main():
|
||||
logger.info("Starte Duplikat-Check mit ausführlichem Logging...")
|
||||
sheet_handler = GoogleSheetHandler()
|
||||
crm_df = sheet_handler.get_sheet_as_dataframe(CRM_SHEET_NAME)
|
||||
match_df = sheet_handler.get_sheet_as_dataframe(MATCHING_SHEET_NAME)
|
||||
if crm_df is None or crm_df.empty or match_df is None or match_df.empty:
|
||||
logger.error("Leere Daten in CRM oder Matching Tab. Abbruch.")
|
||||
logger.info("Starte den Duplikats-Check (v2.0 mit Blocking und Maximum Logging)...")
|
||||
# GoogleSheetHandler initialisieren
|
||||
try:
|
||||
sheet_handler = GoogleSheetHandler()
|
||||
logger.info("GoogleSheetHandler initialisiert")
|
||||
except Exception as e:
|
||||
logger.critical(f"FEHLER bei Initialisierung des GoogleSheetHandler: {e}")
|
||||
return
|
||||
|
||||
# CRM-Daten laden
|
||||
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:
|
||||
logger.critical(f"Konnte keine Daten aus '{CRM_SHEET_NAME}' laden. Abbruch.")
|
||||
return
|
||||
logger.info(f"{len(crm_df)} Zeilen aus '{CRM_SHEET_NAME}' geladen")
|
||||
|
||||
# Matching-Daten laden
|
||||
logger.info(f"Lade zu prüfende Daten aus '{MATCHING_SHEET_NAME}'...")
|
||||
match_df = sheet_handler.get_sheet_as_dataframe(MATCHING_SHEET_NAME)
|
||||
if match_df is None or match_df.empty:
|
||||
logger.critical(f"Konnte keine Daten aus '{MATCHING_SHEET_NAME}' laden. Abbruch.")
|
||||
return
|
||||
logger.info(f"{len(match_df)} Zeilen aus '{MATCHING_SHEET_NAME}' geladen")
|
||||
|
||||
# Normalisierung
|
||||
for df, name in [(crm_df, 'CRM'), (match_df, 'Matching')]:
|
||||
for df, label in [(crm_df, 'CRM'), (match_df, 'Matching')]:
|
||||
df['norm_name'] = df['CRM Name'].fillna('').apply(normalize_company_name)
|
||||
df['norm_domain'] = df['CRM Website'].fillna('').apply(normalize_domain)
|
||||
df['city'] = df['CRM Ort'].fillna('').apply(lambda x: str(x).casefold().strip())
|
||||
logger.debug(f"{name}-Daten nach Normalisierung. Erste Zeile: {df.iloc[0].to_dict()}")
|
||||
logger.debug(f"{label}-Daten nach Normalisierung. Erste Zeile: {df.iloc[0].to_dict()}")
|
||||
|
||||
# Blocking per Domain
|
||||
indexer = recordlinkage.Index()
|
||||
@@ -64,13 +79,13 @@ def main():
|
||||
candidate_pairs = indexer.index(crm_df, match_df)
|
||||
logger.info(f"Blocking abgeschlossen: {len(candidate_pairs)} Kandidatenpaare gefunden")
|
||||
|
||||
# Vergleichsregeln
|
||||
# Vergleichsregeln definieren
|
||||
compare = recordlinkage.Compare()
|
||||
compare.exact('norm_domain', 'norm_domain', label='domain')
|
||||
compare.string('norm_name', 'norm_name', method='jarowinkler', label='name_sim')
|
||||
compare.exact('city', 'city', label='city')
|
||||
features = compare.compute(candidate_pairs, crm_df, match_df)
|
||||
logger.debug(f"Feature-DataFrame Vorschau:\n{features.head()}" )
|
||||
logger.debug(f"Feature-DataFrame Vorschau:\n{features.head()}")
|
||||
|
||||
# Score berechnen
|
||||
features['score'] = (
|
||||
@@ -80,36 +95,29 @@ def main():
|
||||
)
|
||||
logger.info("Scores berechnet")
|
||||
|
||||
# Best Match pro neuer Zeile mit Logging der Kandidaten
|
||||
# Best Match pro neuer Zeile mit detailliertem Logging
|
||||
results = []
|
||||
crm_idx_col = []
|
||||
match_idx_col = []
|
||||
for match_idx, group in features.reset_index().groupby('level_1'):
|
||||
crm_idx_col.append(match_idx)
|
||||
# sortiere Kandidaten nach Score
|
||||
sorted_group = group.sort_values('score', ascending=False)
|
||||
logger.debug(f"Matching-Index {match_idx}: untersuchte Kandidaten:\n{sorted_group[['level_0','score','domain','name_sim','city']]}" )
|
||||
top = sorted_group.iloc[0]
|
||||
if top['score'] >= SCORE_THRESHOLD:
|
||||
results.append((top['level_0'], match_idx, top['score']))
|
||||
logger.info(f"Zeile {match_idx}: Match mit CRM-Index {top['level_0']} Score {top['score']:.2f}")
|
||||
logger.info(f"--- Prüfe: Zeile {match_idx} ---")
|
||||
df_block = group.sort_values('score', ascending=False)
|
||||
logger.debug(f" Kandidaten für Zeile {match_idx}:\n{df_block[['level_0','score','domain','name_sim','city']].to_string(index=False)}")
|
||||
top = df_block.iloc[0]
|
||||
crm_idx = top['level_0'] if top['score'] >= SCORE_THRESHOLD else None
|
||||
if crm_idx is not None:
|
||||
logger.info(f" --> Match: CRM-Index {crm_idx} mit Score {top['score']:.2f}")
|
||||
else:
|
||||
results.append((None, match_idx, top['score']))
|
||||
logger.info(f"Zeile {match_idx}: Kein ausreichender Score (top {top['score']:.2f})")
|
||||
logger.info(f" --> Kein Match (höchster Score {top['score']:.2f})")
|
||||
results.append((crm_idx, match_idx, top['score']))
|
||||
|
||||
# Ausgabe DataFrame
|
||||
# Ausgabe DataFrame zusammenstellen
|
||||
crm_df = crm_df.reset_index()
|
||||
match_df = match_df.reset_index()
|
||||
output = match_df[['CRM Name','CRM Website','CRM Ort','CRM Land']].copy()
|
||||
output['Matched CRM Name'] = ''
|
||||
output['Matched CRM Website'] = ''
|
||||
output['Matched CRM Ort'] = ''
|
||||
output['Matched CRM Land'] = ''
|
||||
output['Score'] = 0.0
|
||||
output[['Matched CRM Name','Matched CRM Website','Matched CRM Ort','Matched CRM Land','Score']] = ''
|
||||
|
||||
for crm_idx, match_idx, score in results:
|
||||
if crm_idx is not None:
|
||||
row_crm = crm_df.loc[crm_df['index'] == crm_idx].iloc[0]
|
||||
row_crm = crm_df.loc[crm_df['index']==crm_idx].iloc[0]
|
||||
output.at[match_idx, 'Matched CRM Name'] = row_crm['CRM Name']
|
||||
output.at[match_idx, 'Matched CRM Website'] = row_crm['CRM Website']
|
||||
output.at[match_idx, 'Matched CRM Ort'] = row_crm['CRM Ort']
|
||||
@@ -120,7 +128,7 @@ def main():
|
||||
data = [output.columns.tolist()] + output.values.tolist()
|
||||
success = sheet_handler.clear_and_write_data(MATCHING_SHEET_NAME, data)
|
||||
if success:
|
||||
logger.info("Erfolgreich geschrieben ins Google Sheet")
|
||||
logger.info(f"Erfolgreich geschrieben: {len([r for r in results if r[0] is not None])} Matches")
|
||||
else:
|
||||
logger.error("Fehler beim Schreiben ins Google Sheet.")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user