textUtils.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import json
  2. from typing import TYPE_CHECKING
  3. if TYPE_CHECKING:
  4. from core.connection import ConnectionHandler
  5. TAG = __name__
  6. EMOJI_MAP = {
  7. "😂": "funny",
  8. "😭": "crying",
  9. "😠": "angry",
  10. "😔": "sad",
  11. "😍": "loving",
  12. "😲": "surprised",
  13. "😱": "shocked",
  14. "🤔": "thinking",
  15. "😌": "relaxed",
  16. "😴": "sleepy",
  17. "😜": "silly",
  18. "🙄": "confused",
  19. "😶": "neutral",
  20. "🙂": "happy",
  21. "😆": "laughing",
  22. "😳": "embarrassed",
  23. "😉": "winking",
  24. "😎": "cool",
  25. "🤤": "delicious",
  26. "😘": "kissy",
  27. "😏": "confident",
  28. }
  29. EMOJI_RANGES = [
  30. (0x1F600, 0x1F64F),
  31. (0x1F300, 0x1F5FF),
  32. (0x1F680, 0x1F6FF),
  33. (0x1F900, 0x1F9FF),
  34. (0x1FA70, 0x1FAFF),
  35. (0x2600, 0x26FF),
  36. (0x2700, 0x27BF),
  37. ]
  38. def get_string_no_punctuation_or_emoji(s):
  39. """去除字符串首尾的空格、标点符号和表情符号"""
  40. chars = list(s)
  41. # 处理开头的字符
  42. start = 0
  43. while start < len(chars) and is_punctuation_or_emoji(chars[start]):
  44. start += 1
  45. # 处理结尾的字符
  46. end = len(chars) - 1
  47. while end >= start and is_punctuation_or_emoji(chars[end]):
  48. end -= 1
  49. return "".join(chars[start : end + 1])
  50. def is_punctuation_or_emoji(char):
  51. """检查字符是否为空格、指定标点或表情符号"""
  52. # 定义需要去除的中英文标点(包括全角/半角)
  53. punctuation_set = {
  54. ",",
  55. ",", # 中文逗号 + 英文逗号
  56. "。",
  57. ".", # 中文句号 + 英文句号
  58. "!",
  59. "!", # 中文感叹号 + 英文感叹号
  60. "“",
  61. "”",
  62. '"', # 中文双引号 + 英文引号
  63. ":",
  64. ":", # 中文冒号 + 英文冒号
  65. "-",
  66. "-", # 英文连字符 + 中文全角横线
  67. "、", # 中文顿号
  68. "[",
  69. "]", # 方括号
  70. "【",
  71. "】", # 中文方括号
  72. }
  73. if char.isspace() or char in punctuation_set:
  74. return True
  75. return is_emoji(char)
  76. async def get_emotion(conn: "ConnectionHandler", text):
  77. """获取文本内的情绪消息"""
  78. emoji = "🙂"
  79. emotion = "happy"
  80. for char in text:
  81. if char in EMOJI_MAP:
  82. emoji = char
  83. emotion = EMOJI_MAP[char]
  84. break
  85. try:
  86. await conn.websocket.send(
  87. json.dumps(
  88. {
  89. "type": "llm",
  90. "text": emoji,
  91. "emotion": emotion,
  92. "session_id": conn.session_id,
  93. }
  94. )
  95. )
  96. except Exception as e:
  97. conn.logger.bind(tag=TAG).warning(f"发送情绪表情失败,错误:{e}")
  98. return
  99. def is_emoji(char):
  100. """检查字符是否为emoji表情"""
  101. code_point = ord(char)
  102. return any(start <= code_point <= end for start, end in EMOJI_RANGES)
  103. def check_emoji(text):
  104. """去除文本中的所有emoji表情"""
  105. return "".join(char for char in text if not is_emoji(char) and char != "\n")