user_manager.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:fenc=utf-8
  4. from typing import Dict, Optional, Tuple, Any
  5. import json
  6. import time
  7. import os
  8. import abc
  9. class UserManager(abc.ABC):
  10. @abc.abstractmethod
  11. def get_user_profile(self, user_id) -> Dict:
  12. pass
  13. @abc.abstractmethod
  14. def save_user_profile(self, user_id, profile: Dict) -> None:
  15. pass
  16. @abc.abstractmethod
  17. def list_all_users(self):
  18. pass
  19. class LocalUserManager(UserManager):
  20. def get_user_profile(self, user_id) -> Dict:
  21. """加载用户个人资料,如不存在则创建默认资料。主要用于本地调试"""
  22. try:
  23. with open(f"user_profiles/{user_id}.json", "r", encoding="utf-8") as f:
  24. return json.load(f)
  25. except FileNotFoundError:
  26. # 创建默认用户资料
  27. default_profile = {
  28. "name": "",
  29. "nickname": "",
  30. "preferred_nickname": "",
  31. "age": 0,
  32. "region": '',
  33. "interests": [],
  34. "family_members": {},
  35. "health_conditions": [],
  36. "medications": [],
  37. "reminder_preferences": {
  38. "medication": True,
  39. "health": True,
  40. "weather": True,
  41. "news": False
  42. },
  43. "interaction_style": "standard", # standard, verbose, concise
  44. "interaction_frequency": "medium", # low, medium, high
  45. "last_topics": [],
  46. "created_at": int(time.time() * 1000),
  47. "human_intervention_history": []
  48. }
  49. self.save_user_profile(user_id, default_profile)
  50. return default_profile
  51. def save_user_profile(self, user_id, profile: Dict) -> None:
  52. if not user_id:
  53. raise Exception("Invalid user_id: {}".format(user_id))
  54. with open(f"user_profiles/{user_id}.json", "w", encoding="utf-8") as f:
  55. json.dump(profile, f, ensure_ascii=False, indent=2)
  56. def list_all_users(self):
  57. json_files = []
  58. for root, dirs, files in os.walk('user_profiles/'):
  59. for file in files:
  60. if file.endswith('.json'):
  61. json_files.append(os.path.splitext(file)[0])
  62. return json_files