Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,53 @@
|
|
|
|
1 |
import gradio as gr
|
|
|
2 |
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
import gradio as gr
|
3 |
+
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
4 |
|
5 |
+
# Load the model and tokenizer
|
6 |
+
def load_model():
|
7 |
+
model_name = "gpt2"
|
8 |
+
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
|
9 |
+
model = GPT2LMHeadModel.from_pretrained(model_name)
|
10 |
+
return tokenizer, model
|
11 |
+
|
12 |
+
# Function to generate response with instructions
|
13 |
+
def generate_response(user_input, instructions="Be friendly and helpful, and ensure your response is accurate and relevant."):
|
14 |
+
tokenizer, model = load_model()
|
15 |
+
model.eval()
|
16 |
+
|
17 |
+
# Add instructions at the beginning of the user input
|
18 |
+
prompt = instructions + " " + user_input
|
19 |
+
|
20 |
+
input_ids = tokenizer.encode(prompt, return_tensors="pt")
|
21 |
+
with torch.no_grad():
|
22 |
+
output = model.generate(
|
23 |
+
input_ids,
|
24 |
+
max_length=100,
|
25 |
+
pad_token_id=tokenizer.eos_token_id,
|
26 |
+
no_repeat_ngram_size=2, # Avoid repeating phrases
|
27 |
+
temperature=0.7, # Control randomness
|
28 |
+
top_k=50, # Limit token selection
|
29 |
+
top_p=0.9, # Nucleus sampling
|
30 |
+
do_sample=True # Enable sampling
|
31 |
+
)
|
32 |
+
|
33 |
+
response = tokenizer.decode(output[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
|
34 |
+
return response
|
35 |
+
|
36 |
+
# Gradio interface
|
37 |
+
def chatbot_interface():
|
38 |
+
interface = gr.Interface(
|
39 |
+
fn=generate_response, # Function to process the input
|
40 |
+
inputs=[
|
41 |
+
gr.Textbox(label="Enter your message", placeholder="Ask a question or make a request."),
|
42 |
+
gr.Textbox(label="Instruction for the bot", placeholder="For example: Be friendly and helpful, ensure accuracy.")
|
43 |
+
], # Two text boxes: one for input and one for instructions
|
44 |
+
outputs="text", # Output type - text
|
45 |
+
title="GPT-2 Chatbot with Accuracy and Relevance Instructions", # Application title
|
46 |
+
description="This is a chatbot based on the GPT-2 model. You can provide instructions to adjust the style of the bot's responses, ensuring accuracy and relevance.", # Description
|
47 |
+
theme="compact" # Interface theme
|
48 |
+
)
|
49 |
+
interface.launch()
|
50 |
+
|
51 |
+
# Run the interface
|
52 |
+
if __name__ == "__main__":
|
53 |
+
chatbot_interface()
|