Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement recommend algorithm 1 at main #14

Merged
merged 10 commits into from Sep 3, 2021
3 changes: 3 additions & 0 deletions server/.gitignore
Expand Up @@ -291,4 +291,7 @@ $RECYCLE.BIN/
# Windows shortcuts
*.lnk

#hide api key
config.py

# End of https://www.toptal.com/developers/gitignore/api/windows,linux,vim,django,python,visualstudiocode
134 changes: 126 additions & 8 deletions server/recommend/recommend1/recommend1.py
@@ -1,12 +1,130 @@
# -*-coding:utf-8-*-

import os
import requests
import json
from googletrans import Translator


class recommend1:
def __init__(self):
"""Will be implemented later."""
pass
"""Set radius and api key for google nearby search."""
self.radius = 100
self.key = os.environ["GOOGLE_PLACES_KEY"]

def call_api(self, lat, lng):
url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?"\
+ "location=" + str(lat) + "," + str(lng)\
+ "&radius=" + str(self.radius)\
+ "&key=" + self.key

response = requests.get(url)

if(response.status_code == 200):
response_body = response.text
return(response_body)
else:
print("Error Code:" + response.status_code)

def call_review(self, place_key):
url = "https://maps.googleapis.com/maps/api/place/details/json?"\
+ "place_id=" + place_key\
+ "&fields=name,rating,review"\
+ "&key=" + self.key

response = requests.get(url)

if(response.status_code == 200):
response_body = response.text
return(response_body)
else:
print("Error Code:" + response.status_code)

@classmethod
def LocalAlignment(cls, String1, String2, GapPenalty):
Match, MisMatch = 15, -5
DP = []
for _ in range(len(String2)+1):
DP.append([0]*(len(String1)+1))

for y in enumerate(String2):
for x in enumerate(String1):
MatchTest = 0

if(String1[x] == String2[y]):
MatchTest = Match
else:
MatchTest = MisMatch

DP[y+1][x+1] = max(DP[y][x] + MatchTest,
DP[y][x+1] + GapPenalty,
DP[y+1][x] + GapPenalty, 0)

return DP

@classmethod
def word_tanslate(cls, word):
translator = Translator()
result = translator.translate(word, dest="en")
return result.text

@classmethod
def json2list(cls, js):
return json.loads(js)

def recommend(self, lat, lng, keyword, epsilon):
filtering_result = []
translated_keyword = self.word_tanslate(keyword)

places_info = []
api_result = self.call_api(lat, lng)
places = self.json2list(api_result)
# analyze each place infomation
for place in places['results']:
place_info = []

place_info.append(place['name'])
place_info.append(place['place_id'])

try:
if(place['business_status'] != 'OPERATIONAL'):
continue
except KeyError:
continue

place_info.append(place['geometry']['location']['lat'])
place_info.append(place['geometry']['location']['lng'])

places_info.append(place_info)

for x, _ in enumerate(places_info):
place_key = places_info[x][1]
review_result = self.call_review(place_key)
reviews = self.json2list(review_result)
alig_max = 0
for y in range(len(reviews['result'])):
try:
reviewtext = reviews['result']['reviews'][y]['text']
reviewtext = reviewtext.replace(" ", "").lower()
transtext = translated_keyword.replace(" ", "").lower()
alig_score = self.LocalAlignment(reviewtext,
transtext,
(epsilon-101))
if(max(map(max, alig_score)) > alig_max):
alig_max = max(map(max, alig_score))
except Exception:
break
places_info[x].insert(0, alig_max)
places_info.sort(reverse=True)

@staticmethod
def recommend(lat, lng, keyword, epsilon):
"""Returns list of place recommendation using local alignment.
while(len(filtering_result) < 5):
try:
rank_place = places_info.pop(0)
filtering_result.append({"name": rank_place[1],
"lat": rank_place[3],
"long": rank_place[4],
"filtering": 1})
except Exception:
break

This function will be implemented later.
"""
return([["test", 1.0, 1.0], ["test2", 2.0, 2.0]])
return(filtering_result)
6 changes: 3 additions & 3 deletions server/recommend/views.py
Expand Up @@ -15,8 +15,8 @@
class STCViewSet(viewsets.ViewSet):
@classmethod
def list(self, request):
# recommender1 = recommend1()
# recommender2 = recommend2()
recommender1 = recommend1()

UserID = request.query_params["User_ID"]
latitude = request.query_params["lat"]
longitude = request.query_params["long"]
Expand All @@ -30,7 +30,7 @@ def list(self, request):
"epsilon": epsilon}
serializer = PlaceRequestSerializer(data=requestData)
if serializer.is_valid():
requestResult1 = recommend1.recommend(
requestResult1 = recommender1.recommend(
latitude, longitude, keywords, epsilon
)
requestResult2 = recommend2.recommend(
Expand Down
1 change: 1 addition & 0 deletions server/requirements.txt
Expand Up @@ -11,3 +11,4 @@ six
urllib3
tensorflow-gpu
typing
googletrans==4.0.0rc1