Spaces:
Sleeping
Sleeping
| import os | |
| from datetime import datetime | |
| # Garante a compatibilidade do caminho do log entre os ambientes | |
| LOG_FILE_PATH = "/tmp/recommender.log" | |
| if os.name == 'nt': | |
| LOG_FILE_PATH = "recommender.log" | |
| def save_log(user_id: int, history: dict, response: str): | |
| log_entry = ( | |
| f"[{datetime.now().isoformat(sep=' ', timespec='seconds')}]\n" | |
| f"Usuário: {user_id}\n" | |
| f"Histórico: {history}\n" | |
| f"Recomendação: {response.strip()}\n" | |
| f"{'-'*40}\n" | |
| ) | |
| with open(LOG_FILE_PATH, "a", encoding="utf-8") as f: | |
| f.write(log_entry) | |
| def get_user_history(user_id: int) -> dict: | |
| history = {} | |
| try: | |
| with open(LOG_FILE_PATH, "r", encoding="utf-8") as f: | |
| lines = f.readlines() | |
| # Itera de trás para frente para pegar a entrada mais recente | |
| for i in range(len(lines) - 1, -1, -1): | |
| line = lines[i] | |
| # Procura pela linha de Usuário | |
| if line.startswith(f"Usuário: {user_id}"): | |
| # Se achou o usuário, procura o histórico nas linhas seguintes (que no reverse são anteriores) | |
| # Mas como a estrutura é fixa (Usuário -> Histórico), o Histórico está na linha i+1 | |
| if i + 1 < len(lines) and lines[i+1].startswith("Histórico:"): | |
| try: | |
| history_str = lines[i+1].split(":", 1)[1].strip() | |
| history = eval(history_str) | |
| return history # Retorna imediatamente a última versão encontrada | |
| except Exception as e: | |
| print(f"Erro ao ler histórico: {e}") | |
| continue | |
| except FileNotFoundError: | |
| pass | |
| return history | |
| def get_all_users() -> dict: | |
| users = {} | |
| try: | |
| with open(LOG_FILE_PATH, "r", encoding="utf-8") as f: | |
| lines = f.readlines() | |
| current_user = None | |
| for i, line in enumerate(lines): | |
| if line.startswith("Usuário:"): | |
| current_user = int(line.split(":")[1].strip()) | |
| elif line.startswith("Histórico:") and current_user is not None: | |
| history = eval(line.split(":", 1)[1].strip()) | |
| users[current_user] = history | |
| except FileNotFoundError: | |
| pass | |
| return users | |