File size: 1,719 Bytes
4402d23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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"}