129 lines
4.9 KiB
Python
129 lines
4.9 KiB
Python
import re
|
|
import logging
|
|
import pandas as pd
|
|
import recordlinkage
|
|
from rapidfuzz import fuzz
|
|
from google_sheet_handler import GoogleSheetHandler
|
|
|
|
# --- Konfiguration ---
|
|
CRM_SHEET_NAME = "CRM_Accounts"
|
|
MATCHING_SHEET_NAME = "Matching_Accounts"
|
|
SCORE_THRESHOLD = 0.8
|
|
WEIGHTS = {
|
|
'domain': 0.5,
|
|
'name': 0.4,
|
|
'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:
|
|
s = str(name).casefold()
|
|
for src, dst in [('ä','ae'), ('ö','oe'), ('ü','ue'), ('ß','ss')]:
|
|
s = s.replace(src, dst)
|
|
s = re.sub(r'[^a-z0-9\s]', ' ', s)
|
|
stops = ['gmbh','ag','kg','ug','ohg','holding','group','international']
|
|
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)
|
|
s = s.split('/')[0]
|
|
if s.startswith('www.'):
|
|
s = s[4:]
|
|
return s
|
|
|
|
|
|
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.")
|
|
return
|
|
|
|
# Normalisierung
|
|
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())
|
|
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
|
|
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()}" )
|
|
|
|
# Score berechnen
|
|
features['score'] = (
|
|
WEIGHTS['domain'] * features['domain'] +
|
|
WEIGHTS['name'] * features['name_sim'] +
|
|
WEIGHTS['city'] * features['city']
|
|
)
|
|
logger.info("Scores berechnet")
|
|
|
|
# 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})")
|
|
|
|
# Ausgabe DataFrame
|
|
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
|
|
|
|
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:
|
|
logger.info("Erfolgreich geschrieben ins Google Sheet")
|
|
else:
|
|
logger.error("Fehler beim Schreiben ins Google Sheet.")
|
|
|
|
if __name__ == '__main__':
|
|
main()
|