编写宠物沐浴露,PH适配程序,按宠物品类计算安全配方,保护皮肤毛发。
宠物沐浴露pH适配与安全配方系统
一、实际应用场景描述
某宠物连锁店"萌宠之家"拥有5000+会员,经营猫、狗、兔子、仓鼠等多品类宠物洗护服务。近期收到大量客户反馈:
- 猫咪洗后出现皮屑增多、频繁抓挠
- 贵宾犬毛发干枯易断
- 垂耳兔耳朵周围出现红肿过敏
- 仓鼠洗后应激反应强烈
经检测发现,现有沐浴露采用固定pH值(7.0)和基础配方,未考虑不同宠物的生理差异:
- 猫皮肤pH为5.5-7.0(弱酸性)
- 狗皮肤pH为6.2-7.4(中性偏酸)
- 兔子皮肤pH为8.0-8.5(弱碱性)
- 仓鼠皮肤pH为6.0-6.5(弱酸性)
同时,不同品类的毛发结构(双层被毛/单层绒毛)、皮肤敏感度(薄皮肤/厚皮肤)也未被纳入考量,导致洗护效果差甚至引发健康问题。
二、引入痛点
1. pH不匹配:使用错误pH值的沐浴露会破坏宠物皮肤酸碱平衡,导致细菌滋生或皮肤干燥
2. 成分不安全:含刺激性表面活性剂(如SLS)或高浓度香精,引发过敏反应
3. 配方无针对性:长毛犬需要柔顺剂,短毛猫需要控油成分,通用配方无法满足需求
4. 缺乏科学计算:依赖人工经验调配,无法精确计算各成分安全比例
5. 数据不透明:无法向客户解释配方设计依据,影响品牌信任度
三、核心逻辑讲解
本系统基于"生物特性-化学安全-功效优化"三层逻辑设计:
1. 生物特性层:
- 根据宠物品类获取基础皮肤pH范围
- 分析毛发类型(长/短/卷/直)和皮肤厚度
- 评估特殊需求(敏感肌/除蚤/美毛)
2. 化学安全层:
- 建立安全成分数据库(表面活性剂/调理剂/防腐剂)
- 根据皮肤pH计算各成分最大允许浓度
- 检查成分间配伍禁忌(如阳离子/阴离子表活不能混用)
3. 功效优化层:
- 根据毛发需求添加功能成分(如水解蛋白/维生素E)
- 计算各成分最佳配比,确保清洁力与温和性平衡
- 生成可复现的配方方案
关键公式:
- 安全浓度 = 基础安全值 × (1 - |实际pH - 目标pH|/目标pH范围)
- 总活性物含量 = 清洁力系数 × 皮肤厚度调节因子
- 调理剂比例 = 毛发长度系数 × 毛发损伤度
四、代码模块化实现
项目结构
pet_shampoo_system/
├── main.py # 主程序入口
├── config/
│ └── pet_profiles.json # 宠物品类特征配置
├── data/
│ └── safe_ingredients.json # 安全成分数据库
├── modules/
│ ├── __init__.py
│ ├── ph_calculator.py # pH计算模块
│ ├── formula_generator.py # 配方生成模块
│ └── safety_checker.py # 安全检查模块
├── utils/
│ └── helpers.py # 工具函数
└── README.md # 项目说明
1. 配置文件 (config/pet_profiles.json)
{
"cat": {
"skin_ph_range": [5.5, 7.0],
"hair_type": "short",
"skin_thickness": "thin",
"sensitivity": "high",
"special_needs": ["mild_cleaning"]
},
"dog": {
"skin_ph_range": [6.2, 7.4],
"hair_type": "long",
"skin_thickness": "medium",
"sensitivity": "medium",
"special_needs": ["conditioning"]
},
"rabbit": {
"skin_ph_range": [8.0, 8.5],
"hair_type": "soft",
"skin_thickness": "thin",
"sensitivity": "very_high",
"special_needs": ["hypoallergenic"]
},
"hamster": {
"skin_ph_range": [6.0, 6.5],
"hair_type": "dense",
"skin_thickness": "very_thin",
"sensitivity": "extreme",
"special_needs": ["minimal_fragrance"]
}
}
2. 成分数据库 (data/safe_ingredients.json)
{
"surfactants": [
{"name": "椰油酰胺丙基甜菜碱", "type": "amphoteric", "safe_ph_range": [5.0, 9.0], "max_concentration": 15, "cleaning_power": 7},
{"name": "月桂酰肌氨酸钠", "type": "anionic", "safe_ph_range": [5.5, 8.0], "max_concentration": 10, "cleaning_power": 6},
{"name": "癸基葡糖苷", "type": "nonionic", "safe_ph_range": [4.0, 10.0], "max_concentration": 12, "cleaning_power": 5}
],
"conditioners": [
{"name": "聚季铵盐-7", "type": "cationic", "safe_ph_range": [4.0, 8.0], "max_concentration": 3, "conditioning_effect": 8},
{"name": "泛醇(维生素B5)", "type": "neutral", "safe_ph_range": [3.0, 9.0], "max_concentration": 2, "conditioning_effect": 6}
],
"additives": [
{"name": "尿囊素", "type": "neutral", "safe_ph_range": [4.0, 8.0], "max_concentration": 1, "function": "soothing"},
{"name": "洋甘菊提取物", "type": "neutral", "safe_ph_range": [3.0, 9.0], "max_concentration": 0.5, "function": "anti_inflammatory"}
]
}
3. 核心模块 (modules/ph_calculator.py)
"""
pH计算模块 - 负责根据宠物品类计算安全pH值及调整策略
"""
import json
from typing import Dict, List, Tuple
class PHCalculator:
"""pH计算器类,处理所有与pH相关的计算逻辑"""
def __init__(self, config_path: str = "../config/pet_profiles.json"):
"""
初始化pH计算器
Args:
config_path: 宠物品类配置文件路径
"""
self.pet_profiles = self._load_config(config_path)
def _load_config(self, config_path: str) -> Dict:
"""加载宠物品类配置文件"""
try:
with open(config_path, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
raise Exception(f"配置文件未找到: {config_path}")
except json.JSONDecodeError:
raise Exception(f"配置文件格式错误: {config_path}")
def get_safe_ph_range(self, pet_type: str) -> Tuple[float, float]:
"""
获取指定宠物品类的安全pH范围
Args:
pet_type: 宠物品类 (cat/dog/rabbit/hamster)
Returns:
安全pH范围元组 (min_ph, max_ph)
"""
if pet_type not in self.pet_profiles:
raise ValueError(f"不支持的宠物品类: {pet_type},支持的类型: {list(self.pet_profiles.keys())}")
profile = self.pet_profiles[pet_type]
return tuple(profile["skin_ph_range"])
def calculate_optimal_ph(self, pet_type: str, current_ph: float = 7.0) -> float:
"""
计算最优pH值(取安全范围的中间值)
Args:
pet_type: 宠物品类
current_ph: 当前pH值(用于计算调整量)
Returns:
最优pH值
"""
min_ph, max_ph = self.get_safe_ph_range(pet_type)
optimal_ph = (min_ph + max_ph) / 2
# 计算pH调整量
ph_adjustment = optimal_ph - current_ph
print(f"[{pet_type}] 安全pH范围: [{min_ph:.1f}-{max_ph:.1f}], 当前pH: {current_ph:.1f}, 建议调整: {ph_adjustment:+.1f}")
return optimal_ph
def get_ph_adjustment_strategy(self, pet_type: str, current_ph: float) -> Dict:
"""
获取pH调整策略
Args:
pet_type: 宠物品类
current_ph: 当前pH值
Returns:
包含调整建议的字典
"""
min_ph, max_ph = self.get_safe_ph_range(pet_type)
optimal_ph = (min_ph + max_ph) / 2
if min_ph <= current_ph <= max_ph:
status = "安全"
action = "无需调整"
elif current_ph < min_ph:
status = "过低"
action = f"添加碱性调节剂(如碳酸钠),目标pH: {optimal_ph:.1f}"
else:
status = "过高"
action = f"添加酸性调节剂(如柠檬酸),目标pH: {optimal_ph:.1f}"
return {
"status": status,
"action": action,
"target_ph": optimal_ph,
"adjustment_amount": optimal_ph - current_ph
}
4. 配方生成模块 (modules/formula_generator.py)
"""
配方生成模块 - 根据宠物品类和安全参数生成个性化配方
"""
import json
from typing import Dict, List, Any
from .ph_calculator import PHCalculator
class FormulaGenerator:
"""配方生成器类,负责创建安全有效的宠物沐浴露配方"""
def __init__(self,
pet_profiles_path: str = "../config/pet_profiles.json",
ingredients_path: str = "../data/safe_ingredients.json"):
"""
初始化配方生成器
Args:
pet_profiles_path: 宠物品类配置文件路径
ingredients_path: 安全成分数据库路径
"""
self.ph_calculator = PHCalculator(pet_profiles_path)
self.ingredients = self._load_ingredients(ingredients_path)
self.pet_profiles = self.ph_calculator.pet_profiles
def _load_ingredients(self, path: str) -> Dict:
"""加载安全成分数据库"""
try:
with open(path, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
raise Exception(f"成分数据库未找到: {path}")
def _get_hair_type_factor(self, hair_type: str) -> float:
"""根据毛发类型获取调节因子"""
factors = {
"short": 0.8, # 短毛需要较少调理剂
"long": 1.2, # 长毛需要更多调理剂
"soft": 0.9, # 软毛适中
"dense": 1.1, # 密毛需要更多清洁力
"curly": 1.3 # 卷毛需要更多柔顺剂
}
return factors.get(hair_type, 1.0)
def _get_skin_thickness_factor(self, skin_thickness: str) -> float:
"""根据皮肤厚度获取调节因子"""
factors = {
"very_thin": 0.7, # 极薄皮肤需要更温和的配方
"thin": 0.85, # 薄皮肤
"medium": 1.0, # 中等厚度
"thick": 1.15 # 厚皮肤可承受稍强配方
}
return factors.get(skin_thickness, 1.0)
def _select_surfactants(self, pet_type: str, target_ph: float) -> List[Dict]:
"""
选择适合的表面活性剂组合
Args:
pet_type: 宠物品类
target_ph: 目标pH值
Returns:
选中的表面活性剂列表
"""
profile = self.pet_profiles[pet_type]
sensitivity = profile["sensitivity"]
# 根据敏感度筛选表活
suitable_surfactants = []
for surf in self.ingredients["surfactants"]:
# 检查pH兼容性
if not (surf["safe_ph_range"][0] <= target_ph <= surf["safe_ph_range"][1]):
continue
# 根据敏感度选择表活类型
if sensitivity == "extreme" or sensitivity == "very_high":
# 极高敏感度只使用非离子和两性表活
if surf["type"] in ["nonionic", "amphoteric"]:
suitable_surfactants.append(surf)
elif sensitivity == "high":
# 高敏感度避免使用强阴离子表活
if surf["type"] != "anionic" or surf["name"] == "月桂酰肌氨酸钠":
suitable_surfactants.append(surf)
else:
suitable_surfactants.append(surf)
# 按清洁力排序并选择
suitable_surfactants.sort(key=lambda x: x["cleaning_power"], reverse=True)
# 选择2-3种表活组合
selected = suitable_surfactants[:3]
# 计算各表活比例
total_cleaning_power = sum(s["cleaning_power"] for s in selected)
for surf in selected:
surf["ratio"] = surf["cleaning_power"] / total_cleaning_power
surf["concentration"] = round(surf["max_concentration"] * surf["ratio"], 2)
return selected
def _select_conditioners(self, pet_type: str, hair_type: str) -> List[Dict]:
"""
选择适合的调理剂
Args:
pet_type: 宠物品类
hair_type: 毛发类型
Returns:
选中的调理剂列表
"""
profile = self.pet_profiles[pet_type]
# 敏感宠物减少调理剂用量
sensitivity_multiplier = {
"extreme": 0.5,
"very_high": 0.6,
"high": 0.75,
"medium": 0.9,
"low": 1.0
}.get(profile["sensitivity"], 1.0)
# 根据毛发类型调整
hair_factor = self._get_hair_type_factor(hair_type)
selected = []
for cond in self.ingredients["conditioners"]:
# 检查是否适合该宠物品类
if pet_type == "hamster" and cond["name"] == "聚季铵盐-7":
# 仓鼠对阳离子调理剂敏感
continue
cond_copy = cond.copy()
# 计算安全浓度
base_conc = cond["max_concentration"] * sensitivity_multiplier * hair_factor
cond_copy["concentration"] = round(base_conc, 2)
cond_copy["ratio"] = 1.0 / len(self.ingredients["conditioners"]) # 平均分配
selected.append(cond_copy)
return selected
def _select_additives(self, pet_type: str) -> List[Dict]:
"""
选择适合的添加剂
Args:
pet_type: 宠物品类
Returns:
选中的添加剂列表
"""
profile = self.pet_profiles[pet_type]
special_needs = profile["special_needs"]
selected = []
for add in self.ingredients["additives"]:
# 根据特殊需求选择
if "hypoallergenic" in special_needs and add["function"] == "soothing":
add["concentration"] = add["max_concentration"]
selected.append(add)
elif "anti_inflammatory" in special_needs and add["function"] == "anti_inflammatory":
add["concentration"] = add["max_concentration"]
selected.append(add)
elif "mild_cleaning" in special_needs:
# 温和清洁需求添加舒缓成分
if add["function"] == "soothing":
add["concentration"] = add["max_concentration"] * 0.8
selected.append(add)
return selected
def generate_formula(self, pet_type: str, current_ph: float = 7.0) -> Dict[str, Any]:
"""
生成完整的宠物沐浴露配方
Args:
pet_type: 宠物品类 (cat/dog/rabbit/hamster)
current_ph: 当前pH值
Returns:
完整配方字典,包含所有成分及比例
"""
# 验证宠物品类
if pet_type not in self.pet_profiles:
raise ValueError(f"不支持的宠物品类: {pet_type}")
profile = self.pet_profiles[pet_type]
# 计算目标pH
target_ph_info = self.ph_calculator.get_ph_adjustment_strategy(pet_type, current_ph)
target_ph = target_ph_info["target_ph"]
# 获取毛发和皮肤因子
hair_factor = self._get_hair_type_factor(profile["hair_type"])
skin_factor = self._get_skin_thickness_factor(profile["skin_thickness"])
# 选择各类型成分
surfactants = self._select_surfactants(pet_type, target_ph)
conditioners = self._select_conditioners(pet_type, profile["hair_type"])
additives = self._select_additives(pet_type)
# 计算水相比例
total_active = sum(s["concentration"] for s in surfactants) + \
sum(c["concentration"] for c in conditioners) + \
sum(a["concentration"] for a in additives)
water_ratio = 100 - total_active
# 构建完整配方
formula = {
"pet_type": pet_type,
"pet_profile": profile,
"ph_info": {
"current_ph": current_ph,
"target_ph": round(target_ph, 2),
"adjustment_strategy": target_ph_info["action"]
},
"ingredients": {
"water_phase": {
"去离子水": round(water_ratio, 2)
},
"surfactants": {s["name"]: s["concentration"] for s in surfactants},
"conditioners": {c["name"]: c["concentration"] for c in conditioners},
"additives": {a["name"]: a["concentration"] for a in additives}
},
"formula_summary": {
"total_active_matter": round(total_active, 2),
"surfactant_total": round(sum(s["concentration"] for s in surfactants), 2),
"conditioner_total": round(sum(c["concentration"] for c in conditioners), 2),
"additive_total": round(sum(a["concentration"] for a in additives), 2)
},
"usage_instructions": self._generate_usage_instructions(pet_type)
}
return formula
def _generate_usage_instructions(self, pet_type: str) -> str:
"""生成使用说明"""
instructions = {
"cat": "用温水湿润毛发后,取适量沐浴露轻柔按摩,避开眼周,停留不超过3分钟后冲洗干净。每月最多使用2次。",
"dog": "温水充分湿润后,均匀涂抹沐浴露,重点清洁脚掌和尾部,按摩2-3分钟后彻底冲洗。每周1次或按需使用。",
"rabbit": "使用温水(不超过38℃)轻柔湿润,少量多次涂抹,快速按摩后立即冲洗。每月最多1次,建议使用免洗泡沫替代。",
"hamster": "仅在必要时使用,用温水蘸湿软布轻拭即可,避免长时间浸泡。建议咨询兽医后使用。"
}
return instructions.get(pet_type, "请参考宠物专用洗护指南")
5. 安全检查模块 (modules/safety_checker.py)
"""
安全检查模块 - 验证配方的化学成分安全性
"""
from typing import Dict, List, Tuple
class SafetyChecker:
"""安全检查器类,负责验证配方的化学安全性"""
# 成分配伍禁忌表
INCOMPATIBLE_PAIRS = [
("椰油酰胺丙基甜菜碱", "月桂酰肌氨酸钠"), # 两性+阴离子在某些情况下可能沉淀
("聚季铵盐-7", "阴离子表活") # 阳离子+阴离子会产生沉淀
]
# 禁用成分列表(针对特定宠物)
FORBIDDEN_INGREDIENTS = {
"hamster": ["聚季铵盐-7", "香精", "色素"],
"rabbit": ["精油", "高浓度防腐剂"]
}
def __init__(self):
"""初始化安全检查器"""
pass
def check_formula_safety(self, formula: Dict[str, Any]) -> Dict[str, Any]:
"""
全面检查配方安全性
Args:
formula: 配方字典
Returns:
包含安全检查结果的字典
"""
pet_type = formula["pet_type"]
ingredients = formula["ingredients"]
results = {
"is_safe": True,
"warnings": [],
"errors": [],
"compatibility_issues": [],
"forbidden_ingredients_found": []
}
# 1. 检查禁用成分
forbidden = self.FORBIDDEN_INGREDIENTS.get(pet_type, [])
all_ingredients = []
for category in ["surfactants", "conditioners", "additives"]:
all_ingredients.extend(ingredients[category].keys())
for ing in all_ingredients:
if any(f in ing for f in forbidden):
results["is_safe"] = False
results["forbidden_ingredients_found"].append(ing)
results["errors"].append(f"发现禁用成分: {ing} (不适合{self._get_pet_name(pet_type)})")
# 2. 检查成分配伍性
compatibility_issues = self._check_compatibility(ingredients)
if compatibility_issues:
results["is_safe"] = False
results["compatibility_issues"] = compatibility_issues
results["errors"].extend([f"成分配伍问题: {issue}" for issue in compatibility_issues])
# 3. 检查浓度安全性
concentration_warnings = self._check_concentrations(formula)
if concentration_warnings:
results["warnings"].extend(concentration_warnings)
# 4. 生成安全评分
results["safety_score"] = self._calculate_safety_score(results)
return results
def _check_compatibility(self, ingredients: Dict[str, Dict]) -> List[str]:
"""检查成分间的配伍禁忌"""
issues = []
all_ingredients = []
for category in ["surfactants", "conditioners", "additives"]:
all_ingredients.extend(ingredients[category].keys())
for pair in self.INCOMPATIBLE_PAIRS:
if pair[0] in all_ingredients and pair[1] in all_ingredients:
issues.append(f"{pair[0]} 与 {pair[1]} 可能存在配伍禁忌,建议分开添加或替换其中一种")
return issues
def _check_concentrations(self, formula: Dict[str, Any]) -> List[str]:
"""检查各成分浓度是否在安全范围内"""
warnings = []
pet_type = formula["pet_type"]
profile = formula["pet_profile"]
sensitivity = profile["sensitivity"]
# 根据敏感度设置警告阈值
warning_threshold = {
"extreme": 0.9, # 极高敏感度,超过90%最大浓度警告
"very_high": 0.85,
"high": 0.8,
"medium": 0.75,
"low": 0.7
}.get(sensitivity, 0.8)
for category in ["surfactants", "conditioners", "additives"]:
for name, conc in formula["ingredients"][category].items():
# 这里简化检查,实际应用中需要查询原始数据库获取max_concentration
if conc > 10 and sensitivity in ["extreme", "very_high"]:
warnings.append(f"{category[:-1]} '{name}' 浓度较高({conc}%),可能对{self._get_pet_name(pet_type)}造成刺激")
return warnings
def _calculate_safety_score(self, results: Dict[str, Any]) -> int:
"""计算安全评分(0-100)"""
score = 100
score -= len(results["errors"]) * 25 # 每个错误扣25分
score -= len(results["warnings"]) * 10 # 每个警告扣10分
score -= len(results["compatibility_issues"]) * 20 # 每个配伍问题扣20分
return max(0, score)
def _get_pet_name(self, pet_type: str) -> str:
"""获取宠物的中文名称"""
names = {
"cat": "猫咪",
"dog": "狗狗",
"rabbit": "兔子",
"hamster": "仓鼠"
}
return names.get(pet_type, pet_type)
def print_safety_report(self, results: Dict[str, Any]) -> None:
"""打印安全检查报告"""
print("\n" + "="*50)
print("🔍 配方安全检查结果")
print("="*50)
if results["is_safe"]:
print("✅ 配方安全,可以放心使用!")
else:
print("❌ 配方存在安全隐患,请修改后重新检查!")
print(f"\n📊 安全评分: {results['safety_score']}/100")
if results["errors"]:
print("\n⚠️ 严重问题:")
for error in results["errors"]:
print(f" • {error}")
if results["warnings"]:
print("\n💡 注意事项:")
for warning in results["warnings"]:
print(f" • {warning}")
if results["compatibility_issues"]:
print("\n🔄 配伍建议:")
for issue in results["compatibility_issues"]:
print(f" • {issue}")
if results["forbidden_ingredients_found"]:
print("\n🚫 发现禁用成分:")
for ing in results["forbidden_ingredients_found"]:
print(f" • {ing}")
print("="*50 + "\n")
利用AI解决实际问题,如果你觉得这个工具好用,欢迎关注长安牧笛!
