Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# https://ai-brewery.medium.com/conversational-chatbot-using-transformers-and-streamlit-73d621afde9
|
2 |
+
import streamlit as st
|
3 |
+
import torch
|
4 |
+
import transformers
|
5 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
6 |
+
|
7 |
+
@st.cache(hash_funcs=
|
8 |
+
{transformers.models.gpt2.tokenization_gpt2_fast.GPT2TokenizerFast: hash},
|
9 |
+
suppress_st_warning=True)
|
10 |
+
|
11 |
+
def load_data():
|
12 |
+
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
|
13 |
+
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
|
14 |
+
return tokenizer, model
|
15 |
+
|
16 |
+
tokenizer, model = load_data()
|
17 |
+
|
18 |
+
st.write("Welcome to the Chatbot. I am still learning, please be patient")
|
19 |
+
input = st.text_input('User:')
|
20 |
+
if 'count' not in st.session_state or st.session_state.count == 6:
|
21 |
+
st.session_state.count = 0
|
22 |
+
st.session_state.chat_history_ids = None
|
23 |
+
st.session_state.old_response = ''
|
24 |
+
else:
|
25 |
+
st.session_state.count += 1
|
26 |
+
|
27 |
+
|
28 |
+
new_user_input_ids = tokenizer.encode(input + tokenizer.eos_token, return_tensors='pt')
|
29 |
+
|
30 |
+
bot_input_ids = torch.cat([st.session_state.chat_history_ids, new_user_input_ids], dim=-1) if st.session_state.count > 1 else new_user_input_ids
|
31 |
+
|
32 |
+
st.session_state.chat_history_ids = model.generate(bot_input_ids, max_length=5000, pad_token_id=tokenizer.eos_token_id)
|
33 |
+
|
34 |
+
response = tokenizer.decode(st.session_state.chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
|
35 |
+
|
36 |
+
if st.session_state.old_response == response:
|
37 |
+
bot_input_ids = new_user_input_ids
|
38 |
+
|
39 |
+
st.session_state.chat_history_ids = model.generate(bot_input_ids, max_length=5000, pad_token_id=tokenizer.eos_token_id)
|
40 |
+
response = tokenizer.decode(st.session_state.chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
|
41 |
+
|
42 |
+
st.write(f"Chatbot: {response}")
|
43 |
+
st.session_state.old_response = response
|