Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,64 +1,143 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
""
|
| 7 |
-
|
|
|
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
messages.append({"role": "user", "content": val[0]})
|
| 23 |
-
if val[1]:
|
| 24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
response
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
"""
|
| 44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
| 45 |
-
"""
|
| 46 |
-
demo = gr.ChatInterface(
|
| 47 |
-
respond,
|
| 48 |
-
additional_inputs=[
|
| 49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 52 |
-
gr.Slider(
|
| 53 |
-
minimum=0.1,
|
| 54 |
-
maximum=1.0,
|
| 55 |
-
value=0.95,
|
| 56 |
-
step=0.05,
|
| 57 |
-
label="Top-p (nucleus sampling)",
|
| 58 |
-
),
|
| 59 |
-
],
|
| 60 |
-
)
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
|
|
|
| 63 |
if __name__ == "__main__":
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py - Complete Chatbot with Fine-tuning and Deployment
|
| 2 |
import gradio as gr
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline, Trainer, TrainingArguments
|
| 4 |
+
from datasets import load_dataset, Dataset
|
| 5 |
+
import torch
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from huggingface_hub import notebook_login, Repository
|
| 8 |
|
| 9 |
+
# Configuration
|
| 10 |
+
MODEL_NAME = "t5-small" # Lightweight model good for chatbots
|
| 11 |
+
DATASET_NAME = "AmazonQA"
|
| 12 |
+
FINETUNED_MODEL_NAME = "MujtabaShopifyChatbot"
|
| 13 |
+
HF_TOKEN = "your_huggingface_token" # Replace with your token
|
| 14 |
|
| 15 |
+
# --- Step 1: Load and Prepare Dataset ---
|
| 16 |
+
def load_and_preprocess_data():
|
| 17 |
+
print("Loading AmazonQA dataset...")
|
| 18 |
+
dataset = load_dataset(DATASET_NAME)
|
| 19 |
+
|
| 20 |
+
# Convert to pandas for easier processing
|
| 21 |
+
df = pd.DataFrame(dataset['train'])
|
| 22 |
+
|
| 23 |
+
# Preprocessing - create consistent Q&A pairs
|
| 24 |
+
df = df[['question', 'answer']].dropna()
|
| 25 |
+
df = df[:5000] # Use subset for faster training
|
| 26 |
+
|
| 27 |
+
# Convert back to Hugging Face Dataset
|
| 28 |
+
processed_dataset = Dataset.from_pandas(df)
|
| 29 |
+
|
| 30 |
+
# Split into train and eval
|
| 31 |
+
split_dataset = processed_dataset.train_test_split(test_size=0.1)
|
| 32 |
+
return split_dataset
|
| 33 |
|
| 34 |
+
# --- Step 2: Tokenization ---
|
| 35 |
+
def tokenize_data(dataset):
|
| 36 |
+
print("Tokenizing data...")
|
| 37 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 38 |
+
|
| 39 |
+
def preprocess_function(examples):
|
| 40 |
+
inputs = [f"question: {q} answer:" for q in examples["question"]]
|
| 41 |
+
targets = examples["answer"]
|
| 42 |
+
|
| 43 |
+
model_inputs = tokenizer(inputs, max_length=128, truncation=True)
|
| 44 |
+
labels = tokenizer(targets, max_length=128, truncation=True)
|
| 45 |
+
|
| 46 |
+
model_inputs["labels"] = labels["input_ids"]
|
| 47 |
+
return model_inputs
|
| 48 |
|
| 49 |
+
tokenized_dataset = dataset.map(preprocess_function, batched=True)
|
| 50 |
+
return tokenized_dataset
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
+
# --- Step 3: Fine-tuning ---
|
| 53 |
+
def fine_tune_model(tokenized_dataset):
|
| 54 |
+
print("Fine-tuning model...")
|
| 55 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)
|
| 56 |
+
|
| 57 |
+
training_args = TrainingArguments(
|
| 58 |
+
output_dir="./results",
|
| 59 |
+
evaluation_strategy="epoch",
|
| 60 |
+
learning_rate=2e-5,
|
| 61 |
+
per_device_train_batch_size=8,
|
| 62 |
+
per_device_eval_batch_size=8,
|
| 63 |
+
num_train_epochs=3,
|
| 64 |
+
weight_decay=0.01,
|
| 65 |
+
save_total_limit=3,
|
| 66 |
+
fp16=torch.cuda.is_available(),
|
| 67 |
+
push_to_hub=True,
|
| 68 |
+
hub_model_id=FINETUNED_MODEL_NAME,
|
| 69 |
+
hub_token=HF_TOKEN,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
trainer = Trainer(
|
| 73 |
+
model=model,
|
| 74 |
+
args=training_args,
|
| 75 |
+
train_dataset=tokenized_dataset["train"],
|
| 76 |
+
eval_dataset=tokenized_dataset["test"],
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
trainer.train()
|
| 80 |
+
trainer.push_to_hub()
|
| 81 |
+
return model
|
| 82 |
|
| 83 |
+
# --- Step 4: Chatbot Interface ---
|
| 84 |
+
def initialize_chatbot():
|
| 85 |
+
print("Loading chatbot...")
|
| 86 |
+
try:
|
| 87 |
+
# Try loading fine-tuned model first
|
| 88 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(FINETUNED_MODEL_NAME)
|
| 89 |
+
tokenizer = AutoTokenizer.from_pretrained(FINETUNED_MODEL_NAME)
|
| 90 |
+
except:
|
| 91 |
+
# Fallback to pre-trained model
|
| 92 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)
|
| 93 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 94 |
+
|
| 95 |
+
chatbot_pipe = pipeline("text2text-generation", model=model, tokenizer=tokenizer)
|
| 96 |
+
return chatbot_pipe
|
| 97 |
|
| 98 |
+
def generate_response(message, history):
|
| 99 |
+
# Format the input for the model
|
| 100 |
+
input_text = f"question: {message} answer:"
|
| 101 |
+
|
| 102 |
+
# Generate response
|
| 103 |
+
response = chatbot_pipe(input_text, max_length=128, do_sample=True)[0]['generated_text']
|
| 104 |
+
|
| 105 |
+
# Clean up the response
|
| 106 |
+
if "answer:" in response:
|
| 107 |
+
response = response.split("answer:")[-1].strip()
|
| 108 |
+
return response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
# --- Step 5: Deployment ---
|
| 111 |
+
def deploy_chatbot():
|
| 112 |
+
print("Launching chatbot interface...")
|
| 113 |
+
demo = gr.ChatInterface(
|
| 114 |
+
fn=generate_response,
|
| 115 |
+
title="Mujtaba's Shopify Chatbot",
|
| 116 |
+
description="Ask me anything about products, shipping, or returns!",
|
| 117 |
+
examples=[
|
| 118 |
+
"What's the return policy?",
|
| 119 |
+
"How long does shipping take to Karachi?",
|
| 120 |
+
"Do you have size charts for kurtas?"
|
| 121 |
+
],
|
| 122 |
+
theme="soft"
|
| 123 |
+
)
|
| 124 |
+
return demo
|
| 125 |
|
| 126 |
+
# --- Main Execution ---
|
| 127 |
if __name__ == "__main__":
|
| 128 |
+
# Login to Hugging Face Hub
|
| 129 |
+
notebook_login()
|
| 130 |
+
|
| 131 |
+
# Dataset preparation
|
| 132 |
+
dataset = load_and_preprocess_data()
|
| 133 |
+
tokenized_dataset = tokenize_data(dataset)
|
| 134 |
+
|
| 135 |
+
# Fine-tuning (uncomment to run)
|
| 136 |
+
# fine_tune_model(tokenized_dataset)
|
| 137 |
+
|
| 138 |
+
# Initialize chatbot
|
| 139 |
+
chatbot_pipe = initialize_chatbot()
|
| 140 |
+
|
| 141 |
+
# Launch interface
|
| 142 |
+
demo = deploy_chatbot()
|
| 143 |
+
demo.launch(share=True)
|