Dafox91 commited on
Commit
9247f45
·
verified ·
1 Parent(s): 9afc375

Create Python

Browse files
Files changed (1) hide show
  1. Python +45 -0
Python ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # chatbot/app.py
2
+
3
+ import torch
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ import gradio as gr
6
+
7
+ # Load pretrained DialoGPT model and tokenizer
8
+ checkpoint = "microsoft/DialoGPT-medium"
9
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint)
10
+ model = AutoModelForCausalLM.from_pretrained(checkpoint)
11
+
12
+ # Chat history for session
13
+ chat_history_ids = None
14
+
15
+ def respond(user_input, history=[]):
16
+ global chat_history_ids
17
+
18
+ # Encode user input and append to chat history
19
+ new_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
20
+
21
+ if chat_history_ids is not None:
22
+ bot_input_ids = torch.cat([chat_history_ids, new_input_ids], dim=-1)
23
+ else:
24
+ bot_input_ids = new_input_ids
25
+
26
+ chat_history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)
27
+
28
+ output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
29
+
30
+ history.append((user_input, output))
31
+ return history, history
32
+
33
+ # Gradio UI
34
+ with gr.Blocks() as demo:
35
+ chatbot = gr.Chatbot()
36
+ msg = gr.Textbox(label="Type your message here")
37
+ clear = gr.Button("Clear Chat")
38
+
39
+ state = gr.State([])
40
+
41
+ msg.submit(respond, [msg, state], [chatbot, state])
42
+ clear.click(lambda: ([], []), None, [chatbot, state])
43
+
44
+ if __name__ == "__main__":
45
+ demo.launch()