Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
3 |
+
|
4 |
+
# Load the model and tokenizer from Hugging Face model hub
|
5 |
+
model_name = "gpt2" # You can replace "gpt2" with your fine-tuned model if you have one
|
6 |
+
model = GPT2LMHeadModel.from_pretrained(model_name)
|
7 |
+
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
|
8 |
+
|
9 |
+
def chat_with_me(input_text, history=[]):
|
10 |
+
# Encode the new input with history
|
11 |
+
new_input_ids = tokenizer.encode(input_text + tokenizer.eos_token, return_tensors="pt")
|
12 |
+
|
13 |
+
# Append the new user input to the chat history
|
14 |
+
bot_input_ids = torch.cat([torch.tensor(history), new_input_ids], dim=-1) if history else new_input_ids
|
15 |
+
|
16 |
+
# Generate the model's response
|
17 |
+
history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)
|
18 |
+
|
19 |
+
# Decode the response and append to history
|
20 |
+
response = tokenizer.decode(history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
|
21 |
+
history += new_input_ids.tolist()
|
22 |
+
|
23 |
+
return response, history
|
24 |
+
|
25 |
+
with gr.Blocks() as demo:
|
26 |
+
with gr.Row():
|
27 |
+
chat = gr.Chatbot()
|
28 |
+
user_input = gr.Textbox(placeholder="Ask me anything...")
|
29 |
+
with gr.Row():
|
30 |
+
clear = gr.Button("Clear")
|
31 |
+
|
32 |
+
# Define interactions
|
33 |
+
user_input.submit(chat_with_me, [user_input, chat], [chat, user_input])
|
34 |
+
clear.click(lambda: None, None, chat)
|
35 |
+
|
36 |
+
demo.launch()
|