Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion app/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,10 @@ def get_summaries_up_to(db: Session, movie_id: int, summary_id: int) -> List[Mov
.filter(MovieManagerSummary.movie_id == movie_id)\
.filter(MovieManagerSummary.summary_id <= summary_id)\
.order_by(MovieManagerSummary.summary_id)\
.all()
.all()

def get_custom_prompts(db: Session, movie_id: int) -> Optional[List[str]]:
"""영화의 커스텀 프롬프트들 조회"""
summaries = db.query(Movie).filter(Movie.id == movie_id).first()
if summaries and summaries.custom_prompts:
return summaries.custom_prompts
5 changes: 4 additions & 1 deletion app/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, BigInteger
from sqlalchemy import Column, String, Text, DateTime, ForeignKey, BigInteger
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from sqlalchemy.dialects.postgresql import ARRAY
from app.database import Base

class Movie(Base):
Expand All @@ -11,6 +12,8 @@ class Movie(Base):
status = Column(String(50), default="PENDING") # PENDING, PROCEEDING[N/M], ORGANIZING, COMPLETE, FAILED_*
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())

custom_prompts = Column(ARRAY(String), nullable=True)

# 관계 설정
summaries = relationship("MovieManagerSummary", back_populates="movie")
Expand Down
25 changes: 25 additions & 0 deletions app/routers/marengo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# app/routers/marengo.py

from fastapi import APIRouter, HTTPException
from app.services.marengo_service import init_marengo_client, get_marengo_response
from app.schemas import ChatRequest, ChatResponse

router = APIRouter(prefix="/marengo", tags=["marengo"])

# init_marengo_client 하던 곳
init_marengo_client()

@router.post("", response_model=ChatResponse)
def chat_endpoint(req: ChatRequest):
"""
사용자가 보낸 메시지를 Marengo API에 전달 후, 임베딩 벡터를 반환합니다.
"""
try:
result = get_marengo_response(req.message)
print("Raw response from Marengo:", result)
# If the result is a list of TextBlock, concatenate their text fields
if isinstance(result, list):
result = "".join(block.text for block in result)
return ChatResponse(response=result)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Marengo API 호출 오류: {e}")
3 changes: 1 addition & 2 deletions app/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,5 @@ class MovieManagerRequest(BaseModel):
threshold: float = 30.0

class MovieManagerResponse(BaseModel):
final_story: str # 전체 줄거리
final_review: str # 전체 평론
prompt2results: List[tuple]
thumbnail_folder_uri: str = None # 썸네일 후보 폴더 URI
53 changes: 53 additions & 0 deletions app/services/marengo_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# app/services/marengo_service.py

from dotenv import load_dotenv
import boto3
import os
import json

load_dotenv()

marengo_client = None
MARENGO_MODEL_ID = None

def init_marengo_client():
"""
애플리케이션 시작 시 한 번만 호출되어야 하는 함수로,
환경변수에서 자격증명과 모델 ID를 읽어 Bedrock 클라이언트를 초기화합니다.
"""
global marengo_client, MARENGO_MODEL_ID

if marengo_client is not None:
return # 이미 초기화된 경우 재할당하지 않음

aws_key = os.getenv("AWS_ACCESS_KEY_ID")
aws_secret = os.getenv("AWS_SECRET_ACCESS_KEY")
aws_region = os.getenv("AWS_DEFAULT_REGION") or "us-east-1"
MARENGO_MODEL_ID = "apac." + os.getenv("MARENGO_MODEL_ID")

if not (aws_key and aws_secret and MARENGO_MODEL_ID):
raise RuntimeError("필수 환경 변수가 설정되지 않았습니다: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, MARENGO_MODEL_ID")

marengo_client = boto3.client(service_name='bedrock-runtime',
region_name=aws_region,
aws_access_key_id=aws_key,
aws_secret_access_key=aws_secret)

def get_marengo_response(user_message: str) -> str:
"""
Bedrock Marengo API를 호출하여 텍스트 응답을 반환합니다.
"""

message = {
"inputType": "text",
"inputText": user_message
}

if marengo_client is None:
raise RuntimeError("Marengo Bedrock 클라이언트가 초기화되지 않았습니다.")
response = marengo_client.invoke_model(
modelId=MARENGO_MODEL_ID,
body=json.dumps(message)
)

return response.content
Loading