duplicate_checker.py aktualisiert
This commit is contained in:
@@ -10,13 +10,15 @@ from google_sheet_handler import GoogleSheetHandler
|
||||
# --- Konfiguration ---
|
||||
CRM_SHEET_NAME = "CRM_Accounts"
|
||||
MATCHING_SHEET_NAME = "Matching_Accounts"
|
||||
SCORE_THRESHOLD = 0.8
|
||||
# Threshold gesenkt und konfigurierbar im Code
|
||||
SCORE_THRESHOLD = 0.75
|
||||
WEIGHTS = {
|
||||
'domain': 0.5,
|
||||
'name': 0.4,
|
||||
'city': 0.1,
|
||||
}
|
||||
LOG_DIR = '/log'
|
||||
# Relativer Log-Ordner
|
||||
LOG_DIR = 'log'
|
||||
LOG_FILENAME = 'duplicate_check.log'
|
||||
|
||||
# --- Logging Setup ---
|
||||
@@ -30,11 +32,13 @@ log_path = os.path.join(LOG_DIR, LOG_FILENAME)
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
formatter = logging.Formatter('%(asctime)s - %(levelname)-8s - %(name)s - %(message)s')
|
||||
|
||||
# Console handler
|
||||
console_handler = logging.StreamHandler()
|
||||
console_handler.setLevel(logging.INFO)
|
||||
console_handler.setFormatter(formatter)
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
# File handler
|
||||
try:
|
||||
file_handler = logging.FileHandler(log_path, mode='a', encoding='utf-8')
|
||||
@@ -55,6 +59,7 @@ def normalize_company_name(name: str) -> str:
|
||||
tokens = [t for t in s.split() if t and t not in stops]
|
||||
return ' '.join(tokens)
|
||||
|
||||
|
||||
def normalize_domain(url: str) -> str:
|
||||
s = str(url).casefold().strip()
|
||||
s = re.sub(r'^https?://', '', s)
|
||||
@@ -65,8 +70,8 @@ def normalize_domain(url: str) -> str:
|
||||
|
||||
|
||||
def main():
|
||||
logger.info("Starte den Duplikats-Check (v2.0 mit korrekten Missing-Werten)...")
|
||||
# Initialize GoogleSheetHandler
|
||||
logger.info("Starte den Duplikats-Check mit Fallback-Blocking...")
|
||||
# GoogleSheetHandler initialisieren
|
||||
try:
|
||||
sheet_handler = GoogleSheetHandler()
|
||||
logger.info("GoogleSheetHandler initialisiert")
|
||||
@@ -74,7 +79,7 @@ def main():
|
||||
logger.critical(f"FEHLER bei Initialisierung des GoogleSheetHandler: {e}")
|
||||
return
|
||||
|
||||
# Load data
|
||||
# Daten laden
|
||||
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:
|
||||
@@ -82,29 +87,35 @@ def main():
|
||||
return
|
||||
logger.info(f"{len(crm_df)} CRM-Zeilen, {len(match_df)} Matching-Zeilen geladen")
|
||||
|
||||
# Normalize fields
|
||||
# Normalisierung
|
||||
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())
|
||||
# Replace empty strings with NaN so they aren't considered matches
|
||||
df['name_token'] = df['norm_name'].apply(lambda x: x.split()[0] if x else np.nan)
|
||||
# Leere Werte als NaN markieren
|
||||
df['norm_domain'].replace('', np.nan, inplace=True)
|
||||
df['city'].replace('', np.nan, inplace=True)
|
||||
logger.debug(f"{label}-Daten normalisiert: Beispiel: {{'norm_name': df.iloc[0]['norm_name'], 'norm_domain': df.iloc[0]['norm_domain'], 'city': df.iloc[0]['city']}}")
|
||||
logger.debug(f"{label}-Normalisierung: norm_domain={df.iloc[0]['norm_domain']}, name_token={df.iloc[0]['name_token']}")
|
||||
|
||||
# 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")
|
||||
# Blocking: Domain und Name-Token
|
||||
index_dom = recordlinkage.Index()
|
||||
index_dom.block('norm_domain')
|
||||
pairs_dom = index_dom.index(crm_df, match_df)
|
||||
index_name = recordlinkage.Index()
|
||||
index_name.block('name_token')
|
||||
pairs_name = index_name.index(crm_df, match_df)
|
||||
# Union der Kandidatenpaare
|
||||
candidate_pairs = pairs_dom.append(pairs_name).drop_duplicates()
|
||||
logger.info(f"Blocking abgeschlossen: Dom-Paare={len(pairs_dom)}, Name-Paare={len(pairs_name)}, Gesamt={len(candidate_pairs)}")
|
||||
|
||||
# Vergleichsregeln definieren
|
||||
compare = recordlinkage.Compare()
|
||||
compare.exact('norm_domain', 'norm_domain', label='domain', missing_value=0)
|
||||
compare.string('norm_name', 'norm_name', method='jarowinkler', label='name_sim')
|
||||
compare.exact('city', 'city', label='city', missing_value=0)
|
||||
compare.string('norm_name', 'norm_name', method='jarowinkler', label='name_sim')
|
||||
compare.exact('city', 'city', label='city', missing_value=0)
|
||||
features = compare.compute(candidate_pairs, crm_df, match_df)
|
||||
logger.debug(f"Features berechnet: {features.head()}\n...")
|
||||
logger.debug(f"Features berechnet: {features.head()}...")
|
||||
|
||||
# Score berechnen
|
||||
features['score'] = (
|
||||
@@ -114,19 +125,17 @@ def main():
|
||||
)
|
||||
logger.info("Scores berechnet")
|
||||
|
||||
# Detailed per-match logging
|
||||
# Per-Match Logging und Auswahl
|
||||
results = []
|
||||
crm_idx_map = crm_df.reset_index()
|
||||
crm_map = crm_df.reset_index()
|
||||
for match_idx, group in features.reset_index().groupby('level_1'):
|
||||
logger.info(f"--- Prüfe Matching-Zeile {match_idx} ---")
|
||||
df_block = group.sort_values('score', ascending=False).copy()
|
||||
# Enrich with CRM info
|
||||
df_block['CRM Name'] = df_block['level_0'].map(crm_idx_map.set_index('index')['CRM Name'])
|
||||
df_block['CRM Website'] = df_block['level_0'].map(crm_idx_map.set_index('index')['CRM Website'])
|
||||
df_block['CRM Ort'] = df_block['level_0'].map(crm_idx_map.set_index('index')['CRM Ort'])
|
||||
logger.debug("Kandidaten (Index, Score, Domain, Name_sim, City, CRM Name):")
|
||||
for _, row in df_block.iterrows():
|
||||
logger.debug(f" [{int(row['level_0'])}] score={row['score']:.3f} dom={row['domain']} name={row['name_sim']:.3f} city={row['city']} => {row['CRM Name']}")
|
||||
# CRM-Daten für Log
|
||||
df_block['CRM Name'] = df_block['level_0'].map(crm_map.set_index('index')['CRM Name'])
|
||||
# Log der Top-Kandidaten
|
||||
for _, row in df_block.head(5).iterrows():
|
||||
logger.debug(f"Candidate [{int(row['level_0'])}]: score={row['score']:.3f}, name_sim={row['name_sim']:.3f}, dom={row['domain']}, city={row['city']} => {row['CRM Name']}")
|
||||
top = df_block.iloc[0]
|
||||
crm_idx = top['level_0'] if top['score'] >= SCORE_THRESHOLD else None
|
||||
if crm_idx is not None:
|
||||
@@ -135,13 +144,13 @@ def main():
|
||||
logger.info(f" --> Kein Match (höchster Score {top['score']:.2f})")
|
||||
results.append((crm_idx, match_idx, top['score']))
|
||||
|
||||
# Prepare output
|
||||
match_idx_map = match_df.reset_index()
|
||||
output = match_idx_map[['CRM Name','CRM Website','CRM Ort','CRM Land']].copy()
|
||||
# Ausgabe zusammenstellen
|
||||
match_map = match_df.reset_index()
|
||||
output = match_map[['CRM Name','CRM Website','CRM Ort','CRM Land']].copy()
|
||||
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:
|
||||
crm_row = crm_idx_map[crm_idx_map['index']==crm_idx].iloc[0]
|
||||
crm_row = crm_map[crm_map['index']==crm_idx].iloc[0]
|
||||
output.at[match_idx, 'Matched CRM Name'] = crm_row['CRM Name']
|
||||
output.at[match_idx, 'Matched CRM Website'] = crm_row['CRM Website']
|
||||
output.at[match_idx, 'Matched CRM Ort'] = crm_row['CRM Ort']
|
||||
|
||||
Reference in New Issue
Block a user