Spaces:
Sleeping
Sleeping
| import csv | |
| import os | |
| from datetime import datetime | |
| BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| LOGS_DIR = os.path.join(BASE_DIR, "logs") | |
| SEARCH_LOG_FILE = os.path.join(LOGS_DIR, "search_logs.csv") | |
| def garantir_pasta_logs(): | |
| os.makedirs(LOGS_DIR, exist_ok=True) | |
| def inicializar_arquivo_logs(): | |
| garantir_pasta_logs() | |
| if not os.path.exists(SEARCH_LOG_FILE): | |
| with open(SEARCH_LOG_FILE, "w", newline="", encoding="utf-8") as f: | |
| writer = csv.writer(f) | |
| writer.writerow([ | |
| "timestamp", | |
| "query", | |
| "categoria_inferida", | |
| "answer", | |
| "top1_id", | |
| "top1_name", | |
| "top2_id", | |
| "top2_name", | |
| "top3_id", | |
| "top3_name" | |
| ]) | |
| def salvar_log_busca(resultado): | |
| inicializar_arquivo_logs() | |
| produtos = resultado.get("products", []) | |
| def get_prod(i, campo): | |
| if i < len(produtos): | |
| return produtos[i].get(campo, "") | |
| return "" | |
| with open(SEARCH_LOG_FILE, "a", newline="", encoding="utf-8") as f: | |
| writer = csv.writer(f) | |
| writer.writerow([ | |
| datetime.now().isoformat(), | |
| resultado.get("query", ""), | |
| resultado.get("categoria_inferida", ""), | |
| resultado.get("answer", ""), | |
| get_prod(0, "product_id"), | |
| get_prod(0, "product_name"), | |
| get_prod(1, "product_id"), | |
| get_prod(1, "product_name"), | |
| get_prod(2, "product_id"), | |
| get_prod(2, "product_name"), | |
| ]) | |
| return {"status": "ok"} |