Initial commit - cleaned repository
This commit is contained in:
13
backup-services/ai-writer/backend/Dockerfile
Normal file
13
backup-services/ai-writer/backend/Dockerfile
Normal file
@ -0,0 +1,13 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application
|
||||
COPY . .
|
||||
|
||||
# Run the application
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
|
||||
0
backup-services/ai-writer/backend/app/__init__.py
Normal file
0
backup-services/ai-writer/backend/app/__init__.py
Normal file
218
backup-services/ai-writer/backend/app/article_generator.py
Normal file
218
backup-services/ai-writer/backend/app/article_generator.py
Normal file
@ -0,0 +1,218 @@
|
||||
"""
|
||||
Article Generation Module
|
||||
Claude API를 사용한 기사 생성 로직
|
||||
"""
|
||||
from typing import Dict, Any, List, Optional
|
||||
from datetime import datetime
|
||||
import json
|
||||
import uuid
|
||||
import logging
|
||||
from anthropic import AsyncAnthropic
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Data Models
|
||||
class NewsSource(BaseModel):
|
||||
"""뉴스 소스 정보"""
|
||||
title: str
|
||||
url: str
|
||||
published_date: Optional[str] = None
|
||||
source_site: str = "Unknown"
|
||||
|
||||
class EventInfo(BaseModel):
|
||||
"""이벤트 정보"""
|
||||
name: str
|
||||
date: Optional[str] = None
|
||||
location: Optional[str] = None
|
||||
|
||||
class Entities(BaseModel):
|
||||
"""추출된 엔티티"""
|
||||
people: List[str] = Field(default_factory=list)
|
||||
organizations: List[str] = Field(default_factory=list)
|
||||
groups: List[str] = Field(default_factory=list)
|
||||
countries: List[str] = Field(default_factory=list)
|
||||
events: List[EventInfo] = Field(default_factory=list)
|
||||
keywords: List[str] = Field(default_factory=list)
|
||||
|
||||
class SubTopic(BaseModel):
|
||||
"""기사 소주제"""
|
||||
title: str
|
||||
content: List[str]
|
||||
|
||||
class GeneratedArticle(BaseModel):
|
||||
"""생성된 기사"""
|
||||
news_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
|
||||
title: str
|
||||
summary: str
|
||||
subtopics: List[SubTopic]
|
||||
categories: List[str]
|
||||
entities: Entities
|
||||
sources: List[NewsSource] = Field(default_factory=list)
|
||||
created_at: datetime = Field(default_factory=datetime.now)
|
||||
generation_metadata: Dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
async def generate_article_with_claude(
|
||||
news_data: Dict[str, Any],
|
||||
style: str = "professional",
|
||||
claude_api_key: str = None
|
||||
) -> GeneratedArticle:
|
||||
"""Claude API를 사용하여 기사 생성"""
|
||||
|
||||
if not claude_api_key:
|
||||
import os
|
||||
claude_api_key = os.getenv("CLAUDE_API_KEY")
|
||||
|
||||
# Initialize Claude client
|
||||
claude_client = AsyncAnthropic(api_key=claude_api_key)
|
||||
|
||||
# Collect source information
|
||||
sources_info = []
|
||||
|
||||
# Prepare the prompt
|
||||
system_prompt = """당신은 전문적인 한국 언론사의 수석 기자입니다.
|
||||
제공된 데이터를 기반으로 깊이 있고 통찰력 있는 기사를 작성해야 합니다.
|
||||
기사는 다음 요구사항을 충족해야 합니다:
|
||||
|
||||
1. 소주제는 최소 2개, 최대 6개로 구성해야 합니다
|
||||
2. 각 소주제는 최소 1개, 최대 10개의 문단으로 구성해야 합니다
|
||||
3. 전문적이고 객관적인 어조를 유지해야 합니다
|
||||
4. 사실에 기반한 분석과 통찰을 제공해야 합니다
|
||||
5. 한국 독자를 대상으로 작성되어야 합니다
|
||||
6. 이벤트 정보는 가능한 일시와 장소를 포함해야 합니다
|
||||
7. 핵심 키워드를 최대 10개까지 추출해야 합니다
|
||||
|
||||
반드시 다음 JSON 형식으로 응답하세요:
|
||||
{
|
||||
"title": "기사 제목",
|
||||
"summary": "한 줄 요약 (100자 이내)",
|
||||
"subtopics": [
|
||||
{
|
||||
"title": "소주제 제목",
|
||||
"content": ["문단1", "문단2", ...] // 1-10개 문단
|
||||
}
|
||||
], // 2-6개 소주제
|
||||
"categories": ["카테고리1", "카테고리2"],
|
||||
"entities": {
|
||||
"people": ["인물1", "인물2"],
|
||||
"organizations": ["기관1", "기관2"],
|
||||
"groups": ["단체1", "단체2"],
|
||||
"countries": ["나라1", "나라2"],
|
||||
"events": [
|
||||
{
|
||||
"name": "이벤트명",
|
||||
"date": "2025년 1월 15일", // 선택사항
|
||||
"location": "서울 코엑스" // 선택사항
|
||||
}
|
||||
],
|
||||
"keywords": ["키워드1", "키워드2", ...] // 최대 10개
|
||||
}
|
||||
}"""
|
||||
|
||||
# Prepare news content for Claude and collect sources
|
||||
news_content = []
|
||||
for item in news_data.get("news_items", []):
|
||||
# Add RSS source info
|
||||
rss_title = item.get('rss_title', '')
|
||||
rss_link = item.get('rss_link', '')
|
||||
rss_published = item.get('rss_published', '')
|
||||
|
||||
if rss_title and rss_link:
|
||||
sources_info.append(NewsSource(
|
||||
title=rss_title,
|
||||
url=rss_link,
|
||||
published_date=rss_published,
|
||||
source_site="RSS Feed"
|
||||
))
|
||||
|
||||
item_text = f"제목: {rss_title}\n"
|
||||
for result in item.get("google_results", []):
|
||||
# Add Google search result sources
|
||||
if "title" in result and "link" in result:
|
||||
sources_info.append(NewsSource(
|
||||
title=result.get('title', ''),
|
||||
url=result.get('link', ''),
|
||||
published_date=None,
|
||||
source_site="Google Search"
|
||||
))
|
||||
|
||||
if "full_content" in result and result["full_content"]:
|
||||
content = result["full_content"]
|
||||
if isinstance(content, dict):
|
||||
item_text += f"출처: {content.get('url', '')}\n"
|
||||
item_text += f"내용: {content.get('content', '')[:1000]}...\n\n"
|
||||
else:
|
||||
item_text += f"내용: {str(content)[:1000]}...\n\n"
|
||||
news_content.append(item_text)
|
||||
|
||||
combined_content = "\n".join(news_content[:10]) # Limit to prevent token overflow
|
||||
|
||||
user_prompt = f"""다음 뉴스 데이터를 기반으로 종합적인 기사를 작성하세요:
|
||||
|
||||
키워드: {news_data.get('keyword', '')}
|
||||
수집된 뉴스 수: {len(news_data.get('news_items', []))}
|
||||
|
||||
뉴스 내용:
|
||||
{combined_content}
|
||||
|
||||
스타일: {style}
|
||||
- professional: 전통적인 뉴스 기사 스타일
|
||||
- analytical: 분석적이고 심층적인 스타일
|
||||
- investigative: 탐사보도 스타일
|
||||
|
||||
위의 데이터를 종합하여 통찰력 있는 기사를 JSON 형식으로 작성해주세요."""
|
||||
|
||||
try:
|
||||
# Call Claude API
|
||||
response = await claude_client.messages.create(
|
||||
model="claude-3-5-sonnet-20241022",
|
||||
max_tokens=4000,
|
||||
temperature=0.7,
|
||||
system=system_prompt,
|
||||
messages=[
|
||||
{"role": "user", "content": user_prompt}
|
||||
]
|
||||
)
|
||||
|
||||
# Parse response
|
||||
content = response.content[0].text
|
||||
|
||||
# Extract JSON from response
|
||||
json_start = content.find('{')
|
||||
json_end = content.rfind('}') + 1
|
||||
if json_start != -1 and json_end > json_start:
|
||||
json_str = content[json_start:json_end]
|
||||
article_data = json.loads(json_str)
|
||||
else:
|
||||
raise ValueError("No valid JSON found in response")
|
||||
|
||||
# Create article object
|
||||
article = GeneratedArticle(
|
||||
title=article_data.get("title", ""),
|
||||
summary=article_data.get("summary", ""),
|
||||
subtopics=[
|
||||
SubTopic(
|
||||
title=st.get("title", ""),
|
||||
content=st.get("content", [])
|
||||
) for st in article_data.get("subtopics", [])
|
||||
],
|
||||
categories=article_data.get("categories", []),
|
||||
entities=Entities(**article_data.get("entities", {})),
|
||||
sources=sources_info,
|
||||
generation_metadata={
|
||||
"style": style,
|
||||
"keyword": news_data.get('keyword', ''),
|
||||
"model": "claude-3-5-sonnet-20241022",
|
||||
"timestamp": datetime.now().isoformat()
|
||||
}
|
||||
)
|
||||
|
||||
logger.info(f"Successfully generated article: {article.title}")
|
||||
return article
|
||||
|
||||
except json.JSONDecodeError as e:
|
||||
logger.error(f"Failed to parse Claude response as JSON: {e}")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error generating article with Claude: {e}")
|
||||
raise
|
||||
746
backup-services/ai-writer/backend/app/main.py
Normal file
746
backup-services/ai-writer/backend/app/main.py
Normal file
@ -0,0 +1,746 @@
|
||||
"""
|
||||
AI Writer Service
|
||||
Claude API를 사용한 전문적인 뉴스 기사 생성 서비스
|
||||
"""
|
||||
from fastapi import FastAPI, HTTPException, BackgroundTasks
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from typing import List, Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, Field
|
||||
import httpx
|
||||
import asyncio
|
||||
import logging
|
||||
import json
|
||||
import uuid
|
||||
from anthropic import AsyncAnthropic
|
||||
import os
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI(
|
||||
title="AI Writer Service",
|
||||
description="Claude API를 사용한 전문적인 뉴스 기사 생성 서비스",
|
||||
version="1.0.0"
|
||||
)
|
||||
|
||||
# CORS 설정
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Configuration
|
||||
NEWS_AGGREGATOR_URL = os.getenv("NEWS_AGGREGATOR_URL", "http://news-aggregator-backend:8000")
|
||||
CLAUDE_API_KEY = os.getenv("CLAUDE_API_KEY", "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")
|
||||
MONGODB_URL = os.getenv("MONGODB_URL", "mongodb://mongodb:27017")
|
||||
DB_NAME = os.getenv("DB_NAME", "ai_writer_db")
|
||||
|
||||
# Claude client
|
||||
claude_client = AsyncAnthropic(api_key=CLAUDE_API_KEY)
|
||||
|
||||
# HTTP Client
|
||||
http_client = httpx.AsyncClient(timeout=120.0)
|
||||
|
||||
# Queue Manager
|
||||
from app.queue_manager import RedisQueueManager
|
||||
from app.queue_models import NewsJobData, JobResult, JobStatus, QueueStats
|
||||
queue_manager = RedisQueueManager(
|
||||
redis_url=os.getenv("REDIS_URL", "redis://redis:6379")
|
||||
)
|
||||
|
||||
# MongoDB client (optional for storing generated articles)
|
||||
from motor.motor_asyncio import AsyncIOMotorClient
|
||||
mongo_client = None
|
||||
db = None
|
||||
|
||||
# Data Models
|
||||
class NewsSource(BaseModel):
|
||||
"""참고한 뉴스 소스 정보"""
|
||||
title: str = Field(..., description="뉴스 제목")
|
||||
url: str = Field(..., description="뉴스 URL")
|
||||
published_date: Optional[str] = Field(None, description="발행일")
|
||||
source_site: Optional[str] = Field(None, description="출처 사이트")
|
||||
class SubTopic(BaseModel):
|
||||
"""기사 소주제"""
|
||||
title: str = Field(..., description="소주제 제목")
|
||||
content: List[str] = Field(..., description="소주제 내용 (문단 리스트)", min_items=1, max_items=10)
|
||||
|
||||
class Event(BaseModel):
|
||||
"""이벤트 정보"""
|
||||
name: str = Field(..., description="이벤트명")
|
||||
date: Optional[str] = Field(None, description="일시")
|
||||
location: Optional[str] = Field(None, description="장소")
|
||||
|
||||
class NewsEntities(BaseModel):
|
||||
"""뉴스에 포함된 개체들"""
|
||||
people: List[str] = Field(default_factory=list, description="뉴스에 포함된 인물")
|
||||
organizations: List[str] = Field(default_factory=list, description="뉴스에 포함된 기관")
|
||||
groups: List[str] = Field(default_factory=list, description="뉴스에 포함된 단체")
|
||||
countries: List[str] = Field(default_factory=list, description="뉴스에 포함된 나라")
|
||||
events: List[Event] = Field(default_factory=list, description="뉴스에 포함된 일정/이벤트 (일시와 장소 포함)")
|
||||
keywords: List[str] = Field(default_factory=list, description="핵심 키워드 (최대 10개)", max_items=10)
|
||||
|
||||
class GeneratedArticle(BaseModel):
|
||||
"""생성된 기사"""
|
||||
news_id: str = Field(..., description="뉴스 아이디")
|
||||
title: str = Field(..., description="뉴스 제목")
|
||||
created_at: str = Field(..., description="생성년월일시분초")
|
||||
summary: str = Field(..., description="한 줄 요약")
|
||||
subtopics: List[SubTopic] = Field(..., description="소주제 리스트", min_items=2, max_items=6)
|
||||
categories: List[str] = Field(..., description="카테고리 리스트")
|
||||
entities: NewsEntities = Field(..., description="뉴스에 포함된 개체들")
|
||||
source_keyword: Optional[str] = Field(None, description="원본 검색 키워드")
|
||||
source_count: Optional[int] = Field(None, description="참조한 소스 수")
|
||||
sources: List[NewsSource] = Field(default_factory=list, description="참고한 뉴스 소스 목록")
|
||||
|
||||
class ArticleGenerationRequest(BaseModel):
|
||||
"""기사 생성 요청"""
|
||||
keyword: str = Field(..., description="검색 키워드")
|
||||
limit: int = Field(5, description="처리할 RSS 항목 수", ge=1, le=20)
|
||||
google_results_per_title: int = Field(3, description="각 제목당 구글 검색 결과 수", ge=1, le=10)
|
||||
lang: str = Field("ko", description="언어 코드")
|
||||
country: str = Field("KR", description="국가 코드")
|
||||
style: str = Field("professional", description="기사 스타일 (professional/analytical/investigative)")
|
||||
|
||||
class PerItemGenerationRequest(BaseModel):
|
||||
"""개별 아이템별 기사 생성 요청"""
|
||||
keyword: str = Field(..., description="검색 키워드")
|
||||
limit: Optional[int] = Field(None, description="처리할 RSS 항목 수 (None이면 전체)")
|
||||
google_results_per_title: int = Field(3, description="각 제목당 구글 검색 결과 수", ge=1, le=10)
|
||||
lang: str = Field("ko", description="언어 코드")
|
||||
country: str = Field("KR", description="국가 코드")
|
||||
style: str = Field("professional", description="기사 스타일 (professional/analytical/investigative)")
|
||||
skip_existing: bool = Field(True, description="이미 생성된 기사는 건너뛰기")
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
"""서비스 시작"""
|
||||
global mongo_client, db
|
||||
try:
|
||||
mongo_client = AsyncIOMotorClient(MONGODB_URL)
|
||||
db = mongo_client[DB_NAME]
|
||||
logger.info("AI Writer Service starting...")
|
||||
logger.info(f"Connected to MongoDB: {MONGODB_URL}")
|
||||
|
||||
# Redis 큐 연결
|
||||
await queue_manager.connect()
|
||||
logger.info("Connected to Redis queue")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to connect to services: {e}")
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown():
|
||||
"""서비스 종료"""
|
||||
await http_client.aclose()
|
||||
if mongo_client:
|
||||
mongo_client.close()
|
||||
await queue_manager.disconnect()
|
||||
logger.info("AI Writer Service stopped")
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {
|
||||
"service": "AI Writer Service",
|
||||
"version": "1.0.0",
|
||||
"description": "Claude API를 사용한 전문적인 뉴스 기사 생성 서비스",
|
||||
"endpoints": {
|
||||
"generate_article": "POST /api/generate",
|
||||
"generate_per_item": "POST /api/generate/per-item",
|
||||
"generate_from_aggregated": "POST /api/generate/from-aggregated",
|
||||
"get_article": "GET /api/articles/{article_id}",
|
||||
"list_articles": "GET /api/articles",
|
||||
"health": "GET /health"
|
||||
}
|
||||
}
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
"""헬스 체크"""
|
||||
try:
|
||||
# Check News Aggregator service
|
||||
aggregator_response = await http_client.get(f"{NEWS_AGGREGATOR_URL}/health")
|
||||
aggregator_healthy = aggregator_response.status_code == 200
|
||||
|
||||
# Check MongoDB
|
||||
mongo_healthy = False
|
||||
if db is not None:
|
||||
await db.command("ping")
|
||||
mongo_healthy = True
|
||||
|
||||
return {
|
||||
"status": "healthy" if (aggregator_healthy and mongo_healthy) else "degraded",
|
||||
"services": {
|
||||
"news_aggregator": "healthy" if aggregator_healthy else "unhealthy",
|
||||
"mongodb": "healthy" if mongo_healthy else "unhealthy",
|
||||
"claude_api": "configured"
|
||||
},
|
||||
"timestamp": datetime.now().isoformat()
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
"status": "unhealthy",
|
||||
"error": str(e),
|
||||
"timestamp": datetime.now().isoformat()
|
||||
}
|
||||
|
||||
async def generate_article_with_claude(news_data: Dict[str, Any], style: str = "professional") -> GeneratedArticle:
|
||||
"""Claude API를 사용하여 기사 생성"""
|
||||
|
||||
# Collect source information
|
||||
sources_info = []
|
||||
|
||||
# Prepare the prompt
|
||||
system_prompt = """당신은 전문적인 한국 언론사의 수석 기자입니다.
|
||||
제공된 데이터를 기반으로 깊이 있고 통찰력 있는 기사를 작성해야 합니다.
|
||||
기사는 다음 요구사항을 충족해야 합니다:
|
||||
|
||||
1. 소주제는 최소 2개, 최대 6개로 구성해야 합니다
|
||||
2. 각 소주제는 최소 1개, 최대 10개의 문단으로 구성해야 합니다
|
||||
3. 전문적이고 객관적인 어조를 유지해야 합니다
|
||||
4. 사실에 기반한 분석과 통찰을 제공해야 합니다
|
||||
5. 한국 독자를 대상으로 작성되어야 합니다
|
||||
6. 이벤트 정보는 가능한 일시와 장소를 포함해야 합니다
|
||||
7. 핵심 키워드를 최대 10개까지 추출해야 합니다
|
||||
|
||||
반드시 다음 JSON 형식으로 응답하세요:
|
||||
{
|
||||
"title": "기사 제목",
|
||||
"summary": "한 줄 요약 (100자 이내)",
|
||||
"subtopics": [
|
||||
{
|
||||
"title": "소주제 제목",
|
||||
"content": ["문단1", "문단2", ...] // 1-10개 문단
|
||||
}
|
||||
], // 2-6개 소주제
|
||||
"categories": ["카테고리1", "카테고리2"],
|
||||
"entities": {
|
||||
"people": ["인물1", "인물2"],
|
||||
"organizations": ["기관1", "기관2"],
|
||||
"groups": ["단체1", "단체2"],
|
||||
"countries": ["나라1", "나라2"],
|
||||
"events": [
|
||||
{
|
||||
"name": "이벤트명",
|
||||
"date": "2025년 1월 15일", // 선택사항
|
||||
"location": "서울 코엑스" // 선택사항
|
||||
}
|
||||
],
|
||||
"keywords": ["키워드1", "키워드2", ...] // 최대 10개
|
||||
}
|
||||
}"""
|
||||
|
||||
# Prepare news content for Claude and collect sources
|
||||
news_content = []
|
||||
for item in news_data.get("news_items", []):
|
||||
# Add RSS source info
|
||||
rss_title = item.get('rss_title', '')
|
||||
rss_link = item.get('rss_link', '')
|
||||
rss_published = item.get('rss_published', '')
|
||||
|
||||
if rss_title and rss_link:
|
||||
sources_info.append(NewsSource(
|
||||
title=rss_title,
|
||||
url=rss_link,
|
||||
published_date=rss_published,
|
||||
source_site="RSS Feed"
|
||||
))
|
||||
|
||||
item_text = f"제목: {rss_title}\n"
|
||||
for result in item.get("google_results", []):
|
||||
# Add Google search result sources
|
||||
if "title" in result and "link" in result:
|
||||
sources_info.append(NewsSource(
|
||||
title=result.get('title', ''),
|
||||
url=result.get('link', ''),
|
||||
published_date=None,
|
||||
source_site="Google Search"
|
||||
))
|
||||
|
||||
if "full_content" in result and result["full_content"]:
|
||||
content = result["full_content"]
|
||||
if isinstance(content, dict):
|
||||
item_text += f"출처: {content.get('url', '')}\n"
|
||||
item_text += f"내용: {content.get('content', '')[:1000]}...\n\n"
|
||||
else:
|
||||
item_text += f"내용: {str(content)[:1000]}...\n\n"
|
||||
news_content.append(item_text)
|
||||
|
||||
combined_content = "\n".join(news_content[:10]) # Limit to prevent token overflow
|
||||
|
||||
user_prompt = f"""다음 뉴스 데이터를 기반으로 종합적인 기사를 작성하세요:
|
||||
|
||||
키워드: {news_data.get('keyword', '')}
|
||||
수집된 뉴스 수: {len(news_data.get('news_items', []))}
|
||||
|
||||
뉴스 내용:
|
||||
{combined_content}
|
||||
|
||||
스타일: {style}
|
||||
- professional: 전통적인 뉴스 기사 스타일
|
||||
- analytical: 분석적이고 심층적인 스타일
|
||||
- investigative: 탐사보도 스타일
|
||||
|
||||
위의 데이터를 종합하여 통찰력 있는 기사를 JSON 형식으로 작성해주세요."""
|
||||
|
||||
try:
|
||||
# Call Claude API
|
||||
response = await claude_client.messages.create(
|
||||
model="claude-3-5-sonnet-20241022", # Latest Claude model
|
||||
max_tokens=4000,
|
||||
temperature=0.7,
|
||||
system=system_prompt,
|
||||
messages=[
|
||||
{"role": "user", "content": user_prompt}
|
||||
]
|
||||
)
|
||||
|
||||
# Parse Claude's response
|
||||
content = response.content[0].text
|
||||
|
||||
# Extract JSON from response
|
||||
import re
|
||||
json_match = re.search(r'\{.*\}', content, re.DOTALL)
|
||||
if json_match:
|
||||
article_data = json.loads(json_match.group())
|
||||
else:
|
||||
# If no JSON found, try to parse the entire content
|
||||
article_data = json.loads(content)
|
||||
|
||||
# Create GeneratedArticle object
|
||||
entities_data = article_data.get("entities", {})
|
||||
events_data = entities_data.get("events", [])
|
||||
|
||||
# Parse events - handle both old string format and new object format
|
||||
parsed_events = []
|
||||
for event in events_data:
|
||||
if isinstance(event, str):
|
||||
# Old format: just event name as string
|
||||
parsed_events.append(Event(name=event))
|
||||
elif isinstance(event, dict):
|
||||
# New format: event object with name, date, location
|
||||
parsed_events.append(Event(
|
||||
name=event.get("name", ""),
|
||||
date=event.get("date"),
|
||||
location=event.get("location")
|
||||
))
|
||||
|
||||
article = GeneratedArticle(
|
||||
news_id=str(uuid.uuid4()),
|
||||
title=article_data.get("title", "제목 없음"),
|
||||
created_at=datetime.now().isoformat(),
|
||||
summary=article_data.get("summary", ""),
|
||||
subtopics=[
|
||||
SubTopic(
|
||||
title=st.get("title", ""),
|
||||
content=st.get("content", [])
|
||||
) for st in article_data.get("subtopics", [])
|
||||
],
|
||||
categories=article_data.get("categories", []),
|
||||
entities=NewsEntities(
|
||||
people=entities_data.get("people", []),
|
||||
organizations=entities_data.get("organizations", []),
|
||||
groups=entities_data.get("groups", []),
|
||||
countries=entities_data.get("countries", []),
|
||||
events=parsed_events,
|
||||
keywords=entities_data.get("keywords", [])
|
||||
),
|
||||
source_keyword=news_data.get("keyword"),
|
||||
source_count=len(news_data.get("news_items", [])),
|
||||
sources=sources_info
|
||||
)
|
||||
|
||||
return article
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error generating article with Claude: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Failed to generate article: {str(e)}")
|
||||
|
||||
@app.post("/api/generate")
|
||||
async def generate_article(request: ArticleGenerationRequest):
|
||||
"""
|
||||
뉴스 수집부터 기사 생성까지 전체 파이프라인 실행
|
||||
RSS → Google Search → AI 기사 생성
|
||||
단일 종합 기사 생성 (기존 방식)
|
||||
"""
|
||||
try:
|
||||
# Step 1: Get aggregated news from News Aggregator service
|
||||
logger.info(f"Fetching aggregated news for keyword: {request.keyword}")
|
||||
|
||||
aggregator_response = await http_client.get(
|
||||
f"{NEWS_AGGREGATOR_URL}/api/aggregate",
|
||||
params={
|
||||
"q": request.keyword,
|
||||
"limit": request.limit,
|
||||
"google_results_per_title": request.google_results_per_title,
|
||||
"lang": request.lang,
|
||||
"country": request.country
|
||||
}
|
||||
)
|
||||
aggregator_response.raise_for_status()
|
||||
news_data = aggregator_response.json()
|
||||
|
||||
if not news_data.get("news_items"):
|
||||
raise HTTPException(status_code=404, detail="No news items found for the given keyword")
|
||||
|
||||
# Step 2: Generate article using Claude
|
||||
logger.info(f"Generating article with Claude for {len(news_data['news_items'])} news items")
|
||||
article = await generate_article_with_claude(news_data, request.style)
|
||||
|
||||
# Step 3: Store article in MongoDB (optional)
|
||||
if db is not None:
|
||||
try:
|
||||
article_dict = article.dict()
|
||||
await db.articles.insert_one(article_dict)
|
||||
logger.info(f"Article saved with ID: {article.news_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to save article to MongoDB: {e}")
|
||||
|
||||
return article
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"HTTP error from aggregator service: {e}")
|
||||
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"Error in generate_article: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@app.post("/api/generate/from-aggregated", response_model=GeneratedArticle)
|
||||
async def generate_from_aggregated_data(news_data: Dict[str, Any], style: str = "professional"):
|
||||
"""
|
||||
이미 수집된 뉴스 데이터로부터 직접 기사 생성
|
||||
(News Aggregator 결과를 직접 입력받아 처리)
|
||||
"""
|
||||
try:
|
||||
if not news_data.get("news_items"):
|
||||
raise HTTPException(status_code=400, detail="No news items in provided data")
|
||||
|
||||
# Generate article using Claude
|
||||
logger.info(f"Generating article from {len(news_data['news_items'])} news items")
|
||||
article = await generate_article_with_claude(news_data, style)
|
||||
|
||||
# Store article in MongoDB
|
||||
if db is not None:
|
||||
try:
|
||||
article_dict = article.dict()
|
||||
await db.articles.insert_one(article_dict)
|
||||
logger.info(f"Article saved with ID: {article.news_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to save article to MongoDB: {e}")
|
||||
|
||||
return article
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in generate_from_aggregated_data: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@app.get("/api/articles/{article_id}", response_model=GeneratedArticle)
|
||||
async def get_article(article_id: str):
|
||||
"""저장된 기사 조회"""
|
||||
if db is None:
|
||||
raise HTTPException(status_code=503, detail="Database not available")
|
||||
|
||||
article = await db.articles.find_one({"news_id": article_id})
|
||||
if not article:
|
||||
raise HTTPException(status_code=404, detail="Article not found")
|
||||
|
||||
# Convert MongoDB document to GeneratedArticle
|
||||
article.pop("_id", None)
|
||||
return GeneratedArticle(**article)
|
||||
|
||||
@app.get("/api/articles")
|
||||
async def list_articles(
|
||||
skip: int = 0,
|
||||
limit: int = 10,
|
||||
keyword: Optional[str] = None,
|
||||
category: Optional[str] = None
|
||||
):
|
||||
"""저장된 기사 목록 조회"""
|
||||
if db is None:
|
||||
raise HTTPException(status_code=503, detail="Database not available")
|
||||
|
||||
query = {}
|
||||
if keyword:
|
||||
query["source_keyword"] = {"$regex": keyword, "$options": "i"}
|
||||
if category:
|
||||
query["categories"] = category
|
||||
|
||||
cursor = db.articles.find(query).skip(skip).limit(limit).sort("created_at", -1)
|
||||
articles = []
|
||||
async for article in cursor:
|
||||
article.pop("_id", None)
|
||||
articles.append(article)
|
||||
|
||||
total = await db.articles.count_documents(query)
|
||||
|
||||
return {
|
||||
"articles": articles,
|
||||
"total": total,
|
||||
"skip": skip,
|
||||
"limit": limit
|
||||
}
|
||||
|
||||
@app.post("/api/generate/batch")
|
||||
async def generate_batch_articles(keywords: List[str], style: str = "professional"):
|
||||
"""여러 키워드에 대한 기사 일괄 생성"""
|
||||
results = []
|
||||
errors = []
|
||||
|
||||
for keyword in keywords[:5]: # Limit to 5 keywords to prevent overload
|
||||
try:
|
||||
request = ArticleGenerationRequest(
|
||||
keyword=keyword,
|
||||
style=style
|
||||
)
|
||||
article = await generate_article(request)
|
||||
results.append({
|
||||
"keyword": keyword,
|
||||
"status": "success",
|
||||
"article_id": article.news_id,
|
||||
"title": article.title
|
||||
})
|
||||
except Exception as e:
|
||||
errors.append({
|
||||
"keyword": keyword,
|
||||
"status": "error",
|
||||
"error": str(e)
|
||||
})
|
||||
|
||||
return {
|
||||
"success": results,
|
||||
"errors": errors,
|
||||
"total_processed": len(results) + len(errors)
|
||||
}
|
||||
|
||||
@app.post("/api/generate/per-item")
|
||||
async def generate_articles_per_rss_item(request: PerItemGenerationRequest):
|
||||
"""
|
||||
RSS 피드의 각 아이템별로 개별 기사 생성
|
||||
각 RSS 아이템이 독립적인 기사가 됨
|
||||
중복 생성 방지 기능 포함
|
||||
"""
|
||||
try:
|
||||
# Step 1: Get aggregated news from News Aggregator service
|
||||
logger.info(f"Fetching aggregated news for keyword: {request.keyword}")
|
||||
|
||||
# limit이 None이면 모든 항목 처리 (최대 100개로 제한)
|
||||
actual_limit = request.limit if request.limit is not None else 100
|
||||
|
||||
aggregator_response = await http_client.get(
|
||||
f"{NEWS_AGGREGATOR_URL}/api/aggregate",
|
||||
params={
|
||||
"q": request.keyword,
|
||||
"limit": actual_limit,
|
||||
"google_results_per_title": request.google_results_per_title,
|
||||
"lang": request.lang,
|
||||
"country": request.country
|
||||
}
|
||||
)
|
||||
aggregator_response.raise_for_status()
|
||||
news_data = aggregator_response.json()
|
||||
|
||||
if not news_data.get("news_items"):
|
||||
raise HTTPException(status_code=404, detail="No news items found for the given keyword")
|
||||
|
||||
# Step 2: Check for existing articles if skip_existing is True
|
||||
existing_titles = set()
|
||||
skipped_count = 0
|
||||
|
||||
if request.skip_existing and db is not None:
|
||||
# RSS 제목으로 중복 체크 (최근 24시간 내)
|
||||
from datetime import datetime, timedelta
|
||||
cutoff_time = (datetime.now() - timedelta(hours=24)).isoformat()
|
||||
|
||||
existing_cursor = db.articles.find(
|
||||
{
|
||||
"source_keyword": request.keyword,
|
||||
"created_at": {"$gte": cutoff_time}
|
||||
},
|
||||
{"sources": 1}
|
||||
)
|
||||
|
||||
async for doc in existing_cursor:
|
||||
for source in doc.get("sources", []):
|
||||
if source.get("source_site") == "RSS Feed":
|
||||
existing_titles.add(source.get("title", ""))
|
||||
|
||||
# Step 3: Generate individual article for each RSS item
|
||||
generated_articles = []
|
||||
|
||||
for item in news_data["news_items"]:
|
||||
try:
|
||||
rss_title = item.get('rss_title', '')
|
||||
|
||||
# Skip if already exists
|
||||
if request.skip_existing and rss_title in existing_titles:
|
||||
logger.info(f"Skipping already generated article: {rss_title}")
|
||||
skipped_count += 1
|
||||
continue
|
||||
|
||||
logger.info(f"Generating article for RSS item: {rss_title or 'Unknown'}")
|
||||
|
||||
# Create individual news_data for this item
|
||||
individual_news_data = {
|
||||
"keyword": news_data.get("keyword"),
|
||||
"news_items": [item] # Single item only
|
||||
}
|
||||
|
||||
# Generate article for this single item
|
||||
article = await generate_article_with_claude(individual_news_data, request.style)
|
||||
|
||||
# Store in MongoDB
|
||||
if db is not None:
|
||||
try:
|
||||
article_dict = article.dict()
|
||||
await db.articles.insert_one(article_dict)
|
||||
logger.info(f"Article saved with ID: {article.news_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to save article to MongoDB: {e}")
|
||||
|
||||
generated_articles.append(article)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to generate article for item: {e}")
|
||||
# Continue with next item even if one fails
|
||||
continue
|
||||
|
||||
if not generated_articles and skipped_count == 0:
|
||||
raise HTTPException(status_code=500, detail="Failed to generate any articles")
|
||||
|
||||
# Return all generated articles
|
||||
return {
|
||||
"total_generated": len(generated_articles),
|
||||
"total_items": len(news_data["news_items"]),
|
||||
"skipped_duplicates": skipped_count,
|
||||
"articles": generated_articles
|
||||
}
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"HTTP error from aggregator service: {e}")
|
||||
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"Error in generate_articles_per_rss_item: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
# Queue Management Endpoints
|
||||
|
||||
@app.post("/api/queue/enqueue")
|
||||
async def enqueue_items(request: PerItemGenerationRequest):
|
||||
"""
|
||||
RSS 아이템들을 큐에 추가 (비동기 처리)
|
||||
Consumer 워커가 백그라운드에서 처리
|
||||
"""
|
||||
try:
|
||||
# Step 1: Get aggregated news from News Aggregator service
|
||||
logger.info(f"Fetching aggregated news for enqueue: {request.keyword}")
|
||||
|
||||
actual_limit = request.limit if request.limit is not None else 100
|
||||
|
||||
aggregator_response = await http_client.get(
|
||||
f"{NEWS_AGGREGATOR_URL}/api/aggregate",
|
||||
params={
|
||||
"q": request.keyword,
|
||||
"limit": actual_limit,
|
||||
"google_results_per_title": request.google_results_per_title,
|
||||
"lang": request.lang,
|
||||
"country": request.country
|
||||
}
|
||||
)
|
||||
aggregator_response.raise_for_status()
|
||||
news_data = aggregator_response.json()
|
||||
|
||||
if not news_data.get("news_items"):
|
||||
raise HTTPException(status_code=404, detail="No news items found for the given keyword")
|
||||
|
||||
# Step 2: Check for existing articles if skip_existing is True
|
||||
existing_titles = set()
|
||||
skipped_count = 0
|
||||
|
||||
if request.skip_existing and db is not None:
|
||||
from datetime import datetime, timedelta
|
||||
cutoff_time = (datetime.now() - timedelta(hours=24)).isoformat()
|
||||
|
||||
existing_cursor = db.articles.find(
|
||||
{
|
||||
"source_keyword": request.keyword,
|
||||
"created_at": {"$gte": cutoff_time}
|
||||
},
|
||||
{"sources": 1}
|
||||
)
|
||||
|
||||
async for doc in existing_cursor:
|
||||
for source in doc.get("sources", []):
|
||||
if source.get("source_site") == "RSS Feed":
|
||||
existing_titles.add(source.get("title", ""))
|
||||
|
||||
# Step 3: Enqueue items for processing
|
||||
enqueued_jobs = []
|
||||
|
||||
for item in news_data["news_items"]:
|
||||
rss_title = item.get('rss_title', '')
|
||||
|
||||
# Skip if already exists
|
||||
if request.skip_existing and rss_title in existing_titles:
|
||||
logger.info(f"Skipping already generated article: {rss_title}")
|
||||
skipped_count += 1
|
||||
continue
|
||||
|
||||
# Create job data
|
||||
job_data = NewsJobData(
|
||||
job_id=str(uuid.uuid4()),
|
||||
keyword=request.keyword,
|
||||
rss_title=rss_title,
|
||||
rss_link=item.get('rss_link'),
|
||||
rss_published=item.get('rss_published'),
|
||||
google_results=item.get('google_results', []),
|
||||
style=request.style,
|
||||
created_at=datetime.now()
|
||||
)
|
||||
|
||||
# Enqueue job
|
||||
job_id = await queue_manager.enqueue(job_data)
|
||||
enqueued_jobs.append({
|
||||
"job_id": job_id,
|
||||
"title": rss_title[:100]
|
||||
})
|
||||
|
||||
logger.info(f"Enqueued job {job_id} for: {rss_title}")
|
||||
|
||||
return {
|
||||
"total_enqueued": len(enqueued_jobs),
|
||||
"total_items": len(news_data["news_items"]),
|
||||
"skipped_duplicates": skipped_count,
|
||||
"jobs": enqueued_jobs,
|
||||
"message": f"{len(enqueued_jobs)} jobs added to queue for processing"
|
||||
}
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"HTTP error from aggregator service: {e}")
|
||||
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"Error in enqueue_items: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@app.get("/api/queue/stats", response_model=QueueStats)
|
||||
async def get_queue_stats():
|
||||
"""큐 상태 및 통계 조회"""
|
||||
try:
|
||||
stats = await queue_manager.get_stats()
|
||||
return stats
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting queue stats: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@app.delete("/api/queue/clear")
|
||||
async def clear_queue():
|
||||
"""큐 초기화 (관리자용)"""
|
||||
try:
|
||||
await queue_manager.clear_queue()
|
||||
return {"message": "Queue cleared successfully"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error clearing queue: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
250
backup-services/ai-writer/backend/app/queue_manager.py
Normal file
250
backup-services/ai-writer/backend/app/queue_manager.py
Normal file
@ -0,0 +1,250 @@
|
||||
"""
|
||||
Redis Queue Manager for AI Writer Service
|
||||
Redis를 사용한 작업 큐 관리
|
||||
"""
|
||||
import redis.asyncio as redis
|
||||
import json
|
||||
import uuid
|
||||
from typing import Optional, List, Dict, Any
|
||||
from datetime import datetime, timedelta
|
||||
import logging
|
||||
from queue_models import NewsJobData, JobResult, JobStatus, QueueStats
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class RedisQueueManager:
|
||||
"""Redis 기반 작업 큐 매니저"""
|
||||
|
||||
def __init__(self, redis_url: str = "redis://redis:6379"):
|
||||
self.redis_url = redis_url
|
||||
self.redis_client: Optional[redis.Redis] = None
|
||||
|
||||
# Redis 키 정의
|
||||
self.QUEUE_KEY = "ai_writer:queue:pending"
|
||||
self.PROCESSING_KEY = "ai_writer:queue:processing"
|
||||
self.COMPLETED_KEY = "ai_writer:queue:completed"
|
||||
self.FAILED_KEY = "ai_writer:queue:failed"
|
||||
self.STATS_KEY = "ai_writer:stats"
|
||||
self.WORKERS_KEY = "ai_writer:workers"
|
||||
self.LOCK_PREFIX = "ai_writer:lock:"
|
||||
|
||||
async def connect(self):
|
||||
"""Redis 연결"""
|
||||
if not self.redis_client:
|
||||
self.redis_client = await redis.from_url(
|
||||
self.redis_url,
|
||||
encoding="utf-8",
|
||||
decode_responses=True
|
||||
)
|
||||
logger.info("Connected to Redis queue")
|
||||
|
||||
async def disconnect(self):
|
||||
"""Redis 연결 해제"""
|
||||
if self.redis_client:
|
||||
await self.redis_client.close()
|
||||
self.redis_client = None
|
||||
logger.info("Disconnected from Redis queue")
|
||||
|
||||
async def enqueue(self, job_data: NewsJobData) -> str:
|
||||
"""작업을 큐에 추가"""
|
||||
try:
|
||||
if not job_data.job_id:
|
||||
job_data.job_id = str(uuid.uuid4())
|
||||
|
||||
# JSON으로 직렬화
|
||||
job_json = job_data.json()
|
||||
|
||||
# 우선순위에 따라 큐에 추가
|
||||
if job_data.priority > 0:
|
||||
# 높은 우선순위는 앞쪽에
|
||||
await self.redis_client.lpush(self.QUEUE_KEY, job_json)
|
||||
else:
|
||||
# 일반 우선순위는 뒤쪽에
|
||||
await self.redis_client.rpush(self.QUEUE_KEY, job_json)
|
||||
|
||||
# 통계 업데이트
|
||||
await self.redis_client.hincrby(self.STATS_KEY, "total_jobs", 1)
|
||||
await self.redis_client.hincrby(self.STATS_KEY, "pending_jobs", 1)
|
||||
|
||||
logger.info(f"Job {job_data.job_id} enqueued")
|
||||
return job_data.job_id
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to enqueue job: {e}")
|
||||
raise
|
||||
|
||||
async def dequeue(self, timeout: int = 0) -> Optional[NewsJobData]:
|
||||
"""큐에서 작업 가져오기 (블로킹 가능)"""
|
||||
try:
|
||||
# 대기 중인 작업을 가져와서 처리 중 목록으로 이동
|
||||
if timeout > 0:
|
||||
result = await self.redis_client.blmove(
|
||||
self.QUEUE_KEY,
|
||||
self.PROCESSING_KEY,
|
||||
timeout,
|
||||
"LEFT",
|
||||
"RIGHT"
|
||||
)
|
||||
else:
|
||||
result = await self.redis_client.lmove(
|
||||
self.QUEUE_KEY,
|
||||
self.PROCESSING_KEY,
|
||||
"LEFT",
|
||||
"RIGHT"
|
||||
)
|
||||
|
||||
if result:
|
||||
# 통계 업데이트
|
||||
await self.redis_client.hincrby(self.STATS_KEY, "pending_jobs", -1)
|
||||
await self.redis_client.hincrby(self.STATS_KEY, "processing_jobs", 1)
|
||||
|
||||
return NewsJobData.parse_raw(result)
|
||||
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to dequeue job: {e}")
|
||||
return None
|
||||
|
||||
async def mark_completed(self, job_id: str, article_id: str):
|
||||
"""작업을 완료로 표시"""
|
||||
try:
|
||||
# 처리 중 목록에서 작업 찾기
|
||||
processing_jobs = await self.redis_client.lrange(self.PROCESSING_KEY, 0, -1)
|
||||
|
||||
for job_json in processing_jobs:
|
||||
job = NewsJobData.parse_raw(job_json)
|
||||
if job.job_id == job_id:
|
||||
# 처리 중 목록에서 제거
|
||||
await self.redis_client.lrem(self.PROCESSING_KEY, 1, job_json)
|
||||
|
||||
# 완료 결과 생성
|
||||
result = JobResult(
|
||||
job_id=job_id,
|
||||
status=JobStatus.COMPLETED,
|
||||
article_id=article_id,
|
||||
completed_at=datetime.now()
|
||||
)
|
||||
|
||||
# 완료 목록에 추가 (최대 1000개 유지)
|
||||
await self.redis_client.lpush(self.COMPLETED_KEY, result.json())
|
||||
await self.redis_client.ltrim(self.COMPLETED_KEY, 0, 999)
|
||||
|
||||
# 통계 업데이트
|
||||
await self.redis_client.hincrby(self.STATS_KEY, "processing_jobs", -1)
|
||||
await self.redis_client.hincrby(self.STATS_KEY, "completed_jobs", 1)
|
||||
|
||||
logger.info(f"Job {job_id} marked as completed")
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to mark job as completed: {e}")
|
||||
|
||||
async def mark_failed(self, job_id: str, error_message: str):
|
||||
"""작업을 실패로 표시"""
|
||||
try:
|
||||
# 처리 중 목록에서 작업 찾기
|
||||
processing_jobs = await self.redis_client.lrange(self.PROCESSING_KEY, 0, -1)
|
||||
|
||||
for job_json in processing_jobs:
|
||||
job = NewsJobData.parse_raw(job_json)
|
||||
if job.job_id == job_id:
|
||||
# 처리 중 목록에서 제거
|
||||
await self.redis_client.lrem(self.PROCESSING_KEY, 1, job_json)
|
||||
|
||||
# 재시도 확인
|
||||
if job.retry_count < job.max_retries:
|
||||
job.retry_count += 1
|
||||
# 다시 큐에 추가
|
||||
await self.redis_client.rpush(self.QUEUE_KEY, job.json())
|
||||
await self.redis_client.hincrby(self.STATS_KEY, "pending_jobs", 1)
|
||||
logger.info(f"Job {job_id} requeued (retry {job.retry_count}/{job.max_retries})")
|
||||
else:
|
||||
# 실패 결과 생성
|
||||
result = JobResult(
|
||||
job_id=job_id,
|
||||
status=JobStatus.FAILED,
|
||||
error_message=error_message,
|
||||
completed_at=datetime.now()
|
||||
)
|
||||
|
||||
# 실패 목록에 추가
|
||||
await self.redis_client.lpush(self.FAILED_KEY, result.json())
|
||||
await self.redis_client.ltrim(self.FAILED_KEY, 0, 999)
|
||||
|
||||
# 통계 업데이트
|
||||
await self.redis_client.hincrby(self.STATS_KEY, "failed_jobs", 1)
|
||||
logger.error(f"Job {job_id} marked as failed: {error_message}")
|
||||
|
||||
await self.redis_client.hincrby(self.STATS_KEY, "processing_jobs", -1)
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to mark job as failed: {e}")
|
||||
|
||||
async def get_stats(self) -> QueueStats:
|
||||
"""큐 통계 조회"""
|
||||
try:
|
||||
stats_data = await self.redis_client.hgetall(self.STATS_KEY)
|
||||
|
||||
# 활성 워커 수 계산
|
||||
workers = await self.redis_client.smembers(self.WORKERS_KEY)
|
||||
active_workers = 0
|
||||
for worker_id in workers:
|
||||
# 워커가 최근 1분 이내에 활동했는지 확인
|
||||
last_ping = await self.redis_client.get(f"{self.WORKERS_KEY}:{worker_id}")
|
||||
if last_ping:
|
||||
last_ping_time = datetime.fromisoformat(last_ping)
|
||||
if datetime.now() - last_ping_time < timedelta(minutes=1):
|
||||
active_workers += 1
|
||||
|
||||
return QueueStats(
|
||||
pending_jobs=int(stats_data.get("pending_jobs", 0)),
|
||||
processing_jobs=int(stats_data.get("processing_jobs", 0)),
|
||||
completed_jobs=int(stats_data.get("completed_jobs", 0)),
|
||||
failed_jobs=int(stats_data.get("failed_jobs", 0)),
|
||||
total_jobs=int(stats_data.get("total_jobs", 0)),
|
||||
workers_active=active_workers
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to get stats: {e}")
|
||||
return QueueStats(
|
||||
pending_jobs=0,
|
||||
processing_jobs=0,
|
||||
completed_jobs=0,
|
||||
failed_jobs=0,
|
||||
total_jobs=0,
|
||||
workers_active=0
|
||||
)
|
||||
|
||||
async def register_worker(self, worker_id: str):
|
||||
"""워커 등록"""
|
||||
await self.redis_client.sadd(self.WORKERS_KEY, worker_id)
|
||||
await self.redis_client.set(
|
||||
f"{self.WORKERS_KEY}:{worker_id}",
|
||||
datetime.now().isoformat(),
|
||||
ex=300 # 5분 후 자동 만료
|
||||
)
|
||||
|
||||
async def ping_worker(self, worker_id: str):
|
||||
"""워커 활동 업데이트"""
|
||||
await self.redis_client.set(
|
||||
f"{self.WORKERS_KEY}:{worker_id}",
|
||||
datetime.now().isoformat(),
|
||||
ex=300
|
||||
)
|
||||
|
||||
async def unregister_worker(self, worker_id: str):
|
||||
"""워커 등록 해제"""
|
||||
await self.redis_client.srem(self.WORKERS_KEY, worker_id)
|
||||
await self.redis_client.delete(f"{self.WORKERS_KEY}:{worker_id}")
|
||||
|
||||
async def clear_queue(self):
|
||||
"""큐 초기화 (테스트용)"""
|
||||
await self.redis_client.delete(self.QUEUE_KEY)
|
||||
await self.redis_client.delete(self.PROCESSING_KEY)
|
||||
await self.redis_client.delete(self.COMPLETED_KEY)
|
||||
await self.redis_client.delete(self.FAILED_KEY)
|
||||
await self.redis_client.delete(self.STATS_KEY)
|
||||
logger.info("Queue cleared")
|
||||
49
backup-services/ai-writer/backend/app/queue_models.py
Normal file
49
backup-services/ai-writer/backend/app/queue_models.py
Normal file
@ -0,0 +1,49 @@
|
||||
"""
|
||||
Queue Models for AI Writer Service
|
||||
Redis 큐에서 사용할 데이터 모델 정의
|
||||
"""
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, List, Dict, Any
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
|
||||
class JobStatus(str, Enum):
|
||||
"""작업 상태"""
|
||||
PENDING = "pending"
|
||||
PROCESSING = "processing"
|
||||
COMPLETED = "completed"
|
||||
FAILED = "failed"
|
||||
SKIPPED = "skipped"
|
||||
|
||||
class NewsJobData(BaseModel):
|
||||
"""큐에 들어갈 뉴스 작업 데이터"""
|
||||
job_id: str = Field(..., description="작업 고유 ID")
|
||||
keyword: str = Field(..., description="원본 검색 키워드")
|
||||
rss_title: str = Field(..., description="RSS 제목")
|
||||
rss_link: Optional[str] = Field(None, description="RSS 링크")
|
||||
rss_published: Optional[str] = Field(None, description="RSS 발행일")
|
||||
google_results: List[Dict[str, Any]] = Field(default_factory=list, description="구글 검색 결과")
|
||||
style: str = Field("professional", description="기사 스타일")
|
||||
created_at: datetime = Field(default_factory=datetime.now, description="작업 생성 시간")
|
||||
priority: int = Field(0, description="우선순위 (높을수록 우선)")
|
||||
retry_count: int = Field(0, description="재시도 횟수")
|
||||
max_retries: int = Field(3, description="최대 재시도 횟수")
|
||||
|
||||
class JobResult(BaseModel):
|
||||
"""작업 결과"""
|
||||
job_id: str = Field(..., description="작업 고유 ID")
|
||||
status: JobStatus = Field(..., description="작업 상태")
|
||||
article_id: Optional[str] = Field(None, description="생성된 기사 ID")
|
||||
error_message: Optional[str] = Field(None, description="에러 메시지")
|
||||
processing_time: Optional[float] = Field(None, description="처리 시간(초)")
|
||||
completed_at: Optional[datetime] = Field(None, description="완료 시간")
|
||||
|
||||
class QueueStats(BaseModel):
|
||||
"""큐 통계"""
|
||||
pending_jobs: int = Field(..., description="대기 중인 작업 수")
|
||||
processing_jobs: int = Field(..., description="처리 중인 작업 수")
|
||||
completed_jobs: int = Field(..., description="완료된 작업 수")
|
||||
failed_jobs: int = Field(..., description="실패한 작업 수")
|
||||
total_jobs: int = Field(..., description="전체 작업 수")
|
||||
workers_active: int = Field(..., description="활성 워커 수")
|
||||
average_processing_time: Optional[float] = Field(None, description="평균 처리 시간(초)")
|
||||
201
backup-services/ai-writer/backend/app/worker.py
Normal file
201
backup-services/ai-writer/backend/app/worker.py
Normal file
@ -0,0 +1,201 @@
|
||||
"""
|
||||
AI Writer Consumer Worker
|
||||
큐에서 작업을 가져와 기사를 생성하는 백그라운드 워커
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
import os
|
||||
|
||||
from motor.motor_asyncio import AsyncIOMotorClient
|
||||
from anthropic import AsyncAnthropic
|
||||
|
||||
from queue_manager import RedisQueueManager
|
||||
from queue_models import NewsJobData, JobStatus
|
||||
from article_generator import generate_article_with_claude
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class AIWriterWorker:
|
||||
"""AI Writer 백그라운드 워커"""
|
||||
|
||||
def __init__(self, worker_id: Optional[str] = None):
|
||||
self.worker_id = worker_id or str(uuid.uuid4())
|
||||
self.queue_manager = RedisQueueManager(
|
||||
redis_url=os.getenv("REDIS_URL", "redis://redis:6379")
|
||||
)
|
||||
|
||||
# MongoDB 설정
|
||||
self.mongodb_url = os.getenv("MONGODB_URL", "mongodb://mongodb:27017")
|
||||
self.db_name = os.getenv("DB_NAME", "ai_writer_db")
|
||||
self.mongo_client = None
|
||||
self.db = None
|
||||
|
||||
# Claude 클라이언트
|
||||
self.claude_api_key = os.getenv("CLAUDE_API_KEY")
|
||||
self.claude_client = AsyncAnthropic(api_key=self.claude_api_key)
|
||||
|
||||
# 실행 상태
|
||||
self.running = False
|
||||
self.tasks = []
|
||||
|
||||
async def start(self, num_workers: int = 1):
|
||||
"""워커 시작"""
|
||||
logger.info(f"Starting AI Writer Worker {self.worker_id} with {num_workers} concurrent workers")
|
||||
|
||||
try:
|
||||
# Redis 연결
|
||||
await self.queue_manager.connect()
|
||||
await self.queue_manager.register_worker(self.worker_id)
|
||||
|
||||
# MongoDB 연결
|
||||
self.mongo_client = AsyncIOMotorClient(self.mongodb_url)
|
||||
self.db = self.mongo_client[self.db_name]
|
||||
logger.info("Connected to MongoDB")
|
||||
|
||||
self.running = True
|
||||
|
||||
# 여러 워커 태스크 생성
|
||||
for i in range(num_workers):
|
||||
task = asyncio.create_task(self._process_jobs(f"{self.worker_id}-{i}"))
|
||||
self.tasks.append(task)
|
||||
|
||||
# 워커 핑 태스크
|
||||
ping_task = asyncio.create_task(self._ping_worker())
|
||||
self.tasks.append(ping_task)
|
||||
|
||||
# 모든 태스크 대기
|
||||
await asyncio.gather(*self.tasks)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Worker error: {e}")
|
||||
finally:
|
||||
await self.stop()
|
||||
|
||||
async def stop(self):
|
||||
"""워커 정지"""
|
||||
logger.info(f"Stopping AI Writer Worker {self.worker_id}")
|
||||
self.running = False
|
||||
|
||||
# 태스크 취소
|
||||
for task in self.tasks:
|
||||
task.cancel()
|
||||
|
||||
# 워커 등록 해제
|
||||
await self.queue_manager.unregister_worker(self.worker_id)
|
||||
|
||||
# 연결 해제
|
||||
await self.queue_manager.disconnect()
|
||||
if self.mongo_client:
|
||||
self.mongo_client.close()
|
||||
|
||||
logger.info(f"Worker {self.worker_id} stopped")
|
||||
|
||||
async def _process_jobs(self, sub_worker_id: str):
|
||||
"""작업 처리 루프"""
|
||||
logger.info(f"Sub-worker {sub_worker_id} started")
|
||||
|
||||
while self.running:
|
||||
try:
|
||||
# 큐에서 작업 가져오기 (5초 타임아웃)
|
||||
job = await self.queue_manager.dequeue(timeout=5)
|
||||
|
||||
if job:
|
||||
logger.info(f"[{sub_worker_id}] Processing job {job.job_id}: {job.rss_title[:50]}")
|
||||
start_time = datetime.now()
|
||||
|
||||
try:
|
||||
# 기사 생성
|
||||
article = await self._generate_article(job)
|
||||
|
||||
# MongoDB에 저장
|
||||
if article and self.db is not None:
|
||||
article_dict = article.dict()
|
||||
await self.db.articles.insert_one(article_dict)
|
||||
|
||||
# 처리 시간 계산
|
||||
processing_time = (datetime.now() - start_time).total_seconds()
|
||||
|
||||
# 완료 표시
|
||||
await self.queue_manager.mark_completed(
|
||||
job.job_id,
|
||||
article.news_id
|
||||
)
|
||||
|
||||
logger.info(f"[{sub_worker_id}] Job {job.job_id} completed in {processing_time:.2f}s")
|
||||
else:
|
||||
raise Exception("Failed to generate article")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[{sub_worker_id}] Job {job.job_id} failed: {e}")
|
||||
await self.queue_manager.mark_failed(job.job_id, str(e))
|
||||
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
except Exception as e:
|
||||
logger.error(f"[{sub_worker_id}] Worker error: {e}")
|
||||
await asyncio.sleep(1)
|
||||
|
||||
logger.info(f"Sub-worker {sub_worker_id} stopped")
|
||||
|
||||
async def _generate_article(self, job: NewsJobData):
|
||||
"""기사 생성"""
|
||||
# 작업 데이터를 기존 형식으로 변환
|
||||
news_data = {
|
||||
"keyword": job.keyword,
|
||||
"news_items": [{
|
||||
"rss_title": job.rss_title,
|
||||
"rss_link": job.rss_link,
|
||||
"rss_published": job.rss_published,
|
||||
"google_results": job.google_results
|
||||
}]
|
||||
}
|
||||
|
||||
# 기사 생성 (기존 함수 재사용)
|
||||
return await generate_article_with_claude(news_data, job.style)
|
||||
|
||||
async def _ping_worker(self):
|
||||
"""워커 활동 신호 전송"""
|
||||
while self.running:
|
||||
try:
|
||||
await self.queue_manager.ping_worker(self.worker_id)
|
||||
await asyncio.sleep(30) # 30초마다 핑
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
except Exception as e:
|
||||
logger.error(f"Ping error: {e}")
|
||||
|
||||
def signal_handler(signum, frame):
|
||||
"""시그널 핸들러"""
|
||||
logger.info(f"Received signal {signum}")
|
||||
sys.exit(0)
|
||||
|
||||
async def main():
|
||||
"""메인 함수"""
|
||||
# 시그널 핸들러 등록
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
|
||||
# 워커 수 설정 (환경변수 또는 기본값)
|
||||
num_workers = int(os.getenv("WORKER_COUNT", "3"))
|
||||
|
||||
# 워커 시작
|
||||
worker = AIWriterWorker()
|
||||
try:
|
||||
await worker.start(num_workers=num_workers)
|
||||
except KeyboardInterrupt:
|
||||
logger.info("Keyboard interrupt received")
|
||||
finally:
|
||||
await worker.stop()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@ -0,0 +1,62 @@
|
||||
{
|
||||
"news_id": "49bdf2f3-4dbc-47eb-8c49-5d9536f41d87",
|
||||
"title": "유럽 전기차 시장의 새로운 전환점: 현대차·기아의 소형 전기차 전략과 글로벌 경쟁 구도",
|
||||
"created_at": "2025-09-13T00:29:13.376541",
|
||||
"summary": "현대차와 기아가 IAA 2025에서 소형 전기차 콘셉트 모델을 공개하며 유럽 시장 공략을 가속화, 배터리 협력과 가격 경쟁력으로 승부수",
|
||||
"subtopics": [
|
||||
{
|
||||
"title": "현대차·기아의 유럽 소형 전기차 시장 공략",
|
||||
"content": [
|
||||
"현대자동차와 기아가 IAA 2025에서 콘셉트 쓰리와 EV2를 공개하며 유럽 소형 전기차 시장 공략에 박차를 가하고 있다. 이는 유럽의 급성장하는 소형 전기차 수요에 대응하기 위한 전략적 움직임으로 평가된다.",
|
||||
"특히 두 모델은 실용성과 경제성을 모두 갖춘 제품으로, 유럽 소비자들의 니즈를 정확히 겨냥했다는 평가를 받고 있다. 현대차그룹은 이를 통해 유럽 시장에서의 입지를 더욱 강화할 것으로 전망된다.",
|
||||
"현지 전문가들은 현대차그룹의 이번 전략이 유럽 전기차 시장의 '골든타임'을 잡기 위한 시의적절한 움직임이라고 분석하고 있다."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "배터리 공급망 전략의 중요성 부각",
|
||||
"content": [
|
||||
"전기차 시장에서 배터리 공급망 확보가 핵심 경쟁력으로 부상하고 있다. IAA 모빌리티에서 폴스타가 SK온을 배터리 파트너로 공개적으로 언급한 것이 주목받고 있다.",
|
||||
"배터리 제조사 선정에 대한 정보가 제한적인 가운데, 안정적인 배터리 공급망 구축이 전기차 제조사들의 성패를 좌우할 것으로 예상된다.",
|
||||
"특히 소형 전기차의 경우 가격 경쟁력이 중요한 만큼, 효율적인 배터리 수급 전략이 시장 점유율 확대의 관건이 될 전망이다."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "글로벌 전기차 시장의 경쟁 구도 변화",
|
||||
"content": [
|
||||
"유럽 전기차 시장에서 소형 모델을 중심으로 한 경쟁이 본격화되면서, 제조사들의 전략적 포지셔닝이 더욱 중요해지고 있다.",
|
||||
"현대차그룹은 품질과 기술력을 바탕으로 한 프리미엄 이미지와 함께, 합리적인 가격대의 소형 전기차 라인업으로 시장 공략을 가속화하고 있다.",
|
||||
"이러한 변화는 글로벌 자동차 산업의 패러다임 전환을 반영하며, 향후 전기차 시장의 주도권 경쟁이 더욱 치열해질 것으로 예상된다."
|
||||
]
|
||||
}
|
||||
],
|
||||
"categories": [
|
||||
"자동차",
|
||||
"경제",
|
||||
"환경",
|
||||
"기술"
|
||||
],
|
||||
"entities": {
|
||||
"people": [],
|
||||
"organizations": [
|
||||
"현대자동차",
|
||||
"기아",
|
||||
"SK온",
|
||||
"폴스타"
|
||||
],
|
||||
"groups": [
|
||||
"유럽 자동차 제조사",
|
||||
"배터리 제조업체"
|
||||
],
|
||||
"countries": [
|
||||
"대한민국",
|
||||
"독일",
|
||||
"유럽연합"
|
||||
],
|
||||
"events": [
|
||||
"IAA 2025",
|
||||
"IAA 모빌리티"
|
||||
]
|
||||
},
|
||||
"source_keyword": "전기차",
|
||||
"source_count": 3
|
||||
}
|
||||
@ -0,0 +1,66 @@
|
||||
{
|
||||
"news_id": "8a51bead-4558-4351-a5b2-b5e5ba1b3d38",
|
||||
"title": "현대차·기아, 유럽 전기차 시장서 소형 모델로 새 돌파구 모색",
|
||||
"created_at": "2025-09-13T00:29:35.661926",
|
||||
"summary": "IAA 모빌리티 2025에서 현대차·기아가 소형 전기차 콘셉트카를 공개하며 유럽 시장 공략 가속화. 배터리 공급망 확보와 가격 경쟁력이 성공 관건",
|
||||
"subtopics": [
|
||||
{
|
||||
"title": "유럽 소형 전기차 시장 공략 본격화",
|
||||
"content": [
|
||||
"현대차와 기아가 IAA 모빌리티 2025에서 각각 콘셉트 쓰리와 EV2를 공개하며 유럽 소형 전기차 시장 공략에 시동을 걸었다. 이는 유럽의 높은 환경 규제와 도심 이동성 수요에 대응하기 위한 전략적 움직임으로 해석된다.",
|
||||
"특히 두 모델은 기존 전기차 대비 컴팩트한 사이즈와 효율적인 배터리 시스템을 갖추고 있어, 유럽 소비자들의 실용적 수요를 겨냥했다는 평가를 받고 있다.",
|
||||
"업계 전문가들은 현대차그룹의 이번 행보가 테슬라와 중국 업체들이 주도하고 있는 유럽 전기차 시장에서 새로운 돌파구를 마련할 수 있을 것으로 전망하고 있다."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "배터리 공급망 확보 과제",
|
||||
"content": [
|
||||
"전기차 성공의 핵심 요소인 배터리 수급에서 SK온이 주요 공급 파트너로 부상했다. 폴스타가 SK온을 배터리 공급사로 공개적으로 언급한 것이 이를 방증한다.",
|
||||
"그러나 업계에서는 배터리 제조사들의 정보 공개가 제한적이어서 실제 공급망 구조를 파악하기 어려운 상황이다. 이는 글로벌 배터리 수급 경쟁이 치열해지고 있음을 시사한다.",
|
||||
"안정적인 배터리 공급망 확보는 향후 소형 전기차의 가격 경쟁력과 직결되는 만큼, 현대차그룹의 추가적인 파트너십 구축이 예상된다."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "가격 경쟁력 확보 전략",
|
||||
"content": [
|
||||
"소형 전기차 시장에서의 성공을 위해서는 합리적인 가격대 책정이 필수적이다. 현대차그룹은 규모의 경제를 통한 원가 절감을 목표로 하고 있다.",
|
||||
"특히 유럽 시장에서는 테슬라와 중국 업체들의 공격적인 가격 정책에 대응해야 하는 상황이다. 현대차그룹은 프리미엄 품질을 유지하면서도 경쟁력 있는 가격대를 제시하는 것을 목표로 하고 있다.",
|
||||
"전문가들은 배터리 기술 혁신과 생산 효율화를 통해 가격 경쟁력을 확보하는 것이 향후 성공의 핵심이 될 것으로 전망하고 있다."
|
||||
]
|
||||
}
|
||||
],
|
||||
"categories": [
|
||||
"자동차",
|
||||
"경제",
|
||||
"산업",
|
||||
"기술"
|
||||
],
|
||||
"entities": {
|
||||
"people": [
|
||||
"김성수",
|
||||
"조용하",
|
||||
"박종면"
|
||||
],
|
||||
"organizations": [
|
||||
"현대자동차",
|
||||
"기아",
|
||||
"SK온",
|
||||
"폴스타"
|
||||
],
|
||||
"groups": [
|
||||
"유럽 자동차 제조사",
|
||||
"중국 전기차 업체"
|
||||
],
|
||||
"countries": [
|
||||
"대한민국",
|
||||
"독일",
|
||||
"중국"
|
||||
],
|
||||
"events": [
|
||||
"IAA 모빌리티 2025",
|
||||
"전기차 배터리 공급 계약"
|
||||
]
|
||||
},
|
||||
"source_keyword": "전기차",
|
||||
"source_count": 3
|
||||
}
|
||||
@ -0,0 +1,62 @@
|
||||
{
|
||||
"news_id": "2c4cb595-9542-45ee-b4b9-2135c46950e3",
|
||||
"title": "현대차·기아, 유럽 전기차 시장서 소형 모델로 승부수...배터리 협력 강화 주목",
|
||||
"created_at": "2025-09-13T00:28:51.371773",
|
||||
"summary": "현대차·기아가 유럽 전기차 시장에서 콘셉트 쓰리와 EV2로 소형 전기차 시장 공략 나서, 배터리 협력사 선정 등 경쟁력 강화 움직임 본격화",
|
||||
"subtopics": [
|
||||
{
|
||||
"title": "유럽 소형 전기차 시장 공략 본격화",
|
||||
"content": [
|
||||
"현대자동차그룹이 유럽 전기차 시장 공략을 위해 소형 전기차 라인업 확대에 나섰다. IAA 모빌리티 2025에서 공개된 현대차의 콘셉트 쓰리와 기아의 EV2는 유럽 시장 맞춤형 전략의 핵심으로 평가받고 있다.",
|
||||
"특히 소형 전기차 시장은 유럽에서 급성장이 예상되는 세그먼트로, 현대차그룹은 합리적인 가격대와 실용성을 앞세워 시장 선점을 노리고 있다.",
|
||||
"현대차그룹의 이번 전략은 유럽의 환경 규제 강화와 소비자들의 실용적인 전기차 수요 증가에 대응하는 동시에, 중국 전기차 업체들의 유럽 진출에 대한 선제적 대응으로 해석된다."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "배터리 협력 관계 재편 움직임",
|
||||
"content": [
|
||||
"전기차 경쟁력의 핵심인 배터리 수급과 관련해 업계의 이목이 집중되고 있다. IAA 모빌리티에서 폴스타가 SK온을 배터리 공급사로 지목한 것이 주목받고 있다.",
|
||||
"글로벌 자동차 업체들의 배터리 조달 전략이 다변화되는 가운데, 한국 배터리 업체들과의 협력 강화 움직임이 감지되고 있다.",
|
||||
"특히 현대차그룹은 안정적인 배터리 수급을 위해 다양한 배터리 제조사들과의 협력 관계를 검토 중인 것으로 알려졌다."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "글로벌 전기차 시장 경쟁 심화",
|
||||
"content": [
|
||||
"전기차 시장에서 브랜드 간 경쟁이 치열해지는 가운데, 현대차그룹은 차별화된 제품 라인업과 기술력으로 시장 지위 강화에 나서고 있다.",
|
||||
"특히 유럽 시장에서는 테슬라, 폭스바겐 그룹, 중국 업체들과의 경쟁이 불가피한 상황이며, 현대차그룹은 품질과 기술력을 앞세워 경쟁력 확보에 주력하고 있다.",
|
||||
"시장 전문가들은 현대차그룹의 소형 전기차 전략이 향후 글로벌 시장에서의 입지 강화에 중요한 전환점이 될 것으로 전망하고 있다."
|
||||
]
|
||||
}
|
||||
],
|
||||
"categories": [
|
||||
"자동차",
|
||||
"경제",
|
||||
"산업"
|
||||
],
|
||||
"entities": {
|
||||
"people": [
|
||||
"김성수",
|
||||
"박영효"
|
||||
],
|
||||
"organizations": [
|
||||
"현대자동차",
|
||||
"기아",
|
||||
"SK온",
|
||||
"폴스타"
|
||||
],
|
||||
"groups": [
|
||||
"현대차그룹",
|
||||
"폭스바겐 그룹"
|
||||
],
|
||||
"countries": [
|
||||
"대한민국",
|
||||
"독일"
|
||||
],
|
||||
"events": [
|
||||
"IAA 모빌리티 2025"
|
||||
]
|
||||
},
|
||||
"source_keyword": "전기차",
|
||||
"source_count": 3
|
||||
}
|
||||
@ -0,0 +1,63 @@
|
||||
{
|
||||
"news_id": "ee154fb8-a913-4aa9-9fc9-fa421fd2d7c0",
|
||||
"title": "2025년 기술 혁신의 분기점: AI·양자컴퓨팅이 그리는 새로운 미래",
|
||||
"created_at": "2025-09-13T00:32:14.008706",
|
||||
"summary": "2025년, AI와 양자컴퓨팅의 상용화가 가져올 산업 전반의 혁신적 변화와 사회적 영향을 심층 분석한 전망",
|
||||
"subtopics": [
|
||||
{
|
||||
"title": "생성형 AI가 재편하는 산업 생태계",
|
||||
"content": [
|
||||
"2025년은 생성형 AI가 산업 전반에 본격적으로 도입되는 원년이 될 전망이다. 특히 의료 진단, 신약 개발, 교육 커리큘럼 설계 등 전문 분야에서 AI의 역할이 획기적으로 확대될 것으로 예측된다.",
|
||||
"기업들의 업무 프로세스도 근본적인 변화를 맞이할 것으로 보인다. 창의적 작업 영역에서도 AI의 활용이 일상화되며, 인간-AI 협업 모델이 새로운 표준으로 자리잡을 것으로 전망된다.",
|
||||
"다만 AI 도입에 따른 노동시장 재편과 윤리적 문제에 대한 사회적 합의가 시급한 과제로 대두될 것으로 예상된다. 특히 AI 의존도 증가에 따른 데이터 보안과 알고리즘 편향성 문제는 중요한 해결 과제가 될 것이다."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "양자컴퓨팅의 상용화와 산업혁신",
|
||||
"content": [
|
||||
"양자컴퓨팅 기술이 실용화 단계에 진입하면서, 금융권의 리스크 분석과 암호화폐 보안 시스템에 획기적인 변화가 예상된다. 특히 복잡한 금융 모델링과 시장 예측에서 양자컴퓨터의 활용이 크게 증가할 전망이다.",
|
||||
"제약 산업에서는 신약 개발 프로세스가 대폭 단축될 것으로 기대된다. 양자컴퓨터를 활용한 분자 시뮬레이션이 가능해지면서, 신약 개발 비용 절감과 효율성 증대가 실현될 것이다.",
|
||||
"물류 및 공급망 관리 분야에서도 양자컴퓨팅의 영향력이 확대될 전망이다. 복잡한 경로 최적화와 재고 관리에 양자 알고리즘을 적용함으로써, 물류 비용 절감과 효율성 향상이 가능해질 것으로 예측된다."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "기술 혁신에 따른 사회경제적 변화",
|
||||
"content": [
|
||||
"AI와 양자컴퓨팅의 발전은 노동시장의 구조적 변화를 가속화할 것으로 전망된다. 단순 반복 업무는 자동화되는 반면, AI 시스템 관리와 양자컴퓨팅 전문가 같은 새로운 직종의 수요가 급증할 것으로 예상된다.",
|
||||
"교육 시스템도 큰 변화를 맞이할 것으로 보인다. AI 기반 맞춤형 학습과 양자컴퓨팅 원리에 대한 이해가 새로운 필수 교육과정으로 자리잡을 것으로 전망된다.",
|
||||
"이러한 기술 혁신은 국가 간 기술 격차를 더욱 심화시킬 가능성이 있다. 선진국과 개발도상국 간의 디지털 격차 해소가 국제사회의 주요 과제로 대두될 것으로 예측된다."
|
||||
]
|
||||
}
|
||||
],
|
||||
"categories": [
|
||||
"기술",
|
||||
"산업",
|
||||
"미래전망",
|
||||
"경제"
|
||||
],
|
||||
"entities": {
|
||||
"people": [],
|
||||
"organizations": [
|
||||
"금융권",
|
||||
"제약회사",
|
||||
"물류기업"
|
||||
],
|
||||
"groups": [
|
||||
"AI 개발자",
|
||||
"양자컴퓨팅 전문가",
|
||||
"교육기관"
|
||||
],
|
||||
"countries": [
|
||||
"한국",
|
||||
"미국",
|
||||
"중국"
|
||||
],
|
||||
"events": [
|
||||
"AI 상용화",
|
||||
"양자컴퓨터 실용화",
|
||||
"디지털 전환"
|
||||
]
|
||||
},
|
||||
"source_keyword": "2025년 기술 트렌드",
|
||||
"source_count": 2
|
||||
}
|
||||
@ -0,0 +1,62 @@
|
||||
{
|
||||
"news_id": "3109c578-9b08-4cd0-a9d6-3d92b97e64d4",
|
||||
"title": "2025년 기술 혁신의 물결, AI·양자컴퓨팅이 이끄는 새로운 패러다임",
|
||||
"created_at": "2025-09-13T00:31:52.782760",
|
||||
"summary": "2025년, 생성형 AI와 양자컴퓨팅의 상용화로 산업 전반에 혁신적 변화가 예상되며, 인간-AI 협업이 일상화될 전망",
|
||||
"subtopics": [
|
||||
{
|
||||
"title": "생성형 AI가 주도하는 창의적 혁신",
|
||||
"content": [
|
||||
"2025년은 생성형 AI 기술이 전례 없는 수준으로 발전하여 창의적 영역에서도 획기적인 변화가 예상된다. 기존에 인간의 고유 영역으로 여겨졌던 예술 창작, 콘텐츠 제작, 디자인 분야에서 AI가 핵심 협력자로 자리잡을 전망이다.",
|
||||
"특히 의료 분야에서는 AI가 질병 진단과 치료 계획 수립에 적극적으로 활용될 것으로 예측된다. AI는 방대한 의료 데이터를 분석하여 개인 맞춤형 치료법을 제시하고, 의료진의 의사결정을 효과적으로 지원할 것으로 기대된다.",
|
||||
"교육 분야에서도 AI 기반의 맞춤형 학습 시스템이 보편화될 전망이다. 학습자의 이해도와 진도에 따라 최적화된 커리큘럼을 제공하고, 실시간으로 학습 성과를 분석하여 개선점을 제시하는 등 교육의 질적 향상이 기대된다."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "양자컴퓨팅의 산업 혁신 주도",
|
||||
"content": [
|
||||
"2025년은 양자컴퓨팅이 실용화 단계에 진입하는 원년이 될 것으로 전망된다. 특히 금융 산업에서는 복잡한 위험 분석과 포트폴리오 최적화에 양자컴퓨팅을 활용하여 투자 전략의 정확도를 높일 것으로 예상된다.",
|
||||
"제약 산업에서는 양자컴퓨터를 활용한 신약 개발이 가속화될 전망이다. 분자 구조 시뮬레이션과 신약 후보 물질 스크리닝 과정에서 양자컴퓨팅의 강점이 발휘될 것으로 기대된다.",
|
||||
"물류 분야에서도 양자컴퓨팅을 통한 최적화가 실현될 전망이다. 복잡한 공급망 관리와 배송 경로 최적화에 양자컴퓨팅을 도입함으로써 물류 비용 절감과 효율성 향상이 가능해질 것으로 예측된다."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "인간-기계 협업의 새로운 패러다임",
|
||||
"content": [
|
||||
"2025년에는 AI와 인간의 협업이 일상화되면서 업무 방식의 근본적인 변화가 예상된다. 단순 반복적인 업무는 AI가 담당하고, 인간은 전략적 의사결정과 창의적 문제 해결에 집중하는 방식으로 업무 분담이 이루어질 것이다.",
|
||||
"이러한 변화는 노동시장의 구조적 변화로 이어질 전망이다. AI와 협업할 수 있는 디지털 역량이 필수적인 직무 역량으로 부상하며, 새로운 형태의 직업이 등장할 것으로 예측된다.",
|
||||
"하지만 이러한 변화 속에서도 윤리적 판단과 감성적 소통과 같은 인간 고유의 가치는 더욱 중요해질 것으로 전망된다. 기술 발전이 가져올 혜택을 최대화하면서도 인간 중심의 가치를 지켜나가는 균형이 중요한 과제로 대두될 것이다."
|
||||
]
|
||||
}
|
||||
],
|
||||
"categories": [
|
||||
"기술",
|
||||
"미래전망",
|
||||
"산업동향"
|
||||
],
|
||||
"entities": {
|
||||
"people": [],
|
||||
"organizations": [
|
||||
"AI 기업들",
|
||||
"제약회사들",
|
||||
"물류기업들"
|
||||
],
|
||||
"groups": [
|
||||
"의료진",
|
||||
"교육자",
|
||||
"기술전문가"
|
||||
],
|
||||
"countries": [
|
||||
"한국",
|
||||
"미국",
|
||||
"중국"
|
||||
],
|
||||
"events": [
|
||||
"2025년 기술혁신",
|
||||
"양자컴퓨팅 상용화",
|
||||
"AI 혁명"
|
||||
]
|
||||
},
|
||||
"source_keyword": "2025년 기술 트렌드",
|
||||
"source_count": 2
|
||||
}
|
||||
73
backup-services/ai-writer/backend/generated_article.json
Normal file
73
backup-services/ai-writer/backend/generated_article.json
Normal file
@ -0,0 +1,73 @@
|
||||
{
|
||||
"news_id": "ea9f3734-6a93-4ca7-8ebe-b85612e2fd0a",
|
||||
"title": "정부, 내년 AI 산업에 10조원 투자...한국 경제 체질 대전환 나선다",
|
||||
"created_at": "2025-09-13T01:09:43.892704",
|
||||
"summary": "정부가 2025년 인공지능 산업 육성을 위해 10조원 규모의 대규모 투자를 단행하며 디지털 경제 전환 가속화에 나선다",
|
||||
"subtopics": [
|
||||
{
|
||||
"title": "정부의 AI 산업 육성 청사진",
|
||||
"content": [
|
||||
"정부가 2025년 인공지능(AI) 산업 육성을 위해 10조원 규모의 투자를 단행한다. 이는 한국 경제의 디지털 전환을 가속화하고 글로벌 AI 강국으로 도약하기 위한 전략적 결정이다.",
|
||||
"투자의 주요 방향은 AI 기술 개발, 인프라 구축, 전문인력 양성 등으로, 특히 반도체와 같은 핵심 산업과의 시너지 창출에 중점을 둘 예정이다."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "민관 협력 체계 구축",
|
||||
"content": [
|
||||
"정부는 AI 산업 육성을 위해 대기업, 스타트업, 연구기관 등과의 협력 체계를 강화한다. 소버린AI를 비롯한 국내 AI 기업들과의 협력을 통해 실질적인 세계 2위 AI 강국 도약을 목표로 하고 있다.",
|
||||
"특히 AI 전문가 공모와 전담 조직 신설 등을 통해 체계적인 산업 육성 기반을 마련할 계획이다."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "글로벌 경쟁력 강화 전략",
|
||||
"content": [
|
||||
"정부는 국내 AI 기업들의 글로벌 경쟁력 강화를 위해 기술 개발 지원, 해외 시장 진출 지원, 규제 개선 등 다각적인 지원책을 마련한다.",
|
||||
"특히 AI 산업의 핵심 인프라인 반도체 분야에서 SK하이닉스의 HBM4 개발 완료 등 가시적인 성과가 나타나고 있어, 이를 기반으로 한 시너지 효과가 기대된다."
|
||||
]
|
||||
}
|
||||
],
|
||||
"categories": [
|
||||
"경제",
|
||||
"기술",
|
||||
"산업정책"
|
||||
],
|
||||
"entities": {
|
||||
"people": [
|
||||
"하정우 소버린AI 대표"
|
||||
],
|
||||
"organizations": [
|
||||
"소버린AI",
|
||||
"SK하이닉스",
|
||||
"과학기술정보통신부"
|
||||
],
|
||||
"groups": [
|
||||
"AI 기업",
|
||||
"스타트업"
|
||||
],
|
||||
"countries": [
|
||||
"대한민국",
|
||||
"미국"
|
||||
],
|
||||
"events": [
|
||||
{
|
||||
"name": "2025년 AI 산업 육성 계획 발표",
|
||||
"date": "2025년",
|
||||
"location": "대한민국"
|
||||
}
|
||||
],
|
||||
"keywords": [
|
||||
"인공지능",
|
||||
"AI 산업",
|
||||
"디지털 전환",
|
||||
"10조원 투자",
|
||||
"반도체",
|
||||
"HBM4",
|
||||
"글로벌 경쟁력",
|
||||
"민관협력",
|
||||
"전문인력 양성",
|
||||
"기술개발"
|
||||
]
|
||||
},
|
||||
"source_keyword": "인공지능",
|
||||
"source_count": 5
|
||||
}
|
||||
9
backup-services/ai-writer/backend/requirements.txt
Normal file
9
backup-services/ai-writer/backend/requirements.txt
Normal file
@ -0,0 +1,9 @@
|
||||
fastapi==0.104.1
|
||||
uvicorn[standard]==0.24.0
|
||||
httpx==0.25.2
|
||||
pydantic==2.5.0
|
||||
motor==3.1.1
|
||||
pymongo==4.3.3
|
||||
anthropic==0.39.0
|
||||
python-multipart==0.0.6
|
||||
redis[hiredis]==5.0.1
|
||||
168
backup-services/ai-writer/backend/test_ai_writer.py
Executable file
168
backup-services/ai-writer/backend/test_ai_writer.py
Executable file
@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
AI Writer Service Test
|
||||
Claude API를 사용한 전문적인 뉴스 기사 생성 테스트
|
||||
"""
|
||||
import asyncio
|
||||
import httpx
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
# Service URL
|
||||
SERVICE_URL = "http://localhost:8019"
|
||||
|
||||
async def test_article_generation():
|
||||
"""인공지능 키워드로 기사 생성 테스트"""
|
||||
async with httpx.AsyncClient(timeout=120.0) as client:
|
||||
print("\n" + "="*70)
|
||||
print(" AI Writer Service - 전문 기사 생성 테스트 ")
|
||||
print("="*70)
|
||||
|
||||
print("\n📰 '인공지능' 키워드로 전문 기사 생성 중...")
|
||||
print("-" * 50)
|
||||
|
||||
# Generate article
|
||||
response = await client.post(
|
||||
f"{SERVICE_URL}/api/generate",
|
||||
json={
|
||||
"keyword": "인공지능",
|
||||
"limit": 5,
|
||||
"google_results_per_title": 3,
|
||||
"lang": "ko",
|
||||
"country": "KR",
|
||||
"style": "professional"
|
||||
}
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
article = response.json()
|
||||
|
||||
print(f"\n✅ 기사 생성 완료!")
|
||||
print(f"\n📌 기사 ID: {article['news_id']}")
|
||||
print(f"📅 생성 시간: {article['created_at']}")
|
||||
print(f"\n📰 제목: {article['title']}")
|
||||
print(f"📝 요약: {article['summary']}")
|
||||
|
||||
print(f"\n🔍 카테고리: {', '.join(article['categories'])}")
|
||||
|
||||
# Print subtopics
|
||||
print(f"\n📚 소주제 ({len(article['subtopics'])}개):")
|
||||
for i, subtopic in enumerate(article['subtopics'], 1):
|
||||
print(f"\n [{i}] {subtopic['title']}")
|
||||
print(f" 문단 수: {len(subtopic['content'])}개")
|
||||
for j, paragraph in enumerate(subtopic['content'][:1], 1): # Show first paragraph only
|
||||
print(f" 미리보기: {paragraph[:150]}...")
|
||||
|
||||
# Print entities
|
||||
entities = article['entities']
|
||||
print(f"\n🏷️ 추출된 개체:")
|
||||
if entities['people']:
|
||||
print(f" 👤 인물: {', '.join(entities['people'])}")
|
||||
if entities['organizations']:
|
||||
print(f" 🏢 기관: {', '.join(entities['organizations'])}")
|
||||
if entities['groups']:
|
||||
print(f" 👥 단체: {', '.join(entities['groups'])}")
|
||||
if entities['countries']:
|
||||
print(f" 🌍 국가: {', '.join(entities['countries'])}")
|
||||
if entities.get('events'):
|
||||
events = entities['events']
|
||||
if events:
|
||||
print(f" 📅 이벤트 ({len(events)}개):")
|
||||
for evt in events[:3]: # 처음 3개만 표시
|
||||
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)
|
||||
else:
|
||||
# 이전 형식 (문자열) 지원
|
||||
print(f" - {evt}")
|
||||
if entities.get('keywords'):
|
||||
keywords = entities['keywords']
|
||||
if keywords:
|
||||
print(f" 🔑 키워드: {', '.join(keywords[:5])}" +
|
||||
("..." if len(keywords) > 5 else ""))
|
||||
|
||||
print(f"\n📊 참조 소스: {article.get('source_count', 0)}개")
|
||||
|
||||
# Save full article to file
|
||||
with open('generated_article.json', 'w', encoding='utf-8') as f:
|
||||
json.dump(article, f, ensure_ascii=False, indent=2)
|
||||
print(f"\n💾 전체 기사가 'generated_article.json'에 저장되었습니다.")
|
||||
|
||||
else:
|
||||
print(f"❌ 오류: {response.status_code}")
|
||||
print(f" 상세: {response.text}")
|
||||
|
||||
async def test_health_check():
|
||||
"""서비스 상태 확인"""
|
||||
async with httpx.AsyncClient() as client:
|
||||
print("\n" + "="*60)
|
||||
print("서비스 Health Check")
|
||||
print("="*60)
|
||||
|
||||
response = await client.get(f"{SERVICE_URL}/health")
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
print(f"✓ AI Writer 서비스 상태: {data.get('status', 'unknown')}")
|
||||
if 'services' in data:
|
||||
print(f" - News Aggregator: {data['services'].get('news_aggregator', 'unknown')}")
|
||||
print(f" - MongoDB: {data['services'].get('mongodb', 'unknown')}")
|
||||
print(f" - Claude API: {data['services'].get('claude_api', 'unknown')}")
|
||||
if 'error' in data:
|
||||
print(f" - Error: {data['error']}")
|
||||
else:
|
||||
print(f"✗ Health check 실패: {response.status_code}")
|
||||
|
||||
async def test_batch_generation():
|
||||
"""여러 키워드 일괄 처리 테스트"""
|
||||
async with httpx.AsyncClient(timeout=180.0) as client:
|
||||
print("\n" + "="*60)
|
||||
print("일괄 기사 생성 테스트")
|
||||
print("="*60)
|
||||
|
||||
keywords = ["AI 혁신", "디지털 전환", "스마트시티"]
|
||||
print(f"\n키워드: {', '.join(keywords)}")
|
||||
|
||||
response = await client.post(
|
||||
f"{SERVICE_URL}/api/generate/batch",
|
||||
json=keywords,
|
||||
params={"style": "analytical"}
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
print(f"\n✅ 처리 완료: {data['total_processed']}개")
|
||||
|
||||
if data['success']:
|
||||
print("\n성공한 기사:")
|
||||
for item in data['success']:
|
||||
print(f" - {item['keyword']}: {item['title'][:50]}...")
|
||||
|
||||
if data['errors']:
|
||||
print("\n실패한 항목:")
|
||||
for item in data['errors']:
|
||||
print(f" - {item['keyword']}: {item['error']}")
|
||||
else:
|
||||
print(f"❌ 오류: {response.status_code}")
|
||||
|
||||
async def main():
|
||||
"""메인 테스트 실행"""
|
||||
print("\n" + "="*70)
|
||||
print(" AI Writer Service Test Suite ")
|
||||
print(" RSS → Google Search → Claude AI 기사 생성 ")
|
||||
print("="*70)
|
||||
|
||||
# Run tests
|
||||
await test_health_check()
|
||||
await test_article_generation()
|
||||
# await test_batch_generation() # Optional: batch test
|
||||
|
||||
print("\n" + "="*70)
|
||||
print(" 테스트 완료 ")
|
||||
print("="*70)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
240
backup-services/ai-writer/backend/test_prompt_generation.py
Normal file
240
backup-services/ai-writer/backend/test_prompt_generation.py
Normal file
@ -0,0 +1,240 @@
|
||||
#!/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())
|
||||
19
backup-services/ai-writer/worker/Dockerfile
Normal file
19
backup-services/ai-writer/worker/Dockerfile
Normal file
@ -0,0 +1,19 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy requirements
|
||||
COPY backend/requirements.txt .
|
||||
|
||||
# Install dependencies
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application code
|
||||
COPY backend/app /app
|
||||
|
||||
# Set environment variables
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
ENV WORKER_COUNT=3
|
||||
|
||||
# Run worker
|
||||
CMD ["python", "worker.py"]
|
||||
Reference in New Issue
Block a user