diff --git a/.env b/.env new file mode 100644 index 0000000..ac74257 --- /dev/null +++ b/.env @@ -0,0 +1 @@ +OPENAI_API_KEY='' \ No newline at end of file diff --git a/analysis.http b/analysis.http index 9a16ea4..9ce3610 100644 --- a/analysis.http +++ b/analysis.http @@ -3,5 +3,14 @@ POST localhost:8000/analysis Content-Type: application/json { - "content": "test" + "content": "행복한 일기 나는 불행해.. 흑흑" +} + +### + +POST https://8dbe-211-244-225-211.ngrok-free.app/analysis +Content-Type: application/json + +{ + "content": "^_ㅁㄴ" } \ No newline at end of file diff --git a/app/main.py b/app/main.py index 370d29f..e5de3e2 100644 --- a/app/main.py +++ b/app/main.py @@ -2,14 +2,13 @@ import uvicorn from fastapi import FastAPI -import router.analysis_router as analysis_router +import app.router.analysis_router as analysis_router # FastAPI 애플리케이션(app) 초기화 app = FastAPI() # FastAPI 의 router를 등록 app.include_router(analysis_router.router) - # 실행 if __name__ == "__main__": uvicorn.run(app, port=8000) \ No newline at end of file diff --git a/app/router/analysis_router.py b/app/router/analysis_router.py index f2585a5..14105b9 100644 --- a/app/router/analysis_router.py +++ b/app/router/analysis_router.py @@ -1,9 +1,11 @@ import json - +import os +from idlelib.iomenu import encoding +from fastapi import HTTPException from fastapi import APIRouter from pydantic import BaseModel from starlette.responses import JSONResponse -# from app.model.analysis_model import analysis_model +from app.model.analysis_model import analysis router = APIRouter() @@ -12,27 +14,93 @@ class Diary(BaseModel): content: str +# 현재 스크립트의 디렉토리를 기준으로 상대 경로 설정 +current_dir = os.path.dirname(os.path.abspath(__file__)) +data_dir = os.path.join(current_dir, 'data') + # JSON 데이터 로드 try: - with open(r"data/emotionTypeDescriptions.json", "r") as f: + with open(os.path.join(data_dir, "emotionTypeDescriptions.json"), "r", encoding="utf-8") as f: emotionTypeDescriptions = json.load(f) except FileNotFoundError: emotionTypeDescriptions = {} - print("Error : ", "emotionTypeDescriptions.json 가 없음") + print("Error : emotionTypeDescriptions.json 파일을 찾을 수 없습니다.") try: - with open(r"data/typeDescription.json", "r") as f: + with open(os.path.join(data_dir, "typeDescription.json"), "r", encoding="utf-8") as f: typeDescriptions = json.load(f) except FileNotFoundError: typeDescriptions = {} - print("Error : ", "typeDescription.json 가 없음") + print("Error : typeDescription.json 파일을 찾을 수 없습니다.") +def get_default_response(): + return { + "rjmd": { + "R": get_default_type_data(), + "J": get_default_type_data(), + "M": get_default_type_data(), + "D": get_default_type_data() + }, + "emotions": [ + { + "name": "없음", + "per": 100, + "desc": ["감정을 분석할 수 없습니다."], + "color": "#808080" + } + ], + "happy": {"per": 0} + } + +def get_default_type_data(): + return { + "type": "N", # Neutral + "per": 100, + "desc": "분석할 수 없습니다." + } @router.post("/analysis") -async def analysis_router(diary: Diary): +async def analysis_router(diary: Diary) -> JSONResponse: content = diary.content if content is None: - return JSONResponse({"error": "본문이 제공되지 않습니다.", "content": content}, status_code=400) - # 일기 내용을 받아서 사용 + return JSONResponse({"error": "본문이 비어있습니다.", "content": content}, status_code=400) + try: + response = json.loads(analysis(content)) + print(response) + + if not response or "rjmd" not in response: + # 기본값 설정 + response = get_default_response() + + rjmd = response["rjmd"] + + for key in ["R", "J", "M", "D"]: + if key not in rjmd or "type" not in rjmd[key]: + rjmd[key] = get_default_type_data() + + type_value = rjmd[key]["type"] + rjmd[key]["title"] = typeDescriptions[key][type_value]["title"] + rjmd[key]["desc"] = typeDescriptions[key][type_value]["description"] + + type_combination = f"{rjmd['R']['type']}{rjmd['J']['type']}{rjmd['M']['type']}{rjmd['D']['type']}" + rjmd["title"] = emotionTypeDescriptions[type_combination]["title"] + rjmd["desc"] = emotionTypeDescriptions[type_combination]["description"] + except json.JSONDecodeError: + raise HTTPException(status_code=500, detail="분석 결과를 JSON으로 파싱하는데 실패했습니다.") + except Exception as e: + error_message = str(e) + print(error_message) + if "Message content must be non-empty" in error_message: + raise HTTPException(status_code=400, detail="분석할 내용이 비어 있습니다. 유효한 텍스트를 입력해 주세요.") + elif "invalid_request_error" in error_message: + raise HTTPException(status_code=400, detail="잘못된 요청입니다. 입력 내용을 확인해 주세요.") + else: + raise HTTPException(status_code=500, detail=f"일기 분석 중 오류가 발생했습니다: {error_message}") + response_data = JSONResponse( + content=response, + media_type="application/json", + headers={"Content-Type": "application/json; charset=utf-8"}, status_code=200 + ) + decoded_string = json.dumps(response_data.body.decode('utf-8')) + print(decoded_string) - # response = analysis_model() 분석 함수 - return JSONResponse(content=content) + return response_data