ramzan118 commited on
Commit
c6052b4
·
verified ·
1 Parent(s): a8179fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -16
app.py CHANGED
@@ -3,24 +3,23 @@ import gradio as gr
3
  from transformers import AutoModelForCausalLM, AutoTokenizer
4
  import torch
5
 
6
- # Load the pre-trained DialoGPT model and tokenizer
7
  tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
8
  model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small")
9
 
10
- # Define chat function compatible with gr.ChatInterface
11
  def chat_with_bot(message, history):
12
- # Format chat history into a single input string
13
- new_user_input_ids = tokenizer.encode(message + tokenizer.eos_token, return_tensors="pt")
14
 
15
- bot_input_ids = new_user_input_ids
16
- if history:
17
- for user_input, bot_reply in history:
18
- previous = tokenizer.encode(user_input + tokenizer.eos_token + bot_reply + tokenizer.eos_token, return_tensors="pt")
19
- bot_input_ids = torch.cat([bot_input_ids, previous], dim=-1)
20
 
21
- # Generate response
22
  output_ids = model.generate(
23
- bot_input_ids,
24
  max_length=1000,
25
  pad_token_id=tokenizer.eos_token_id,
26
  do_sample=True,
@@ -28,14 +27,12 @@ def chat_with_bot(message, history):
28
  top_p=0.95
29
  )
30
 
31
- # Extract reply from output
32
- response = tokenizer.decode(output_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
33
-
34
- # Append to chat history and return
35
  history.append((message, response))
36
  return response, history
37
 
38
- # Launch Chat Interface
39
  gr.ChatInterface(
40
  fn=chat_with_bot,
41
  title="Muhammad’s ChatGPT",
 
3
  from transformers import AutoModelForCausalLM, AutoTokenizer
4
  import torch
5
 
6
+ # Load DialoGPT model
7
  tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
8
  model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small")
9
 
10
+ # Define the chatbot function
11
  def chat_with_bot(message, history):
12
+ # Build the conversation history into input_ids
13
+ input_ids = tokenizer.encode(message + tokenizer.eos_token, return_tensors="pt")
14
 
15
+ for user_msg, bot_msg in history:
16
+ user_ids = tokenizer.encode(user_msg + tokenizer.eos_token, return_tensors="pt")
17
+ bot_ids = tokenizer.encode(bot_msg + tokenizer.eos_token, return_tensors="pt")
18
+ input_ids = torch.cat([user_ids, bot_ids, input_ids], dim=-1)
 
19
 
20
+ # Generate a response
21
  output_ids = model.generate(
22
+ input_ids,
23
  max_length=1000,
24
  pad_token_id=tokenizer.eos_token_id,
25
  do_sample=True,
 
27
  top_p=0.95
28
  )
29
 
30
+ # Decode and return the response
31
+ response = tokenizer.decode(output_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
 
 
32
  history.append((message, response))
33
  return response, history
34
 
35
+ # Launch the Gradio ChatInterface
36
  gr.ChatInterface(
37
  fn=chat_with_bot,
38
  title="Muhammad’s ChatGPT",