Skip to content

Commit

Permalink
풀 리퀘스트 병합 #3
Browse files Browse the repository at this point in the history
andrew
  • Loading branch information
whdms2008 authored Sep 5, 2024
2 parents a4998b0 + 80345b8 commit ce0adae
Show file tree
Hide file tree
Showing 4 changed files with 91 additions and 14 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
OPENAI_API_KEY=''
11 changes: 10 additions & 1 deletion analysis.http
Original file line number Diff line number Diff line change
Expand Up @@ -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": "^_ㅁㄴ"
}
3 changes: 1 addition & 2 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
90 changes: 79 additions & 11 deletions app/router/analysis_router.py
Original file line number Diff line number Diff line change
@@ -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()

Expand All @@ -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

0 comments on commit ce0adae

Please sign in to comment.