Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
+
import torch
|
4 |
+
|
5 |
+
# Load pre-trained DialoGPT-small model and tokenizer
|
6 |
+
model_name = "microsoft/DialoGPT-small"
|
7 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
8 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
9 |
+
|
10 |
+
# Set device to GPU if available for faster inference, otherwise fallback to CPU
|
11 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
12 |
+
model.to(device)
|
13 |
+
|
14 |
+
# Initialize chat history
|
15 |
+
if 'history' not in st.session_state:
|
16 |
+
st.session_state['history'] = []
|
17 |
+
|
18 |
+
def generate_response(input_text):
|
19 |
+
# Encode the new user input, add end of string token
|
20 |
+
new_user_input_ids = tokenizer.encode(input_text + tokenizer.eos_token, return_tensors='pt').to(device)
|
21 |
+
|
22 |
+
# Append the new user input tokens to the chat history
|
23 |
+
bot_input_ids = torch.cat([torch.tensor(st.session_state['history']).to(device), new_user_input_ids], dim=-1) if st.session_state['history'] else new_user_input_ids
|
24 |
+
|
25 |
+
# Generate a response from the model
|
26 |
+
chat_history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id, top_k=50, top_p=0.95, temperature=0.7)
|
27 |
+
|
28 |
+
# Decode the model's output and add it to the history
|
29 |
+
chat_history_ids = chat_history_ids[:, bot_input_ids.shape[-1]:] # only take the latest generated tokens
|
30 |
+
bot_output = tokenizer.decode(chat_history_ids[0], skip_special_tokens=True)
|
31 |
+
|
32 |
+
# Update session state history with the new tokens
|
33 |
+
st.session_state['history'] = chat_history_ids[0].tolist()
|
34 |
+
|
35 |
+
return bot_output
|
36 |
+
|
37 |
+
# Streamlit Interface
|
38 |
+
st.title("Chat with DialoGPT")
|
39 |
+
|
40 |
+
# Create input box for user
|
41 |
+
user_input = st.text_input("You: ", "")
|
42 |
+
|
43 |
+
if user_input:
|
44 |
+
# Generate and display the bot's response
|
45 |
+
response = generate_response(user_input)
|
46 |
+
st.write(f"Bot: {response}")
|