Skip to content

Commit

Permalink
Merge branch 'refs/heads/main' into staging
Browse files Browse the repository at this point in the history
  • Loading branch information
stopmin committed Jul 19, 2024
2 parents 9ea5efe + 68f798f commit 7e16878
Show file tree
Hide file tree
Showing 5 changed files with 153 additions and 119 deletions.
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@

- **implicit**: 협업 필터링 기반의 추천 알고리즘
- **사용자 선호도 분석**: 사용자 행동 데이터를 기반으로 맞춤형 추천 제공
- [추천 시스템](https://bubble-pick-143.notion.site/89314631a2404d76811c6ab6f550b43c?pvs=4)

---

Expand Down
3 changes: 3 additions & 0 deletions app/model/prompt/graphic_article/2024-07-10.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,6 @@ Response format:
"body": 매일의 판매액을 한눈에 볼 수 있게 했어요 📈\n매출 데이터는 날짜별로 그룹화했어요 🗓️\n날짜 순서대로 정렬했어요 📅\n그래프에서 각 날짜의 판매액을 확인할 수 있어요 🛒\n이제 일별 매출 트렌드를 알 수 있어요 😊
}
}
경고: groupby에서 preprocess_groupby 메서드를 사용할 때는 다음과 같이 받아와야 합니다.
async def preprocess_groupby(self, df, by, agg_func):
return df.groupby(by).agg(agg_func).reset_index()
92 changes: 39 additions & 53 deletions app/router/user_type_router.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
from typing import List, Dict
from typing import Dict, List

from fastapi import APIRouter, Depends
from groq import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.repository import model_to_dict
from app.database.session import get_db_session
from app.model.user_type import UserType
from app.recommend.recommend_service import RecommendService, user_id_to_classification_id, \
user_type_to_classification_id
from app.recommend.recommend_service import user_type_to_classification_id
from app.repository.crawled_article_crud import CrawledArticleRepository
from app.repository.recommend_crud import RecommendRepository
from app.service.user_type_service import (
UserTypeQuestionnaire,
UserTypeQuestionnaireRequestDTO,
UserTypeService, calculate_user_type,
UserTypeService,
calculate_user_type,
)
from app.utils.generic_response import GenericResponseDTO

Expand All @@ -27,73 +25,61 @@ class ArticleResponseDTO(BaseModel):
content: str
pubDate: str
image: str


class UserTypeResponseDTO(BaseModel):
userType: Dict
recommendNews: List[ArticleResponseDTO]



@user_type_router.get(
"/user-type/questionnaire",
"/usertype/form",
response_model=GenericResponseDTO[List[UserTypeQuestionnaire]],
)
async def get_questionnaire():
data = await UserTypeService().get_questionnaire()
return GenericResponseDTO[List[UserTypeQuestionnaire]](
data=data, message="Questionnaire retrieved successfully", result=True
data=data, message="유형검사 질문지 조회에 성공", result=True
)


@user_type_router.post("/user-type", response_model=GenericResponseDTO[UserTypeResponseDTO])
@user_type_router.post(
"/usertype/calculate", response_model=GenericResponseDTO[UserTypeResponseDTO]
)
async def create_user_type_by_answers(
request: UserTypeQuestionnaireRequestDTO,
session: AsyncSession = Depends(get_db_session),
):
recommendNew_ids = []
if request.id == None:
userType = calculate_user_type(
request, UserTypeService().get_questionnaire_data()
)
recommendNew_ids = await RecommendRepository().get(
pk=await user_type_to_classification_id(userType),
session=session)
recommendNew_ids = recommendNew_ids.recommend_article_ids
else :
userType = await UserTypeService().create_user_type(request, session)
recommendNew_ids = await RecommendRepository().get(
pk=await user_id_to_classification_id(user_id=userType.user_id, session=session),
session=session)
recommendNew_ids = recommendNew_ids.recommend_article_ids
userType = calculate_user_type(request, UserTypeService().get_questionnaire_data())
recommendNew_ids = await RecommendRepository().get(
pk=await user_type_to_classification_id(userType), session=session
)
recommendNew_ids = recommendNew_ids.recommend_article_ids
recommendNews = []

for id in recommendNew_ids:
temp_article = await CrawledArticleRepository().get(pk=id, session=session)
recommendNews.append(ArticleResponseDTO(
id=id,
title=temp_article.simple_title,
content=temp_article.simple_content,
pubDate=temp_article.published_at.strftime("%Y-%m-%d"),
image=temp_article.image_url
))
if request.id == None:
return GenericResponseDTO[UserTypeResponseDTO](
data=UserTypeResponseDTO(
userType={'ISSUE_FINDER': userType[0],
'LIFESTYLE_CONSUMER': userType[1],
'ENTERTAINER': userType[2],
'TECH_SPECIALIST': userType[3],
'PROFESSIONALS': userType[4]},
recommendNews=recommendNews
), message="user type created successfully", result=True
)
else:
return GenericResponseDTO[UserTypeResponseDTO](
data=UserTypeResponseDTO(
userType={'ISSUE_FINDER': userType.user_type_issue_finder,
'LIFESTYLE_CONSUMER': userType.user_type_lifestyle_consumer,
'ENTERTAINER': userType.user_type_entertainer,
'TECH_SPECIALIST': userType.user_type_tech_specialist,
'PROFESSIONALS': userType.user_type_professionals},
recommendNews=recommendNews
), message="user type created successfully", result=True
recommendNews.append(
ArticleResponseDTO(
id=id,
title=temp_article.simple_title,
content=temp_article.simple_content,
pubDate=temp_article.published_at.strftime("%Y-%m-%d"),
image=temp_article.image_url,
)
)

return GenericResponseDTO[UserTypeResponseDTO](
data=UserTypeResponseDTO(
userType={
"ISSUE_FINDER": userType[0],
"LIFESTYLE_CONSUMER": userType[1],
"ENTERTAINER": userType[2],
"TECH_SPECIALIST": userType[3],
"PROFESSIONALS": userType[4],
},
recommendNews=recommendNews,
),
message="유형검사 결과가 성공",
result=True,
)
60 changes: 41 additions & 19 deletions app/service/api_visualization_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
# pylint: disable=R0911
# pylint: disable=C0206
# pylint: disable=C0327
import json
from enum import Enum
from typing import List

import pandas as pd
import plotly.express as px
import plotly.io as pio
from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession

Expand Down Expand Up @@ -316,31 +316,53 @@ async def create_article(
if not await graph_service.get_api_data(data):
raise HTTPException(status_code=400, detail="Couldn't get data")

# 여기가 ai보고 데이터 받아오라고 하는 곳.
ai_result = await graph_service.graph_info(title=title)

fig = await graph_service.plot_graph(
ai_result["graph_type"],
ai_result["x_value"],
ai_result["y_value"],
ai_result["preprocessing_steps"],
**ai_result["kwargs"],
# 전처리 완료
await graph_service.apply_preprocessing(
graph_service.dataset, ai_result["preprocessing_steps"]
)

# html 다 만든 것
html_str = pio.to_html(fig, full_html=True)

# 둘 다 html_str은 뱉는 걸로.
# return이 두 개입니다.
# 그래프 그리는 부분
# 근데 이 곳을 제끼고 return 을 달리하라는 거임.

# fig = await graph_service.plot_graph(
# ai_result["graph_type"],
# ai_result["x_value"],
# ai_result["y_value"],
# ai_result["preprocessing_steps"],
# **ai_result["kwargs"],
# )
#
# # html 다 만든 것
# html_str = pio.to_html(fig, full_html=True)

x = graph_service.dataset[ai_result["x_value"]].tolist()
y = graph_service.dataset[ai_result["y_value"]].tolist()
graph_type = ai_result["graph_type"]
# 우선 무슨 값을 넣을 지 몰라서 hard coding 합니다.
mode = "lines+markers"
marker = "{color: 'red'}"

data = [{"x": x, "y": y, "type": graph_type, "mode": mode, "marker": marker}]

layout = {"title": title}

chart_config = {
"data": data,
"layout": layout,
}

json_data = json.dumps(chart_config, ensure_ascii=False)
if user_input:
return html_str, ""
# 유저의 통제시 그냥 html만 리턴!
return json_data, ""
# 기사를 만드는 경우는 저장을 한다!

repository = ApiVisualizationService()
content = ai_result["article"]["body"]
await repository.create_article(
title=title,
graph_html=html_str,
content=content,
graph_html=json.dumps(chart_config),
content=ai_result["article"]["body"],
session=session,
)
return html_str, content
return json_data, ai_result["article"]["body"]
Loading

0 comments on commit 7e16878

Please sign in to comment.