Skip to content

Commit

Permalink
hoit1302/attiary_model:2.2
Browse files Browse the repository at this point in the history
  • Loading branch information
hoit1302 committed May 17, 2022
1 parent d807998 commit 68dc29a
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 21 deletions.
4 changes: 2 additions & 2 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ Lib
*.cfg

preprocess
kss_example.py
*/__pycache__/*
*/__pycache__/*
checkpoint/emotion_pn_v5.pth
3 changes: 1 addition & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,4 @@ RUN pip install -r requirements.txt

EXPOSE 5000

CMD python ./app.py
# CMD ["python3", "-m", "flask", "run", "--host=0.0.0.0"]
CMD python ./app.py
17 changes: 9 additions & 8 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
from model.chatbot.kogpt2 import chatbot as ch_v1
from model.chatbot.kobert import chatbot as ch_v2
from model.chatbot.kogpt2 import chatbot as ch_kogpt2
from model.chatbot.kobert import chatbot as ch_kobert
from model.emotion import service as emotion
from util.emotion import Emotion
from util.depression import Depression
Expand All @@ -12,14 +12,15 @@
Emotion = Emotion()
Depression = Depression()

@app.route('/')
def hello():
return "deep learning server is running 💗"


@app.route('/emotion')
def classifyEmotion():
sentence = request.args.get("s")
if sentence is None or len(sentence) == 0:
if sentence is None or len(sentence) == 0 or sentence == '\n':
return jsonify({
"emotion_no": 2,
"emotion": "중립"
Expand All @@ -36,7 +37,7 @@ def classifyEmotion():
@app.route('/diary')
def classifyEmotionDiary():
sentence = request.args.get("s")
if sentence is None or len(sentence) == 0:
if sentence is None or len(sentence) == 0 or sentence == '\n':
return jsonify({
"joy": 0,
"hope": 0,
Expand Down Expand Up @@ -66,12 +67,12 @@ def classifyEmotionDiary():
@app.route('/chatbot/g')
def reactChatbotV1():
sentence = request.args.get("s")
if sentence is None or len(sentence) == 0:
if sentence is None or len(sentence) == 0 or sentence == '\n':
return jsonify({
"answer": "듣고 있어요. 더 말씀해주세요~ (끄덕끄덕)"
})

answer = ch_v1.predict(sentence)
answer = ch_kogpt2.predict(sentence)
return jsonify({
"answer": answer
})
Expand All @@ -80,12 +81,12 @@ def reactChatbotV1():
@app.route('/chatbot/b')
def reactChatbotV2():
sentence = request.args.get("s")
if sentence is None or len(sentence) == 0:
if sentence is None or len(sentence) == 0 or sentence == '\n':
return jsonify({
"answer": "듣고 있어요. 더 말씀해주세요~ (끄덕끄덕)"
})

answer, category, desc, softmax = ch_v2.chat(sentence)
answer, category, desc, softmax = ch_kobert.chat(sentence)
return jsonify({
"answer": answer,
"category": category,
Expand Down
10 changes: 10 additions & 0 deletions model/chatbot/kobert/chatbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,14 @@ def chat(sent):
print(chat("남들이 나를 어떻게 생각할지 신경쓰게 돼"))
print("\'자존감이 낮아지는 것 같아\' 챗봇 응답: ", end='')
print(chat("자존감이 낮아지는 것 같아"))
print("\'뭘 해도 금방 지쳐\' 챗봇 응답: ", end='')
print(chat("뭘 해도 금방 지쳐"))
print("\'걔한테 진짜 크게 배신 당했어\' 챗봇 응답: ", end='')
print(chat("걔한테 진짜 크게 배신 당했어"))
print("\'내일 놀이공원 갈건데 사람 별로 없었으면 좋겠다\' 챗봇 응답: ", end='')
print(chat("내일 놀이공원 갈건데 사람 별로 없었으면 좋겠다"))
print("\'오늘은 구름이랑 달이 너무너무 예쁘더라\' 챗봇 응답: ", end='')
print(chat("오늘은 구름이랑 달이 너무너무 예쁘더라"))
print("\'그래도 내가 머리는 좀 좋아\' 챗봇 응답: ", end='')
print(chat("그래도 내가 머리는 좀 좋아"))
print("=" * 50)
30 changes: 21 additions & 9 deletions model/chatbot/kogpt2/chatbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ def add_model_specific_args(parent_parser):
return parser

def forward(self, inputs):
# (batch, seq_len, hiddens)
output = self.kogpt2(inputs, return_dict=True)
return output.logits

Expand All @@ -82,19 +81,28 @@ def chat(self, input_sentence, sent='0'):
sent_tokens = tok.tokenize(sent)
with torch.no_grad():
q = input_sentence.strip()
q = q[len(q) - 32:]
a = ''
while 1:
input_ids = torch.LongTensor(tok.encode(U_TKN + q + SENT + sent + S_TKN + a)).unsqueeze(dim=0)
pred = self(input_ids)
gen = tok.convert_ids_to_tokens(
torch.argmax(
pred,
dim=-1).squeeze().numpy().tolist())[-1]
if gen == EOS:
gen = tok.convert_ids_to_tokens(torch.argmax(pred, dim=-1).squeeze().numpy().tolist())[-1]
# print(gen) # <pad>
if gen == EOS or gen == PAD: # PAD 무한 루프 에러 방지
break
a += gen.replace('▁', ' ')
return a.strip()
a = a.strip()
period_pos = a.rfind(".")
question_pos = a.rfind("?")
exclamation_pos = a.rfind("!")
last_pos = len(a) - 1
# print (str(period_pos) + " " + str(question_pos) + " " + str(exclamation_pos))
if last_pos == period_pos or last_pos == question_pos or last_pos == exclamation_pos:
return a
mark_pos = max(max(period_pos, question_pos), exclamation_pos)
a = a[:mark_pos + 1]
if a == "":
return "(끄덕끄덕) 듣고 있어요. 더 말씀해주세요!"
return a


parser = KoGPT2Chat.add_model_specific_args(parser)
Expand All @@ -111,10 +119,14 @@ def predict(sent):

print("=" * 50)
print("[*] kogpt2 chatbot test")
print("\'특별한 이유가 없는데 그냥 불안해\' 챗봇 응답: " + predict("특별한 이유가 없는데 그냥 불안해"))
print("\'특별한 이유가 없는데 그냥 불안하고 눈물이 나와\' 챗봇 응답: " + predict("특별한 이유가 없는데 그냥 불안하고 눈물이 나와"))
print("\'이 세상에서 완전히 사라지고 싶어\' 챗봇 응답: " + predict("이 세상에서 완전히 사라지고 싶어"))
print("\'가슴이 답답해서 터질 것만 같아요.\' 챗봇 응답: " + predict("가슴이 답답해서 터질 것만 같아요."))
print("\'남들이 나를 어떻게 생각할지 신경쓰게 돼\' 챗봇 응답: " + predict("남들이 나를 어떻게 생각할지 신경쓰게 돼"))
print("\'자존감이 낮아지는 것 같아\' 챗봇 응답: " + predict("자존감이 낮아지는 것 같아"))
print("\'뭘 해도 금방 지쳐\' 챗봇 응답: " + predict("뭘 해도 금방 지쳐"))
print("\'걔한테 진짜 크게 배신 당했어\' 챗봇 응답: " + predict("걔한테 진짜 크게 배신 당했어"))
print("\'내일 놀이공원 갈건데 사람 별로 없었으면 좋겠다\' 챗봇 응답: " + predict("내일 놀이공원 갈건데 사람 별로 없었으면 좋겠다"))
print("\'오늘은 구름이랑 달이 너무너무 예쁘더라\' 챗봇 응답: " + predict("오늘은 구름이랑 달이 너무너무 예쁘더라"))
print("\'그래도 내가 머리는 좀 좋아\' 챗봇 응답: " + predict("그래도 내가 머리는 좀 좋아"))
print("=" * 50)

0 comments on commit 68dc29a

Please sign in to comment.