pharmacy-pos-qr-system/backend/ashwagandha_sleep_research.py
시골약사 97cf89a9c2 feat: PubMed 기반 GraphRAG 연구 스크립트 추가
근거 기반 약물 추천을 위한 PubMed 논문 검색 및 분석 스크립트:

1. pubmed_search.py
   - PubMed 논문 검색 기본 템플릿
   - Biopython Entrez API 활용
   - 3가지 주제 검색 예시 포함

2. fetch_paper_abstract.py
   - PMID로 논문 초록 가져오기
   - 특정 논문 상세 정보 조회

3. analyze_statin_myopathy.py
   - Statin 근육병증과 CoQ10 보충 연구 분석
   - CK(Creatine Kinase) 측정의 의미 설명

4. ashwagandha_sleep_research.py
   - Ashwagandha의 수면 개선 효과 연구
   - 작용 메커니즘 분석 (코르티솔, GABA)
   - 다른 수면 보조제와 비교

5. naproxen_advantages_research.py
   - Naproxen의 심혈관 안전성 연구
   - NSAID 간 비교 분석
   - 약동학 및 업셀링 시나리오

6. pycnogenol_multi_indication_research.py
   - 피크노제놀의 7가지 적응증 연구
   - 발기부전, 당뇨망막병증, 정맥기능부전 등
   - 우선순위 점수화

7. pycnogenol_womens_health_research.py
   - 피크노제놀의 여성 건강 효능
   - 갱년기, 생리통, 피부 미용

8. sqlite_graph_example.py
   - SQLite 그래프 쿼리 예제
   - Cypher 스타일 추론 시연
   - GraphRAG 개념 실습

각 스크립트는 Windows 한글 인코딩 처리 포함.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-24 21:04:33 +09:00

320 lines
11 KiB
Python

"""
Ashwagandha(아쉬와간다) 수면 개선 효과 논문 검색 및 분석
"""
import sys
import os
# UTF-8 인코딩 강제
if sys.platform == 'win32':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
from Bio import Entrez
from dotenv import load_dotenv
load_dotenv()
Entrez.email = os.getenv('PUBMED_EMAIL', 'test@example.com')
api_key = os.getenv('PUBMED_API_KEY')
if api_key:
Entrez.api_key = api_key
def search_ashwagandha_sleep(max_results=5):
"""Ashwagandha 수면 개선 효과 논문 검색"""
query = "ashwagandha sleep quality insomnia"
try:
print("=" * 80)
print("PubMed 검색: Ashwagandha 수면 개선 효과")
print("=" * 80)
print(f"검색어: '{query}'")
print("-" * 80)
# 1. 검색
handle = Entrez.esearch(
db="pubmed",
term=query,
retmax=max_results,
sort="relevance"
)
record = Entrez.read(handle)
handle.close()
pmids = record["IdList"]
total_count = int(record["Count"])
if not pmids:
print("[WARNING] 검색 결과 없음")
return []
print(f"[OK] 총 {total_count}건 검색됨, 상위 {len(pmids)}건 조회 중...\n")
# 2. 논문 상세 정보 가져오기
handle = Entrez.efetch(
db="pubmed",
id=pmids,
rettype="medline",
retmode="xml"
)
papers = Entrez.read(handle)
handle.close()
results = []
for idx, paper in enumerate(papers['PubmedArticle'], 1):
try:
article = paper['MedlineCitation']['Article']
# PMID
pmid = str(paper['MedlineCitation']['PMID'])
# 제목
title = article.get('ArticleTitle', '(제목 없음)')
# 초록 (전체)
abstract_parts = article.get('Abstract', {}).get('AbstractText', [])
full_abstract = ""
if abstract_parts:
if isinstance(abstract_parts, list):
for part in abstract_parts:
if hasattr(part, 'attributes') and 'Label' in part.attributes:
label = part.attributes['Label']
full_abstract += f"\n\n**{label}**\n{str(part)}"
else:
full_abstract += f"\n{str(part)}"
else:
full_abstract = str(abstract_parts)
else:
full_abstract = "(초록 없음)"
# 저널
journal = article.get('Journal', {}).get('Title', '(저널 없음)')
# 출판 연도
pub_date = article.get('Journal', {}).get('JournalIssue', {}).get('PubDate', {})
year = pub_date.get('Year', '(연도 없음)')
# 저자
authors = article.get('AuthorList', [])
if authors:
first_author = authors[0]
last_name = first_author.get('LastName', '')
initials = first_author.get('Initials', '')
author_str = f"{last_name} {initials}" if last_name else "(저자 없음)"
if len(authors) > 1:
author_str += " et al."
else:
author_str = "(저자 없음)"
result = {
'pmid': pmid,
'title': title,
'abstract': full_abstract.strip(),
'journal': journal,
'year': year,
'author': author_str
}
results.append(result)
# 출력
print(f"[{idx}] PMID: {pmid}")
print(f"제목: {title}")
print(f"저자: {author_str}")
print(f"저널: {journal} ({year})")
print(f"링크: https://pubmed.ncbi.nlm.nih.gov/{pmid}/")
print("-" * 80)
print(f"초록:\n{full_abstract}")
print("=" * 80)
print()
except Exception as e:
print(f"[ERROR] 논문 파싱 실패: {e}")
continue
return results
except Exception as e:
print(f"[ERROR] PubMed 검색 실패: {e}")
return []
def analyze_sleep_mechanism():
"""Ashwagandha 수면 개선 메커니즘 설명"""
print("\n\n" + "=" * 80)
print("Ashwagandha(위타니아 솜니페라) 수면 개선 메커니즘")
print("=" * 80)
mechanisms = [
{
"메커니즘": "1. 코르티솔 감소 (스트레스 호르몬)",
"설명": """
Ashwagandha는 HPA axis(시상하부-뇌하수체-부신 축)를 조절하여
코르티솔 분비를 감소시킵니다.
코르티솔 ↓ → 스트레스 감소 → 수면 품질 향상
【작용 성분】
- Withanolides (위타놀라이드)
- Withaferin A
"""
},
{
"메커니즘": "2. GABA 수용체 활성화",
"설명": """
GABA = 뇌의 억제성 신경전달물질
(진정, 이완 효과)
Ashwagandha → GABA-A 수용체 활성화
→ 뇌 활동 억제
→ 수면 유도
벤조디아제핀과 유사한 메커니즘이지만
의존성이 훨씬 낮음
"""
},
{
"메커니즘": "3. 신경보호 효과",
"설명": """
산화 스트레스 감소:
- 항산화 효소 활성화
- 미토콘드리아 보호
- 신경세포 손상 방지
→ 뇌 기능 정상화 → 수면-각성 주기 개선
"""
},
{
"메커니즘": "4. 불안 감소 (Anxiolytic effect)",
"설명": """
불안 → 불면증의 주요 원인
Ashwagandha는:
- 세로토닌 수치 조절
- 도파민 대사 개선
- 편도체 활성 억제
→ 불안 감소 → 수면 개선
"""
}
]
for item in mechanisms:
print(f"\n{item['메커니즘']}")
print(item['설명'])
print("-" * 80)
def compare_sleep_aids():
"""수면 보조제 비교"""
print("\n\n" + "=" * 80)
print("수면 보조제 비교: Ashwagandha vs 기타")
print("=" * 80)
comparison = """
┌─────────────────┬──────────────┬──────────────┬──────────────┬──────────────┐
│ 성분 │ 작용기전 │ 효과시간 │ 의존성 │ 부작용 │
├─────────────────┼──────────────┼──────────────┼──────────────┼──────────────┤
│ Ashwagandha │ 스트레스 감소│ 2-4주 │ 거의 없음 │ 매우 적음 │
│ (300-600mg) │ GABA 활성화 │ (누적 효과) │ │ │
├─────────────────┼──────────────┼──────────────┼──────────────┼──────────────┤
│ 멜라토닌 │ 수면-각성 │ 30-60분 │ 없음 │ 적음 │
│ (0.5-5mg) │ 주기 조절 │ (즉시 효과) │ │ (다음날 졸림)│
├─────────────────┼──────────────┼──────────────┼──────────────┼──────────────┤
│ L-Theanine │ 알파파 증가 │ 1-2시간 │ 없음 │ 거의 없음 │
│ (200-400mg) │ 이완 효과 │ │ │ │
├─────────────────┼──────────────┼──────────────┼──────────────┼──────────────┤
│ 마그네슘 │ NMDA 차단 │ 1-2주 │ 없음 │ 설사 가능 │
│ (300-500mg) │ GABA 증가 │ │ │ (과량 시) │
├─────────────────┼──────────────┼──────────────┼──────────────┼──────────────┤
│ 벤조디아제핀 │ GABA-A │ 15-30분 │ ⚠️ 매우 높음│ 많음 │
│ (처방약) │ 직접 작용 │ (즉시 효과) │ │ (내성, 금단) │
└─────────────────┴──────────────┴──────────────┴──────────────┴──────────────┘
【Ashwagandha 장점】
✅ 근본 원인 해결 (스트레스 감소)
✅ 의존성 없음
✅ 부작용 매우 적음
✅ 장기 복용 안전
【Ashwagandha 단점】
❌ 즉각적인 효과 없음 (2-4주 필요)
❌ 갑상선 기능항진증 환자 주의
❌ 임신/수유 중 금기
"""
print(comparison)
def main():
"""메인 실행"""
print("\n" + "=" * 80)
print("Ashwagandha 수면 개선 효과 연구 분석")
print("=" * 80)
print()
# 1. 논문 검색
results = search_ashwagandha_sleep(max_results=5)
# 2. 메커니즘 설명
analyze_sleep_mechanism()
# 3. 수면 보조제 비교
compare_sleep_aids()
# 4. 최종 요약
print("\n\n" + "=" * 80)
print("최종 요약: Ashwagandha 수면 개선 효과")
print("=" * 80)
summary = """
📊 근거 수준: ⭐⭐⭐⭐ (다수의 RCT 존재)
✅ 주요 효과:
1. 수면의 질 개선 (Sleep Quality Index ↑)
2. 수면 잠복기 감소 (잠들기까지 걸리는 시간 ↓)
3. 총 수면 시간 증가
4. 야간 각성 감소
📋 권장 용량:
- 일반적: 300-600mg/일 (표준화 추출물)
- 복용 시간: 저녁 식후
- 기간: 최소 2-4주 (누적 효과)
⚠️ 주의사항:
- 갑상선 기능항진증: 복용 금지
- 임신/수유: 안전성 미확립
- 자가면역질환: 의사 상담 필요
- 진정제와 병용 시 주의
💊 약국 추천 시나리오:
"스트레스로 인한 불면증"
→ Ashwagandha + 멜라토닌 병용
(Ashwagandha: 장기 개선 / 멜라토닌: 즉시 효과)
📚 GraphRAG 활용:
지식 그래프:
(Stress) -causes-> (Insomnia)
(Ashwagandha) -reduces-> (Cortisol)
(Low_Cortisol) -improves-> (Sleep_Quality)
(PMID:xxxxxxx) -supports-> (Ashwagandha -> Sleep)
"""
print(summary)
print("\n" + "=" * 80)
print(f"{len(results)}개 논문 분석 완료")
print("=" * 80)
if __name__ == '__main__':
main()