Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
# The huggingface model id for Microsoft's phi-2 model
|
| 7 |
+
checkpoint = "microsoft/phi-2"
|
| 8 |
+
|
| 9 |
+
# Download and load model and tokenizer
|
| 10 |
+
tokenizer = AutoTokenizer.from_pretrained(checkpoint, trust_remote_code=True)
|
| 11 |
+
model = AutoModelForCausalLM.from_pretrained(checkpoint, torch_dtype=torch.float32, device_map="cpu", trust_remote_code=True)
|
| 12 |
+
|
| 13 |
+
# Text generation pipeline
|
| 14 |
+
phi2 = pipeline("text-generation", tokenizer=tokenizer, model=model)
|
| 15 |
+
|
| 16 |
+
# Function that accepts a prompt and generates text using the phi2 pipeline
|
| 17 |
+
def generate(prompt, chat_history):
|
| 18 |
+
|
| 19 |
+
instruction = "You are a helpful assistant to 'User'. You do not respond as 'User' or pretend to be 'User'. You only respond once as 'Assistant'."
|
| 20 |
+
final_prompt = f"Instruction: {instruction}\n"
|
| 21 |
+
|
| 22 |
+
for sent, received in chat_history:
|
| 23 |
+
final_prompt += "User: " + sent + "\n"
|
| 24 |
+
final_prompt += "Assistant: " + received + "\n"
|
| 25 |
+
|
| 26 |
+
final_prompt += "User: " + prompt + "\n"
|
| 27 |
+
final_prompt += "Output:"
|
| 28 |
+
|
| 29 |
+
generated_text = phi2(final_prompt, max_length=256)[0]["generated_text"]
|
| 30 |
+
response = generated_text.split("Output:")[1].split("User:")[0]
|
| 31 |
+
|
| 32 |
+
if "Assistant:" in response:
|
| 33 |
+
response = response.split("Assistant:")[1].strip()
|
| 34 |
+
|
| 35 |
+
chat_history.append((prompt, response))
|
| 36 |
+
|
| 37 |
+
return "", chat_history
|
| 38 |
+
|
| 39 |
+
# Chat interface with gradio
|
| 40 |
+
with gr.Blocks() as demo:
|
| 41 |
+
gr.Markdown("# Phi-2 Chatbot Demo")
|
| 42 |
+
|
| 43 |
+
chatbot = gr.Chatbot()
|
| 44 |
+
msg = gr.Textbox()
|
| 45 |
+
|
| 46 |
+
clear = gr.ClearButton([msg, chatbot])
|
| 47 |
+
msg.submit(fn=generate, inputs=[msg, chatbot], outputs=[msg, chatbot])
|
| 48 |
+
|
| 49 |
+
demo.launch()
|