Files
site11/backup-services/ai-writer/backend/test_prompt_generation.py
2025-09-28 20:41:57 +09:00

240 lines
9.7 KiB
Python

#!/usr/bin/env python3
"""
AI Writer Service - 프롬프트 기반 기사 생성 테스트
다양한 스타일과 키워드로 기사를 생성하는 테스트
"""
import asyncio
import httpx
import json
from datetime import datetime
# Service URL
SERVICE_URL = "http://localhost:8019"
async def test_different_styles():
"""다양한 스타일로 기사 생성 테스트"""
test_cases = [
{
"keyword": "전기차",
"style": "professional",
"description": "전통적인 뉴스 기사 스타일"
},
{
"keyword": "전기차",
"style": "analytical",
"description": "분석적이고 심층적인 스타일"
},
{
"keyword": "전기차",
"style": "investigative",
"description": "탐사보도 스타일"
}
]
async with httpx.AsyncClient(timeout=180.0) as client:
for test_case in test_cases:
print("\n" + "="*70)
print(f" {test_case['description']} 테스트")
print("="*70)
print(f"키워드: {test_case['keyword']}")
print(f"스타일: {test_case['style']}")
print("-" * 50)
try:
response = await client.post(
f"{SERVICE_URL}/api/generate",
json={
"keyword": test_case["keyword"],
"limit": 3, # RSS 항목 수 줄여서 빠른 테스트
"google_results_per_title": 2,
"lang": "ko",
"country": "KR",
"style": test_case["style"]
}
)
if response.status_code == 200:
article = response.json()
print(f"\n✅ 기사 생성 성공!")
print(f"📰 제목: {article['title']}")
print(f"📝 요약: {article['summary']}")
print(f"🔍 카테고리: {', '.join(article['categories'])}")
print(f"📚 소주제 수: {len(article['subtopics'])}")
# 키워드 출력
if 'entities' in article and 'keywords' in article['entities']:
keywords = article['entities']['keywords']
print(f"🔑 키워드 ({len(keywords)}개): {', '.join(keywords[:5])}" +
("..." if len(keywords) > 5 else ""))
# 이벤트 정보 출력
if 'entities' in article and 'events' in article['entities']:
events = article['entities']['events']
if events:
print(f"📅 이벤트 ({len(events)}개):")
for evt in events[:2]: # 처음 2개만 표시
if isinstance(evt, dict):
evt_str = f" - {evt.get('name', '')}"
if evt.get('date'):
evt_str += f" [{evt['date']}]"
if evt.get('location'):
evt_str += f" @{evt['location']}"
print(evt_str)
# 첫 번째 소주제의 첫 문단만 출력
if article['subtopics']:
first_topic = article['subtopics'][0]
print(f"\n첫 번째 소주제: {first_topic['title']}")
if first_topic['content']:
print(f"미리보기: {first_topic['content'][0][:200]}...")
# 파일로 저장
filename = f"article_{test_case['keyword']}_{test_case['style']}.json"
with open(filename, 'w', encoding='utf-8') as f:
json.dump(article, f, ensure_ascii=False, indent=2)
print(f"\n💾 '{filename}'에 저장됨")
else:
print(f"❌ 오류: {response.status_code}")
print(f"상세: {response.text}")
except Exception as e:
print(f"❌ 테스트 실패: {e}")
# 다음 테스트 전 잠시 대기
await asyncio.sleep(2)
async def test_different_keywords():
"""다양한 키워드로 기사 생성 테스트"""
keywords = ["블록체인", "메타버스", "우주개발", "기후변화", "K-POP"]
async with httpx.AsyncClient(timeout=180.0) as client:
print("\n" + "="*70)
print(" 다양한 키워드 테스트")
print("="*70)
for keyword in keywords:
print(f"\n🔍 키워드: {keyword}")
print("-" * 30)
try:
response = await client.post(
f"{SERVICE_URL}/api/generate",
json={
"keyword": keyword,
"limit": 2, # 빠른 테스트를 위해 줄임
"google_results_per_title": 2,
"lang": "ko",
"country": "KR",
"style": "professional"
}
)
if response.status_code == 200:
article = response.json()
print(f"✅ 성공: {article['title'][:50]}...")
print(f" 카테고리: {', '.join(article['categories'][:3])}")
else:
print(f"❌ 실패: {response.status_code}")
except Exception as e:
print(f"❌ 오류: {e}")
await asyncio.sleep(1)
async def test_custom_prompt():
"""커스텀 프롬프트 테스트 - 직접 aggregated 데이터 제공"""
# 미리 수집된 데이터를 시뮬레이션
custom_news_data = {
"keyword": "2025년 기술 트렌드",
"news_items": [
{
"rss_title": "AI와 로봇이 바꾸는 2025년 일상",
"google_results": [
{
"title": "전문가들이 예측하는 2025년 AI 혁명",
"snippet": "2025년 AI 기술이 일상생활 전반을 혁신할 전망...",
"full_content": {
"url": "https://example.com/ai-2025",
"content": "2025년에는 AI가 의료, 교육, 업무 등 모든 분야에서 인간과 협업하는 시대가 열릴 것으로 전망된다. 특히 생성형 AI의 발전으로 창의적 작업에서도 AI의 역할이 크게 확대될 것이다."
}
}
]
},
{
"rss_title": "양자컴퓨터 상용화 임박",
"google_results": [
{
"title": "IBM, 2025년 1000큐비트 양자컴퓨터 출시 예정",
"snippet": "IBM이 2025년 상용 양자컴퓨터 출시를 앞두고...",
"full_content": {
"url": "https://example.com/quantum-2025",
"content": "양자컴퓨팅이 드디어 실용화 단계에 접어들었다. 2025년에는 금융, 제약, 물류 등 다양한 산업에서 양자컴퓨터를 활용한 혁신이 시작될 전망이다."
}
}
]
}
]
}
async with httpx.AsyncClient(timeout=180.0) as client:
print("\n" + "="*70)
print(" 커스텀 데이터로 기사 생성")
print("="*70)
for style in ["professional", "analytical"]:
print(f"\n스타일: {style}")
print("-" * 30)
try:
response = await client.post(
f"{SERVICE_URL}/api/generate/from-aggregated",
json=custom_news_data,
params={"style": style}
)
if response.status_code == 200:
article = response.json()
print(f"✅ 제목: {article['title']}")
print(f" 요약: {article['summary']}")
# 스타일별로 저장
filename = f"custom_article_{style}.json"
with open(filename, 'w', encoding='utf-8') as f:
json.dump(article, f, ensure_ascii=False, indent=2)
print(f" 💾 '{filename}'에 저장됨")
else:
print(f"❌ 실패: {response.text}")
except Exception as e:
print(f"❌ 오류: {e}")
await asyncio.sleep(2)
async def main():
"""메인 테스트 실행"""
print("\n" + "="*70)
print(" AI Writer 프롬프트 기반 기사 생성 테스트")
print("="*70)
# 1. 다양한 스타일 테스트
print("\n[1] 스타일별 기사 생성 테스트")
await test_different_styles()
# 2. 다양한 키워드 테스트
print("\n[2] 키워드별 기사 생성 테스트")
await test_different_keywords()
# 3. 커스텀 데이터 테스트
print("\n[3] 커스텀 데이터 기사 생성 테스트")
await test_custom_prompt()
print("\n" + "="*70)
print(" 모든 테스트 완료!")
print("="*70)
if __name__ == "__main__":
asyncio.run(main())