颠覆礼物越贵感情越深 - 心意值计算系统一、实际应用场景描述场景小李准备给女朋友小美过生日预算只有200元。传统观念认为便宜没好货但小李想证明真心不在于价格。他使用本系统分析小美的喜好、性格特点结合两人共同回忆计算出最优礼物方案。最终花150元制作了一本回忆手账定制星空灯小美感动落泪比往年千元礼物更珍贵。适用人群- 学生党/刚工作预算有限但想表达真心的年轻人- 注重情感连接胜过物质价值的伴侣/朋友- 希望理性规划礼物支出的人群二、引入痛点传统送礼的三大误区误区 表现 后果价格至上 买最贵的就是最好的 经济压力大对方可能觉得浪费自我感动 送自己喜欢而非对方需要的 礼物闲置情感传达失效缺乏策略 临时抱佛脚随便买 无法体现用心程度市场现状- 某电商平台数据显示300元以上礼物退货率高达23%主要原因为不符合预期- 心理学研究68%的人更珍视被记住的细节而非昂贵物品三、核心逻辑讲解智能决策模型架构┌─────────────────────────────────────────────────────────┐│ 心意值计算系统 │├─────────────────────────────────────────────────────────┤│ 输入层: 关系数据 对方画像 预算约束 │├─────────────────────────────────────────────────────────┤│ 处理层: ││ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ││ │ 心意权重计算 │ │ 惊喜度评估 │ │ 成本效益分析 │ ││ └─────────────┘ └─────────────┘ └─────────────┘ │├─────────────────────────────────────────────────────────┤│ 输出层: 最优礼物方案 (高心意值 高惊喜度 低成本) │└─────────────────────────────────────────────────────────┘核心算法公式心意值 (Heart Value, HV) Σ(回忆权重 × 个性化系数 × 稀缺性因子)惊喜度 (Surprise Index, SI) (意外发现概率 × 情感共鸣度) / 市场常见度综合评分 HV × 0.6 SI × 0.4 - 成本惩罚因子四、代码模块化实现项目结构gift_heart_system/├── main.py # 主程序入口├── gift_core.py # 核心计算模块├── data_models.py # 数据模型定义├── surprise_engine.py # 惊喜度评估引擎├── utils.py # 工具函数├── config.py # 配置文件└── README.md # 使用说明1. config.py - 配置文件配置参数文件定义系统运行的核心参数和权重# 关系类型权重配置RELATIONSHIP_WEIGHTS {恋人: {base: 1.0, emotional_depth: 0.9, long_term_factor: 0.8},夫妻: {base: 0.95, emotional_depth: 0.85, long_term_factor: 0.9},挚友: {base: 0.85, emotional_depth: 0.8, long_term_factor: 0.7},普通朋友: {base: 0.6, emotional_depth: 0.5, long_term_factor: 0.4},家人: {base: 0.9, emotional_depth: 0.7, long_term_factor: 0.95}}# 预算区间配置BUDGET_TIERS {budget: (0, 100), # 低预算standard: (101, 500), # 标准预算premium: (501, 2000) # 高预算}# 心意值计算权重HEART_VALUE_WEIGHTS {memory_importance: 0.35, # 回忆重要性personalization: 0.30, # 个性化程度scarcity_factor: 0.20, # 稀缺性因子effort_level: 0.15 # 投入精力}# 惊喜度评估维度SURPRISE_DIMENSIONS {unexpectedness: 0.40, # 意外程度emotional_resonance: 0.35, # 情感共鸣market_rarity: 0.25 # 市场稀有度}2. data_models.py - 数据模型数据模型定义模块使用Python dataclass定义核心数据结构from dataclasses import dataclass, fieldfrom typing import List, Dict, Optionalfrom enum import Enumimport datetimeclass RelationshipType(Enum):关系类型枚举LOVER 恋人SPOUSE 夫妻CLOSE_FRIEND 挚友FRIEND 普通朋友FAMILY 家人dataclassclass Memory:共同回忆数据模型Attributes:title: 回忆标题date: 发生日期description: 详细描述emotional_weight: 情感权重 (1-10)shared_location: 共同地点related_items: 相关物品列表title: strdate: datetime.datedescription: stremotional_weight: int # 1-10评分shared_location: Optional[str] Nonerelated_items: List[str] field(default_factorylist)def __post_init__(self):验证数据有效性if not 1 self.emotional_weight 10:raise ValueError(情感权重必须在1-10之间)dataclassclass PersonProfile:收礼者画像模型Attributes:name: 姓名age: 年龄relationship: 关系类型interests: 兴趣爱好列表personality_traits: 性格特征recent_needs: 近期需求dislikes: 不喜欢的事物love_language: 爱的表达方式name: strage: intrelationship: RelationshipTypeinterests: List[str]personality_traits: List[str]recent_needs: List[str] field(default_factorylist)dislikes: List[str] field(default_factorylist)love_language: str quality_time # quality_time, gifts, acts, words, touch# 爱的语言类型LOVE_LANGUAGES [quality_time, # 优质时光gifts, # 礼物acts_of_service, # 服务行为words_of_affirmation, # 肯定的言语physical_touch # 身体接触]def validate(self):验证画像数据完整性required_fields [name, age, relationship, interests]for field in required_fields:if not getattr(self, field):raise ValueError(f缺少必填字段: {field})if self.love_language not in self.LOVE_LANGUAGES:raise ValueError(f无效的爱的语言类型: {self.love_language})dataclassclass GiftOption:礼物选项模型Attributes:name: 礼物名称cost: 成本价格category: 类别personalization_level: 个性化程度 (0-1)effort_required: 所需精力 (小时)surprise_potential: 惊喜潜力 (0-1)memory_connection: 回忆关联度 (0-1)scarcity_score: 稀缺性评分 (0-1)name: strcost: floatcategory: strpersonalization_level: float # 0-1effort_required: float # 小时surprise_potential: float # 0-1memory_connection: float # 0-1scarcity_score: float # 0-1def __post_init__(self):数据范围验证ranges {personalization_level: (0, 1),surprise_potential: (0, 1),memory_connection: (0, 1),scarcity_score: (0, 1)}for attr, (min_val, max_val) in ranges.items():value getattr(self, attr)if not min_val value max_val:raise ValueError(f{attr} 必须在 {min_val}-{max_val} 之间)3. surprise_engine.py - 惊喜度评估引擎惊喜度评估引擎基于智能决策理论的多维度评估系统from typing import List, Dictfrom data_models import GiftOption, PersonProfilefrom config import SURPRISE_DIMENSIONSclass SurpriseEngine:惊喜度评估引擎类核心功能:1. 计算单个礼物的惊喜指数2. 批量评估多个礼物选项3. 生成惊喜度分析报告def __init__(self, profile: PersonProfile):初始化惊喜引擎Args:profile: 收礼者画像self.profile profileself.dimensions SURPRISE_DIMENSIONSdef calculate_unexpectedness(self, gift: GiftOption) - float:计算意外程度 (Unexpectedness)算法逻辑:- 检查礼物是否在对方兴趣列表中- 考虑爱的语言匹配度- 评估是否超出日常消费习惯Returns:意外程度得分 (0-1)score 0.0# 因素1: 兴趣匹配反向指标 (越不匹配越意外)interest_match sum(1 for interest in self.profile.interestsif interest.lower() in gift.name.lower())interest_factor max(0, 1 - (interest_match / len(self.profile.interests))) if self.profile.interests else 0.5score interest_factor * 0.4# 因素2: 爱的语言契合度language_bonus 0.3 if self._matches_love_language(gift) else 0.1score language_bonus# 因素3: 价格与历史消费对比price_surprise self._calculate_price_surprise(gift.cost)score price_surprise * 0.3return min(1.0, score)def _matches_love_language(self, gift: GiftOption) - bool:检查礼物是否匹配对方的爱的语言language self.profile.love_languagemapping {quality_time: [体验, 活动, 陪伴, 手工],gifts: [定制, 专属, 收藏],acts_of_service: [实用, 帮助, 便利],words_of_affirmation: [信件, 卡片, 文字],physical_touch: [饰品, 温暖, 舒适]}keywords mapping.get(language, [])return any(keyword in gift.name for keyword in keywords)def _calculate_price_surprise(self, cost: float) - float:根据收礼者画像估算价格惊喜度假设: 基于年龄和关系推断消费习惯base_surprise 0.5# 年龄因素: 年轻人更容易被低价惊喜if self.profile.age 25:base_surprise 0.2elif self.profile.age 40:base_surprise - 0.1# 关系因素: 亲密关系对价格敏感度更低if self.profile.relationship in [RelationshipType.LOVER, RelationshipType.SPOUSE]:base_surprise 0.15return min(1.0, base_surprise)def calculate_emotional_resonance(self, gift: GiftOption) - float:计算情感共鸣度 (Emotional Resonance)基于:- 个性化程度- 回忆关联度- 性格匹配度score 0.0# 个性化贡献score gift.personalization_level * 0.4# 回忆关联贡献score gift.memory_connection * 0.35# 性格匹配度personality_match self._calculate_personality_match(gift)score personality_match * 0.25return min(1.0, score)def _calculate_personality_match(self, gift: GiftOption) - float:计算性格匹配度traits self.profile.personality_traitsif not traits:return 0.5match_count 0total_traits len(traits)# 性格-礼物映射规则trait_gift_rules {浪漫: [定制, 星空, 手写, 照片],务实: [实用, 高效, 工具, 收纳],文艺: [书籍, 艺术, 手工, 音乐],科技: [数码, 智能, 创新, 黑科技],怀旧: [复古, 经典, 老物件, 纪念]}for trait in traits:if trait in trait_gift_rules:keywords trait_gift_rules[trait]if any(kw in gift.name for kw in keywords):match_count 1return match_count / total_traits if total_traits 0 else 0.5def calculate_market_rarity(self, gift: GiftOption) - float:计算市场稀有度 (Market Rarity)基于:- 稀缺性评分- 定制化程度- 工业化程度判断score 0.0# 稀缺性直接贡献score gift.scarcity_score * 0.5# 个性化带来的稀有度提升personalization_boost gift.personalization_level * 0.3score personalization_boost# 手工/定制vs工业制品if 定制 in gift.name or 手工 in gift.name or 专属 in gift.name:score 0.2return min(1.0, score)def evaluate_gift(self, gift: GiftOption) - Dict:综合评估单个礼物的惊喜度Returns:包含各维度得分和总分的字典unexpectedness self.calculate_unexpectedness(gift)emotional_resonance self.calculate_emotional_resonance(gift)market_rarity self.calculate_market_rarity(gift)# 加权计算总分total_score (unexpectedness * self.dimensions[unexpectedness] emotional_resonance * self.dimensions[emotional_resonance] market_rarity * self.dimensions[market_rarity])return {gift_name: gift.name,dimensions: {unexpectedness: round(unexpectedness, 3),emotional_resonance: round(emotional_resonance, 3),market_rarity: round(market_rarity, 3)},total_surprise_index: round(total_score, 3),recommendation: self._get_recommendation(total_score)}def _get_recommendation(self, score: float) - str:根据分数生成推荐语if score 0.8:return ⭐⭐⭐⭐⭐ 惊喜炸弹预计对方会非常感动elif score 0.6:return ⭐⭐⭐⭐ 很棒的惊喜选择值得考虑elif score 0.4:return ⭐⭐⭐ 中等惊喜建议优化个性化元素else:return ⭐⭐ 惊喜度偏低建议重新设计def batch_evaluate(self, gifts: List[GiftOption]) - List[Dict]:批量评估礼物列表results []for gift in gifts:evaluation self.evaluate_gift(gift)results.append(evaluation)# 按惊喜指数排序results.sort(keylambda x: x[total_surprise_index], reverseTrue)return results4. gift_core.py - 核心计算模块核心计算模块整合心意值和惊喜度计算输出最优方案from typing import List, Dict, Tuple, Optionalfrom dataclasses import dataclassfrom data_models import Memory, PersonProfile, GiftOption, RelationshipTypefrom surprise_engine import SurpriseEnginefrom config import RELATIONSHIP_WEIGHTS, HEART_VALUE_WEIGHTS, BUDGET_TIERSdataclassclass GiftRecommendation:礼物推荐结果Attributes:gift: 推荐的礼物heart_value: 心意值surprise_index: 惊喜度cost_effectiveness: 性价比得分overall_score: 综合评分rationale: 推荐理由gift: GiftOptionheart_value: floatsurprise_index: floatcost_effectiveness: floatoverall_score: floatrationale: strclass GiftHeartCalculator:心意值计算器核心类核心算法:Heart Value Σ(Memory_Weight × Personalization × Scarcity) × Relationship_Multiplierdef __init__(self, profile: PersonProfile, memories: List[Memory], budget: float):初始化计算器Args:profile: 收礼者画像memories: 共同回忆列表budget: 预算上限self.profile profileself.memories memoriesself.budget budgetself.surprise_engine SurpriseEngine(profile)self.weights HEART_VALUE_WEIGHTSself.relationship_config RELATIONSHIP_WEIGHTS[profile.relationship.value]def calculate_heart_value(self, gift: GiftOption) - float:计算单个礼物的心意值 (Heart Value)计算公式详解:HV (MW × PW × SF × EM) × RM其中:- MW: Memory Weight (回忆权重)- PW: Personalization Weight (个性化权重)- SF: Scarcity Factor (稀缺性因子)- EM: Effort Multiplier (精力乘数)- RM: Relationship Multiplier (关系乘数)# 1. 计算回忆关联度memory_connection self._calculate_memory_connection(gift)# 2. 计算各维度得分memory_score memory_connection * self.weights[memory_importance]personalization_score gift.personalization_level * self.weights[personalization]scarcity_score gift.scarcity_score * self.weights[scarcity_factor]effort_score self._calculate_effort_multiplier(gift.effort_required) * self.weights[effort_level]# 3. 基础心意值base_hv memory_score personalization_score scarcity_score effort_score# 4. 关系乘数调整relationship_multiplier self._calculate_relationship_multiplier()# 5. 最终心意值heart_value base_hv * relationship_multiplierreturn min(10.0, heart_value) # 上限10分def _calculate_memory_connection(self, gift: GiftOption) - float:计算礼物与共同回忆的关联度算法:- 遍历所有回忆- 检查礼物是否与回忆中的关键词/地点/物品关联- 加权平均计算关联度if not self.memories:return 0.3 # 无回忆数据时返回基础值total_connection 0.0total_weight 0.0for memory in self.memories:connection_strength 0.0# 检查地点关联if memory.shared_location and memory.shared_location.lower() in gift.name.lower():connection_strength 0.4# 检查物品关联for item in memory.related_items:if item.lower() in gift.name.lower():connection_strength 0.3break# 检查描述关键词memory_keywords self._extract_keywords(memory.description)gift_keywords self._extract_keywords(gift.name)keyword_overlap len(set(memory_keywords) set(gift_keywords))if keyword_overlap 0:connection_strength min(0.3, keyword_overlap * 0.1)# 加权累加total_connection connection_strength * memory.emotional_weighttotal_weight memory.emotional_weight# 计算加权平均if total_weight 0:return min(1.0, total_connection / total_weight)return 0.3def _extract_keywords(self, text: str) - List[str]:简单关键词提取实际应用中可使用NLP库# 停用词过滤stop_words {的, 了, 在, 是, 我, 有, 和, 就, 不, 人, 都, 一, 一个, 上, 也, 很, 到, 说, 要, 去, 你, 会, 着, 没有, 看, 好, 自己, 这}# 分词简化版words [w.strip() for w in text.replace(, ).replace(。, ).split() if w.strip()]# 过滤停用词和单字keywords [w for w in words if w not in stop_words and len(w) 1]return keywords[:10] # 取前10个关键词def _calculate_effort_multiplier(self, effort_hours: float) - float:根据投入精力计算乘数逻辑: 更多精力投入 更高心意值if effort_hours 1:return 0.5elif effort_hours 3:return 0.7elif effort_hours 8:return 0.9elif effort_hours 20:return 1.0else:return 1.1 # 超过20小时有边际递减但保持高值def _calculate_relationship_multiplier(self) - float:计算关系乘数config self.relationship_configreturn (config[base] config[emotional_depth] config[long_term_factor]) / 3def calculate_cost_effectiveness(self, gift: GiftOption, heart_value: float, surprise_index: float) - float:计算性价比 (Cost Effectiveness)公式: CE (HV × 0.6 SI × 0.4) / (Cost / Budget_Baseline)预算基准设为200元作为标准化参考baseline_budget 200.0# 归一化心意值和惊喜度normalized_hv heart_value / 10.0 # HV最高10分normalized_si surprise_index # SI已在0-1范围# 效用得分utility_score normalized_hv * 0.6 normalized_si * 0.4# 成本比率相对于基准预算cost_ratio gift.cost / baseline_budget if gift.cost 0 else 1.0# 性价比 效用 / 相对成本cost_effectiveness utility_score / cost_ratioreturn cost_effectivenessdef generate_recommendations(self, gift_options: List[GiftOption]) - List[GiftRecommendation]:生成礼物推荐列表Args:gift_options: 候选礼物列表Returns:排序后的推荐列表recommendations []for gift in gift_options:# 跳过超预算选项if gift.cost self.budget:continue# 计算各项指标heart_value self.calculate_heart_value(gift)surprise_result self.surprise_engine.evaluate_gift(gift)surprise_index surprise_result[total_surprise_index]cost_effectiveness self.calculate_cost_effectiveness(gift, heart_value, surprise_index)# 计算综合评分overall_score self._calculate_overall_score(heart_value, surprise_index, cost_effectiveness)# 生成推荐理由rationale self._generate_rationale(gift, heart_value, surprise_index, cost_effectiveness)recommendation GiftRecommendation(giftgift,heart_valueround(heart_value, 2),surprise_indexsurprise_index,cost_effectivenessround(cost_effectiveness, 3),overall_scoreround(overall_score, 3),rationalerationale)recommendations.append(recommendation)# 按综合评分降序排序recommendations.sort(keylambda x: x.overall_score, reverseTrue)return recommendationsdef _calculate_overall_score(self, heart_value: float, surprise_index: float, cost_effectiveness: float) - float:计算综合评分综合考虑:- 心意值 (权重40%)- 惊喜度 (权重35%)- 性价比 (权重25%)性价比利用AI解决实际问题如果你觉得这个工具好用欢迎关注长安牧笛
颠覆“礼物越贵感情越深”,计算心意与惊喜权重,颠覆高价送礼,输出低成本高感动方案。
颠覆礼物越贵感情越深 - 心意值计算系统一、实际应用场景描述场景小李准备给女朋友小美过生日预算只有200元。传统观念认为便宜没好货但小李想证明真心不在于价格。他使用本系统分析小美的喜好、性格特点结合两人共同回忆计算出最优礼物方案。最终花150元制作了一本回忆手账定制星空灯小美感动落泪比往年千元礼物更珍贵。适用人群- 学生党/刚工作预算有限但想表达真心的年轻人- 注重情感连接胜过物质价值的伴侣/朋友- 希望理性规划礼物支出的人群二、引入痛点传统送礼的三大误区误区 表现 后果价格至上 买最贵的就是最好的 经济压力大对方可能觉得浪费自我感动 送自己喜欢而非对方需要的 礼物闲置情感传达失效缺乏策略 临时抱佛脚随便买 无法体现用心程度市场现状- 某电商平台数据显示300元以上礼物退货率高达23%主要原因为不符合预期- 心理学研究68%的人更珍视被记住的细节而非昂贵物品三、核心逻辑讲解智能决策模型架构┌─────────────────────────────────────────────────────────┐│ 心意值计算系统 │├─────────────────────────────────────────────────────────┤│ 输入层: 关系数据 对方画像 预算约束 │├─────────────────────────────────────────────────────────┤│ 处理层: ││ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ││ │ 心意权重计算 │ │ 惊喜度评估 │ │ 成本效益分析 │ ││ └─────────────┘ └─────────────┘ └─────────────┘ │├─────────────────────────────────────────────────────────┤│ 输出层: 最优礼物方案 (高心意值 高惊喜度 低成本) │└─────────────────────────────────────────────────────────┘核心算法公式心意值 (Heart Value, HV) Σ(回忆权重 × 个性化系数 × 稀缺性因子)惊喜度 (Surprise Index, SI) (意外发现概率 × 情感共鸣度) / 市场常见度综合评分 HV × 0.6 SI × 0.4 - 成本惩罚因子四、代码模块化实现项目结构gift_heart_system/├── main.py # 主程序入口├── gift_core.py # 核心计算模块├── data_models.py # 数据模型定义├── surprise_engine.py # 惊喜度评估引擎├── utils.py # 工具函数├── config.py # 配置文件└── README.md # 使用说明1. config.py - 配置文件配置参数文件定义系统运行的核心参数和权重# 关系类型权重配置RELATIONSHIP_WEIGHTS {恋人: {base: 1.0, emotional_depth: 0.9, long_term_factor: 0.8},夫妻: {base: 0.95, emotional_depth: 0.85, long_term_factor: 0.9},挚友: {base: 0.85, emotional_depth: 0.8, long_term_factor: 0.7},普通朋友: {base: 0.6, emotional_depth: 0.5, long_term_factor: 0.4},家人: {base: 0.9, emotional_depth: 0.7, long_term_factor: 0.95}}# 预算区间配置BUDGET_TIERS {budget: (0, 100), # 低预算standard: (101, 500), # 标准预算premium: (501, 2000) # 高预算}# 心意值计算权重HEART_VALUE_WEIGHTS {memory_importance: 0.35, # 回忆重要性personalization: 0.30, # 个性化程度scarcity_factor: 0.20, # 稀缺性因子effort_level: 0.15 # 投入精力}# 惊喜度评估维度SURPRISE_DIMENSIONS {unexpectedness: 0.40, # 意外程度emotional_resonance: 0.35, # 情感共鸣market_rarity: 0.25 # 市场稀有度}2. data_models.py - 数据模型数据模型定义模块使用Python dataclass定义核心数据结构from dataclasses import dataclass, fieldfrom typing import List, Dict, Optionalfrom enum import Enumimport datetimeclass RelationshipType(Enum):关系类型枚举LOVER 恋人SPOUSE 夫妻CLOSE_FRIEND 挚友FRIEND 普通朋友FAMILY 家人dataclassclass Memory:共同回忆数据模型Attributes:title: 回忆标题date: 发生日期description: 详细描述emotional_weight: 情感权重 (1-10)shared_location: 共同地点related_items: 相关物品列表title: strdate: datetime.datedescription: stremotional_weight: int # 1-10评分shared_location: Optional[str] Nonerelated_items: List[str] field(default_factorylist)def __post_init__(self):验证数据有效性if not 1 self.emotional_weight 10:raise ValueError(情感权重必须在1-10之间)dataclassclass PersonProfile:收礼者画像模型Attributes:name: 姓名age: 年龄relationship: 关系类型interests: 兴趣爱好列表personality_traits: 性格特征recent_needs: 近期需求dislikes: 不喜欢的事物love_language: 爱的表达方式name: strage: intrelationship: RelationshipTypeinterests: List[str]personality_traits: List[str]recent_needs: List[str] field(default_factorylist)dislikes: List[str] field(default_factorylist)love_language: str quality_time # quality_time, gifts, acts, words, touch# 爱的语言类型LOVE_LANGUAGES [quality_time, # 优质时光gifts, # 礼物acts_of_service, # 服务行为words_of_affirmation, # 肯定的言语physical_touch # 身体接触]def validate(self):验证画像数据完整性required_fields [name, age, relationship, interests]for field in required_fields:if not getattr(self, field):raise ValueError(f缺少必填字段: {field})if self.love_language not in self.LOVE_LANGUAGES:raise ValueError(f无效的爱的语言类型: {self.love_language})dataclassclass GiftOption:礼物选项模型Attributes:name: 礼物名称cost: 成本价格category: 类别personalization_level: 个性化程度 (0-1)effort_required: 所需精力 (小时)surprise_potential: 惊喜潜力 (0-1)memory_connection: 回忆关联度 (0-1)scarcity_score: 稀缺性评分 (0-1)name: strcost: floatcategory: strpersonalization_level: float # 0-1effort_required: float # 小时surprise_potential: float # 0-1memory_connection: float # 0-1scarcity_score: float # 0-1def __post_init__(self):数据范围验证ranges {personalization_level: (0, 1),surprise_potential: (0, 1),memory_connection: (0, 1),scarcity_score: (0, 1)}for attr, (min_val, max_val) in ranges.items():value getattr(self, attr)if not min_val value max_val:raise ValueError(f{attr} 必须在 {min_val}-{max_val} 之间)3. surprise_engine.py - 惊喜度评估引擎惊喜度评估引擎基于智能决策理论的多维度评估系统from typing import List, Dictfrom data_models import GiftOption, PersonProfilefrom config import SURPRISE_DIMENSIONSclass SurpriseEngine:惊喜度评估引擎类核心功能:1. 计算单个礼物的惊喜指数2. 批量评估多个礼物选项3. 生成惊喜度分析报告def __init__(self, profile: PersonProfile):初始化惊喜引擎Args:profile: 收礼者画像self.profile profileself.dimensions SURPRISE_DIMENSIONSdef calculate_unexpectedness(self, gift: GiftOption) - float:计算意外程度 (Unexpectedness)算法逻辑:- 检查礼物是否在对方兴趣列表中- 考虑爱的语言匹配度- 评估是否超出日常消费习惯Returns:意外程度得分 (0-1)score 0.0# 因素1: 兴趣匹配反向指标 (越不匹配越意外)interest_match sum(1 for interest in self.profile.interestsif interest.lower() in gift.name.lower())interest_factor max(0, 1 - (interest_match / len(self.profile.interests))) if self.profile.interests else 0.5score interest_factor * 0.4# 因素2: 爱的语言契合度language_bonus 0.3 if self._matches_love_language(gift) else 0.1score language_bonus# 因素3: 价格与历史消费对比price_surprise self._calculate_price_surprise(gift.cost)score price_surprise * 0.3return min(1.0, score)def _matches_love_language(self, gift: GiftOption) - bool:检查礼物是否匹配对方的爱的语言language self.profile.love_languagemapping {quality_time: [体验, 活动, 陪伴, 手工],gifts: [定制, 专属, 收藏],acts_of_service: [实用, 帮助, 便利],words_of_affirmation: [信件, 卡片, 文字],physical_touch: [饰品, 温暖, 舒适]}keywords mapping.get(language, [])return any(keyword in gift.name for keyword in keywords)def _calculate_price_surprise(self, cost: float) - float:根据收礼者画像估算价格惊喜度假设: 基于年龄和关系推断消费习惯base_surprise 0.5# 年龄因素: 年轻人更容易被低价惊喜if self.profile.age 25:base_surprise 0.2elif self.profile.age 40:base_surprise - 0.1# 关系因素: 亲密关系对价格敏感度更低if self.profile.relationship in [RelationshipType.LOVER, RelationshipType.SPOUSE]:base_surprise 0.15return min(1.0, base_surprise)def calculate_emotional_resonance(self, gift: GiftOption) - float:计算情感共鸣度 (Emotional Resonance)基于:- 个性化程度- 回忆关联度- 性格匹配度score 0.0# 个性化贡献score gift.personalization_level * 0.4# 回忆关联贡献score gift.memory_connection * 0.35# 性格匹配度personality_match self._calculate_personality_match(gift)score personality_match * 0.25return min(1.0, score)def _calculate_personality_match(self, gift: GiftOption) - float:计算性格匹配度traits self.profile.personality_traitsif not traits:return 0.5match_count 0total_traits len(traits)# 性格-礼物映射规则trait_gift_rules {浪漫: [定制, 星空, 手写, 照片],务实: [实用, 高效, 工具, 收纳],文艺: [书籍, 艺术, 手工, 音乐],科技: [数码, 智能, 创新, 黑科技],怀旧: [复古, 经典, 老物件, 纪念]}for trait in traits:if trait in trait_gift_rules:keywords trait_gift_rules[trait]if any(kw in gift.name for kw in keywords):match_count 1return match_count / total_traits if total_traits 0 else 0.5def calculate_market_rarity(self, gift: GiftOption) - float:计算市场稀有度 (Market Rarity)基于:- 稀缺性评分- 定制化程度- 工业化程度判断score 0.0# 稀缺性直接贡献score gift.scarcity_score * 0.5# 个性化带来的稀有度提升personalization_boost gift.personalization_level * 0.3score personalization_boost# 手工/定制vs工业制品if 定制 in gift.name or 手工 in gift.name or 专属 in gift.name:score 0.2return min(1.0, score)def evaluate_gift(self, gift: GiftOption) - Dict:综合评估单个礼物的惊喜度Returns:包含各维度得分和总分的字典unexpectedness self.calculate_unexpectedness(gift)emotional_resonance self.calculate_emotional_resonance(gift)market_rarity self.calculate_market_rarity(gift)# 加权计算总分total_score (unexpectedness * self.dimensions[unexpectedness] emotional_resonance * self.dimensions[emotional_resonance] market_rarity * self.dimensions[market_rarity])return {gift_name: gift.name,dimensions: {unexpectedness: round(unexpectedness, 3),emotional_resonance: round(emotional_resonance, 3),market_rarity: round(market_rarity, 3)},total_surprise_index: round(total_score, 3),recommendation: self._get_recommendation(total_score)}def _get_recommendation(self, score: float) - str:根据分数生成推荐语if score 0.8:return ⭐⭐⭐⭐⭐ 惊喜炸弹预计对方会非常感动elif score 0.6:return ⭐⭐⭐⭐ 很棒的惊喜选择值得考虑elif score 0.4:return ⭐⭐⭐ 中等惊喜建议优化个性化元素else:return ⭐⭐ 惊喜度偏低建议重新设计def batch_evaluate(self, gifts: List[GiftOption]) - List[Dict]:批量评估礼物列表results []for gift in gifts:evaluation self.evaluate_gift(gift)results.append(evaluation)# 按惊喜指数排序results.sort(keylambda x: x[total_surprise_index], reverseTrue)return results4. gift_core.py - 核心计算模块核心计算模块整合心意值和惊喜度计算输出最优方案from typing import List, Dict, Tuple, Optionalfrom dataclasses import dataclassfrom data_models import Memory, PersonProfile, GiftOption, RelationshipTypefrom surprise_engine import SurpriseEnginefrom config import RELATIONSHIP_WEIGHTS, HEART_VALUE_WEIGHTS, BUDGET_TIERSdataclassclass GiftRecommendation:礼物推荐结果Attributes:gift: 推荐的礼物heart_value: 心意值surprise_index: 惊喜度cost_effectiveness: 性价比得分overall_score: 综合评分rationale: 推荐理由gift: GiftOptionheart_value: floatsurprise_index: floatcost_effectiveness: floatoverall_score: floatrationale: strclass GiftHeartCalculator:心意值计算器核心类核心算法:Heart Value Σ(Memory_Weight × Personalization × Scarcity) × Relationship_Multiplierdef __init__(self, profile: PersonProfile, memories: List[Memory], budget: float):初始化计算器Args:profile: 收礼者画像memories: 共同回忆列表budget: 预算上限self.profile profileself.memories memoriesself.budget budgetself.surprise_engine SurpriseEngine(profile)self.weights HEART_VALUE_WEIGHTSself.relationship_config RELATIONSHIP_WEIGHTS[profile.relationship.value]def calculate_heart_value(self, gift: GiftOption) - float:计算单个礼物的心意值 (Heart Value)计算公式详解:HV (MW × PW × SF × EM) × RM其中:- MW: Memory Weight (回忆权重)- PW: Personalization Weight (个性化权重)- SF: Scarcity Factor (稀缺性因子)- EM: Effort Multiplier (精力乘数)- RM: Relationship Multiplier (关系乘数)# 1. 计算回忆关联度memory_connection self._calculate_memory_connection(gift)# 2. 计算各维度得分memory_score memory_connection * self.weights[memory_importance]personalization_score gift.personalization_level * self.weights[personalization]scarcity_score gift.scarcity_score * self.weights[scarcity_factor]effort_score self._calculate_effort_multiplier(gift.effort_required) * self.weights[effort_level]# 3. 基础心意值base_hv memory_score personalization_score scarcity_score effort_score# 4. 关系乘数调整relationship_multiplier self._calculate_relationship_multiplier()# 5. 最终心意值heart_value base_hv * relationship_multiplierreturn min(10.0, heart_value) # 上限10分def _calculate_memory_connection(self, gift: GiftOption) - float:计算礼物与共同回忆的关联度算法:- 遍历所有回忆- 检查礼物是否与回忆中的关键词/地点/物品关联- 加权平均计算关联度if not self.memories:return 0.3 # 无回忆数据时返回基础值total_connection 0.0total_weight 0.0for memory in self.memories:connection_strength 0.0# 检查地点关联if memory.shared_location and memory.shared_location.lower() in gift.name.lower():connection_strength 0.4# 检查物品关联for item in memory.related_items:if item.lower() in gift.name.lower():connection_strength 0.3break# 检查描述关键词memory_keywords self._extract_keywords(memory.description)gift_keywords self._extract_keywords(gift.name)keyword_overlap len(set(memory_keywords) set(gift_keywords))if keyword_overlap 0:connection_strength min(0.3, keyword_overlap * 0.1)# 加权累加total_connection connection_strength * memory.emotional_weighttotal_weight memory.emotional_weight# 计算加权平均if total_weight 0:return min(1.0, total_connection / total_weight)return 0.3def _extract_keywords(self, text: str) - List[str]:简单关键词提取实际应用中可使用NLP库# 停用词过滤stop_words {的, 了, 在, 是, 我, 有, 和, 就, 不, 人, 都, 一, 一个, 上, 也, 很, 到, 说, 要, 去, 你, 会, 着, 没有, 看, 好, 自己, 这}# 分词简化版words [w.strip() for w in text.replace(, ).replace(。, ).split() if w.strip()]# 过滤停用词和单字keywords [w for w in words if w not in stop_words and len(w) 1]return keywords[:10] # 取前10个关键词def _calculate_effort_multiplier(self, effort_hours: float) - float:根据投入精力计算乘数逻辑: 更多精力投入 更高心意值if effort_hours 1:return 0.5elif effort_hours 3:return 0.7elif effort_hours 8:return 0.9elif effort_hours 20:return 1.0else:return 1.1 # 超过20小时有边际递减但保持高值def _calculate_relationship_multiplier(self) - float:计算关系乘数config self.relationship_configreturn (config[base] config[emotional_depth] config[long_term_factor]) / 3def calculate_cost_effectiveness(self, gift: GiftOption, heart_value: float, surprise_index: float) - float:计算性价比 (Cost Effectiveness)公式: CE (HV × 0.6 SI × 0.4) / (Cost / Budget_Baseline)预算基准设为200元作为标准化参考baseline_budget 200.0# 归一化心意值和惊喜度normalized_hv heart_value / 10.0 # HV最高10分normalized_si surprise_index # SI已在0-1范围# 效用得分utility_score normalized_hv * 0.6 normalized_si * 0.4# 成本比率相对于基准预算cost_ratio gift.cost / baseline_budget if gift.cost 0 else 1.0# 性价比 效用 / 相对成本cost_effectiveness utility_score / cost_ratioreturn cost_effectivenessdef generate_recommendations(self, gift_options: List[GiftOption]) - List[GiftRecommendation]:生成礼物推荐列表Args:gift_options: 候选礼物列表Returns:排序后的推荐列表recommendations []for gift in gift_options:# 跳过超预算选项if gift.cost self.budget:continue# 计算各项指标heart_value self.calculate_heart_value(gift)surprise_result self.surprise_engine.evaluate_gift(gift)surprise_index surprise_result[total_surprise_index]cost_effectiveness self.calculate_cost_effectiveness(gift, heart_value, surprise_index)# 计算综合评分overall_score self._calculate_overall_score(heart_value, surprise_index, cost_effectiveness)# 生成推荐理由rationale self._generate_rationale(gift, heart_value, surprise_index, cost_effectiveness)recommendation GiftRecommendation(giftgift,heart_valueround(heart_value, 2),surprise_indexsurprise_index,cost_effectivenessround(cost_effectiveness, 3),overall_scoreround(overall_score, 3),rationalerationale)recommendations.append(recommendation)# 按综合评分降序排序recommendations.sort(keylambda x: x.overall_score, reverseTrue)return recommendationsdef _calculate_overall_score(self, heart_value: float, surprise_index: float, cost_effectiveness: float) - float:计算综合评分综合考虑:- 心意值 (权重40%)- 惊喜度 (权重35%)- 性价比 (权重25%)性价比利用AI解决实际问题如果你觉得这个工具好用欢迎关注长安牧笛