Skip to content

Commit

Permalink
Merge pull request #248 from KMU-WINK/feat/177-check-item-in-wish
Browse files Browse the repository at this point in the history
구글 추천 기능에 inWish 필드 추가하기 & 코드 클리닉
  • Loading branch information
hyeonseung-lee authored Oct 3, 2024
2 parents 672ace7 + 5b72879 commit 5064373
Show file tree
Hide file tree
Showing 16 changed files with 31 additions and 148 deletions.
1 change: 0 additions & 1 deletion backend/.gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
.env
./venv
/wmw/
cc.ko.300.bin
17 changes: 0 additions & 17 deletions backend/app/external_services/areaBasedAPI.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,6 @@


AREA_CODE = {
# "서울": 1,
# "인천": 2,
# "대전": 3,
# "대구": 4,
# "광주": 5,
# "부산": 6,
# "울산": 7,
# "세종특별자치시": 8,
# "경기도": 31,
# "강원특별자치도": 32,
# "충청북도": 33,
# "충청남도": 34,
# "경상북도": 35,
# "경상남도": 36,
# "전북특별자치도": 37,
# "전라남도": 38,
# "제주도": 39,
"강릉": [32, 1],
"부산": [6],
"제주": [39],
Expand Down
28 changes: 0 additions & 28 deletions backend/app/external_services/jobAPI.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,6 @@
API_KEY = os.getenv("API_KEY")

AREA_CODE = {
# "서울": 1,
# "인천": 2,
# "대전": 3,
# "대구": 4,
# "광주": 5,
# "부산": 6,
# "울산": 7,
# "세종특별자치시": 8,
# "경기도": 31,
# "강원특별자치도": 32,
# "충청북도": 33,
# "충청남도": 34,
# "경상북도": 35,
# "경상남도": 36,
# "전북특별자치도": 37,
# "전라남도": 38,
# "제주도": 39,
"강릉": [32, 1],
"부산": [6],
"제주": [39],
Expand All @@ -35,17 +18,6 @@
}

AREA_CODE_OPEN = {
# "서울": "R3010",
# "인천": "R3011",
# "대전": "R3012",
# "대구": "R3013",
# "광주": "R3015",
# "울산": "R3016",
# "경기": "R3017",
# "충남": "R3019",
# "충북": "R3020",
# "경북": "R3021",
# "세종": "R3026",
"강릉": "R3018", # 강원도로 전환
"부산": "R3014",
"제주": "R3025",
Expand Down
2 changes: 1 addition & 1 deletion backend/app/models/Interest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import validates, relationship
from sqlalchemy.orm import relationship
from ..db.connection import Base


Expand Down
5 changes: 2 additions & 3 deletions backend/app/routers/ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ def get_interests_by_id(id: str, db: Session = Depends(get_db)):

model_name = "distilbert-base-uncased"
# model_name = "bert-base-multilingual-cased"

# 모델은 프로세스 풀 외부에서 로드
tokenizer = BertTokenizer.from_pretrained(model_name)
model = BertModel.from_pretrained(model_name)
Expand Down Expand Up @@ -178,7 +179,5 @@ async def recommend_tourist_spots(request: Request, db: Session = Depends(get_db
if wishs:
for item in result:
item["inWish"] = item["contentid"] in wishs
# for r in result:
# print(r)
print(f"Total time: {int((time.time() - ts) * 1000)}ms")

return result
3 changes: 0 additions & 3 deletions backend/app/routers/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ async def naverAuth(

access_token = _result.get("access_token")

print(_result)
if not access_token:
raise ValueError("Access token not found in response")

Expand Down Expand Up @@ -304,9 +303,7 @@ def verify_jwt_token(token: str):

def get_current_user(request: Request, db: Session = Depends(get_db)):
# 쿠키에서 accessToken 가져오기
print(request.cookies)
token = request.cookies.get("accessToken")
print(token)
# 요청에서 Access token이 넘어오지 않았을 때
if token is None:
raise HTTPException(
Expand Down
47 changes: 23 additions & 24 deletions backend/app/routers/google.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
from fastapi import Request, APIRouter, Depends, HTTPException
import requests, os, random
import xml.etree.ElementTree as ET
import googlemaps
from sqlalchemy.orm import Session
from .auth import get_current_user
from ..db.session import get_db
from dotenv import load_dotenv
from ..models.Spot import Spot
from ..models.Stay import Stay

load_dotenv()
API_KEY = os.getenv("API_KEY")
Expand All @@ -25,7 +28,6 @@


def get_additional_info(location, query):
print("api", location, query)
url = "http://apis.data.go.kr/B551011/KorService1/searchKeyword1"
params = {
"serviceKey": API_KEY,
Expand Down Expand Up @@ -64,11 +66,8 @@ def get_places(query, location, radius):
data = response.json()
return data["results"]
except requests.exceptions.JSONDecodeError as e:
print(f"JSONDecodeError: {e}")
print("Response content:", response.text)
raise e
else:
print(f"Error: {response.status_code}")
raise HTTPException(status_code=400, detail="No data found in get_places")


Expand All @@ -78,15 +77,12 @@ def get_lat_lng(location):
response = requests.get(GOOGLE_URL, params=params)
if response.status_code == 200:
data = response.json()
# print("Geocoding API response:", data)
if data["results"]:
location = data["results"][0]["geometry"]["location"]
return location["lat"], location["lng"]
else:
print("No results found for the location.")
raise ValueError("No results found for the location.")
else:
print(f"Error: {response.status_code}")
raise HTTPException(status_code=400, detail="No data found in get_lat_lng")


Expand Down Expand Up @@ -120,44 +116,44 @@ def sentence(request: Request):

# 1. 문장 먼저 주기
@router.get("/list")
async def main(request: Request, region_idx: int, keyword_idx: int):
async def main(
request: Request, region_idx: int, keyword_idx: int, db: Session = Depends(get_db)
):
current_user = get_current_user(request, db)
if current_user is None:
raise HTTPException(
status_code=400,
detail=f"user not found. request.header.Authorization: {request.headers.get('Authorization')}",
)
else:
stay_wish = db.query(Stay).filter(Stay.user_id == current_user.id).all()
spot_wish = db.query(Spot).filter(Spot.user_id == current_user.id).all()
wishs = [wish.content_id for wish in stay_wish + spot_wish]

if region_idx < 0 or region_idx >= len(keys):
raise HTTPException(status_code=400, detail="Invalid region index")
if keyword_idx < 0 or keyword_idx >= len(LOCATION_QUERY[keys[region_idx]]):
raise HTTPException(status_code=400, detail="Invalid keyword index")
location = keys[region_idx] # 예: "부산"
query = LOCATION_QUERY[location][keyword_idx] # 예: "부산 관광지"
# print(location, query)
radius = 10000 # 반경 10km
# 도시 이름으로 위도와 경도 가져오기
lat, lng = get_lat_lng(location)
# if lat is None or lng is None:
# print("위도와 경도를 가져올 수 없습니다.")
# return

lat_lng = f"{lat},{lng}"

# 관광지 검색
places = get_places(location + query, location, radius)
# if not places:
# print("관광지 없음")
# return

# 각 관광지의 리뷰 수와 이름 가져오기
places_with_reviews = []
for place in places:
place_id = place["place_id"]
place_name = place["name"]
reviews = place.get("user_ratings_total") # 리뷰 수
if reviews is not None:
places_with_reviews.append((place_name, reviews))

# 리뷰 수로 정렬 (내림차순: 리뷰가 많은 순)
places_with_reviews.sort(key=lambda x: x[1], reverse=True)
# print(places_with_reviews)

tour_result = get_additional_info(location, query)
# print(tour_result)

titles = [item["title"] for item in tour_result]
result = []
# # 결과 출력 및 추가 정보 가져오기 (추가 정보가 없는 경우 제외)
Expand All @@ -167,6 +163,9 @@ async def main(request: Request, region_idx: int, keyword_idx: int):
result.append(tour_result[idx])

if len(result):
if wishs:
for item in result:
item["inWish"] = item["contentid"] in wishs
return result
else:
raise HTTPException(status_code=500, detail="No data found in google reccomend")
1 change: 0 additions & 1 deletion backend/app/routers/initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@


# region을 사전에 만들어놓기 위한 코드입니다.
# @router.get("/store_region_to_db", include_in_schema=False) -> docs에서 사라집니다.
@router.get("/store_region_to_db", include_in_schema=False)
def store_region_to_db(db: Session = Depends(get_db)):
regions = ["강릉", "부산", "제주", "경주", "여수", "전주", "춘천"]
Expand Down
8 changes: 1 addition & 7 deletions backend/app/routers/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
from ..db.session import get_db
from .auth import get_current_user

# from ..utils.related_keyword import find_similar_words

router = APIRouter(
prefix="/jobs",
tags=["jobs"],
Expand All @@ -21,11 +19,7 @@ async def read_jobs(
pageNo: int = 1,
db: Session = Depends(get_db),
):
# if len(keyword) > 0:
# print(find_similar_words(keyword))
# 이 (가변 개수) 키워드들을 어떻게 검색으로 적용할지?
# latency를 줄이면서...
# have to connect API

if len(area) == 0 and len(keyword) == 0:
raise HTTPException(
status_code=400, detail="Please provide either area or keyword"
Expand Down
4 changes: 0 additions & 4 deletions backend/app/routers/spots.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@
from ..models.Spot import Spot
from ..models.Stay import Stay

# from datetime import datetime

# formatted_date = datetime.now().strftime("%Y-%m-%d")

router = APIRouter(
prefix="/spots",
tags=["spots"],
Expand Down
28 changes: 3 additions & 25 deletions backend/app/routers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,6 @@ def get_works_by_id(id: str, db: Session = Depends(get_db)):
return work_names


# root path


@router.get("")
async def read_users(db: Session = Depends(get_db)):
return db.query(User).all()
Expand Down Expand Up @@ -294,7 +291,6 @@ async def update_user_work(user: WorkUpdate, db: Session = Depends(get_db)):
@router.patch("/profile")
async def update_user_profile(request: Request, db: Session = Depends(get_db)):
current_user = get_current_user(request, db)
# current_user = db.query(User).filter(User.id == 1).first() #for test
form = await request.form()
profile: UploadFile = form.get("profile")
if not profile:
Expand All @@ -314,25 +310,7 @@ async def update_user_profile(request: Request, db: Session = Depends(get_db)):
return "Profile updated successfully"


# user recommendation
@router.get("/recommend")
async def recommend_user(request: Request, db: Session = Depends(get_db)):
# current_user = get_current_user(request, db)
current_user = db.query(User).filter(User.id == 7).first() # for test

if current_user is None:
raise HTTPException(
status_code=400,
detail=f"user not found. request.header.Authorization: {request.headers.get('Authorization')}",
)

regions = get_regions_by_id(current_user.id, db)
interests = get_interests_by_id(current_user.id, db)
# works = get_works_by_id(current_user.id, db)
return "result"


@router.delete("")
async def delete_user(id: int):
# @router.delete("")
# async def delete_user(id: int):

return "delete_user"
# return "delete_user"
1 change: 0 additions & 1 deletion backend/app/routers/wishs.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy.orm import Session
from ..db.session import get_db
from ..models.User import User
from ..models.Spot import Spot
from ..models.Stay import Stay
from ..models.Job import Job
Expand Down
1 change: 0 additions & 1 deletion backend/app/schemas/interest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from pydantic import BaseModel
from typing import List, Optional


class InterestBase(BaseModel):
Expand Down
1 change: 0 additions & 1 deletion backend/app/schemas/region.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from pydantic import BaseModel
from typing import List, Optional


class RegionBase(BaseModel):
Expand Down
2 changes: 1 addition & 1 deletion backend/app/schemas/user.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pydantic import BaseModel, Field
from pydantic import BaseModel
from typing import List, Optional


Expand Down
30 changes: 0 additions & 30 deletions backend/app/utils/related_keyword.py

This file was deleted.

0 comments on commit 5064373

Please sign in to comment.