demo.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 智能邮件助手 - 演示版本
  5. EmailSmartAssistant - Demo Version
  6. 无需配置真实邮箱,直接体验所有功能
  7. """
  8. import json
  9. import re
  10. from datetime import datetime, timedelta
  11. from collections import Counter
  12. class EmailDemo:
  13. def __init__(self):
  14. self.demo_emails = [
  15. {
  16. 'id': '1',
  17. 'subject': '紧急:项目进度汇报会议安排',
  18. 'sender': 'manager@company.com',
  19. 'date': '2024-01-15 09:00:00',
  20. 'body': '各位同事,请准备明天下午2点的项目进度汇报会议。需要准备本周工作总结和下周计划。截止时间:2024-01-16 14:00。请确认参会。'
  21. },
  22. {
  23. 'id': '2',
  24. 'subject': '客户咨询:产品功能详情',
  25. 'sender': 'customer@client.com',
  26. 'date': '2024-01-15 10:30:00',
  27. 'body': '您好,我对贵公司的产品很感兴趣,希望了解更多功能详情。请问可以安排一次产品演示吗?我的联系方式:13800138000。期待您的回复。'
  28. },
  29. {
  30. 'id': '3',
  31. 'subject': '系统维护通知',
  32. 'sender': 'noreply@system.com',
  33. 'date': '2024-01-15 11:00:00',
  34. 'body': '系统将于2024-01-20 02:00-04:00进行维护升级,期间服务可能中断。请提前做好准备工作。如有疑问请联系技术支持。'
  35. },
  36. {
  37. 'id': '4',
  38. 'subject': '限时优惠!立即购买享受8折优惠',
  39. 'sender': 'promotion@ads.com',
  40. 'date': '2024-01-15 12:00:00',
  41. 'body': '亲爱的用户,我们的产品正在进行限时促销活动!现在购买可享受8折优惠,机会难得,不要错过!点击链接立即购买。'
  42. },
  43. {
  44. 'id': '5',
  45. 'subject': '个人:周末聚餐安排',
  46. 'sender': 'friend@personal.com',
  47. 'date': '2024-01-15 13:00:00',
  48. 'body': '嗨!这个周末我们一起聚餐吧,时间定在周六晚上7点,地点在市中心的那家川菜馆。请确认是否能参加,我好提前订位。'
  49. },
  50. {
  51. 'id': '6',
  52. 'subject': 'Urgent: Meeting Request',
  53. 'sender': 'boss@company.com',
  54. 'date': '2024-01-15 14:00:00',
  55. 'body': 'Hi team, we need to schedule an urgent meeting tomorrow at 3 PM to discuss the quarterly results. Please prepare your reports and confirm attendance by 5 PM today.'
  56. }
  57. ]
  58. self.classification_rules = {
  59. 'work_keywords': ['会议', '项目', '工作', '任务', '汇报', 'meeting', 'project', 'work', 'task', 'urgent'],
  60. 'customer_keywords': ['客户', '咨询', '购买', '服务', 'customer', 'inquiry', 'purchase', 'service'],
  61. 'personal_keywords': ['个人', '家庭', '朋友', 'personal', 'family', 'friend', '聚餐'],
  62. 'spam_keywords': ['广告', '推广', '营销', '优惠', 'advertisement', 'promotion', 'marketing', '折扣']
  63. }
  64. self.reply_templates = {
  65. 'work': {
  66. 'zh': '感谢您的邮件。关于{subject},我已收到您的信息。我将在24小时内回复您详细的反馈。如有紧急事项,请随时联系我。\n\n此致\n敬礼',
  67. 'en': 'Thank you for your email regarding {subject}. I have received your information and will provide detailed feedback within 24 hours. Please feel free to contact me if there are any urgent matters.\n\nBest regards'
  68. },
  69. 'customer': {
  70. 'zh': '尊敬的客户,\n\n感谢您对我们产品/服务的关注。关于您咨询的{subject},我们将安排专业人员在24小时内为您提供详细解答。\n\n如有其他问题,欢迎随时联系我们。\n\n此致\n敬礼',
  71. 'en': 'Dear Valued Customer,\n\nThank you for your interest in our products/services. Regarding your inquiry about {subject}, we will arrange for a professional to provide you with detailed answers within 24 hours.\n\nPlease feel free to contact us if you have any other questions.\n\nBest regards'
  72. },
  73. 'general': {
  74. 'zh': '您好,\n\n已收到您的邮件,我将仔细阅读并在24小时内回复。\n\n谢谢!',
  75. 'en': 'Hello,\n\nI have received your email and will read it carefully and reply within 24 hours.\n\nThank you!'
  76. }
  77. }
  78. def classify_email(self, email):
  79. """邮件分类"""
  80. subject = email['subject'].lower()
  81. body = email['body'].lower()
  82. sender = email['sender'].lower()
  83. text_content = f"{subject} {body}"
  84. # 检查垃圾邮件
  85. spam_score = sum(1 for keyword in self.classification_rules['spam_keywords']
  86. if keyword in text_content)
  87. if spam_score >= 2:
  88. return {'type': 'spam', 'priority': 'low', 'sender_type': 'external'}
  89. # 检查工作邮件
  90. work_score = sum(1 for keyword in self.classification_rules['work_keywords']
  91. if keyword in text_content)
  92. # 检查客户邮件
  93. customer_score = sum(1 for keyword in self.classification_rules['customer_keywords']
  94. if keyword in text_content)
  95. # 检查个人邮件
  96. personal_score = sum(1 for keyword in self.classification_rules['personal_keywords']
  97. if keyword in text_content)
  98. # 确定类型
  99. scores = {'work': work_score, 'customer': customer_score, 'personal': personal_score}
  100. email_type = max(scores, key=scores.get) if max(scores.values()) > 0 else 'other'
  101. # 确定优先级
  102. priority = 'high' if any(word in text_content for word in ['紧急', 'urgent', 'asap', '重要']) else 'medium'
  103. if email_type == 'spam':
  104. priority = 'low'
  105. # 确定发件人类型
  106. if 'company.com' in sender:
  107. sender_type = 'colleague'
  108. elif 'noreply' in sender or 'no-reply' in sender:
  109. sender_type = 'system'
  110. elif email_type == 'customer':
  111. sender_type = 'customer'
  112. else:
  113. sender_type = 'external'
  114. return {
  115. 'type': email_type,
  116. 'priority': priority,
  117. 'sender_type': sender_type
  118. }
  119. def extract_info(self, email):
  120. """提取关键信息"""
  121. body = email['body']
  122. # 提取日期
  123. date_patterns = [
  124. r'\d{4}-\d{1,2}-\d{1,2}',
  125. r'\d{1,2}月\d{1,2}日',
  126. r'\d{1,2}/\d{1,2}'
  127. ]
  128. dates = []
  129. for pattern in date_patterns:
  130. dates.extend(re.findall(pattern, body))
  131. # 提取时间
  132. time_patterns = [
  133. r'\d{1,2}:\d{2}',
  134. r'\d{1,2}点',
  135. r'\d{1,2} PM',
  136. r'\d{1,2} AM'
  137. ]
  138. times = []
  139. for pattern in time_patterns:
  140. times.extend(re.findall(pattern, body))
  141. # 提取联系方式
  142. phones = re.findall(r'1[3-9]\d{9}', body)
  143. emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', body)
  144. # 提取待办事项(包含关键词的句子)
  145. todo_keywords = ['需要', '请', '准备', 'need', 'please', 'prepare', '确认']
  146. sentences = body.replace('。', '.').split('.')
  147. todos = []
  148. for sentence in sentences:
  149. if any(keyword in sentence for keyword in todo_keywords):
  150. clean_sentence = sentence.strip()
  151. if len(clean_sentence) > 5:
  152. todos.append(clean_sentence)
  153. return {
  154. 'dates': dates,
  155. 'times': times,
  156. 'phones': phones,
  157. 'emails': emails,
  158. 'todos': todos[:3] # 最多3个
  159. }
  160. def generate_reply(self, email, classification):
  161. """生成回复草稿"""
  162. if classification['type'] == 'spam':
  163. return None
  164. # 检测语言
  165. is_chinese = any('\u4e00' <= char <= '\u9fff' for char in email['body'])
  166. lang = 'zh' if is_chinese else 'en'
  167. # 选择模板
  168. template_type = classification['type'] if classification['type'] in ['work', 'customer'] else 'general'
  169. template = self.reply_templates[template_type][lang]
  170. # 生成回复
  171. reply_content = template.format(subject=email['subject'])
  172. return {
  173. 'to': email['sender'],
  174. 'subject': f"Re: {email['subject']}",
  175. 'content': reply_content,
  176. 'language': lang,
  177. 'template_type': template_type
  178. }
  179. def run_demo(self):
  180. """运行演示"""
  181. print("🤖 智能邮件助手 - 演示版本")
  182. print("=" * 50)
  183. print(f"📧 演示邮件数量: {len(self.demo_emails)}")
  184. print()
  185. results = []
  186. stats = {'total': 0, 'classified': 0, 'replies': 0, 'reminders': 0}
  187. for i, email in enumerate(self.demo_emails, 1):
  188. print(f"处理邮件 {i}/{len(self.demo_emails)}: {email['subject'][:30]}...")
  189. # 分类
  190. classification = self.classify_email(email)
  191. stats['classified'] += 1
  192. # 信息提取
  193. extracted_info = self.extract_info(email)
  194. # 生成回复
  195. reply = self.generate_reply(email, classification)
  196. if reply:
  197. stats['replies'] += 1
  198. # 创建提醒
  199. reminders = len(extracted_info['dates']) + len(extracted_info['todos'])
  200. stats['reminders'] += reminders
  201. results.append({
  202. 'email': email,
  203. 'classification': classification,
  204. 'extracted_info': extracted_info,
  205. 'reply': reply,
  206. 'reminders_count': reminders
  207. })
  208. stats['total'] = len(self.demo_emails)
  209. print("\n✅ 处理完成!")
  210. self.display_results(results, stats)
  211. def display_results(self, results, stats):
  212. """显示结果"""
  213. print("\n📊 处理统计:")
  214. print(f" 总邮件数: {stats['total']}")
  215. print(f" 已分类: {stats['classified']}")
  216. print(f" 生成回复: {stats['replies']}")
  217. print(f" 创建提醒: {stats['reminders']}")
  218. # 分类统计
  219. types = [r['classification']['type'] for r in results]
  220. priorities = [r['classification']['priority'] for r in results]
  221. print("\n📋 分类统计:")
  222. type_counts = Counter(types)
  223. for email_type, count in type_counts.items():
  224. print(f" {email_type}: {count}")
  225. print("\n⚡ 优先级统计:")
  226. priority_counts = Counter(priorities)
  227. for priority, count in priority_counts.items():
  228. print(f" {priority}: {count}")
  229. print("\n📝 处理结果样例:")
  230. print("-" * 50)
  231. for i, result in enumerate(results[:3], 1): # 显示前3个
  232. email = result['email']
  233. classification = result['classification']
  234. extracted = result['extracted_info']
  235. reply = result['reply']
  236. print(f"\n邮件 {i}:")
  237. print(f" 主题: {email['subject']}")
  238. print(f" 发件人: {email['sender']}")
  239. print(f" 分类: {classification['type']} | 优先级: {classification['priority']}")
  240. if extracted['dates']:
  241. print(f" 关键日期: {', '.join(extracted['dates'])}")
  242. if extracted['times']:
  243. print(f" 时间: {', '.join(extracted['times'])}")
  244. if extracted['todos']:
  245. print(f" 待办: {extracted['todos'][0][:50]}...")
  246. if reply:
  247. print(f" 回复草稿 ({reply['language']}): {reply['content'][:80]}...")
  248. print(f" 提醒数量: {result['reminders_count']}")
  249. print("\n🎉 演示完成!")
  250. print("\n💡 下一步:")
  251. print("1. 查看完整功能请运行: jupyter notebook EmailSmartAssistant.ipynb")
  252. print("2. 配置真实邮箱请编辑: config/email_config.json")
  253. print("3. 安装完整依赖请运行: pip install -r requirements.txt")
  254. if __name__ == "__main__":
  255. demo = EmailDemo()
  256. demo.run_demo()