pharmacy-pos-qr-system/backend/fetch_paper_abstract.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

123 lines
3.8 KiB
Python

"""
PubMed에서 특정 논문의 전체 초록 가져오기
"""
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 fetch_abstract(pmid):
"""PMID로 논문 전체 초록 가져오기"""
try:
handle = Entrez.efetch(
db="pubmed",
id=pmid,
rettype="abstract",
retmode="xml"
)
papers = Entrez.read(handle)
handle.close()
if not papers['PubmedArticle']:
print(f"[ERROR] PMID {pmid} 논문을 찾을 수 없습니다.")
return None
paper = papers['PubmedArticle'][0]
article = paper['MedlineCitation']['Article']
# 제목
title = article.get('ArticleTitle', '(제목 없음)')
# 저자
authors = article.get('AuthorList', [])
author_names = []
for author in authors[:3]: # 처음 3명만
last_name = author.get('LastName', '')
initials = author.get('Initials', '')
if last_name:
author_names.append(f"{last_name} {initials}")
authors_str = ', '.join(author_names)
if len(authors) > 3:
authors_str += ' et al.'
# 저널
journal = article.get('Journal', {}).get('Title', '(저널 없음)')
# 출판 연도
pub_date = article.get('Journal', {}).get('JournalIssue', {}).get('PubDate', {})
year = pub_date.get('Year', '(연도 없음)')
# 초록 (전체)
abstract_parts = article.get('Abstract', {}).get('AbstractText', [])
full_abstract = ""
if abstract_parts:
if isinstance(abstract_parts, list):
for part in abstract_parts:
# Label이 있는 경우 (Background, Methods, Results 등)
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 = "(초록 없음)"
print("=" * 80)
print(f"PMID: {pmid}")
print("=" * 80)
print(f"제목: {title}")
print(f"저자: {authors_str}")
print(f"저널: {journal} ({year})")
print(f"링크: https://pubmed.ncbi.nlm.nih.gov/{pmid}/")
print("=" * 80)
print(f"초록:{full_abstract}")
print("=" * 80)
return {
'pmid': pmid,
'title': title,
'authors': authors_str,
'journal': journal,
'year': year,
'abstract': full_abstract.strip()
}
except Exception as e:
print(f"[ERROR] 논문 가져오기 실패: {e}")
return None
if __name__ == '__main__':
# PMID: 30371340 - Statin과 CoQ10 메타분석
pmid = "30371340"
print("\n[INFO] 논문 초록 가져오는 중...\n")
result = fetch_abstract(pmid)
if result:
print("\n\n[한글 요약]")
print("=" * 80)
print("이 논문은 2018년 발표된 메타분석 연구로,")
print("Statin(고지혈증 치료제) 복용으로 인한 근육 통증(근육병증)에")
print("CoQ10 보충제가 효과가 있는지를 여러 무작위 대조 실험(RCT)을")
print("종합 분석한 연구입니다.")
print("=" * 80)