astrology-ziwei-api / archive /integrate_all_rules.py
th
chore: 归档17个一次性规则提取/整合脚本 — 生产目录卫生
8218f34
Raw History Blame Contribute Delete
6.73 kB
#!/usr/bin/env python3
"""
一次性整合所有剩余规则
从Google Notebook提取的578条规则中,整合所有未添加的规则
"""
import json
import re
# 读取Google Notebook提取的全部578条规则
print("📖 读取Google Notebook提取的规则文件...")
with open('/Volumes/sparksverse/agent-knowledge/mingli-knowledge/eastern/ziwei/interpretations/02-practical-divination rules.md', 'r', encoding='utf-8') as f:
content = f.read()
# 提取JSON数组(从```json标记后开始)
# 首先移除markdown代码块标记
content = re.sub(r'```json\s*', '', content)
content = re.sub(r'```\s*$', '', content)
# 修复age_range字段的格式错误
# 修复 "age_range":, 和 "age_range": null
content = re.sub(r'"age_range"\s*:\s*,', '"age_range": [20, 70],', content)
content = re.sub(r'"age_range"\s*:\s*null', '"age_range": [20, 70]', content)
# 提取JSON数组
json_match = re.search(r'\[\s*\{', content)
if not json_match:
print("❌ 未找到JSON数组起始位置")
exit(1)
json_start = json_match.start()
# 找到最后一个 }]
json_end = content.rfind('}]') + 2
json_content = content[json_start:json_end]
print("🔄 解析JSON数据...")
try:
all_rules = json.loads(json_content)
except json.JSONDecodeError as e:
print(f"❌ JSON解析错误: {e}")
print(f"错误位置: {e.pos}")
print(f"错误行: {e.lineno}")
print(f"错误列: {e.colno}")
# 显示错误附近的内容
error_context_start = max(0, e.pos - 100)
error_context_end = min(len(json_content), e.pos + 100)
print(f"\n错误上下文:\n{json_content[error_context_start:error_context_end]}")
exit(1)
print(f"✅ 成功解析 {len(all_rules)} 条规则")
# 已经整合的规则ID
# SC301-SC400: Batch 02 (100条)
# SC401-SC420: Batch 01 (20条)
integrated_ids = set([f'SC{i:03d}' for i in range(301, 401)]) # SC301-SC400
integrated_ids.update([f'SC{i:03d}' for i in range(401, 421)]) # SC401-SC420
print(f"\n已整合规则数量: {len(integrated_ids)}")
print(f"已整合ID范围: SC301-SC400 (100条), SC401-SC420 (20条)")
# 筛选出未整合的规则
new_rules = []
for rule in all_rules:
rule_id = rule.get('id', '')
if rule_id not in integrated_ids:
new_rules.append(rule)
print(f"\n未整合规则数量: {len(new_rules)}")
# 为未整合的规则重新分配ID
# 分配范围: SC501开始
print("\n🔢 重新分配规则ID...")
next_id = 501
id_mapping = {}
for rule in new_rules:
old_id = rule['id']
new_id = f'SC{next_id:03d}'
id_mapping[old_id] = new_id
rule['id'] = new_id
next_id += 1
print(f"✅ 重新分配完成: SC501-SC{next_id-1:03d} ({len(new_rules)}条)")
# 修复格式问题
print("\n🔧 修复格式问题...")
fixed_count = 0
for rule in new_rules:
# 修复age_range
if 'age_range' not in rule or rule['age_range'] is None or rule['age_range'] == '':
rule['age_range'] = [20, 70]
fixed_count += 1
# 修复effect_level中的"微WEAK"
if rule.get('effect_level') == '微WEAK':
rule['effect_level'] = 'VERY_WEAK'
fixed_count += 1
print(f"✅ 修复 {fixed_count} 处格式问题")
# 生成Python代码格式的规则
print("\n📝 生成Python代码...")
def format_rule_to_python(rule):
"""将规则转换为Python代码格式,使用正确的Enum语法"""
# Category映射
category_map = {
'性格特质': 'RuleCategory.PERSONALITY',
'事业财运': 'RuleCategory.CAREER',
'婚姻感情': 'RuleCategory.RELATIONSHIP',
'健康状况': 'RuleCategory.HEALTH',
'运势走向': 'RuleCategory.FORTUNE',
'才华能力': 'RuleCategory.TALENT',
'人际交往': 'RuleCategory.SOCIAL'
}
# EffectLevel映射
effect_map = {
'极强': 'EffectLevel.VERY_STRONG',
'强': 'EffectLevel.STRONG',
'中': 'EffectLevel.MEDIUM',
'弱': 'EffectLevel.WEAK',
'微弱': 'EffectLevel.VERY_WEAK',
'VERY_WEAK': 'EffectLevel.VERY_WEAK'
}
category = category_map.get(rule['category'], 'RuleCategory.PERSONALITY')
effect = effect_map.get(rule['effect_level'], 'EffectLevel.MEDIUM')
# 格式化stars_required
stars_str = str(rule['stars_required'])
# 格式化palace_types
palace_str = str(rule['palace_types'])
# 格式化conditions
conditions = rule['conditions']
conditions_str = f"""{{
'same_palace': {conditions.get('same_palace', False)},
'transformations': {conditions.get('transformations')},
'brightness': {conditions.get('brightness')},
'palace_position': {conditions.get('palace_position')}
}}"""
# 格式化interpretations
interp = rule['interpretations']
interp_str = f"""{{
'core_meaning': {repr(interp.get('core_meaning', ''))},
'personality': {interp.get('personality', [])},
'career': {interp.get('career', [])},
'relationship': {interp.get('relationship', [])},
'fortune_timing': {repr(interp.get('fortune_timing', ''))},
'warnings': {interp.get('warnings', [])}
}}"""
return f""" {{
"id": "{rule['id']}",
"name": "{rule['name']}",
"category": {category},
"stars_required": {stars_str},
"palace_types": {palace_str},
"conditions": {conditions_str},
"interpretations": {interp_str},
"effect_level": {effect},
"compatibility_score": {rule['compatibility_score']},
"age_range": {rule['age_range']},
"source": "{rule['source']}"
}}"""
# 生成所有新规则的Python代码
new_rules_code = ',\n'.join([format_rule_to_python(rule) for rule in new_rules])
# 保存为Python文件
output = f'''"""
Google Notebook 提取规则 - 全部未整合规则
规则数量: {len(new_rules)}条 (SC501-SC{next_id-1:03d})
提取日期: 2025-12-12
来源: 南北派实战断诀
"""
from star_combination_rules import RuleCategory, EffectLevel
ALL_NEW_RULES = [
{new_rules_code}
]
'''
output_file = 'all_new_rules_extracted.py'
with open(output_file, 'w', encoding='utf-8') as f:
f.write(output)
print(f"✅ 已生成: {output_file}")
print(f" 包含 {len(new_rules)} 条新规则")
print(f" ID范围: SC501-SC{next_id-1:03d}")
# 统计信息
print("\n📊 统计信息:")
categories = {}
for rule in new_rules:
cat = rule['category']
categories[cat] = categories.get(cat, 0) + 1
for cat, count in sorted(categories.items(), key=lambda x: -x[1]):
print(f" {cat}: {count}条")
print("\n✅ 整合准备完成!")
print(f"现在有 {len(new_rules)} 条新规则准备添加到系统中")
print(f"原有220条 + 新增{len(new_rules)}条 = 总计{220 + len(new_rules)}条规则")