Spaces:
Sleeping
Sleeping
| import csv | |
| import os | |
| import tempfile | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| DEFAULT_LOGS_DIR = Path(os.getenv("LOGS_DIR", "/data/logs")) | |
| FALLBACK_LOGS_DIR = Path(tempfile.gettempdir()) / "tcc2_agent" / "logs" | |
| def _resolve_logs_dir(): | |
| preferred_dir = os.environ.get("LOGS_DIR", "").strip() | |
| candidates = [Path(preferred_dir)] if preferred_dir else [] | |
| candidates.extend([DEFAULT_LOGS_DIR, FALLBACK_LOGS_DIR]) | |
| for directory in candidates: | |
| try: | |
| directory.mkdir(parents=True, exist_ok=True) | |
| return directory | |
| except OSError: | |
| continue | |
| raise OSError( | |
| "Nao foi possivel criar um diretorio para armazenar a memoria negativa. " | |
| "Defina LOGS_DIR para um caminho gravavel." | |
| ) | |
| def caminho_memoria_negativa(): | |
| return str(_resolve_logs_dir() / "negative_memory.csv") | |
| def inicializar_memoria_negativa(): | |
| memory_file = caminho_memoria_negativa() | |
| if not os.path.exists(memory_file): | |
| with open(memory_file, "w", newline="", encoding="utf-8") as f: | |
| writer = csv.writer(f) | |
| writer.writerow([ | |
| "timestamp", | |
| "search_id", | |
| "rank", | |
| "query", | |
| "product_id", | |
| "product_name", | |
| "rating", | |
| "motivo", | |
| ]) | |
| def salvar_memoria_negativa( | |
| query, | |
| product_id, | |
| product_name, | |
| rating, | |
| motivo="feedback_negativo", | |
| search_id=None, | |
| rank=None, | |
| ): | |
| inicializar_memoria_negativa() | |
| memory_file = caminho_memoria_negativa() | |
| row = [ | |
| datetime.now(timezone.utc).isoformat(), | |
| search_id or "", | |
| rank if rank is not None else "", | |
| query or "", | |
| product_id or "", | |
| product_name or "", | |
| rating if rating is not None else "", | |
| motivo or "feedback_negativo", | |
| ] | |
| try: | |
| with open(memory_file, "a", newline="", encoding="utf-8") as f: | |
| writer = csv.writer(f) | |
| writer.writerow(row) | |
| except Exception as e: | |
| print("Erro ao salvar memoria negativa:", e) | |
| return {"status": "ok"} |