kdrug-inventory-system/add_sample_herb_data.py
시골약사 037e307637 feat: 약재 효능 태그 시스템 추가
- herb_efficacy_tags 테이블 생성 (효능 마스터)
- herb_item_tags 테이블 생성 (약재-효능 다대다 관계)
- 18개 기본 효능 태그 등록 (보혈, 활혈, 보기 등)
- Git 사용 가이드라인 문서 추가

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-02-17 02:57:57 +00:00

341 lines
14 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
한약재 샘플 데이터 추가 스크립트
주요 약재들의 확장 정보와 효능 태그를 추가합니다.
"""
import sqlite3
from datetime import datetime
def get_connection():
"""데이터베이스 연결"""
return sqlite3.connect('database/kdrug.db')
def add_herb_extended_data():
"""약재 확장 정보 추가"""
conn = get_connection()
cursor = conn.cursor()
# 주요 약재들의 확장 정보
herbs_data = [
{
'ingredient_code': '3400H1AHM', # 인삼
'property': '',
'taste': '감,미고',
'meridian_tropism': '비,폐,심',
'main_effects': '대보원기, 보비익폐, 생진지갈, 안신증지',
'indications': '기허증, 비허증, 폐허증, 심기허증, 진액부족, 당뇨병',
'contraindications': '실증, 열증, 음허화왕',
'precautions': '복용 중 무 섭취 금지, 고혈압 환자 주의',
'dosage_range': '3-9g',
'dosage_max': '30g',
'active_compounds': '인삼사포닌(ginsenoside Rb1, Rg1, Rg3), 다당체, 아미노산',
'pharmacological_effects': '면역증강, 항피로, 항산화, 혈당조절, 인지능력개선',
'clinical_applications': '만성피로, 면역력저하, 당뇨병 보조치료, 노인성 인지저하',
'tags': [('보기', 5), ('보양', 4), ('안신', 3), ('진통', 2)]
},
{
'ingredient_code': '3400H1ADL', # 감초
'property': '',
'taste': '',
'meridian_tropism': '비,위,폐,심',
'main_effects': '보비익기, 청열해독, 거담지해, 완급지통, 조화제약',
'indications': '비허증, 해수, 인후통, 소화성궤양, 경련성 통증',
'contraindications': '습증, 수종, 고혈압',
'precautions': '장기복용 시 부종 주의, 칼륨 감소 주의',
'dosage_range': '2-10g',
'dosage_max': '30g',
'active_compounds': 'glycyrrhizin, liquiritin, flavonoid, triterpenoid',
'pharmacological_effects': '항염증, 항궤양, 간보호, 진해거담, 항알레르기',
'clinical_applications': '위염, 위궤양, 기관지염, 약물조화, 간염',
'tags': [('보기', 3), ('청열', 3), ('해독', 4), ('거담', 3), ('항염', 4)]
},
{
'ingredient_code': '3400H1ACD', # 당귀
'property': '',
'taste': '감,신',
'meridian_tropism': '간,심,비',
'main_effects': '보혈활혈, 조경지통, 윤장통변',
'indications': '혈허증, 월경부조, 무월경, 변비, 타박상',
'contraindications': '설사, 습성체질',
'precautions': '과량 복용 시 설사 주의',
'dosage_range': '5-15g',
'dosage_max': '30g',
'active_compounds': 'ligustilide, n-butylidene phthalide, ferulic acid',
'pharmacological_effects': '혈액순환개선, 항혈전, 자궁수축조절, 진정진통',
'clinical_applications': '빈혈, 월경불순, 산후조리, 혈액순환장애',
'tags': [('보혈', 5), ('활혈', 5), ('진통', 3)]
},
{
'ingredient_code': '3400H1AGN', # 황기
'property': '',
'taste': '',
'meridian_tropism': '비,폐',
'main_effects': '보기승양, 고표지한, 이수소종, 탁독배농',
'indications': '기허증, 자한, 부종, 탈항, 자궁탈수',
'contraindications': '표실증, 음허화왕',
'precautions': '감기 초기 금지',
'dosage_range': '10-30g',
'dosage_max': '60g',
'active_compounds': 'astragaloside, polysaccharide, flavonoid',
'pharmacological_effects': '면역조절, 항바이러스, 항산화, 신기능보호',
'clinical_applications': '면역력저하, 만성신장염, 당뇨병, 심부전',
'tags': [('보기', 5), ('이수', 3), ('해표', 2)]
},
{
'ingredient_code': '3400H1AEW', # 작약
'property': '',
'taste': '고,산',
'meridian_tropism': '간,비',
'main_effects': '양혈조경, 유간지통, 렴음지한',
'indications': '혈허증, 월경부조, 간혈부족, 자한도한',
'contraindications': '양허설사',
'precautions': '한성약물과 병용 주의',
'dosage_range': '6-15g',
'dosage_max': '30g',
'active_compounds': 'paeoniflorin, albiflorin, benzoic acid',
'pharmacological_effects': '진정진통, 항경련, 항염증, 면역조절',
'clinical_applications': '월경통, 근육경련, 두통, 자가면역질환',
'tags': [('보혈', 4), ('평간', 4), ('진통', 4)]
},
{
'ingredient_code': '3400H1ACF', # 천궁
'property': '',
'taste': '',
'meridian_tropism': '간,담,심포',
'main_effects': '활혈행기, 거풍지통',
'indications': '혈어증, 두통, 월경불순, 풍습비통',
'contraindications': '음허화왕, 월경과다',
'precautions': '출혈 경향 환자 주의',
'dosage_range': '3-10g',
'dosage_max': '15g',
'active_compounds': 'ligustilide, senkyunolide, ferulic acid',
'pharmacological_effects': '혈관확장, 항혈전, 진정진통, 항염증',
'clinical_applications': '편두통, 혈관성 두통, 어혈증, 월경통',
'tags': [('활혈', 5), ('이기', 4), ('진통', 5)]
},
{
'ingredient_code': '3400H1ACG', # 지황(숙지황)
'property': '',
'taste': '',
'meridian_tropism': '간,신',
'main_effects': '보혈자음, 익정전수',
'indications': '혈허증, 간신음허, 수발조백, 유정도한',
'contraindications': '비허설사, 담습',
'precautions': '소화불량 주의',
'dosage_range': '10-30g',
'dosage_max': '60g',
'active_compounds': 'catalpol, rehmannioside, aucubin',
'pharmacological_effects': '조혈촉진, 면역조절, 혈당강하, 신경보호',
'clinical_applications': '빈혈, 당뇨병, 치매예방, 불임증',
'tags': [('보혈', 5), ('보음', 5)]
},
{
'ingredient_code': '3400H1AFJ', # 백출
'property': '',
'taste': '고,감',
'meridian_tropism': '비,위',
'main_effects': '건비익기, 조습이수, 지한안태',
'indications': '비허증, 식욕부진, 설사, 수종, 자한',
'contraindications': '음허조갈',
'precautions': '진액부족 시 주의',
'dosage_range': '6-15g',
'dosage_max': '30g',
'active_compounds': 'atractylenolide, atractylon',
'pharmacological_effects': '위장운동촉진, 이뇨, 항염증, 항종양',
'clinical_applications': '만성설사, 부종, 임신오조',
'tags': [('보기', 4), ('이수', 4), ('소화', 3)]
},
{
'ingredient_code': '3400H1AGM', # 복령
'property': '',
'taste': '감,담',
'meridian_tropism': '심,비,폐,신',
'main_effects': '이수삼습, 건비안신',
'indications': '수종, 소변불리, 비허설사, 불면, 심계',
'contraindications': '음허진액부족',
'precautions': '이뇨제와 병용 주의',
'dosage_range': '10-15g',
'dosage_max': '30g',
'active_compounds': 'pachymic acid, polysaccharide',
'pharmacological_effects': '이뇨, 진정, 항염증, 면역조절',
'clinical_applications': '부종, 불면증, 만성설사',
'tags': [('이수', 5), ('안신', 3), ('보기', 2)]
},
{
'ingredient_code': '3400H1AGI', # 반하
'property': '',
'taste': '',
'meridian_tropism': '비,위,폐',
'main_effects': '조습화담, 강역지구, 소비산결',
'indications': '습담, 구토, 해수담다, 현훈',
'contraindications': '음허조해, 임신',
'precautions': '임산부 금기, 생품 독성 주의',
'dosage_range': '5-10g',
'dosage_max': '15g',
'active_compounds': 'ephedrine, β-sitosterol',
'pharmacological_effects': '진토, 진해거담, 항종양',
'clinical_applications': '임신오조, 기관지염, 현훈증',
'tags': [('거담', 5), ('소화', 3)]
}
]
for herb in herbs_data:
# herb_master_extended 업데이트
cursor.execute("""
UPDATE herb_master_extended
SET property = ?,
taste = ?,
meridian_tropism = ?,
main_effects = ?,
indications = ?,
contraindications = ?,
precautions = ?,
dosage_range = ?,
dosage_max = ?,
active_compounds = ?,
pharmacological_effects = ?,
clinical_applications = ?,
updated_at = CURRENT_TIMESTAMP
WHERE ingredient_code = ?
""", (
herb['property'], herb['taste'], herb['meridian_tropism'],
herb['main_effects'], herb['indications'], herb['contraindications'],
herb['precautions'], herb['dosage_range'], herb['dosage_max'],
herb['active_compounds'], herb['pharmacological_effects'],
herb['clinical_applications'], herb['ingredient_code']
))
# herb_id 조회
cursor.execute("""
SELECT herb_id FROM herb_master_extended
WHERE ingredient_code = ?
""", (herb['ingredient_code'],))
result = cursor.fetchone()
if result:
herb_id = result[0]
# 효능 태그 매핑
for tag_name, strength in herb.get('tags', []):
# 태그 ID 조회
cursor.execute("""
SELECT tag_id FROM herb_efficacy_tags
WHERE tag_name = ?
""", (tag_name,))
tag_result = cursor.fetchone()
if tag_result:
tag_id = tag_result[0]
# 태그 매핑 추가
cursor.execute("""
INSERT OR REPLACE INTO herb_item_tags
(herb_id, tag_id, strength)
VALUES (?, ?, ?)
""", (herb_id, tag_id, strength))
print(f"{herb['ingredient_code']} 데이터 추가 완료")
conn.commit()
conn.close()
def add_prescription_rules():
"""처방 배합 규칙 추가"""
conn = get_connection()
cursor = conn.cursor()
# 몇 가지 대표적인 배합 규칙 추가
rules = [
# 상수(相須) - 서로 도와서 효과를 증강
{
'herb1': '인삼', 'herb2': '황기',
'relationship': '상수',
'description': '두 약재가 함께 사용되면 보기 효과가 증강됨',
'severity': 0
},
{
'herb1': '당귀', 'herb2': '천궁',
'relationship': '상수',
'description': '혈액순환 개선 효과가 증강됨',
'severity': 0
},
# 상사(相使) - 한 약이 다른 약의 효능을 도움
{
'herb1': '반하', 'herb2': '생강',
'relationship': '상사',
'description': '생강이 반하의 독성을 감소시킴',
'severity': 0
},
# 상반(相反) - 함께 사용하면 독성이나 부작용 발생
{
'herb1': '감초', 'herb2': '감수',
'relationship': '상반',
'description': '십팔반(十八反) - 함께 사용 금기',
'severity': 5,
'is_absolute': True
},
{
'herb1': '인삼', 'herb2': '오령지',
'relationship': '상반',
'description': '십구외(十九畏) - 함께 사용 주의',
'severity': 4,
'is_absolute': False
}
]
for rule in rules:
# herb_id 조회
cursor.execute("""
SELECT herb_id FROM herb_master_extended
WHERE name_korean = ?
""", (rule['herb1'],))
herb1_result = cursor.fetchone()
cursor.execute("""
SELECT herb_id FROM herb_master_extended
WHERE name_korean = ?
""", (rule['herb2'],))
herb2_result = cursor.fetchone()
if herb1_result and herb2_result:
cursor.execute("""
INSERT OR REPLACE INTO prescription_rules
(herb1_id, herb2_id, relationship_type, description,
severity_level, is_absolute)
VALUES (?, ?, ?, ?, ?, ?)
""", (
herb1_result[0], herb2_result[0],
rule['relationship'], rule['description'],
rule['severity'], rule.get('is_absolute', False)
))
print(f"{rule['herb1']} - {rule['herb2']} 규칙 추가")
conn.commit()
conn.close()
def main():
"""메인 실행 함수"""
print("\n" + "="*80)
print("한약재 샘플 데이터 추가")
print("="*80 + "\n")
try:
# 1. 약재 확장 정보 및 태그 추가
print("1. 약재 확장 정보 추가 중...")
add_herb_extended_data()
# 2. 처방 규칙 추가
print("\n2. 처방 배합 규칙 추가 중...")
add_prescription_rules()
print("\n✨ 모든 샘플 데이터가 성공적으로 추가되었습니다!")
except Exception as e:
print(f"\n❌ 오류 발생: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()