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