diff --git a/helpers.py b/helpers.py index 48cf90f5..dc0625d7 100644 --- a/helpers.py +++ b/helpers.py @@ -1034,15 +1034,25 @@ def evaluate_branche_chatgpt(crm_branche, beschreibung, wiki_branche, wiki_kateg logger.debug(f"ChatGPT-Branchenvorschlag '{suggested_branch}' ist gueltig ('{final_branch}').") result["consistency"] = "pending_comparison" else: - logger.debug(f"ChatGPT-Branchenvorschlag '{suggested_branch}' ist NICHT im Ziel-Schema. Starte Fallback...") + logger.debug(f"ChatGPT-Branchenvorschlag '{suggested_branch}' ist NICHT im Ziel-Schema. Starte intelligenten Fallback...") crm_short_branch = crm_branche.strip() if crm_branche and isinstance(crm_branche, str) else "k.A." crm_short_branch_lower = crm_short_branch.lower() - if crm_short_branch != "k.A." and crm_short_branch_lower in allowed_branches_lookup: - final_branch = allowed_branches_lookup[crm_short_branch_lower] - result["consistency"] = "fallback_crm_valid" - fallback_reason = f"Fallback: Ungueltiger ChatGPT-Vorschlag ('{suggested_branch}'). Gueltige CRM-Kurzform '{final_branch}' verwendet." - result["justification"] = f"{fallback_reason} (ChatGPT Begruendung war: {result.get('justification', 'Keine')})" - logger.info(f"Fallback auf gueltige CRM-Kurzform erfolgreich: '{final_branch}'") + + # NEU: Intelligenterer Fallback mit Substring-Suche + best_fallback_match = None + if crm_short_branch_lower != "k.a.": + # Suche nach der ersten erlaubten Branche, die die CRM-Branche als Teil enthält + for allowed_branch_key, allowed_branch_value in allowed_branches_lookup.items(): + if crm_short_branch_lower in allowed_branch_key: + best_fallback_match = allowed_branch_value + logger.info(f"Intelligenter Fallback gefunden: CRM-Branche '{crm_short_branch}' ist Teil von '{best_fallback_match}'.") + break # Nimm den ersten Treffer + + if best_fallback_match: + final_branch = best_fallback_match + result["consistency"] = "fallback_crm_substring" + fallback_reason = f"Fallback (Substring): Ungueltiger Vorschlag ('{suggested_branch}'). CRM-Branche '{crm_short_branch}' passt zu Schema-Eintrag '{final_branch}'." + result["justification"] = f"{fallback_reason} (KI Begruendung: {result.get('justification', 'k.A.')})" result["confidence"] = "N/A (Fallback)" else: final_branch = "FEHLER - UNGUELTIGE ZUWEISUNG"