duplicate_checker.py aktualisiert
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import re
|
||||
import logging
|
||||
import pandas as pd
|
||||
import recordlinkage
|
||||
from rapidfuzz import fuzz
|
||||
@@ -14,14 +15,15 @@ WEIGHTS = {
|
||||
'city': 0.1,
|
||||
}
|
||||
|
||||
# --- Logging Setup ---
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG,
|
||||
format='%(asctime)s - %(levelname)-8s - %(message)s'
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# --- Hilfsfunktionen ---
|
||||
def normalize_company_name(name: str) -> str:
|
||||
"""
|
||||
Vereinfacht Firmennamen:
|
||||
- Unicode-safe Kleinschreibung
|
||||
- Umlaute in ae/oe/ue, ß in ss
|
||||
- Entfernen von Rechtsformen/Stop-Wörtern
|
||||
"""
|
||||
s = str(name).casefold()
|
||||
for src, dst in [('ä','ae'), ('ö','oe'), ('ü','ue'), ('ß','ss')]:
|
||||
s = s.replace(src, dst)
|
||||
@@ -32,7 +34,6 @@ def normalize_company_name(name: str) -> str:
|
||||
|
||||
|
||||
def normalize_domain(url: str) -> str:
|
||||
"""Extrahiere Root-Domain, entferne Protokoll und www-Präfix"""
|
||||
s = str(url).casefold().strip()
|
||||
s = re.sub(r'^https?://', '', s)
|
||||
s = s.split('/')[0]
|
||||
@@ -42,77 +43,86 @@ def normalize_domain(url: str) -> str:
|
||||
|
||||
|
||||
def main():
|
||||
# Google Sheets laden
|
||||
logger.info("Starte Duplikat-Check mit ausführlichem Logging...")
|
||||
sheet_handler = GoogleSheetHandler()
|
||||
crm_df = sheet_handler.get_sheet_as_dataframe(CRM_SHEET_NAME)
|
||||
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:
|
||||
print("Fehler: Leere Daten in einem der Tabs. Abbruch.")
|
||||
logger.error("Leere Daten in CRM oder Matching Tab. Abbruch.")
|
||||
return
|
||||
|
||||
# Normalisierung
|
||||
for df in (crm_df, match_df):
|
||||
df['norm_name'] = df['CRM Name'].fillna('').apply(normalize_company_name)
|
||||
for df, name 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())
|
||||
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()}")
|
||||
|
||||
# Blocking per Domain
|
||||
indexer = recordlinkage.Index()
|
||||
indexer.block('norm_domain')
|
||||
candidate_pairs = indexer.index(crm_df, match_df)
|
||||
logger.info(f"Blocking abgeschlossen: {len(candidate_pairs)} Kandidatenpaare gefunden")
|
||||
|
||||
# Vergleichsregeln definieren
|
||||
# Vergleichsregeln
|
||||
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()}" )
|
||||
|
||||
# Gewichte und Score
|
||||
# Score berechnen
|
||||
features['score'] = (
|
||||
WEIGHTS['domain'] * features['domain'] +
|
||||
WEIGHTS['name'] * features['name_sim'] +
|
||||
WEIGHTS['city'] * features['city']
|
||||
)
|
||||
logger.info("Scores berechnet")
|
||||
|
||||
# Bestes Match pro neuer Zeile
|
||||
matches = features.reset_index()
|
||||
best = matches.sort_values(['level_1','score'], ascending=[True, False]) \
|
||||
.drop_duplicates('level_1')
|
||||
best = best[best['score'] >= SCORE_THRESHOLD] \
|
||||
.rename(columns={'level_0':'crm_idx','level_1':'match_idx'})
|
||||
# Best Match pro neuer Zeile mit Logging der Kandidaten
|
||||
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}")
|
||||
else:
|
||||
results.append((None, match_idx, top['score']))
|
||||
logger.info(f"Zeile {match_idx}: Kein ausreichender Score (top {top['score']:.2f})")
|
||||
|
||||
# Merges
|
||||
crm_df = crm_df.reset_index()
|
||||
# Ausgabe DataFrame
|
||||
crm_df = crm_df.reset_index()
|
||||
match_df = match_df.reset_index()
|
||||
merged = (best
|
||||
.merge(crm_df, left_on='crm_idx', right_on='index')
|
||||
.merge(match_df, left_on='match_idx', right_on='index', suffixes=('_CRM','_NEW'))
|
||||
)
|
||||
|
||||
# Ausgabe aufbauen
|
||||
output = match_df[['CRM Name','CRM Website','CRM Ort','CRM Land']].copy()
|
||||
output['Matched CRM Name'] = ''
|
||||
output['Matched CRM Name'] = ''
|
||||
output['Matched CRM Website'] = ''
|
||||
output['Matched CRM Ort'] = ''
|
||||
output['Matched CRM Land'] = ''
|
||||
output['Score'] = 0.0
|
||||
output['Matched CRM Ort'] = ''
|
||||
output['Matched CRM Land'] = ''
|
||||
output['Score'] = 0.0
|
||||
|
||||
for _, row in merged.iterrows():
|
||||
i = int(row['match_idx'])
|
||||
output.at[i, 'Matched CRM Name'] = row['CRM Name_CRM']
|
||||
output.at[i, 'Matched CRM Website'] = row['CRM Website_CRM']
|
||||
output.at[i, 'Matched CRM Ort'] = row['CRM Ort_CRM']
|
||||
output.at[i, 'Matched CRM Land'] = row['CRM Land_CRM']
|
||||
output.at[i, 'Score'] = row['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]
|
||||
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']
|
||||
output.at[match_idx, 'Matched CRM Land'] = row_crm['CRM Land']
|
||||
output.at[match_idx, 'Score'] = round(score, 3)
|
||||
|
||||
# Zurückschreiben ins Google Sheet
|
||||
data = [output.columns.tolist()] + output.values.tolist()
|
||||
success = sheet_handler.clear_and_write_data(MATCHING_SHEET_NAME, data)
|
||||
if success:
|
||||
print(f"Erfolgreich: {len(best)} Matches mit Score ≥ {SCORE_THRESHOLD}")
|
||||
logger.info("Erfolgreich geschrieben ins Google Sheet")
|
||||
else:
|
||||
print("Fehler beim Schreiben ins Google Sheet.")
|
||||
logger.error("Fehler beim Schreiben ins Google Sheet.")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user