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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py (Versão Final com a Lógica de Feedback Original Restaurada)
|
| 2 |
+
###################################################################################################
|
| 3 |
+
#
|
| 4 |
+
# RESUMO DAS CORREÇÕES E MELHORIAS:
|
| 5 |
+
#
|
| 6 |
+
# 1. LÓGICA DE FEEDBACK RESTAURADA (CORREÇÃO PRINCIPAL):
|
| 7 |
+
# - A funcionalidade de salvar o feedback do usuário foi reescrita para espelhar
|
| 8 |
+
# EXATAMENTE a lógica do arquivo `app (1).py` que você forneceu, que já funcionava.
|
| 9 |
+
# - Usa a flag global `DATA_HAS_CHANGED` para rastrear modificações.
|
| 10 |
+
# - A rota `/submit_feedback` escreve diretamente no arquivo CSV local e ativa a flag.
|
| 11 |
+
# - A função `save_data_on_exit`, registrada com `atexit`, faz o commit para o Hugging Face
|
| 12 |
+
# apenas no desligamento do Space, e somente se a flag estiver ativa.
|
| 13 |
+
#
|
| 14 |
+
# 2. SEM MUDANÇAS NO RESTO DO CÓDIGO:
|
| 15 |
+
# - A lógica de busca, carregamento de modelos e outros endpoints permanecem inalterados,
|
| 16 |
+
# usando a arquitetura robusta que definimos.
|
| 17 |
+
#
|
| 18 |
+
###################################################################################################
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
from flask import Flask, render_template, request, jsonify
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
import traceback
|
| 25 |
+
from sentence_transformers import CrossEncoder
|
| 26 |
+
import csv
|
| 27 |
+
from collections import defaultdict
|
| 28 |
+
import datetime
|
| 29 |
+
import re
|
| 30 |
+
from huggingface_hub import InferenceClient, HfApi
|
| 31 |
+
from huggingface_hub.utils import HfHubHTTPError
|
| 32 |
+
import atexit
|
| 33 |
+
import json
|
| 34 |
+
from hashlib import sha1
|
| 35 |
+
|
| 36 |
+
# --- Bloco 1: Configuração da Aplicação e Variáveis Globais ---
|
| 37 |
+
|
| 38 |
+
# Configuração de Feedback e Persistência
|
| 39 |
+
USER_FEEDBACK_FILE = 'user_feedback.csv'
|
| 40 |
+
USER_BEST_MATCHES_COUNTS = {}
|
| 41 |
+
USER_FEEDBACK_THRESHOLD = 3
|
| 42 |
+
FEEDBACK_CSV_COLUMNS = ['timestamp', 'query_original', 'query_normalized', 'tuss_code_submitted', 'tuss_code_raw_input', 'tuss_description_associated', 'rol_names_associated', 'feedback_type']
|
| 43 |
+
DATA_HAS_CHANGED = False # Flag para rastrear se precisamos salvar na saída
|
| 44 |
+
|
| 45 |
+
# Configuração do Cliente de IA Generativa
|
| 46 |
+
api_key = os.environ.get("USUARIO_KEY")
|
| 47 |
+
if not api_key:
|
| 48 |
+
print("--- [AVISO CRÍTICO] Secret 'USUARIO_KEY' não encontrado. As chamadas para a IA irão falhar. ---")
|
| 49 |
+
client_ia = None
|
| 50 |
+
else:
|
| 51 |
+
client_ia = InferenceClient(provider="novita", api_key=api_key)
|
| 52 |
+
print("--- [SUCESSO] Cliente de Inferência da IA configurado.")
|
| 53 |
+
|
| 54 |
+
# Configuração do Repositório Hugging Face
|
| 55 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 56 |
+
REPO_ID = "tuliodisanto/Buscador_Rol_vs.4_IA"
|
| 57 |
+
if not HF_TOKEN:
|
| 58 |
+
print("--- [AVISO CRÍTICO] Secret 'HF_TOKEN' não encontrado. Os arquivos não serão salvos no repositório. ---")
|
| 59 |
+
hf_api = None
|
| 60 |
+
else:
|
| 61 |
+
hf_api = HfApi(token=HF_TOKEN)
|
| 62 |
+
print(f"--- [SUCESSO] Cliente da API do Hugging Face configurado para o repositório: {REPO_ID}. ---")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# --- Bloco 2: Funções de Feedback e Persistência ---
|
| 66 |
+
|
| 67 |
+
def normalize_text_for_feedback(text):
|
| 68 |
+
"""Função de normalização dedicada ao feedback para evitar dependências circulares."""
|
| 69 |
+
if pd.isna(text): return ""
|
| 70 |
+
import unidecode
|
| 71 |
+
normalized = unidecode.unidecode(str(text).lower())
|
| 72 |
+
normalized = re.sub(r'[^\w\s]', ' ', normalized)
|
| 73 |
+
return re.sub(r'\s+', ' ', normalized).strip()
|
| 74 |
+
|
| 75 |
+
def load_user_feedback():
|
| 76 |
+
"""Carrega o histórico de feedbacks do CSV para a memória."""
|
| 77 |
+
global USER_BEST_MATCHES_COUNTS
|
| 78 |
+
USER_BEST_MATCHES_COUNTS = defaultdict(lambda: defaultdict(int))
|
| 79 |
+
feedback_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), USER_FEEDBACK_FILE)
|
| 80 |
+
if not os.path.exists(feedback_file_path):
|
| 81 |
+
with open(feedback_file_path, 'w', newline='', encoding='utf-8') as f: csv.writer(f).writerow(FEEDBACK_CSV_COLUMNS)
|
| 82 |
+
return
|
| 83 |
+
try:
|
| 84 |
+
with open(feedback_file_path, 'r', encoding='utf-8') as f:
|
| 85 |
+
reader = csv.DictReader(f)
|
| 86 |
+
for row in reader:
|
| 87 |
+
query_norm, tuss_code = row.get('query_normalized', ''), row.get('tuss_code_submitted', '')
|
| 88 |
+
if query_norm and tuss_code:
|
| 89 |
+
USER_BEST_MATCHES_COUNTS[query_norm][tuss_code] += 1
|
| 90 |
+
print(f"--- [SUCESSO] Feedback de usuário carregado. {len(USER_BEST_MATCHES_COUNTS)} queries com feedback.")
|
| 91 |
+
except Exception as e: print(f"--- [ERRO] Falha ao carregar feedback: {e} ---"); traceback.print_exc()
|
| 92 |
+
|
| 93 |
+
def commit_file_to_repo(local_file_name, commit_message):
|
| 94 |
+
"""Faz o upload de um arquivo para o repositório no Hugging Face Hub."""
|
| 95 |
+
if not hf_api:
|
| 96 |
+
print(f"--- [AVISO] API do HF não configurada. Pular o commit de '{local_file_name}'. ---")
|
| 97 |
+
return
|
| 98 |
+
local_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), local_file_name)
|
| 99 |
+
if not os.path.exists(local_file_path) or os.path.getsize(local_file_path) == 0:
|
| 100 |
+
print(f"--- [AVISO] Arquivo '{local_file_name}' não existe ou está vazio. Pular commit. ---")
|
| 101 |
+
return
|
| 102 |
+
try:
|
| 103 |
+
print(f"--- [API HF] Tentando fazer o commit de '{local_file_name}' para o repositório... ---")
|
| 104 |
+
hf_api.upload_file(path_or_fileobj=local_file_path, path_in_repo=local_file_name, repo_id=REPO_ID, repo_type="space", commit_message=commit_message)
|
| 105 |
+
print(f"--- [API HF] Sucesso no commit de '{local_file_name}'. ---")
|
| 106 |
+
except Exception as e:
|
| 107 |
+
print(f"--- [ERRO API HF] Falha no commit de '{local_file_name}': {e} ---")
|
| 108 |
+
|
| 109 |
+
def save_data_on_exit():
|
| 110 |
+
"""Função registrada para ser executada no desligamento da aplicação, salvando dados se necessário."""
|
| 111 |
+
print("--- [SHUTDOWN] Verificando dados para salvar... ---")
|
| 112 |
+
if DATA_HAS_CHANGED:
|
| 113 |
+
print(f"--- [SHUTDOWN] Mudanças detectadas. Fazendo o commit de '{USER_FEEDBACK_FILE}' para o repositório. ---")
|
| 114 |
+
commit_file_to_repo(USER_FEEDBACK_FILE, "Commit automático: Atualiza feedbacks de usuários.")
|
| 115 |
+
else:
|
| 116 |
+
print("--- [SHUTDOWN] Nenhuma mudança nos dados detectada. Nenhum commit necessário. ---")
|
| 117 |
+
|
| 118 |
+
atexit.register(save_data_on_exit)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# --- Bloco 3: Inicialização da Aplicação e Carregamento de Dados ---
|
| 122 |
+
|
| 123 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 124 |
+
try:
|
| 125 |
+
from enhanced_search_v2 import load_and_prepare_database, load_correction_corpus, load_general_dictionary, search_procedure_with_log
|
| 126 |
+
print("--- [SUCESSO] Módulo 'enhanced_search_v2.py' importado. ---")
|
| 127 |
+
except Exception as e:
|
| 128 |
+
print(f"--- [ERRO CRÍTICO] Não foi possível importar 'enhanced_search_v2.py': {e} ---"); traceback.print_exc(); sys.exit(1)
|
| 129 |
+
|
| 130 |
+
app = Flask(__name__)
|
| 131 |
+
|
| 132 |
+
# Declaração das variáveis globais
|
| 133 |
+
DF_ORIGINAL, DF_NORMALIZED, FUZZY_CORPUS, BM25_MODEL, DOC_FREQ = (None, None, None, None, {})
|
| 134 |
+
CORRECTION_CORPUS = ([], [])
|
| 135 |
+
VALID_WORDS_SET = set()
|
| 136 |
+
CROSS_ENCODER_MODEL = None
|
| 137 |
+
|
| 138 |
+
try:
|
| 139 |
+
db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'rol_procedures_database.csv')
|
| 140 |
+
DF_ORIGINAL, DF_NORMALIZED, FUZZY_CORPUS, BM25_MODEL, DOC_FREQ = load_and_prepare_database(db_path)
|
| 141 |
+
|
| 142 |
+
dict_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Dic.csv')
|
| 143 |
+
original_terms, normalized_terms, db_word_set = load_correction_corpus(dict_path, column_name='Termo_Correto')
|
| 144 |
+
CORRECTION_CORPUS = (original_terms, normalized_terms)
|
| 145 |
+
|
| 146 |
+
general_dict_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dicionario_ptbr.txt')
|
| 147 |
+
portuguese_word_set = load_general_dictionary(general_dict_path)
|
| 148 |
+
VALID_WORDS_SET = db_word_set.union(portuguese_word_set)
|
| 149 |
+
print(f"--- [SUCESSO] Dicionário unificado criado com {len(VALID_WORDS_SET)} palavras válidas. ---")
|
| 150 |
+
|
| 151 |
+
load_user_feedback()
|
| 152 |
+
|
| 153 |
+
print("\n--- [SETUP] Carregando modelo Cross-Encoder... ---")
|
| 154 |
+
cross_encoder_model_name = 'cross-encoder/ms-marco-MiniLM-L-6-v2'
|
| 155 |
+
CROSS_ENCODER_MODEL = CrossEncoder(cross_encoder_model_name, device='cpu')
|
| 156 |
+
print(f"--- [SUCESSO] Modelo Cross-Encoder '{cross_encoder_model_name}' carregado. ---")
|
| 157 |
+
|
| 158 |
+
except Exception as e:
|
| 159 |
+
print(f"--- [ERRO CRÍTICO] Falha fatal durante o setup: {e} ---"); traceback.print_exc(); sys.exit(1)
|
| 160 |
+
|
| 161 |
+
# --- Bloco 4: Definição dos Endpoints da API ---
|
| 162 |
+
|
| 163 |
+
@app.route('/')
|
| 164 |
+
def index():
|
| 165 |
+
return render_template('index.html')
|
| 166 |
+
|
| 167 |
+
@app.route('/favicon.ico')
|
| 168 |
+
def favicon():
|
| 169 |
+
return '', 204
|
| 170 |
+
|
| 171 |
+
@app.route('/search', methods=['POST'])
|
| 172 |
+
def search():
|
| 173 |
+
"""Endpoint principal que recebe a query e retorna os resultados da busca."""
|
| 174 |
+
try:
|
| 175 |
+
data = request.get_json()
|
| 176 |
+
query = data.get('query', '').strip()
|
| 177 |
+
|
| 178 |
+
results = search_procedure_with_log(
|
| 179 |
+
query=query,
|
| 180 |
+
df_original=DF_ORIGINAL,
|
| 181 |
+
df_normalized=DF_NORMALIZED,
|
| 182 |
+
fuzzy_search_corpus=FUZZY_CORPUS,
|
| 183 |
+
correction_corpus=CORRECTION_CORPUS,
|
| 184 |
+
valid_words_set=VALID_WORDS_SET,
|
| 185 |
+
bm25_model=BM25_MODEL,
|
| 186 |
+
doc_freq=DOC_FREQ,
|
| 187 |
+
cross_encoder_model=CROSS_ENCODER_MODEL,
|
| 188 |
+
user_best_matches_counts=USER_BEST_MATCHES_COUNTS,
|
| 189 |
+
user_feedback_threshold=USER_FEEDBACK_THRESHOLD
|
| 190 |
+
)
|
| 191 |
+
return jsonify(results)
|
| 192 |
+
except Exception as e:
|
| 193 |
+
print("--- [ERRO FATAL DURANTE A BUSCA] ---"); traceback.print_exc()
|
| 194 |
+
return jsonify({"error": "Ocorreu um erro interno no motor de busca."}), 500
|
| 195 |
+
|
| 196 |
+
@app.route('/submit_feedback', methods=['POST'])
|
| 197 |
+
def submit_feedback_route():
|
| 198 |
+
"""Endpoint para receber e registrar o feedback dos usuários, com lógica de salvamento robusta."""
|
| 199 |
+
global DATA_HAS_CHANGED
|
| 200 |
+
try:
|
| 201 |
+
data = request.get_json()
|
| 202 |
+
query, tuss_code_submitted = data.get('query'), data.get('tuss_code')
|
| 203 |
+
if not query or not tuss_code_submitted: return jsonify({"status": "error", "message": "Dados incompletos."}), 400
|
| 204 |
+
|
| 205 |
+
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), USER_FEEDBACK_FILE)
|
| 206 |
+
|
| 207 |
+
# Abre o arquivo em modo de adição ('a') para não apagar o conteúdo existente
|
| 208 |
+
with open(file_path, 'a', newline='', encoding='utf-8') as f:
|
| 209 |
+
writer = csv.writer(f)
|
| 210 |
+
|
| 211 |
+
# Lógica simples para garantir que o cabeçalho exista (não ideal para concorrência, mas ok aqui)
|
| 212 |
+
f.seek(0, 2) # Vai para o fim do arquivo
|
| 213 |
+
if f.tell() == 0: # Se o ponteiro está no início, o arquivo está vazio
|
| 214 |
+
writer.writerow(FEEDBACK_CSV_COLUMNS)
|
| 215 |
+
|
| 216 |
+
# Constrói e escreve a nova linha de feedback
|
| 217 |
+
query_normalized = normalize_text_for_feedback(query)
|
| 218 |
+
matching_rows = DF_ORIGINAL[DF_ORIGINAL['Codigo_TUSS'].astype(str) == tuss_code_submitted]
|
| 219 |
+
tuss_desc_assoc = " | ".join(matching_rows['Descricao_TUSS'].unique()) if not matching_rows.empty else 'Não encontrado'
|
| 220 |
+
rol_names_assoc = " | ".join(matching_rows['Procedimento_Rol'].unique()) if not matching_rows.empty else 'Não encontrado'
|
| 221 |
+
|
| 222 |
+
writer.writerow([datetime.datetime.now().isoformat(), query, query_normalized, tuss_code_submitted, '', tuss_desc_assoc, rol_names_assoc, 'confirm_result'])
|
| 223 |
+
|
| 224 |
+
# Ativa a flag para indicar que o arquivo foi modificado e precisa ser salvo no desligamento
|
| 225 |
+
DATA_HAS_CHANGED = True
|
| 226 |
+
print(f"--- [DADOS] Feedback recebido para a query '{query}'. Commit agendado para o desligamento. ---")
|
| 227 |
+
|
| 228 |
+
# Recarrega o feedback na memória para que a próxima busca já o considere
|
| 229 |
+
load_user_feedback()
|
| 230 |
+
return jsonify({"status": "success", "message": "Feedback recebido!"}), 200
|
| 231 |
+
except Exception as e:
|
| 232 |
+
print("--- [ERRO NO SUBMIT_FEEDBACK] ---"); traceback.print_exc();
|
| 233 |
+
return jsonify({"status": "error", "message": "Erro interno."}), 500
|
| 234 |
+
|
| 235 |
+
@app.route('/get_tuss_info', methods=['GET'])
|
| 236 |
+
def get_tuss_info():
|
| 237 |
+
"""Endpoint para autocompletar códigos TUSS na interface."""
|
| 238 |
+
tuss_code_prefix = request.args.get('tuss_prefix', '').strip()
|
| 239 |
+
if not tuss_code_prefix: return jsonify([])
|
| 240 |
+
suggestions = []
|
| 241 |
+
if DF_ORIGINAL is not None:
|
| 242 |
+
filtered_df = DF_ORIGINAL[DF_ORIGINAL['Codigo_TUSS'].astype(str).str.startswith(tuss_code_prefix)]
|
| 243 |
+
tuss_grouped = filtered_df.groupby('Codigo_TUSS').agg(tuss_descriptions=('Descricao_TUSS', 'unique'), rol_names=('Procedimento_Rol', 'unique')).reset_index()
|
| 244 |
+
for _, row in tuss_grouped.head(10).iterrows():
|
| 245 |
+
suggestions.append({'tuss_code': str(row['Codigo_TUSS']), 'tuss_description': " | ".join(row['tuss_descriptions']), 'rol_name': " | ".join(row['rol_names'])})
|
| 246 |
+
return jsonify(suggestions)
|
| 247 |
+
|
| 248 |
+
@app.route('/get_ai_suggestion', methods=['POST'])
|
| 249 |
+
def get_ai_suggestion():
|
| 250 |
+
"""Endpoint para obter sugestões de uma IA Generativa baseada nos resultados da busca."""
|
| 251 |
+
if not client_ia: return jsonify({"error": "O serviço de IA não está configurado."}), 503
|
| 252 |
+
try:
|
| 253 |
+
data = request.get_json()
|
| 254 |
+
query, results = data.get('query'), data.get('results', [])
|
| 255 |
+
if not query or not results: return jsonify({"error": "A consulta e os resultados são necessários."}), 400
|
| 256 |
+
|
| 257 |
+
RELEVANT_KEYS_FOR_AI = [ 'Codigo_TUSS', 'Descricao_TUSS', 'Procedimento_Rol', 'CAPITULO', 'GRUPO', 'SUBGRUPO', 'Semantico', 'Sinonimo_1', 'Sinonimo_2' ]
|
| 258 |
+
simplified_results = []
|
| 259 |
+
for r in results:
|
| 260 |
+
unique_id = f"{r.get('Codigo_TUSS')}_{sha1(str(r.get('Procedimento_Rol', '')).encode('utf-8')).hexdigest()[:8]}"
|
| 261 |
+
pruned_result = {'unique_id': unique_id, **{key: r.get(key) for key in RELEVANT_KEYS_FOR_AI if r.get(key) and pd.notna(r.get(key))}}
|
| 262 |
+
if 'Codigo_TUSS' in pruned_result: simplified_results.append(pruned_result)
|
| 263 |
+
|
| 264 |
+
formatted_results_str = json.dumps(simplified_results, indent=2, ensure_ascii=False)
|
| 265 |
+
system_prompt = ( "Você é um especialista em terminologia de procedimentos médicos do Brasil (Tabela TUSS e Rol da ANS). " "Sua tarefa é analisar uma lista de procedimentos e escolher os 3 que melhor correspondem à consulta do usuário, em ordem de relevância." )
|
| 266 |
+
user_prompt = f"""Consulta do usuário: "{query}"
|
| 267 |
+
|
| 268 |
+
### Resultados da Busca para Análise (JSON):
|
| 269 |
+
{formatted_results_str}
|
| 270 |
+
|
| 271 |
+
### Sua Tarefa:
|
| 272 |
+
1. **Pense em voz alta:** Dentro de uma tag `<thought>`, explique seu processo de raciocínio passo a passo.
|
| 273 |
+
2. **Forneça a resposta final:** Após a tag `<thought>`, seu único resultado deve ser um bloco de código JSON contendo uma chave `suggested_ids` com uma lista de **EXATAMENTE 3 strings** do campo `unique_id` que você selecionou, ordenadas da mais para a menos relevante."""
|
| 274 |
+
|
| 275 |
+
completion = client_ia.chat.completions.create( model="baidu/ERNIE-4.5-21B-A3B-PT", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}], max_tokens=1500, temperature=0.1 )
|
| 276 |
+
raw_response = completion.choices[0].message.content.strip()
|
| 277 |
+
|
| 278 |
+
thought_process = "Não foi possível extrair o raciocínio da resposta da IA."
|
| 279 |
+
json_part = None
|
| 280 |
+
|
| 281 |
+
if "<thought>" in raw_response and "</thought>" in raw_response:
|
| 282 |
+
start = raw_response.find("<thought>") + len("<thought>")
|
| 283 |
+
end = raw_response.find("</thought>")
|
| 284 |
+
thought_process = raw_response[start:end].strip()
|
| 285 |
+
|
| 286 |
+
if "```json" in raw_response:
|
| 287 |
+
start = raw_response.find("```json") + len("```json")
|
| 288 |
+
end = raw_response.rfind("```")
|
| 289 |
+
json_str = raw_response[start:end].strip()
|
| 290 |
+
try: json_part = json.loads(json_str)
|
| 291 |
+
except json.JSONDecodeError: pass
|
| 292 |
+
|
| 293 |
+
if not json_part or "suggested_ids" not in json_part or not isinstance(json_part.get("suggested_ids"), list):
|
| 294 |
+
return jsonify({ "error": "A IA não retornou a lista de 'suggested_ids' no formato esperado.", "details": raw_response }), 422
|
| 295 |
+
|
| 296 |
+
return jsonify({ "suggested_ids": json_part["suggested_ids"][:3], "thought_process": thought_process })
|
| 297 |
+
|
| 298 |
+
except Exception as e:
|
| 299 |
+
print("--- [ERRO FATAL NA SUGESTÃO DA IA] ---"); traceback.print_exc()
|
| 300 |
+
return jsonify({"error": f"Ocorreu um erro interno na IA: {str(e)}"}), 500
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
# --- Bloco 5: Execução da Aplicação ---
|
| 304 |
+
|
| 305 |
+
if __name__ == '__main__':
|
| 306 |
+
port = int(os.environ.get("PORT", 7860))
|
| 307 |
+
app.run(host='0.0.0.0', port=port, debug=False)
|
enhanced_search_v2.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# enhanced_search_v2.py (Versão Final com Decomposição de Palavras)
|
| 2 |
+
###################################################################################################
|
| 3 |
+
#
|
| 4 |
+
# RESUMO DAS CORREÇÕES E MELHORIAS:
|
| 5 |
+
#
|
| 6 |
+
# 1. ADIÇÃO DA CAMADA DE DECOMPOSIÇÃO DE PALAVRAS (MUDANÇA PRINCIPAL):
|
| 7 |
+
# - Uma nova camada de pré-processamento foi adicionada para identificar palavras longas
|
| 8 |
+
# que não existem no dicionário (ex: "CirurgicoHisterectomia") e tentar dividi-las
|
| 9 |
+
# em duas palavras válidas (ex: "Cirurgico Histerectomia").
|
| 10 |
+
# - Esta lógica NÃO afeta palavras longas que SÃO válidas e existem no dicionário
|
| 11 |
+
# (ex: "Antipneumococo"), garantindo a precisão da busca.
|
| 12 |
+
#
|
| 13 |
+
# 2. TODAS AS OUTRAS FUNCIONALIDADES MANTIDAS:
|
| 14 |
+
# - Mapeamento, Blocos, RRF, Boosts, Otimização Fuzzy e todas as correções de bugs
|
| 15 |
+
# anteriores foram 100% preservadas.
|
| 16 |
+
#
|
| 17 |
+
###################################################################################################
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
import re
|
| 22 |
+
from unidecode import unidecode
|
| 23 |
+
import time
|
| 24 |
+
from sentence_transformers import util
|
| 25 |
+
import torch
|
| 26 |
+
import math
|
| 27 |
+
from collections import defaultdict
|
| 28 |
+
from rank_bm25 import BM25Okapi
|
| 29 |
+
|
| 30 |
+
# --- Tenta usar a biblioteca RapidFuzz que é muito mais rápida ---
|
| 31 |
+
try:
|
| 32 |
+
# Usa a versão C++ otimizada se estiver instalada
|
| 33 |
+
from rapidfuzz import process, fuzz
|
| 34 |
+
print("--- [SUCESSO] Biblioteca 'rapidfuzz' encontrada. Usando motor otimizado. ---")
|
| 35 |
+
except ImportError:
|
| 36 |
+
# Usa a versão Python pura como fallback
|
| 37 |
+
from thefuzz import process, fuzz
|
| 38 |
+
print("--- [AVISO] 'rapidfuzz' não encontrada. Usando 'thefuzz' como fallback (mais lento). ---")
|
| 39 |
+
|
| 40 |
+
# --- Dicionário de Mapeamento de Variações ---
|
| 41 |
+
COMMON_QUERY_MAPPINGS = {
|
| 42 |
+
"ultra sonografia": "ultrassonografia", "ultra som": "ultrassom", "eco cardiograma": "ecocardiograma",
|
| 43 |
+
"eletro cardiograma": "eletrocardiograma", "eletro encefalograma": "eletroencefalograma",
|
| 44 |
+
"video endoscopia": "videoendoscopia", "video laparoscopia": "videolaparoscopia",
|
| 45 |
+
"eco doppler": "ecodopplercardiograma", "rm": "ressonancia", "rnm": "ressonancia", "tc": "tomografia",
|
| 46 |
+
"usg": "ultrassonografia", "us": "ultrassonografia", "ecg": "eletrocardiograma", "eeg": "eletroencefalograma",
|
| 47 |
+
"raio x": "radiografia", "raiox": "radiografia", "chapa": "radiografia", "ultrasson": "ultrassom",
|
| 48 |
+
"tomografia computadorizada": "tomografia", "ressonancia magnetica": "ressonancia",
|
| 49 |
+
"endoscopia digestiva alta": "endoscopia", "densitometria ossea": "densitometria"
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
# --- Bloco 1: Funções Auxiliares de Normalização e Limpeza --- #
|
| 53 |
+
|
| 54 |
+
def literal_normalize_text(text):
|
| 55 |
+
if pd.isna(text): return ""
|
| 56 |
+
normalized = unidecode(str(text).lower())
|
| 57 |
+
return re.sub(r'^\W+|\W+$', '', normalized).strip()
|
| 58 |
+
|
| 59 |
+
def clean_symbols_from_query(text):
|
| 60 |
+
if pd.isna(text): return ""
|
| 61 |
+
return re.sub(r"[´`'\"/*]", "", str(text)).strip()
|
| 62 |
+
|
| 63 |
+
def normalize_text(text):
|
| 64 |
+
if pd.isna(text): return ""
|
| 65 |
+
normalized = unidecode(str(text).lower())
|
| 66 |
+
normalized = re.sub(r'[^\w\s]', ' ', normalized)
|
| 67 |
+
return re.sub(r'\s+', ' ', normalized).strip()
|
| 68 |
+
|
| 69 |
+
def get_longest_word(query_text):
|
| 70 |
+
words = re.findall(r'\b\w{4,}\b', query_text)
|
| 71 |
+
if not words: return ""
|
| 72 |
+
return max(words, key=len)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# --- Bloco 2: Funções de Formatação e Destaque de Resultados --- #
|
| 76 |
+
|
| 77 |
+
def format_result(row_data, row_index, match_type="", score=0, **kwargs):
|
| 78 |
+
data = row_data.copy()
|
| 79 |
+
is_rol = data.get('Correlacao_Rol', '').strip().lower() == 'sim'
|
| 80 |
+
if not is_rol:
|
| 81 |
+
data['Grupo'], data['Subgrupo'], data['Vigencia'], data['Resolucao_Normativa'] = '', '', '', ''
|
| 82 |
+
data['PAC'], data['DUT'] = '---', '---'
|
| 83 |
+
else:
|
| 84 |
+
data['PAC'] = 'Sim' if data.get('PAC', '').strip().lower() == 'pac' else 'Não'
|
| 85 |
+
original_dut_value = data.get('DUT', '').strip()
|
| 86 |
+
if original_dut_value and original_dut_value.replace('.', '', 1).isdigit():
|
| 87 |
+
data['DUT'] = f'Sim, DUT nº {original_dut_value}'
|
| 88 |
+
else: data['DUT'] = 'Não'
|
| 89 |
+
standard_columns = [ 'Codigo_TUSS', 'Descricao_TUSS', 'Correlacao_Rol', 'Procedimento_Rol', 'Resolucao_Normativa', 'Vigencia', 'OD', 'AMB', 'HCO', 'HSO', 'PAC', 'DUT', 'SUBGRUPO', 'GRUPO', 'CAPITULO', 'Sinonimo_1', 'Sinonimo_2', 'Sinonimo_3', 'Sinonimo_4', 'Semantico' ]
|
| 90 |
+
formatted_data = {col: data.get(col, '') for col in standard_columns}
|
| 91 |
+
result = { "row_index": row_index, "score": round(score), "text_score": round(score), "semantic_score": 0, "match_type": match_type, "is_rol_procedure": is_rol }
|
| 92 |
+
result.update(formatted_data)
|
| 93 |
+
result.update(kwargs)
|
| 94 |
+
return result
|
| 95 |
+
|
| 96 |
+
def _highlight_matches(results, query):
|
| 97 |
+
if not query or not results: return results
|
| 98 |
+
stopwords = {'de', 'do', 'da', 'dos', 'das', 'a', 'o', 'e', 'em', 'um', 'uma', 'para', 'com', 'por', 'para'}
|
| 99 |
+
query_words = {word for word in normalize_text(query).lower().split() if len(word) > 2 and word not in stopwords}
|
| 100 |
+
cols_to_highlight = ['Descricao_TUSS', 'Procedimento_Rol', 'Sinonimo_1', 'Sinonimo_2', 'Sinonimo_3', 'Sinonimo_4', 'Semantico']
|
| 101 |
+
for result in results:
|
| 102 |
+
for col in cols_to_highlight:
|
| 103 |
+
original_text = result.get(col, '')
|
| 104 |
+
if original_text and query_words:
|
| 105 |
+
highlighted_text = original_text
|
| 106 |
+
for word in sorted(list(query_words), key=len, reverse=True):
|
| 107 |
+
pattern = r'\b(' + re.escape(word) + r')\b'
|
| 108 |
+
highlighted_text = re.sub(pattern, r'<b>\1</b>', highlighted_text, flags=re.IGNORECASE)
|
| 109 |
+
result[f"{col}_highlighted"] = highlighted_text
|
| 110 |
+
else:
|
| 111 |
+
result[f"{col}_highlighted"] = original_text
|
| 112 |
+
return results
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# --- Bloco 3: Funções de Carregamento de Dados e Modelos --- #
|
| 116 |
+
|
| 117 |
+
def load_and_prepare_database(db_path):
|
| 118 |
+
try:
|
| 119 |
+
print(f"Carregando e preparando a base de dados de: {db_path}...")
|
| 120 |
+
df_original = pd.read_csv(db_path, dtype=str).fillna('')
|
| 121 |
+
search_cols = ['Descricao_TUSS', 'Procedimento_Rol', 'Sinonimo_1', 'Sinonimo_2', 'Sinonimo_3', 'Sinonimo_4', 'Semantico', 'SUBGRUPO', 'GRUPO', 'CAPITULO']
|
| 122 |
+
df_normalized = df_original.copy()
|
| 123 |
+
df_normalized['Codigo_TUSS_literal'] = df_normalized['Codigo_TUSS'].apply(literal_normalize_text)
|
| 124 |
+
df_normalized['Procedimento_Rol_literal'] = df_normalized['Procedimento_Rol'].apply(literal_normalize_text)
|
| 125 |
+
df_normalized['Descricao_TUSS_literal'] = df_normalized['Descricao_TUSS'].apply(literal_normalize_text)
|
| 126 |
+
df_normalized['full_text_norm'] = ""
|
| 127 |
+
for col in search_cols:
|
| 128 |
+
if col in df_normalized.columns:
|
| 129 |
+
df_normalized[f'{col}_norm'] = df_normalized[col].apply(normalize_text)
|
| 130 |
+
df_normalized['full_text_norm'] += ' ' + df_normalized[f'{col}_norm']
|
| 131 |
+
print("Criando modelo BM25 e calculando frequência de palavras...")
|
| 132 |
+
tokenized_corpus = [doc.split() for doc in df_normalized['full_text_norm']]
|
| 133 |
+
bm25_model = BM25Okapi(tokenized_corpus, k1=1.2)
|
| 134 |
+
print(f"Modelo BM25 otimizado com k1={bm25_model.k1}.")
|
| 135 |
+
doc_freq = defaultdict(int)
|
| 136 |
+
for doc_words in tokenized_corpus:
|
| 137 |
+
for word in set(doc_words): doc_freq[word] += 1
|
| 138 |
+
print("Combinando frequências de palavras (masculino/feminino)...")
|
| 139 |
+
combined_doc_freq = {}
|
| 140 |
+
processed_words = set()
|
| 141 |
+
for word, freq in doc_freq.items():
|
| 142 |
+
if word in processed_words: continue
|
| 143 |
+
pair_word = None
|
| 144 |
+
if word.endswith('o'): pair_word = word[:-1] + 'a'
|
| 145 |
+
elif word.endswith('a'): pair_word = word[:-1] + 'o'
|
| 146 |
+
if pair_word and pair_word in doc_freq:
|
| 147 |
+
combined_freq = freq + doc_freq[pair_word]
|
| 148 |
+
combined_doc_freq[word] = combined_freq
|
| 149 |
+
combined_doc_freq[pair_word] = combined_freq
|
| 150 |
+
processed_words.add(word); processed_words.add(pair_word)
|
| 151 |
+
else:
|
| 152 |
+
combined_doc_freq[word] = freq
|
| 153 |
+
print("Criando corpus para busca fuzzy...")
|
| 154 |
+
fuzzy_search_corpus = []
|
| 155 |
+
for index, row in df_normalized.iterrows():
|
| 156 |
+
for col in search_cols:
|
| 157 |
+
if f'{col}_norm' in row and pd.notna(row[f'{col}_norm']):
|
| 158 |
+
if val := row[f'{col}_norm']: fuzzy_search_corpus.append((val, index))
|
| 159 |
+
print(f"Base de dados pronta com {len(df_original)} procedimentos.")
|
| 160 |
+
return df_original, df_normalized, fuzzy_search_corpus, bm25_model, combined_doc_freq
|
| 161 |
+
except Exception as e:
|
| 162 |
+
print(f"Erro crítico ao carregar/preparar a base de dados: {e}"); raise
|
| 163 |
+
|
| 164 |
+
def load_correction_corpus(dict_path, column_name='Termo_Correto'):
|
| 165 |
+
try:
|
| 166 |
+
df_dict = pd.read_csv(dict_path, dtype=str).fillna('')
|
| 167 |
+
if column_name not in df_dict.columns: return [], [], set()
|
| 168 |
+
original_corpus = df_dict[column_name].dropna().astype(str).tolist()
|
| 169 |
+
normalized_corpus = [normalize_text(term) for term in original_corpus]
|
| 170 |
+
db_word_set = {word for term in normalized_corpus for word in term.split()}
|
| 171 |
+
return original_corpus, normalized_corpus, db_word_set
|
| 172 |
+
except (FileNotFoundError, Exception): return [], [], set()
|
| 173 |
+
|
| 174 |
+
def load_general_dictionary(path):
|
| 175 |
+
try:
|
| 176 |
+
with open(path, 'r', encoding='utf-8') as f: words = {normalize_text(line.strip()) for line in f if line.strip()}
|
| 177 |
+
print(f"Dicionário geral carregado com {len(words)} palavras.")
|
| 178 |
+
return words
|
| 179 |
+
except (FileNotFoundError, Exception): return set()
|
| 180 |
+
|
| 181 |
+
# --- Bloco 4: Funções de Reclassificação, Boosts e IA --- #
|
| 182 |
+
def create_unified_document_text(result_dict):
|
| 183 |
+
text_parts = { result_dict.get(key, '') for key in ['Descricao_TUSS', 'Procedimento_Rol', 'Semantico', 'SUBGRUPO', 'GRUPO', 'CAPITULO', 'Sinonimo_1', 'Sinonimo_2', 'Sinonimo_3', 'Sinonimo_4']}
|
| 184 |
+
return ". ".join(sorted([part for part in text_parts if part and str(part).strip()]))
|
| 185 |
+
|
| 186 |
+
def rerank_with_cross_encoder(query, results_list, model):
|
| 187 |
+
if not model or not results_list or not query:
|
| 188 |
+
return results_list, "Cross-Encoder não fornecido ou lista de candidatos vazia."
|
| 189 |
+
sentence_pairs = [[query, create_unified_document_text(result)] for result in results_list]
|
| 190 |
+
if not sentence_pairs: return results_list, "Não foram encontrados pares para reordenar."
|
| 191 |
+
try:
|
| 192 |
+
raw_scores = model.predict(sentence_pairs, show_progress_bar=False)
|
| 193 |
+
semantic_scores = torch.sigmoid(torch.tensor(raw_scores)).numpy() * 100
|
| 194 |
+
for i, result in enumerate(results_list): result['semantic_score'] = round(semantic_scores[i])
|
| 195 |
+
log_message = f"Scores semânticos calculados para {len(results_list)} candidatos."
|
| 196 |
+
return results_list, log_message
|
| 197 |
+
except Exception as e:
|
| 198 |
+
log_message = f"Erro no Cross-Encoder: {e}"; print(log_message)
|
| 199 |
+
return results_list, log_message
|
| 200 |
+
|
| 201 |
+
def apply_boosts(results, query_words, doc_freq):
|
| 202 |
+
if not results or not query_words: return results, []
|
| 203 |
+
log_messages = []
|
| 204 |
+
jargon_terms = {w for w in query_words if doc_freq.get(w, 0) <= 15 and len(w) > 4}
|
| 205 |
+
if jargon_terms:
|
| 206 |
+
boosted_count = 0
|
| 207 |
+
for r in results:
|
| 208 |
+
text = normalize_text(create_unified_document_text(r))
|
| 209 |
+
if any(re.search(r'\b' + re.escape(term) + r'\b', text) for term in jargon_terms):
|
| 210 |
+
r['text_score'] = min(r['text_score'] * 1.2, 97)
|
| 211 |
+
boosted_count += 1
|
| 212 |
+
if boosted_count > 0: log_messages.append(f"Boost de Jargão para '{list(jargon_terms)}' ({boosted_count} afetados).")
|
| 213 |
+
rare_terms = {w for w in query_words if doc_freq.get(w, 0) <= 5 and len(w) > 4}
|
| 214 |
+
if rare_terms:
|
| 215 |
+
boosted_count = 0
|
| 216 |
+
for r in results:
|
| 217 |
+
text = normalize_text(create_unified_document_text(r))
|
| 218 |
+
if any(re.search(r'\b' + re.escape(term) + r'\b', text) for term in rare_terms):
|
| 219 |
+
r['text_score'] = min(r['text_score'] * 1.3, 97)
|
| 220 |
+
boosted_count += 1
|
| 221 |
+
if boosted_count > 0: log_messages.append(f"Boost Ultra-Raro para '{list(rare_terms)}' ({boosted_count} afetados).")
|
| 222 |
+
for r in results: r['score'] = r['text_score']
|
| 223 |
+
return results, log_messages
|
| 224 |
+
|
| 225 |
+
# --- Bloco 5: Função Principal de Orquestração da Busca --- #
|
| 226 |
+
|
| 227 |
+
def search_procedure_with_log(query, df_original, df_normalized, fuzzy_search_corpus, correction_corpus,
|
| 228 |
+
valid_words_set, bm25_model, doc_freq,
|
| 229 |
+
cross_encoder_model=None, user_best_matches_counts=None, user_feedback_threshold=10):
|
| 230 |
+
start_time = time.time(); original_query = str(query).strip()
|
| 231 |
+
response = { "search_log": [], "results_by_layer": {}, "final_semantic_results": [], "original_query": original_query, "corrected_query": "", "was_corrected": False }
|
| 232 |
+
if not original_query: response["search_log"].append("Query vazia."); return response
|
| 233 |
+
response["search_log"].append(f"Buscando por: '{original_query}'")
|
| 234 |
+
|
| 235 |
+
# --- Etapa 1: Pré-processamento inicial ---
|
| 236 |
+
query_para_literal = literal_normalize_text(original_query)
|
| 237 |
+
response["search_log"].append(f"\n--- Etapa 1: Pré-processamento da Query ---")
|
| 238 |
+
response["search_log"].append(f"Query para busca literal (após limpeza de bordas): '{query_para_literal}'")
|
| 239 |
+
|
| 240 |
+
# --- Etapa 2: Camada de Early Exit ---
|
| 241 |
+
response["search_log"].append("\n--- Etapa 2: Camada de Early Exit (Literal) ---")
|
| 242 |
+
literal_results = []
|
| 243 |
+
seen_indices = set()
|
| 244 |
+
literal_fields = ['Codigo_TUSS_literal', 'Procedimento_Rol_literal', 'Descricao_TUSS_literal']
|
| 245 |
+
for field in literal_fields:
|
| 246 |
+
mask = df_normalized[field] == query_para_literal
|
| 247 |
+
for index in df_normalized.index[mask & ~df_normalized.index.isin(seen_indices)]:
|
| 248 |
+
literal_results.append(format_result(df_original.loc[index], index, "Literal Exata", 100))
|
| 249 |
+
seen_indices.add(index)
|
| 250 |
+
if literal_results:
|
| 251 |
+
response["search_log"].append(f"Encontrado(s) {len(literal_results)} resultado(s) literal(is). ATIVANDO EARLY EXIT.")
|
| 252 |
+
results_with_semantic, log_msg = rerank_with_cross_encoder(normalize_text(original_query), literal_results, cross_encoder_model)
|
| 253 |
+
response["search_log"].append(f"Cálculo de Score Semântico: {log_msg}")
|
| 254 |
+
final_list = sorted(results_with_semantic, key=lambda x: x['text_score'], reverse=True)
|
| 255 |
+
response["final_semantic_results"] = _highlight_matches(final_list, original_query)
|
| 256 |
+
end_time = time.time(); response["search_duration_seconds"] = round(end_time - start_time, 4)
|
| 257 |
+
response["search_log"].append(f"\nBusca concluída em {response['search_duration_seconds']} segundos.")
|
| 258 |
+
print("\n".join(response["search_log"]))
|
| 259 |
+
return response
|
| 260 |
+
else:
|
| 261 |
+
response["search_log"].append("Nenhum resultado literal encontrado. Prosseguindo para a busca completa.")
|
| 262 |
+
|
| 263 |
+
# --- Camada de Mapeamento de Variações ---
|
| 264 |
+
temp_query = original_query.lower()
|
| 265 |
+
query_foi_mapeada = False
|
| 266 |
+
for wrong, right in sorted(COMMON_QUERY_MAPPINGS.items(), key=lambda item: len(item[0]), reverse=True):
|
| 267 |
+
if wrong in temp_query:
|
| 268 |
+
temp_query = temp_query.replace(wrong, right)
|
| 269 |
+
query_foi_mapeada = True
|
| 270 |
+
if query_foi_mapeada:
|
| 271 |
+
response["search_log"].append(f"Variação de termo comum mapeada: '{original_query}' -> '{temp_query}'")
|
| 272 |
+
query_para_processamento = temp_query
|
| 273 |
+
else:
|
| 274 |
+
query_para_processamento = original_query
|
| 275 |
+
|
| 276 |
+
# --- Etapa 3: Busca Completa (se não houve Early Exit) ---
|
| 277 |
+
query_para_geral = clean_symbols_from_query(query_para_processamento)
|
| 278 |
+
|
| 279 |
+
# --- INÍCIO DA NOVA FUNCIONALIDADE: Decomposição de Palavras ---
|
| 280 |
+
decomposed_words = []
|
| 281 |
+
words_decomposed = False
|
| 282 |
+
# Itera sobre as palavras da query após a limpeza de símbolos e mapeamento
|
| 283 |
+
for word in query_para_geral.split():
|
| 284 |
+
# 1. IDENTIFICAÇÃO: A palavra é longa E não está no nosso dicionário de palavras válidas?
|
| 285 |
+
if len(word) > 13 and normalize_text(word) not in valid_words_set:
|
| 286 |
+
was_split = False
|
| 287 |
+
# 2. DECOMPOSIÇÃO: Tenta encontrar um ponto de quebra válido
|
| 288 |
+
# Começamos com prefixos de 4 letras e deixamos no mínimo 4 para o sufixo
|
| 289 |
+
for i in range(4, len(word) - 3):
|
| 290 |
+
prefix = normalize_text(word[:i])
|
| 291 |
+
suffix = normalize_text(word[i:])
|
| 292 |
+
# 3. VALIDAÇÃO: Ambas as partes quebradas são palavras válidas?
|
| 293 |
+
if prefix in valid_words_set and suffix in valid_words_set:
|
| 294 |
+
# 4. SUBSTITUIÇÃO: Se sim, usamos a versão quebrada e paramos de procurar
|
| 295 |
+
decomposed_words.extend([word[:i], word[i:]])
|
| 296 |
+
response["search_log"].append(f"Palavra composta '{word}' decomposta em: '{word[:i]} {word[i:]}'")
|
| 297 |
+
was_split = True
|
| 298 |
+
words_decomposed = True
|
| 299 |
+
break
|
| 300 |
+
# Se, após todos os testes, não encontramos uma quebra válida, mantemos a palavra original
|
| 301 |
+
if not was_split:
|
| 302 |
+
decomposed_words.append(word)
|
| 303 |
+
else:
|
| 304 |
+
# Se a palavra não é suspeita, apenas a mantemos
|
| 305 |
+
decomposed_words.append(word)
|
| 306 |
+
|
| 307 |
+
if words_decomposed:
|
| 308 |
+
query_para_geral = " ".join(decomposed_words)
|
| 309 |
+
# --- FIM DA NOVA FUNCIONALIDADE ---
|
| 310 |
+
|
| 311 |
+
response["search_log"].append(f"Query para busca geral (após limpeza e decomposição): '{query_para_geral}'")
|
| 312 |
+
|
| 313 |
+
original_correction_corpus, normalized_correction_corpus = correction_corpus
|
| 314 |
+
stopwords = {'de', 'do', 'da', 'dos', 'das', 'a', 'o', 'e', 'em', 'um', 'uma', 'para', 'com'}
|
| 315 |
+
final_query_words_list = []
|
| 316 |
+
words_were_corrected = False
|
| 317 |
+
|
| 318 |
+
for word in query_para_geral.split():
|
| 319 |
+
norm_word = normalize_text(word)
|
| 320 |
+
is_candidate_for_correction = ( len(norm_word) > 2 and norm_word not in stopwords and not norm_word.isdigit() and norm_word not in valid_words_set )
|
| 321 |
+
if is_candidate_for_correction:
|
| 322 |
+
best_match, score, _ = process.extractOne(norm_word, normalized_correction_corpus, scorer=fuzz.ratio)
|
| 323 |
+
if score > 85:
|
| 324 |
+
original_term_index = normalized_correction_corpus.index(best_match)
|
| 325 |
+
corrected_word_original = original_correction_corpus[original_term_index]
|
| 326 |
+
corrected_word = corrected_word_original
|
| 327 |
+
if word.istitle():
|
| 328 |
+
corrected_word = corrected_word.title()
|
| 329 |
+
elif word.isupper():
|
| 330 |
+
corrected_word = corrected_word.upper()
|
| 331 |
+
final_query_words_list.append(corrected_word)
|
| 332 |
+
words_were_corrected = True
|
| 333 |
+
else:
|
| 334 |
+
final_query_words_list.append(word)
|
| 335 |
+
else:
|
| 336 |
+
final_query_words_list.append(word)
|
| 337 |
+
|
| 338 |
+
query_corrigida = " ".join(final_query_words_list)
|
| 339 |
+
if words_were_corrected and query_corrigida.strip().lower() != query_para_geral.strip().lower():
|
| 340 |
+
response["was_corrected"] = True
|
| 341 |
+
response["corrected_query"] = query_corrigida
|
| 342 |
+
response["search_log"].append(f"Correção ortográfica aplicada: '{query_para_geral}' -> '{query_corrigida}'")
|
| 343 |
+
|
| 344 |
+
cleaned_query = " ".join([word for word in query_corrigida.split() if normalize_text(word) not in stopwords])
|
| 345 |
+
normalized_cleaned_query = normalize_text(cleaned_query)
|
| 346 |
+
query_words = [word for word in normalized_cleaned_query.split() if len(word) > 1]
|
| 347 |
+
|
| 348 |
+
response["search_log"].append(f"Query para busca (após limpeza de stopwords): '{cleaned_query}'")
|
| 349 |
+
|
| 350 |
+
# --- Camadas do Bloco Protegido ---
|
| 351 |
+
protected_results = []
|
| 352 |
+
# Camada 1: Busca Exata
|
| 353 |
+
exact_fields = [f"{col}_norm" for col in ['Codigo_TUSS', 'Descricao_TUSS', 'Procedimento_Rol', 'Sinonimo_1', 'Sinonimo_2', 'Sinonimo_3', 'Sinonimo_4', 'Semantico']]
|
| 354 |
+
for field in exact_fields:
|
| 355 |
+
if field in df_normalized.columns:
|
| 356 |
+
for index in df_normalized.index[(df_normalized[field] == normalized_cleaned_query) & (~df_normalized.index.isin(seen_indices))]:
|
| 357 |
+
protected_results.append(format_result(df_original.loc[index], index, "Exato", 100))
|
| 358 |
+
seen_indices.add(index)
|
| 359 |
+
# Camada 2: Frase Exata
|
| 360 |
+
if len(query_words) > 1:
|
| 361 |
+
phrase_pattern = r'\b' + re.escape(normalized_cleaned_query) + r'\b'
|
| 362 |
+
for index in df_normalized.index[df_normalized['full_text_norm'].str.contains(phrase_pattern, na=False, regex=True) & ~df_normalized.index.isin(seen_indices)]:
|
| 363 |
+
protected_results.append(format_result(df_original.loc[index], index, "Frase Exata", 99))
|
| 364 |
+
seen_indices.add(index)
|
| 365 |
+
# Camada 3: Lógica (E)
|
| 366 |
+
search_fields_norm = [f"{col}_norm" for col in ['Descricao_TUSS', 'Procedimento_Rol', 'Sinonimo_1', 'Sinonimo_2', 'Sinonimo_3', 'Sinonimo_4', 'Semantico']]
|
| 367 |
+
for field in search_fields_norm:
|
| 368 |
+
if field in df_normalized.columns and query_words:
|
| 369 |
+
mask = pd.Series(True, index=df_normalized.index)
|
| 370 |
+
for word in query_words: mask &= df_normalized[field].str.contains(r'\b' + re.escape(word) + r'\b', na=False)
|
| 371 |
+
for index in df_normalized.index[mask & ~df_normalized.index.isin(seen_indices)]:
|
| 372 |
+
protected_results.append(format_result(df_original.loc[index], index, "Lógica (E)", 98))
|
| 373 |
+
seen_indices.add(index)
|
| 374 |
+
response["search_log"].append(f"\n--- Detalhamento por Camada ---\nBloco Protegido (Exato, Frase, Lógica E): {len(protected_results)} candidatos.")
|
| 375 |
+
|
| 376 |
+
# --- LÓGICA DE RANKING LEXICAL HÍBRIDO OTIMIZADA ---
|
| 377 |
+
broad_candidates_results = []
|
| 378 |
+
if query_words:
|
| 379 |
+
# Passo 1: Geração de Candidatos (União de Fuzzy e BM25)
|
| 380 |
+
broad_candidate_indices = set()
|
| 381 |
+
|
| 382 |
+
temp_fuzzy_corpus = [
|
| 383 |
+
item for item in fuzzy_search_corpus
|
| 384 |
+
if any(word in item[0] for word in query_words)
|
| 385 |
+
]
|
| 386 |
+
response["search_log"].append(f"Fuzzy: Otimização reduziu o corpus de busca para {len(temp_fuzzy_corpus)} candidatos.")
|
| 387 |
+
|
| 388 |
+
fuzzy_matches = process.extract(
|
| 389 |
+
normalized_cleaned_query,
|
| 390 |
+
[item[0] for item in temp_fuzzy_corpus],
|
| 391 |
+
scorer=fuzz.token_set_ratio,
|
| 392 |
+
limit=40,
|
| 393 |
+
score_cutoff=90
|
| 394 |
+
)
|
| 395 |
+
for match_text, score, _ in fuzzy_matches:
|
| 396 |
+
for _, index in [item for item in temp_fuzzy_corpus if item[0] == match_text]:
|
| 397 |
+
if index not in seen_indices:
|
| 398 |
+
broad_candidate_indices.add(index)
|
| 399 |
+
|
| 400 |
+
# Candidatos via BM25
|
| 401 |
+
bm25_scores_all = bm25_model.get_scores(query_words)
|
| 402 |
+
top_n_indices_bm25 = sorted(range(len(bm25_scores_all)), key=lambda i: bm25_scores_all[i], reverse=True)[:25]
|
| 403 |
+
for i in top_n_indices_bm25:
|
| 404 |
+
if bm25_scores_all[i] > 0:
|
| 405 |
+
index = df_normalized.index[i]
|
| 406 |
+
if index not in seen_indices:
|
| 407 |
+
broad_candidate_indices.add(index)
|
| 408 |
+
|
| 409 |
+
response["search_log"].append(f"Bloco Amplo (Fuzzy Otimizado + BM25): {len(broad_candidate_indices)} candidatos únicos encontrados.")
|
| 410 |
+
|
| 411 |
+
# Passo 2: Reclassificação Unificada com BM25 como fonte da verdade
|
| 412 |
+
if broad_candidate_indices:
|
| 413 |
+
candidate_bm25_scores = {df_normalized.index[i]: bm25_scores_all[i] for i in range(len(bm25_scores_all)) if df_normalized.index[i] in broad_candidate_indices}
|
| 414 |
+
max_score = max(candidate_bm25_scores.values()) if candidate_bm25_scores else 1.0
|
| 415 |
+
|
| 416 |
+
for index in broad_candidate_indices:
|
| 417 |
+
score = (candidate_bm25_scores.get(index, 0) / max_score) * 95
|
| 418 |
+
if score > 1:
|
| 419 |
+
broad_candidates_results.append(format_result(df_original.loc[index], index, "Relevância Híbrida", score))
|
| 420 |
+
|
| 421 |
+
response["search_log"].append(f"Bloco Amplo: {len(broad_candidates_results)} candidatos com score de relevância > 1.")
|
| 422 |
+
|
| 423 |
+
unique_candidates = list({r['row_index']: r for r in protected_results + broad_candidates_results}.values())
|
| 424 |
+
|
| 425 |
+
query_norm_fb = normalize_text(response.get("corrected_query") or original_query)
|
| 426 |
+
for r in unique_candidates:
|
| 427 |
+
votes = user_best_matches_counts.get(query_norm_fb, {}).get(r['Codigo_TUSS'], 0)
|
| 428 |
+
if votes >= user_feedback_threshold:
|
| 429 |
+
r.update({'is_user_best_match': True, 'feedback_votes': votes})
|
| 430 |
+
|
| 431 |
+
feedback_priority_list = sorted([r for r in unique_candidates if r.get('is_user_best_match')], key=lambda x: x['feedback_votes'], reverse=True)
|
| 432 |
+
other_candidates = [r for r in unique_candidates if not r.get('is_user_best_match')]
|
| 433 |
+
|
| 434 |
+
final_list = feedback_priority_list
|
| 435 |
+
response["search_log"].append(f"\n--- Etapa 3.1: Verificação de Feedback de Usuário ---\n{len(final_list)} resultado(s) priorizado(s) por feedback de usuário.")
|
| 436 |
+
|
| 437 |
+
protected_candidates_final = [r for r in protected_results if r in other_candidates]
|
| 438 |
+
broad_candidates_final = [r for r in broad_candidates_results if r in other_candidates]
|
| 439 |
+
|
| 440 |
+
response["search_log"].append("\n--- Etapa 4: Processamento dos Blocos e Re-ranking ---")
|
| 441 |
+
|
| 442 |
+
if protected_candidates_final:
|
| 443 |
+
unique_protected = list({r['row_index']: r for r in protected_candidates_final}.values())
|
| 444 |
+
protected_with_scores, log_msg = rerank_with_cross_encoder(normalized_cleaned_query, unique_protected, cross_encoder_model)
|
| 445 |
+
response["search_log"].append(f"Bloco Protegido: {log_msg}")
|
| 446 |
+
sorted_protected = sorted(protected_with_scores, key=lambda x: (x['text_score'], x['semantic_score']), reverse=True)
|
| 447 |
+
final_list.extend(sorted_protected)
|
| 448 |
+
|
| 449 |
+
if broad_candidates_final:
|
| 450 |
+
unique_broad_sorted = sorted(broad_candidates_final, key=lambda x: x['text_score'], reverse=True)[:30]
|
| 451 |
+
response["search_log"].append(f"Bloco Amplo: {len(unique_broad_sorted)} melhores candidatos selecionados para otimização.")
|
| 452 |
+
|
| 453 |
+
boosted_broad, boost_logs = apply_boosts(unique_broad_sorted, query_words, doc_freq)
|
| 454 |
+
for log in boost_logs: response["search_log"].append(log)
|
| 455 |
+
|
| 456 |
+
reranked_broad, log_msg = rerank_with_cross_encoder(normalized_cleaned_query, boosted_broad, cross_encoder_model)
|
| 457 |
+
response["search_log"].append(f"Bloco Amplo: {log_msg}")
|
| 458 |
+
|
| 459 |
+
def apply_rrf_and_sort(results, k=60):
|
| 460 |
+
if not results: return []
|
| 461 |
+
sorted_by_text = sorted(results, key=lambda x: x.get('text_score', 0), reverse=True)
|
| 462 |
+
sorted_by_semantic = sorted(results, key=lambda x: x.get('semantic_score', 0), reverse=True)
|
| 463 |
+
text_ranks = {res['row_index']: i + 1 for i, res in enumerate(sorted_by_text)}
|
| 464 |
+
semantic_ranks = {res['row_index']: i + 1 for i, res in enumerate(sorted_by_semantic)}
|
| 465 |
+
for res in results:
|
| 466 |
+
text_rank = text_ranks.get(res['row_index'], len(results) + 1)
|
| 467 |
+
semantic_rank = semantic_ranks.get(res['row_index'], len(results) + 1)
|
| 468 |
+
rrf_score = (1 / (k + text_rank)) + (1 / (k + semantic_rank))
|
| 469 |
+
res['rrf_score'] = rrf_score
|
| 470 |
+
return sorted(results, key=lambda x: x['rrf_score'], reverse=True)
|
| 471 |
+
|
| 472 |
+
final_reranked_broad = apply_rrf_and_sort(reranked_broad)
|
| 473 |
+
final_list.extend(final_reranked_broad)
|
| 474 |
+
|
| 475 |
+
response["final_semantic_results"] = _highlight_matches(final_list[:20], query_corrigida)
|
| 476 |
+
end_time = time.time(); response["search_duration_seconds"] = round(end_time - start_time, 4)
|
| 477 |
+
response["search_log"].append(f"\nBusca completa em {response['search_duration_seconds']} segundos.")
|
| 478 |
+
|
| 479 |
+
print("\n\n" + "="*20 + " LOG DE BUSCA FINAL " + "="*20)
|
| 480 |
+
print("\n".join(response["search_log"]))
|
| 481 |
+
|
| 482 |
+
return response
|