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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py (Versão Híbrida Final com Bi-Encoder e Cross-Encoder)
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from flask import Flask, render_template, request, jsonify
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import traceback
|
| 7 |
+
import subprocess
|
| 8 |
+
# Importa as duas classes de modelos necessárias
|
| 9 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder
|
| 10 |
+
import csv
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
import datetime
|
| 13 |
+
import re
|
| 14 |
+
from huggingface_hub import InferenceClient, HfApi
|
| 15 |
+
from huggingface_hub.utils import HfHubHTTPError
|
| 16 |
+
import atexit
|
| 17 |
+
import json
|
| 18 |
+
from hashlib import sha1
|
| 19 |
+
|
| 20 |
+
# --- Variáveis e Constantes de Feedback ---
|
| 21 |
+
USER_FEEDBACK_FILE = 'user_feedback.csv'
|
| 22 |
+
USER_BEST_MATCHES_COUNTS = {}
|
| 23 |
+
USER_FEEDBACK_THRESHOLD = 10
|
| 24 |
+
FEEDBACK_CSV_COLUMNS = ['timestamp', 'query_original', 'query_normalized', 'tuss_code_submitted', 'tuss_code_raw_input', 'tuss_description_associated', 'rol_names_associated', 'feedback_type']
|
| 25 |
+
|
| 26 |
+
# --- Configuração do Cliente da IA ---
|
| 27 |
+
api_key = os.environ.get("USUARIO_KEY")
|
| 28 |
+
if not api_key:
|
| 29 |
+
print("--- [AVISO CRÍTICO] Secret 'USUARIO_KEY' não encontrado. As chamadas para a IA irão falhar. ---")
|
| 30 |
+
client_ia = None
|
| 31 |
+
else:
|
| 32 |
+
client_ia = InferenceClient(
|
| 33 |
+
provider="novita",
|
| 34 |
+
api_key=api_key,
|
| 35 |
+
)
|
| 36 |
+
print("--- [SUCESSO] Cliente de Inferência da IA configurado com a chave correta. ---")
|
| 37 |
+
|
| 38 |
+
# --- SEÇÃO DE PERSISTÊNCIA ---
|
| 39 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 40 |
+
REPO_ID = "tuliodisanto/Buscador_Rol_vs.2_IA"
|
| 41 |
+
|
| 42 |
+
if not HF_TOKEN:
|
| 43 |
+
print("--- [AVISO CRÍTICO] Secret 'HF_TOKEN' não encontrado. Os arquivos não serão salvos no repositório. ---")
|
| 44 |
+
hf_api = None
|
| 45 |
+
else:
|
| 46 |
+
hf_api = HfApi(token=HF_TOKEN)
|
| 47 |
+
print(f"--- [SUCESSO] Cliente da API do Hugging Face configurado para o repositório: {REPO_ID}. ---")
|
| 48 |
+
|
| 49 |
+
DATA_HAS_CHANGED = False
|
| 50 |
+
|
| 51 |
+
# --- Funções de Feedback ---
|
| 52 |
+
def normalize_text_for_feedback(text):
|
| 53 |
+
if pd.isna(text): return ""
|
| 54 |
+
try:
|
| 55 |
+
from enhanced_search_v2 import normalize_text as es_normalize_text
|
| 56 |
+
return es_normalize_text(str(text).strip())
|
| 57 |
+
except ImportError:
|
| 58 |
+
import unidecode
|
| 59 |
+
return unidecode.unidecode(str(text).lower().strip())
|
| 60 |
+
|
| 61 |
+
def load_user_feedback():
|
| 62 |
+
global USER_BEST_MATCHES_COUNTS
|
| 63 |
+
USER_BEST_MATCHES_COUNTS = {}
|
| 64 |
+
feedback_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), USER_FEEDBACK_FILE)
|
| 65 |
+
if not os.path.exists(feedback_file_path):
|
| 66 |
+
with open(feedback_file_path, 'w', newline='', encoding='utf-8') as f: csv.writer(f).writerow(FEEDBACK_CSV_COLUMNS)
|
| 67 |
+
return
|
| 68 |
+
try:
|
| 69 |
+
with open(feedback_file_path, 'r', encoding='utf-8') as f:
|
| 70 |
+
reader = csv.reader(f)
|
| 71 |
+
try:
|
| 72 |
+
header = next(reader)
|
| 73 |
+
if [col.strip() for col in header] != FEEDBACK_CSV_COLUMNS:
|
| 74 |
+
print(f"--- [AVISO] Cabeçalho do {USER_FEEDBACK_FILE} incorreto.")
|
| 75 |
+
return
|
| 76 |
+
except StopIteration:
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
for row in reader:
|
| 80 |
+
if len(row) == len(FEEDBACK_CSV_COLUMNS):
|
| 81 |
+
row_dict = dict(zip(FEEDBACK_CSV_COLUMNS, row))
|
| 82 |
+
query_norm, tuss_code = row_dict.get('query_normalized', ''), row_dict.get('tuss_code_submitted', '')
|
| 83 |
+
if query_norm and tuss_code:
|
| 84 |
+
if query_norm not in USER_BEST_MATCHES_COUNTS: USER_BEST_MATCHES_COUNTS[query_norm] = {}
|
| 85 |
+
USER_BEST_MATCHES_COUNTS[query_norm][tuss_code] = USER_BEST_MATCHES_COUNTS[query_norm].get(tuss_code, 0) + 1
|
| 86 |
+
print(f"--- [SUCESSO] Feedback de usuário carregado/sincronizado. ---")
|
| 87 |
+
except Exception as e: print(f"--- [ERRO] Falha ao carregar feedback: {e} ---"); traceback.print_exc()
|
| 88 |
+
|
| 89 |
+
# --- Execução de Scripts e Importações ---
|
| 90 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 91 |
+
try:
|
| 92 |
+
from enhanced_search_v2 import load_and_prepare_database, load_correction_corpus, load_general_dictionary, search_procedure_with_log
|
| 93 |
+
print("--- [SUCESSO] Módulo 'enhanced_search_v2.py' importado. ---")
|
| 94 |
+
except Exception as e: print(f"--- [ERRO CRÍTICO] Não foi possível importar 'enhanced_search_v2.py': {e} ---"); traceback.print_exc(); sys.exit(1)
|
| 95 |
+
|
| 96 |
+
app = Flask(__name__)
|
| 97 |
+
|
| 98 |
+
# --- Carregamento dos Dados e Modelos ---
|
| 99 |
+
# CORREÇÃO 1: Preparar as variáveis para receber todos os 7 valores de load_and_prepare_database
|
| 100 |
+
DF_ORIGINAL, DF_NORMALIZED, FUZZY_CORPUS, BM25_MODEL, DB_WORD_SET, doc_freq, tuss_map = (None, None, None, None, set(), {}, {})
|
| 101 |
+
CORRECTION_CORPUS, NORMALIZED_CORRECTION_CORPUS = [], []
|
| 102 |
+
PORTUGUESE_WORD_SET = set()
|
| 103 |
+
SEMANTIC_MODEL = None # Bi-Encoder
|
| 104 |
+
CROSS_ENCODER_MODEL = None # Cross-Encoder
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
# Carregamento dos dados
|
| 108 |
+
db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'rol_procedures_database.csv')
|
| 109 |
+
# CORREÇÃO 1 (continuação): Desempacotar os 7 valores retornados pela função
|
| 110 |
+
DF_ORIGINAL, DF_NORMALIZED, FUZZY_CORPUS, BM25_MODEL, DB_WORD_SET, doc_freq, tuss_map = load_and_prepare_database(db_path)
|
| 111 |
+
|
| 112 |
+
dict_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Dic.csv')
|
| 113 |
+
CORRECTION_CORPUS, NORMALIZED_CORRECTION_CORPUS = load_correction_corpus(dict_path, column_name='Termo_Correto')
|
| 114 |
+
general_dict_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dicionario_ptbr.txt')
|
| 115 |
+
PORTUGUESE_WORD_SET = load_general_dictionary(general_dict_path)
|
| 116 |
+
load_user_feedback()
|
| 117 |
+
|
| 118 |
+
# Carregamento dos dois modelos semânticos
|
| 119 |
+
print("\n--- [SETUP] Carregando modelo Bi-Encoder (Etapa 1 de reordenação)... ---")
|
| 120 |
+
bi_encoder_model_name = 'sentence-transformers/all-MiniLM-L6-v2'
|
| 121 |
+
SEMANTIC_MODEL = SentenceTransformer(bi_encoder_model_name, device='cpu')
|
| 122 |
+
print(f"--- [SUCESSO] Modelo Bi-Encoder '{bi_encoder_model_name}' carregado. ---")
|
| 123 |
+
|
| 124 |
+
print("\n--- [SETUP] Carregando modelo Cross-Encoder (Etapa 2 de reordenação)... ---")
|
| 125 |
+
cross_encoder_model_name = 'cross-encoder/ms-marco-MiniLM-L-6-v2'
|
| 126 |
+
CROSS_ENCODER_MODEL = CrossEncoder(cross_encoder_model_name, device='cpu')
|
| 127 |
+
print(f"--- [SUCESSO] Modelo Cross-Encoder '{cross_encoder_model_name}' carregado. ---")
|
| 128 |
+
|
| 129 |
+
except Exception as e:
|
| 130 |
+
print(f"--- [ERRO CRÍTICO] Falha fatal durante o setup: {e} ---"); traceback.print_exc(); sys.exit(1)
|
| 131 |
+
|
| 132 |
+
# --- Rotas da Aplicação ---
|
| 133 |
+
@app.route('/')
|
| 134 |
+
def index(): return render_template('index.html')
|
| 135 |
+
|
| 136 |
+
@app.route('/favicon.ico')
|
| 137 |
+
def favicon(): return '', 204
|
| 138 |
+
|
| 139 |
+
@app.route('/search', methods=['POST'])
|
| 140 |
+
def search():
|
| 141 |
+
try:
|
| 142 |
+
data = request.get_json()
|
| 143 |
+
query = data.get('query', '').strip()
|
| 144 |
+
|
| 145 |
+
# CORREÇÃO 2: Reordenar os argumentos da função. Todos os posicionais primeiro, depois os de palavra-chave.
|
| 146 |
+
results = search_procedure_with_log(
|
| 147 |
+
query,
|
| 148 |
+
DF_ORIGINAL,
|
| 149 |
+
DF_NORMALIZED,
|
| 150 |
+
FUZZY_CORPUS,
|
| 151 |
+
(CORRECTION_CORPUS, NORMALIZED_CORRECTION_CORPUS),
|
| 152 |
+
PORTUGUESE_WORD_SET,
|
| 153 |
+
BM25_MODEL,
|
| 154 |
+
DB_WORD_SET,
|
| 155 |
+
doc_freq, # <-- Novo argumento posicional
|
| 156 |
+
tuss_map, # <-- Novo argumento posicional
|
| 157 |
+
limit_per_layer=10,
|
| 158 |
+
semantic_model=SEMANTIC_MODEL,
|
| 159 |
+
cross_encoder_model=CROSS_ENCODER_MODEL,
|
| 160 |
+
user_best_matches_counts=USER_BEST_MATCHES_COUNTS,
|
| 161 |
+
user_feedback_threshold=USER_FEEDBACK_THRESHOLD
|
| 162 |
+
)
|
| 163 |
+
return jsonify(results)
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print("--- [ERRO FATAL DURANTE A BUSCA] ---"); traceback.print_exc()
|
| 166 |
+
return jsonify({"error": "Ocorreu um erro interno no motor de busca."}), 500
|
| 167 |
+
|
| 168 |
+
@app.route('/submit_feedback', methods=['POST'])
|
| 169 |
+
def submit_feedback_route():
|
| 170 |
+
global DATA_HAS_CHANGED
|
| 171 |
+
try:
|
| 172 |
+
data = request.get_json()
|
| 173 |
+
query, tuss_code_submitted = data.get('query'), data.get('tuss_code')
|
| 174 |
+
if not query or not tuss_code_submitted:
|
| 175 |
+
return jsonify({"status": "error", "message": "Dados incompletos."}), 400
|
| 176 |
+
|
| 177 |
+
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), USER_FEEDBACK_FILE)
|
| 178 |
+
with open(file_path, 'a', newline='', encoding='utf-8') as f:
|
| 179 |
+
writer = csv.writer(f)
|
| 180 |
+
query_normalized = normalize_text_for_feedback(query)
|
| 181 |
+
|
| 182 |
+
tuss_descriptions, rol_names = [], []
|
| 183 |
+
if DF_ORIGINAL is not None:
|
| 184 |
+
matching_rows = DF_ORIGINAL[DF_ORIGINAL['Codigo_TUSS'].astype(str) == tuss_code_submitted]
|
| 185 |
+
if not matching_rows.empty:
|
| 186 |
+
tuss_descriptions = matching_rows['Descricao_TUSS'].unique().tolist()
|
| 187 |
+
rol_names = matching_rows['Procedimento_Rol'].unique().tolist()
|
| 188 |
+
tuss_desc_assoc = " | ".join(filter(None, tuss_descriptions)) or 'Não encontrado'
|
| 189 |
+
rol_names_assoc = " | ".join(filter(None, rol_names)) or 'Não encontrado'
|
| 190 |
+
|
| 191 |
+
writer.writerow([datetime.datetime.now().isoformat(), query, query_normalized, tuss_code_submitted, '', tuss_desc_assoc, rol_names_assoc, 'confirm_result'])
|
| 192 |
+
|
| 193 |
+
DATA_HAS_CHANGED = True
|
| 194 |
+
print(f"--- [DADOS] '{USER_FEEDBACK_FILE}' foi modificado. Commit agendado para o desligamento. ---")
|
| 195 |
+
|
| 196 |
+
load_user_feedback()
|
| 197 |
+
|
| 198 |
+
return jsonify({"status": "success", "message": "Feedback recebido!"}), 200
|
| 199 |
+
except Exception as e:
|
| 200 |
+
print("--- [ERRO NO SUBMIT_FEEDBACK] ---"); traceback.print_exc();
|
| 201 |
+
return jsonify({"status": "error", "message": "Erro interno."}), 500
|
| 202 |
+
|
| 203 |
+
@app.route('/get_tuss_info', methods=['GET'])
|
| 204 |
+
def get_tuss_info():
|
| 205 |
+
tuss_code_prefix = request.args.get('tuss_prefix', '').strip()
|
| 206 |
+
if not tuss_code_prefix: return jsonify([])
|
| 207 |
+
suggestions = []
|
| 208 |
+
if DF_ORIGINAL is not None and not DF_ORIGINAL.empty:
|
| 209 |
+
filtered_df = DF_ORIGINAL[DF_ORIGINAL['Codigo_TUSS'].astype(str).str.startswith(tuss_code_prefix)]
|
| 210 |
+
tuss_grouped = filtered_df.groupby('Codigo_TUSS').agg(tuss_descriptions=('Descricao_TUSS', lambda x: list(x.unique())), rol_names=('Procedimento_Rol', lambda x: list(x.unique()))).reset_index()
|
| 211 |
+
for index, row in tuss_grouped.head(10).iterrows():
|
| 212 |
+
tuss_desc = " | ".join(filter(None, row['tuss_descriptions'])) or 'Sem descrição TUSS'
|
| 213 |
+
rol_name = " | ".join(filter(None, row['rol_names'])) or 'Sem procedimento Rol'
|
| 214 |
+
suggestions.append({'tuss_code': str(row['Codigo_TUSS']), 'tuss_description': tuss_desc, 'rol_name': rol_name})
|
| 215 |
+
return jsonify(suggestions)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
@app.route('/get_ai_suggestion', methods=['POST'])
|
| 219 |
+
def get_ai_suggestion():
|
| 220 |
+
if not client_ia:
|
| 221 |
+
return jsonify({"error": "O serviço de IA não está configurado no servidor."}), 503
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
data = request.get_json()
|
| 225 |
+
query = data.get('query')
|
| 226 |
+
results = data.get('results', [])
|
| 227 |
+
|
| 228 |
+
if not query or not results:
|
| 229 |
+
return jsonify({"error": "A consulta e os resultados são necessários."}), 400
|
| 230 |
+
|
| 231 |
+
RELEVANT_KEYS_FOR_AI = [
|
| 232 |
+
'Codigo_TUSS', 'Descricao_TUSS', 'Procedimento_Rol',
|
| 233 |
+
'CAPITULO', 'GRUPO', 'SUBGRUPO', 'Semantico',
|
| 234 |
+
'Sinonimo_1', 'Sinonimo_2'
|
| 235 |
+
]
|
| 236 |
+
simplified_results = []
|
| 237 |
+
for r in results:
|
| 238 |
+
procedimento_rol_str = str(r.get('Procedimento_Rol', ''))
|
| 239 |
+
unique_id = f"{r.get('Codigo_TUSS')}_{sha1(procedimento_rol_str.encode('utf-8')).hexdigest()[:8]}"
|
| 240 |
+
pruned_result = {
|
| 241 |
+
'unique_id': unique_id,
|
| 242 |
+
**{key: r.get(key) for key in RELEVANT_KEYS_FOR_AI
|
| 243 |
+
if r.get(key) and pd.notna(r.get(key)) and str(r.get(key)).strip() not in ['---', '']}
|
| 244 |
+
}
|
| 245 |
+
if 'Codigo_TUSS' in pruned_result:
|
| 246 |
+
simplified_results.append(pruned_result)
|
| 247 |
+
formatted_results_str = json.dumps(simplified_results, indent=2, ensure_ascii=False)
|
| 248 |
+
system_prompt = (
|
| 249 |
+
"Você é um especialista em terminologia de procedimentos médicos do Brasil (Tabela TUSS e Rol da ANS). "
|
| 250 |
+
"Sua tarefa é analisar uma lista de procedimentos e escolher os 3 que melhor correspondem à consulta do usuário, em ordem de relevância."
|
| 251 |
+
)
|
| 252 |
+
user_prompt = (
|
| 253 |
+
f"Consulta do usuário: \"{query}\"\n\n"
|
| 254 |
+
f"### Resultados da Busca para Análise (JSON):\n{formatted_results_str}\n\n"
|
| 255 |
+
"### Sua Tarefa:\n"
|
| 256 |
+
"1. **Pense em voz alta:** Dentro de uma tag `<thought>`, explique seu processo de raciocínio passo a passo. Analise a consulta e compare os resultados, justificando por que um é mais relevante que o outro com base em seu `Procedimento_Rol` e outros campos.\n"
|
| 257 |
+
"2. **Forneça a resposta final:** Após a tag `<thought>`, seu único resultado deve ser um bloco de código JSON. Este JSON **DEVE** conter 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.\n\n"
|
| 258 |
+
"**EXEMPLO DE RESPOSTA OBRIGATÓRIA:**\n"
|
| 259 |
+
"<thought>\n"
|
| 260 |
+
"O Raciocínio da IA fica aqui...\n"
|
| 261 |
+
"</thought>\n"
|
| 262 |
+
"```json\n"
|
| 263 |
+
"{\n"
|
| 264 |
+
' "suggested_ids": ["30602122_abc12345", "30602360_def67890", "30602033_ghi11223"]\n'
|
| 265 |
+
"}\n"
|
| 266 |
+
"```"
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
completion = client_ia.chat.completions.create(
|
| 270 |
+
model="baidu/ERNIE-4.5-21B-A3B-PT",
|
| 271 |
+
messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
|
| 272 |
+
max_tokens=1500, temperature=0.1
|
| 273 |
+
)
|
| 274 |
+
raw_response = completion.choices[0].message.content.strip()
|
| 275 |
+
|
| 276 |
+
thought_process = "Não foi possível extrair o raciocínio da resposta da IA."
|
| 277 |
+
json_part = None
|
| 278 |
+
|
| 279 |
+
if "<thought>" in raw_response and "</thought>" in raw_response:
|
| 280 |
+
start = raw_response.find("<thought>") + len("<thought>")
|
| 281 |
+
end = raw_response.find("</thought>")
|
| 282 |
+
thought_process = raw_response[start:end].strip()
|
| 283 |
+
|
| 284 |
+
if "```json" in raw_response:
|
| 285 |
+
start = raw_response.find("```json") + len("```json")
|
| 286 |
+
end = raw_response.rfind("```")
|
| 287 |
+
json_str = raw_response[start:end].strip()
|
| 288 |
+
try:
|
| 289 |
+
json_part = json.loads(json_str)
|
| 290 |
+
except json.JSONDecodeError: pass
|
| 291 |
+
|
| 292 |
+
if not json_part or "suggested_ids" not in json_part or not isinstance(json_part.get("suggested_ids"), list) or len(json_part["suggested_ids"]) == 0:
|
| 293 |
+
return jsonify({
|
| 294 |
+
"error": "A IA não retornou a lista de 'suggested_ids' no formato JSON esperado.",
|
| 295 |
+
"details": raw_response
|
| 296 |
+
}), 422
|
| 297 |
+
|
| 298 |
+
response_data = {
|
| 299 |
+
"suggested_ids": json_part["suggested_ids"][:3],
|
| 300 |
+
"thought_process": thought_process,
|
| 301 |
+
"query": query,
|
| 302 |
+
"results": simplified_results
|
| 303 |
+
}
|
| 304 |
+
return jsonify(response_data)
|
| 305 |
+
|
| 306 |
+
except Exception as e:
|
| 307 |
+
print("--- [ERRO FATAL NA SUGESTÃO DA IA] ---"); traceback.print_exc()
|
| 308 |
+
return jsonify({"error": f"Ocorreu um erro interno na IA: {str(e)}"}), 500
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
# --- SEÇÃO DE PERSISTÊNCIA ---
|
| 312 |
+
def commit_file_to_repo(local_file_name, commit_message):
|
| 313 |
+
if not hf_api:
|
| 314 |
+
print(f"--- [AVISO] API do HF não configurada. Pular o commit de '{local_file_name}'. ---")
|
| 315 |
+
return
|
| 316 |
+
local_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), local_file_name)
|
| 317 |
+
if not os.path.exists(local_file_path) or os.path.getsize(local_file_path) == 0:
|
| 318 |
+
print(f"--- [AVISO] Arquivo '{local_file_name}' não existe ou está vazio. Pular commit. ---")
|
| 319 |
+
return
|
| 320 |
+
path_in_repo = local_file_name
|
| 321 |
+
try:
|
| 322 |
+
print(f"--- [API HF] Tentando fazer o commit de '{local_file_name}' para o repositório... ---")
|
| 323 |
+
hf_api.upload_file(
|
| 324 |
+
path_or_fileobj=local_file_path, path_in_repo=path_in_repo,
|
| 325 |
+
repo_id=REPO_ID, repo_type="space", commit_message=commit_message)
|
| 326 |
+
print(f"--- [API HF] Sucesso no commit de '{local_file_name}'. ---")
|
| 327 |
+
except Exception as e:
|
| 328 |
+
print(f"--- [ERRO API HF] Falha no commit de '{local_file_name}': {e} ---")
|
| 329 |
+
|
| 330 |
+
def save_data_on_exit():
|
| 331 |
+
print("--- [SHUTDOWN] O aplicativo está desligando. Verificando dados para salvar... ---")
|
| 332 |
+
if DATA_HAS_CHANGED:
|
| 333 |
+
print("--- [SHUTDOWN] Mudanças detectadas. Fazendo o commit dos arquivos para o repositório. ---")
|
| 334 |
+
commit_file_to_repo(USER_FEEDBACK_FILE, "Commit automático: Atualiza feedbacks de usuários.")
|
| 335 |
+
else:
|
| 336 |
+
print("--- [SHUTDOWN] Nenhuma mudança nos dados detectada. Nenhum commit necessário. ---")
|
| 337 |
+
|
| 338 |
+
atexit.register(save_data_on_exit)
|
| 339 |
+
|
| 340 |
+
if __name__ == '__main__':
|
| 341 |
+
port = int(os.environ.get("PORT", 7860))
|
| 342 |
+
app.run(host='0.0.0.0', port=port, debug=False)
|
enhanced_search_v2.py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# enhanced_search_v2.py (Versão Final Comentada e Corrigida)
|
| 2 |
+
###################################################################################################
|
| 3 |
+
#
|
| 4 |
+
# Este arquivo contém o motor de busca principal. Ele implementa uma estratégia de busca em
|
| 5 |
+
# múltiplas camadas, começando pelas buscas de mais alta confiança (exatas) e progredindo
|
| 6 |
+
# para métodos mais abrangentes (relevância de termos, semântica).
|
| 7 |
+
#
|
| 8 |
+
# A ordenação final é o ponto mais sofisticado, usando uma hierarquia de critérios para
|
| 9 |
+
# garantir os resultados mais relevantes no topo:
|
| 10 |
+
# 1. Prioridade Máxima: Feedback explícito do usuário.
|
| 11 |
+
# 2. Ordenação Primária: Score Semântico (a compreensão da IA sobre o contexto).
|
| 12 |
+
# 3. Desempate 1: Score de Texto (quão bem as palavras correspondem).
|
| 13 |
+
# 4. Desempate 2: Cobertura do Rol (procedimentos do Rol têm preferência).
|
| 14 |
+
#
|
| 15 |
+
# A desduplicação é feita pelo índice da linha da planilha, garantindo que cada indicação
|
| 16 |
+
# única (DUT) seja tratada como um resultado distinto.
|
| 17 |
+
#
|
| 18 |
+
###################################################################################################
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
import re
|
| 22 |
+
from thefuzz import process, fuzz
|
| 23 |
+
from unidecode import unidecode
|
| 24 |
+
import time
|
| 25 |
+
from sentence_transformers import util
|
| 26 |
+
import torch
|
| 27 |
+
import math
|
| 28 |
+
from collections import defaultdict
|
| 29 |
+
from rank_bm25 import BM25Okapi
|
| 30 |
+
|
| 31 |
+
# --- FUNÇÕES AUXILIARES DE NORMALIZAÇÃO --- #
|
| 32 |
+
|
| 33 |
+
def literal_normalize_text(text):
|
| 34 |
+
"""
|
| 35 |
+
Normalização "agressiva" para a Camada 0. Remove tudo exceto letras e números,
|
| 36 |
+
ideal para encontrar correspondências literais exatas, ignorando qualquer formatação.
|
| 37 |
+
"""
|
| 38 |
+
if pd.isna(text): return ""
|
| 39 |
+
normalized = unidecode(str(text).lower())
|
| 40 |
+
normalized = re.sub(r'[^\w\s]', ' ', normalized)
|
| 41 |
+
return re.sub(r'\s+', ' ', normalized).strip()
|
| 42 |
+
|
| 43 |
+
def normalize_text(text):
|
| 44 |
+
"""
|
| 45 |
+
Normalização padrão: remove acentos e converte para minúsculas. Usado em quase todas as buscas.
|
| 46 |
+
"""
|
| 47 |
+
if pd.isna(text): return ""
|
| 48 |
+
return unidecode(str(text).lower().strip())
|
| 49 |
+
|
| 50 |
+
def get_longest_word(query_text):
|
| 51 |
+
"""Função de último recurso (fallback): extrai a palavra mais longa para tentar encontrar algo."""
|
| 52 |
+
words = re.findall(r'\b\w{4,}\b', query_text)
|
| 53 |
+
if not words: return ""
|
| 54 |
+
return max(words, key=len)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# --- FUNÇÕES DE FORMATAÇÃO E DESTAQUE --- #
|
| 58 |
+
|
| 59 |
+
def format_result(row_data, row_index, match_type="", score=0):
|
| 60 |
+
"""
|
| 61 |
+
Formata uma linha do DataFrame em um dicionário de resultado padrão,
|
| 62 |
+
incluindo o índice da linha como identificador único.
|
| 63 |
+
"""
|
| 64 |
+
data = row_data.copy()
|
| 65 |
+
is_rol = data.get('Correlacao_Rol', '').strip().lower() == 'sim'
|
| 66 |
+
|
| 67 |
+
if not is_rol:
|
| 68 |
+
data['Grupo'], data['Subgrupo'], data['Vigencia'], data['Resolucao_Normativa'] = '', '', '', ''
|
| 69 |
+
data['PAC'], data['DUT'] = '---', '---'
|
| 70 |
+
else:
|
| 71 |
+
data['PAC'] = 'Sim' if data.get('PAC', '').strip().lower() == 'pac' else 'Não'
|
| 72 |
+
original_dut_value = data.get('DUT', '').strip()
|
| 73 |
+
if original_dut_value and original_dut_value.replace('.', '', 1).isdigit():
|
| 74 |
+
data['DUT'] = f'Sim, DUT nº {original_dut_value}'
|
| 75 |
+
else: data['DUT'] = 'Não'
|
| 76 |
+
|
| 77 |
+
standard_columns = [
|
| 78 |
+
'Codigo_TUSS', 'Descricao_TUSS', 'Correlacao_Rol', 'Procedimento_Rol',
|
| 79 |
+
'Resolucao_Normativa', 'Vigencia', 'OD', 'AMB', 'HCO', 'HSO', 'PAC',
|
| 80 |
+
'DUT', 'SUBGRUPO', 'GRUPO', 'CAPITULO', 'Sinonimo_1', 'Sinonimo_2',
|
| 81 |
+
'Sinonimo_3', 'Sinonimo_4', 'Semantico'
|
| 82 |
+
]
|
| 83 |
+
formatted_data = {col: data.get(col, '') for col in standard_columns}
|
| 84 |
+
|
| 85 |
+
result = {
|
| 86 |
+
"row_index": row_index,
|
| 87 |
+
"score": round(score),
|
| 88 |
+
"text_score": round(score),
|
| 89 |
+
"semantic_score": 0,
|
| 90 |
+
"match_type": match_type,
|
| 91 |
+
"is_rol_procedure": is_rol
|
| 92 |
+
}
|
| 93 |
+
result.update(formatted_data)
|
| 94 |
+
return result
|
| 95 |
+
|
| 96 |
+
def _highlight_matches(results, query):
|
| 97 |
+
"""Adiciona tags <b></b> para destacar os termos da busca na interface do usuário."""
|
| 98 |
+
if not query or not results: return results
|
| 99 |
+
stopwords = {'de', 'do', 'da', 'dos', 'das', 'a', 'o', 'e', 'em', 'um', 'uma', 'para', 'com'}
|
| 100 |
+
query_words = {word for word in normalize_text(query).split() if len(word) > 2 and word not in stopwords}
|
| 101 |
+
cols_to_highlight = ['Descricao_TUSS', 'Procedimento_Rol', 'Sinonimo_1', 'Sinonimo_2', 'Sinonimo_3', 'Sinonimo_4', 'Semantico']
|
| 102 |
+
for result in results:
|
| 103 |
+
for col in cols_to_highlight:
|
| 104 |
+
original_text = result.get(col, '')
|
| 105 |
+
if original_text and query_words:
|
| 106 |
+
highlighted_text = original_text
|
| 107 |
+
for word in sorted(list(query_words), key=len, reverse=True):
|
| 108 |
+
pattern = r'\b(' + re.escape(word) + r')\b'
|
| 109 |
+
highlighted_text = re.sub(pattern, r'<b>\1</b>', highlighted_text, flags=re.IGNORECASE)
|
| 110 |
+
result[f"{col}_highlighted"] = highlighted_text
|
| 111 |
+
else:
|
| 112 |
+
result[f"{col}_highlighted"] = original_text
|
| 113 |
+
return results
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# --- FUNÇÕES DE CARREGAMENTO DE DADOS --- #
|
| 117 |
+
|
| 118 |
+
def load_and_prepare_database(db_path):
|
| 119 |
+
"""
|
| 120 |
+
Carrega a planilha principal e pré-processa todos os dados necessários para a busca ser rápida.
|
| 121 |
+
Esta função é executada apenas uma vez, quando o aplicativo inicia.
|
| 122 |
+
"""
|
| 123 |
+
try:
|
| 124 |
+
print(f"Carregando e preparando a base de dados de: {db_path}...")
|
| 125 |
+
df_original = pd.read_csv(db_path, dtype=str).fillna('')
|
| 126 |
+
search_cols = ['Descricao_TUSS', 'Procedimento_Rol', 'Sinonimo_1', 'Sinonimo_2', 'Sinonimo_3', 'Sinonimo_4', 'Semantico', 'SUBGRUPO', 'GRUPO', 'CAPITULO']
|
| 127 |
+
df_normalized = df_original.copy()
|
| 128 |
+
df_normalized['Codigo_TUSS_literal'] = df_normalized['Codigo_TUSS'].apply(literal_normalize_text)
|
| 129 |
+
df_normalized['Codigo_TUSS_norm'] = df_normalized['Codigo_TUSS'].apply(normalize_text)
|
| 130 |
+
df_normalized['full_text_norm'] = ""
|
| 131 |
+
for col in search_cols:
|
| 132 |
+
if col in df_normalized.columns:
|
| 133 |
+
df_normalized[f'{col}_literal'] = df_normalized[col].apply(literal_normalize_text)
|
| 134 |
+
df_normalized[f'{col}_norm'] = df_normalized[col].apply(normalize_text)
|
| 135 |
+
df_normalized['full_text_norm'] += ' ' + df_normalized[f'{col}_norm']
|
| 136 |
+
print("Criando dicionário da base, modelo BM25 e frequência de palavras...")
|
| 137 |
+
db_word_set = set(); tokenized_corpus = []
|
| 138 |
+
for text in df_normalized['full_text_norm']:
|
| 139 |
+
words = text.split(); tokenized_corpus.append(words); db_word_set.update(words)
|
| 140 |
+
db_word_set.discard('')
|
| 141 |
+
bm25_model = BM25Okapi(tokenized_corpus)
|
| 142 |
+
doc_freq = defaultdict(int)
|
| 143 |
+
for doc_words in tokenized_corpus:
|
| 144 |
+
for word in set(doc_words): doc_freq[word] += 1
|
| 145 |
+
tuss_to_full_text_map = df_normalized.set_index('Codigo_TUSS')['full_text_norm'].to_dict()
|
| 146 |
+
print("Criando corpus para busca fuzzy...")
|
| 147 |
+
fuzzy_search_corpus = []
|
| 148 |
+
for index, row in df_normalized.iterrows():
|
| 149 |
+
for col in ['Descricao_TUSS', 'Procedimento_Rol', 'Sinonimo_1', 'Sinonimo_2', 'Sinonimo_3', 'Sinonimo_4', 'Semantico']:
|
| 150 |
+
if col in df_original.columns and f'{col}_norm' in row and pd.notna(row[f'{col}_norm']):
|
| 151 |
+
val = row[f'{col}_norm']
|
| 152 |
+
if val: fuzzy_search_corpus.append((val, index, f'{col}_norm'))
|
| 153 |
+
print(f"Base de dados pronta com {len(df_original)} procedimentos.")
|
| 154 |
+
return df_original, df_normalized, fuzzy_search_corpus, bm25_model, db_word_set, doc_freq, tuss_to_full_text_map
|
| 155 |
+
except Exception as e: print(f"Erro crítico ao carregar/preparar a base de dados: {e}"); raise
|
| 156 |
+
|
| 157 |
+
def load_general_dictionary(path):
|
| 158 |
+
try:
|
| 159 |
+
with open(path, 'r', encoding='utf-8') as f: words = {normalize_text(line.strip()) for line in f if line.strip()}
|
| 160 |
+
return words
|
| 161 |
+
except (FileNotFoundError, Exception): return set()
|
| 162 |
+
|
| 163 |
+
def load_correction_corpus(dict_path, column_name='Termo_Correto'):
|
| 164 |
+
try:
|
| 165 |
+
df_dict = pd.read_csv(dict_path, dtype=str).fillna('')
|
| 166 |
+
if column_name not in df_dict.columns: return [], []
|
| 167 |
+
original_corpus = df_dict[column_name].dropna().astype(str).tolist()
|
| 168 |
+
normalized_corpus = [normalize_text(term) for term in original_corpus]
|
| 169 |
+
return original_corpus, normalized_corpus
|
| 170 |
+
except (FileNotFoundError, Exception): return [], []
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# --- FUNÇÕES DE RECLASSIFICAÇÃO SEMÂNTICA (IA) --- #
|
| 174 |
+
|
| 175 |
+
def create_unified_document_text(result_dict):
|
| 176 |
+
"""Cria uma string de texto única para a análise da IA."""
|
| 177 |
+
text_parts = {
|
| 178 |
+
result_dict.get('Descricao_TUSS', ''), result_dict.get('Procedimento_Rol', ''),
|
| 179 |
+
result_dict.get('Semantico', ''), result_dict.get('SUBGRUPO', ''),
|
| 180 |
+
result_dict.get('GRUPO', ''), result_dict.get('CAPITULO', '')
|
| 181 |
+
}
|
| 182 |
+
for i in range(1, 5): text_parts.add(result_dict.get(f'Sinonimo_{i}', ''))
|
| 183 |
+
return ". ".join(sorted([part for part in text_parts if part and str(part).strip()]))
|
| 184 |
+
|
| 185 |
+
def rerank_with_cross_encoder(query, results_list, model):
|
| 186 |
+
"""
|
| 187 |
+
Reclassifica os resultados usando o Cross-Encoder e aplica a lógica de ordenação hierárquica.
|
| 188 |
+
"""
|
| 189 |
+
if not model or not results_list or not query: return results_list, "Cross-Encoder não fornecido ou lista de candidatos vazia."
|
| 190 |
+
sentence_pairs = [[query, create_unified_document_text(result)] for result in results_list]
|
| 191 |
+
if not sentence_pairs: return results_list, "Não foram encontrados pares para reordenar."
|
| 192 |
+
|
| 193 |
+
try:
|
| 194 |
+
raw_scores = model.predict(sentence_pairs, show_progress_bar=False)
|
| 195 |
+
semantic_scores_normalized = torch.sigmoid(torch.tensor(raw_scores)).numpy() * 100
|
| 196 |
+
for i, result in enumerate(results_list):
|
| 197 |
+
# A CORREÇÃO: Apenas o 'semantic_score' é preenchido.
|
| 198 |
+
# O 'score' e o 'text_score' originais são mantidos intactos.
|
| 199 |
+
result['semantic_score'] = round(semantic_scores_normalized[i])
|
| 200 |
+
result['match_type'] = "Relevância Semântica (IA)"
|
| 201 |
+
|
| 202 |
+
key_function = lambda x: (x.get('semantic_score', 0), x.get('text_score', 0), x.get('is_rol_procedure', False))
|
| 203 |
+
reranked_results = sorted(results_list, key=key_function, reverse=True)
|
| 204 |
+
|
| 205 |
+
log_message = "Reordenação final por: 1º Semântica, 2º Texto, 3º Cobertura do Rol."
|
| 206 |
+
return reranked_results, log_message
|
| 207 |
+
|
| 208 |
+
except Exception as e:
|
| 209 |
+
log_message = f"Erro no Cross-Encoder: {e}"; print(log_message)
|
| 210 |
+
return results_list, log_message
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# --- FUNÇÃO INTERNA DE BUSCA COM CAMADAS --- #
|
| 214 |
+
|
| 215 |
+
def _run_search_layers(literal_query, normalized_query, response, df_original, df_normalized, fuzzy_search_corpus, bm25_model, limit_per_layer):
|
| 216 |
+
"""
|
| 217 |
+
Executa a busca em múltiplas camadas, da mais precisa para a mais abrangente.
|
| 218 |
+
"""
|
| 219 |
+
matched_indices = set()
|
| 220 |
+
stopwords = {'de', 'do', 'da', 'dos', 'das', 'a', 'o', 'e', 'em', 'um', 'uma', 'para', 'com'}
|
| 221 |
+
query_words = [word for word in normalized_query.split() if word not in stopwords and len(word) > 1]
|
| 222 |
+
|
| 223 |
+
def sort_key(x):
|
| 224 |
+
return (x.get('score', 0), x.get('is_rol_procedure', False))
|
| 225 |
+
|
| 226 |
+
for layer in ["literal_matches", "exact_matches", "logical_matches", "almost_exact_matches", "term_matches", "keyword_matches"]:
|
| 227 |
+
response["results_by_layer"][layer] = []
|
| 228 |
+
|
| 229 |
+
# CAMADA 0: Busca Literal Exata
|
| 230 |
+
temp_results = []
|
| 231 |
+
if literal_query:
|
| 232 |
+
for col in ['Codigo_TUSS_literal', 'Descricao_TUSS_literal', 'Procedimento_Rol_literal']:
|
| 233 |
+
if col in df_normalized.columns:
|
| 234 |
+
for index, _ in df_normalized[df_normalized[col] == literal_query].iterrows():
|
| 235 |
+
if index not in matched_indices: temp_results.append(format_result(df_original.loc[index], index, "Texto Exato", 100)); matched_indices.add(index)
|
| 236 |
+
response["results_by_layer"]["literal_matches"] = sorted(temp_results, key=sort_key, reverse=True)[:limit_per_layer]
|
| 237 |
+
|
| 238 |
+
# CAMADA 1: Busca Normalizada Exata
|
| 239 |
+
temp_results = []
|
| 240 |
+
if normalized_query:
|
| 241 |
+
for index, _ in df_normalized[df_normalized['Codigo_TUSS_norm'] == normalized_query].iterrows():
|
| 242 |
+
if index not in matched_indices: temp_results.append(format_result(df_original.loc[index], index, "Código Exato", 100)); matched_indices.add(index)
|
| 243 |
+
for col in ['Descricao_TUSS_norm', 'Procedimento_Rol_norm']:
|
| 244 |
+
if col in df_normalized.columns:
|
| 245 |
+
for index, _ in df_normalized[df_normalized[col] == normalized_query].iterrows():
|
| 246 |
+
if index not in matched_indices: temp_results.append(format_result(df_original.loc[index], index, "Exato (Normalizado)", 100)); matched_indices.add(index)
|
| 247 |
+
response["results_by_layer"]["exact_matches"] = sorted(temp_results, key=sort_key, reverse=True)[:limit_per_layer]
|
| 248 |
+
|
| 249 |
+
# CAMADA 2: Busca Lógica (E)
|
| 250 |
+
temp_results = []
|
| 251 |
+
if query_words:
|
| 252 |
+
mask = pd.Series(True, index=df_normalized.index)
|
| 253 |
+
for word in query_words: mask &= df_normalized['full_text_norm'].str.contains(r'\b' + re.escape(word) + r'\b', na=False)
|
| 254 |
+
for index, row in df_normalized[mask & ~df_normalized.index.isin(matched_indices)].iterrows():
|
| 255 |
+
score = fuzz.WRatio(normalized_query, row.get('full_text_norm', '')); temp_results.append(format_result(df_original.loc[index], index, "Busca Lógica", score)); matched_indices.add(index)
|
| 256 |
+
response["results_by_layer"]["logical_matches"] = sorted(temp_results, key=sort_key, reverse=True)[:limit_per_layer]
|
| 257 |
+
|
| 258 |
+
# CAMADA 3: Busca por Aproximação (Fuzzy)
|
| 259 |
+
temp_results, processed_indices = [], set()
|
| 260 |
+
if fuzzy_search_corpus:
|
| 261 |
+
for match_text, score in process.extractBests(normalized_query, [item[0] for item in fuzzy_search_corpus], scorer=fuzz.token_set_ratio, limit=limit_per_layer * 3, score_cutoff=90):
|
| 262 |
+
if score == 100 and match_text == normalized_query: continue
|
| 263 |
+
for _, original_index, _ in [item for item in fuzzy_search_corpus if item[0] == match_text]:
|
| 264 |
+
if original_index not in matched_indices and original_index not in processed_indices: temp_results.append(format_result(df_original.loc[original_index], original_index, "Busca por Aproximação", 98)); matched_indices.add(original_index); processed_indices.add(original_index)
|
| 265 |
+
response["results_by_layer"]["almost_exact_matches"] = sorted(temp_results, key=sort_key, reverse=True)[:limit_per_layer]
|
| 266 |
+
|
| 267 |
+
# CAMADA 4: Busca por Relevância de Termos (BM25)
|
| 268 |
+
temp_results = []
|
| 269 |
+
if query_words and bm25_model:
|
| 270 |
+
doc_scores = bm25_model.get_scores(normalized_query.split()); max_score = max(doc_scores) if any(doc_scores) else 1.0
|
| 271 |
+
for i, score in enumerate(doc_scores):
|
| 272 |
+
if score > 0 and (original_index := df_normalized.index[i]) not in matched_indices:
|
| 273 |
+
normalized_score = (score / max_score) * 90 if max_score > 0 else 0; temp_results.append(format_result(df_original.loc[original_index], original_index, "Relevância de Termos", normalized_score)); matched_indices.add(original_index)
|
| 274 |
+
response["results_by_layer"]["term_matches"] = sorted(temp_results, key=sort_key, reverse=True)[:limit_per_layer * 4]
|
| 275 |
+
|
| 276 |
+
# CAMADA 5: Fallback por Palavra-Chave
|
| 277 |
+
if sum(len(v) for k, v in response["results_by_layer"].items()) == 0 and normalized_query:
|
| 278 |
+
if longest_word := get_longest_word(normalized_query):
|
| 279 |
+
temp_results = []
|
| 280 |
+
for index, row in df_normalized[df_normalized['full_text_norm'].str.contains(r'\b' + re.escape(longest_word) + r'\b', na=False) & ~df_normalized.index.isin(matched_indices)].iterrows():
|
| 281 |
+
temp_results.append(format_result(df_original.loc[index], index, f"Palavra-Chave", 80))
|
| 282 |
+
response["results_by_layer"]["keyword_matches"] = sorted(temp_results, key=sort_key, reverse=True)[:limit_per_layer]
|
| 283 |
+
return None
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
# --- FUNÇÃO PRINCIPAL QUE ORQUESTRA A BUSCA --- #
|
| 287 |
+
|
| 288 |
+
def search_procedure_with_log(query, df_original, df_normalized, fuzzy_search_corpus, correction_corpus,
|
| 289 |
+
portuguese_word_set, bm25_model, db_word_set,
|
| 290 |
+
doc_freq, tuss_to_full_text_map,
|
| 291 |
+
limit_per_layer=10,
|
| 292 |
+
semantic_model=None,
|
| 293 |
+
cross_encoder_model=None,
|
| 294 |
+
user_best_matches_counts=None, user_feedback_threshold=10):
|
| 295 |
+
RERANK_LIMIT = 50; start_time = time.time(); original_query = str(query).strip()
|
| 296 |
+
response = {"search_log": [], "results_by_layer": {}, "final_semantic_results": [], "was_corrected": False, "original_query": original_query, "corrected_query": ""}
|
| 297 |
+
if not original_query: response["search_log"].append("Query vazia."); return response
|
| 298 |
+
response["search_log"].append(f"Buscando por: '{original_query}'")
|
| 299 |
+
|
| 300 |
+
# ETAPA 1: CORREÇÃO ORTOGRÁFICA
|
| 301 |
+
stopwords = {'de', 'do', 'da', 'dos', 'das', 'a', 'o', 'e', 'em', 'um', 'uma', 'para', 'com'}; query_after_correction = original_query
|
| 302 |
+
original_correction_corpus, normalized_correction_corpus = correction_corpus; valid_words = portuguese_word_set.union(db_word_set)
|
| 303 |
+
if valid_words and original_correction_corpus:
|
| 304 |
+
words, corrected_words, made_correction = query_after_correction.split(), [], False
|
| 305 |
+
for word in words:
|
| 306 |
+
norm_word = normalize_text(word)
|
| 307 |
+
clean_norm_word = re.sub(r'[^\w]', '', norm_word)
|
| 308 |
+
if len(norm_word) < 4 or norm_word in stopwords or clean_norm_word in valid_words:
|
| 309 |
+
corrected_words.append(word); continue
|
| 310 |
+
|
| 311 |
+
match_norm, score = process.extractOne(clean_norm_word, normalized_correction_corpus, scorer=fuzz.token_set_ratio)
|
| 312 |
+
if score >= 85:
|
| 313 |
+
corrected_word = original_correction_corpus[normalized_correction_corpus.index(match_norm)]
|
| 314 |
+
if word.istitle(): corrected_word = corrected_word.title()
|
| 315 |
+
elif word.isupper(): corrected_word = corrected_word.upper()
|
| 316 |
+
corrected_words.append(corrected_word); made_correction = True
|
| 317 |
+
else: corrected_words.append(word)
|
| 318 |
+
if made_correction: query_after_correction = " ".join(corrected_words); response.update({"was_corrected": True, "corrected_query": query_after_correction}); response["search_log"].append(f"Query corrigida para: '{query_after_correction}'.")
|
| 319 |
+
|
| 320 |
+
# ETAPA 2: PREPARAÇÃO DAS QUERIES
|
| 321 |
+
cleaned_query = " ".join([word for word in query_after_correction.split() if normalize_text(word) not in stopwords]); normalized_query = normalize_text(cleaned_query)
|
| 322 |
+
if not cleaned_query.strip(): response["search_log"].append("Query resultante vazia."); return response
|
| 323 |
+
if cleaned_query != query_after_correction: response["search_log"].append(f"Query limpa (sem stop words): '{cleaned_query}'")
|
| 324 |
+
|
| 325 |
+
# ETAPA 3: EXECUÇÃO DA BUSCA
|
| 326 |
+
_run_search_layers(literal_normalize_text(query_after_correction), normalized_query, response, df_original, df_normalized, fuzzy_search_corpus, bm25_model, limit_per_layer)
|
| 327 |
+
|
| 328 |
+
# ETAPA 4: AGREGAÇÃO E REORDENAÇÃO HÍBRIDA
|
| 329 |
+
layer_names_pt = {
|
| 330 |
+
"literal_matches": "Busca Literal Exata", "exact_matches": "Busca Normalizada Exata",
|
| 331 |
+
"logical_matches": "Busca Lógica", "almost_exact_matches": "Busca por Aproximação",
|
| 332 |
+
"term_matches": "Busca por Relevância de Termos", "keyword_matches": "Busca por Palavra-Chave"
|
| 333 |
+
}
|
| 334 |
+
response["search_log"].append("\n--- Detalhamento por Camada ---")
|
| 335 |
+
for key, name in layer_names_pt.items(): response["search_log"].append(f"Camada '{name}': {len(response['results_by_layer'].get(key, []))} candidatos.")
|
| 336 |
+
|
| 337 |
+
all_candidates = []
|
| 338 |
+
high_confidence_results = response["results_by_layer"].get("literal_matches", []) + response["results_by_layer"].get("exact_matches", [])
|
| 339 |
+
if high_confidence_results:
|
| 340 |
+
response["search_log"].append("\n--- [MODO DE ALTA CONFIANÇA] ---"); all_candidates = high_confidence_results
|
| 341 |
+
else:
|
| 342 |
+
response["search_log"].append("\n--- [MODO DE BUSCA AMPLA] ---")
|
| 343 |
+
for key in layer_names_pt.keys():
|
| 344 |
+
if key not in ["literal_matches", "exact_matches"]: all_candidates.extend(response["results_by_layer"].get(key, []))
|
| 345 |
+
|
| 346 |
+
# Desduplicação por índice de linha para garantir que cada indicação seja única.
|
| 347 |
+
unique_candidates = list({r['row_index']: r for r in all_candidates}.values())
|
| 348 |
+
response["search_log"].append(f"Total de candidatos encontrados: {len(all_candidates)}. Candidatos únicos (após desduplicação): {len(unique_candidates)}.")
|
| 349 |
+
|
| 350 |
+
if user_best_matches_counts:
|
| 351 |
+
query_norm_fb = normalize_text(response.get("corrected_query") or original_query)
|
| 352 |
+
for r in unique_candidates:
|
| 353 |
+
votes = user_best_matches_counts.get(query_norm_fb, {}).get(r['Codigo_TUSS'], 0)
|
| 354 |
+
if votes >= user_feedback_threshold: r.update({'is_user_best_match': True, 'feedback_votes': votes})
|
| 355 |
+
|
| 356 |
+
response["search_log"].append(f"\n--- Análise e Reordenação ---")
|
| 357 |
+
|
| 358 |
+
final_list = []
|
| 359 |
+
if unique_candidates:
|
| 360 |
+
query_for_semantic = response.get("corrected_query") or cleaned_query
|
| 361 |
+
|
| 362 |
+
prioritized_by_feedback = sorted([r for r in unique_candidates if r.get('is_user_best_match')], key=lambda x: (x.get('feedback_votes', 0), x.get('semantic_score', 0), x.get('text_score', 0)), reverse=True)
|
| 363 |
+
to_rerank = [r for r in unique_candidates if not r.get('is_user_best_match')]
|
| 364 |
+
|
| 365 |
+
final_list.extend(prioritized_by_feedback)
|
| 366 |
+
if prioritized_by_feedback: response["search_log"].append(f"{len(prioritized_by_feedback)} resultado(s) priorizado(s) por feedback.")
|
| 367 |
+
|
| 368 |
+
if to_rerank:
|
| 369 |
+
to_rerank_sorted = sorted(to_rerank, key=lambda x: x.get('text_score', 0), reverse=True)
|
| 370 |
+
reranked_by_ia, log_msg = rerank_with_cross_encoder(query_for_semantic, to_rerank_sorted[:RERANK_LIMIT], cross_encoder_model)
|
| 371 |
+
response["search_log"].append(log_msg)
|
| 372 |
+
final_list.extend(reranked_by_ia)
|
| 373 |
+
|
| 374 |
+
response["final_semantic_results"] = _highlight_matches(final_list[:15], query_for_semantic)
|
| 375 |
+
end_time = time.time(); response["search_duration_seconds"] = round(end_time - start_time, 4)
|
| 376 |
+
response["search_log"].append(f"Busca completa em {response['search_duration_seconds']} segundos.")
|
| 377 |
+
print(f"\n\n==================== LOG DE DEPURAÇÃO (QUERY: '{original_query}') ====================")
|
| 378 |
+
for log_item in response["search_log"]: print(log_item)
|
| 379 |
+
return response
|