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from torch.utils.data import Dataset, DataLoader
|
| 6 |
+
from flask import Flask, request, jsonify
|
| 7 |
+
from sklearn.model_selection import train_test_split
|
| 8 |
+
import os
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
# Load data
|
| 12 |
+
url = "https://drive.google.com/uc?id=1RCZShB5ohy1HdU-mogcP16TbeVv9txpY"
|
| 13 |
+
df = pd.read_csv(url)
|
| 14 |
+
|
| 15 |
+
# Tokenizer
|
| 16 |
+
class ScratchTokenizer:
|
| 17 |
+
def __init__(self):
|
| 18 |
+
self.word2idx = {"<PAD>": 0, "<SOS>": 1, "<EOS>": 2, "<UNK>": 3}
|
| 19 |
+
self.idx2word = {0: "<PAD>", 1: "<SOS>", 2: "<EOS>", 3: "<UNK>"}
|
| 20 |
+
self.vocab_size = 4
|
| 21 |
+
|
| 22 |
+
def build_vocab(self, texts):
|
| 23 |
+
for text in texts:
|
| 24 |
+
for word in text.split():
|
| 25 |
+
if word not in self.word2idx:
|
| 26 |
+
self.word2idx[word] = self.vocab_size
|
| 27 |
+
self.idx2word[self.vocab_size] = word
|
| 28 |
+
self.vocab_size += 1
|
| 29 |
+
|
| 30 |
+
def encode(self, text, max_len=200):
|
| 31 |
+
tokens = [self.word2idx.get(word, 3) for word in text.split()]
|
| 32 |
+
tokens = [1] + tokens[:max_len - 2] + [2]
|
| 33 |
+
return tokens + [0] * (max_len - len(tokens))
|
| 34 |
+
|
| 35 |
+
def decode(self, tokens):
|
| 36 |
+
return " ".join([self.idx2word.get(idx, "<UNK>") for idx in tokens if idx > 0])
|
| 37 |
+
|
| 38 |
+
# Train-Test Split
|
| 39 |
+
train_data, test_data = train_test_split(df, test_size=0.2, random_state=42)
|
| 40 |
+
|
| 41 |
+
# Initialize Tokenizer
|
| 42 |
+
tokenizer = ScratchTokenizer()
|
| 43 |
+
tokenizer.build_vocab(train_data["instruction"].tolist() + train_data["response"].tolist())
|
| 44 |
+
|
| 45 |
+
# Dataset Class
|
| 46 |
+
class TextDataset(Dataset):
|
| 47 |
+
def __init__(self, data, tokenizer, max_len=200):
|
| 48 |
+
self.data = data
|
| 49 |
+
self.tokenizer = tokenizer
|
| 50 |
+
self.max_len = max_len
|
| 51 |
+
|
| 52 |
+
def __len__(self):
|
| 53 |
+
return len(self.data)
|
| 54 |
+
|
| 55 |
+
def __getitem__(self, idx):
|
| 56 |
+
src_text = self.data.iloc[idx]["instruction"]
|
| 57 |
+
tgt_text = self.data.iloc[idx]["response"]
|
| 58 |
+
src = torch.tensor(self.tokenizer.encode(src_text), dtype=torch.long)
|
| 59 |
+
tgt = torch.tensor(self.tokenizer.encode(tgt_text), dtype=torch.long)
|
| 60 |
+
return src, tgt
|
| 61 |
+
|
| 62 |
+
# Model
|
| 63 |
+
class GPTModel(nn.Module):
|
| 64 |
+
def __init__(self, vocab_size, embed_size=256, num_heads=8, num_layers=6, max_len=200):
|
| 65 |
+
super(GPTModel, self).__init__()
|
| 66 |
+
self.embedding = nn.Embedding(vocab_size, embed_size)
|
| 67 |
+
self.pos_embedding = nn.Parameter(torch.randn(1, max_len, embed_size))
|
| 68 |
+
self.transformer = nn.TransformerDecoder(
|
| 69 |
+
nn.TransformerDecoderLayer(d_model=embed_size, nhead=num_heads),
|
| 70 |
+
num_layers=num_layers
|
| 71 |
+
)
|
| 72 |
+
self.fc_out = nn.Linear(embed_size, vocab_size)
|
| 73 |
+
|
| 74 |
+
def forward(self, src, tgt):
|
| 75 |
+
src_emb = self.embedding(src) + self.pos_embedding[:, :src.size(1), :]
|
| 76 |
+
tgt_emb = self.embedding(tgt) + self.pos_embedding[:, :tgt.size(1), :]
|
| 77 |
+
tgt_mask = nn.Transformer.generate_square_subsequent_mask(tgt.size(1)).to(tgt.device)
|
| 78 |
+
output = self.transformer(tgt_emb.permute(1, 0, 2), src_emb.permute(1, 0, 2), tgt_mask=tgt_mask)
|
| 79 |
+
return self.fc_out(output.permute(1, 0, 2))
|
| 80 |
+
|
| 81 |
+
# Load model
|
| 82 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 83 |
+
model = GPTModel(tokenizer.vocab_size).to(device)
|
| 84 |
+
|
| 85 |
+
def load_model(model, path="gpt_model.pth"):
|
| 86 |
+
if os.path.exists(path):
|
| 87 |
+
model.load_state_dict(torch.load(path, map_location=device))
|
| 88 |
+
model.eval()
|
| 89 |
+
print("Model loaded successfully.")
|
| 90 |
+
else:
|
| 91 |
+
print("Model file not found!")
|
| 92 |
+
|
| 93 |
+
load_model(model)
|
| 94 |
+
|
| 95 |
+
# Generate Response
|
| 96 |
+
# def generate_response(model, query, max_length=200):
|
| 97 |
+
# model.eval()
|
| 98 |
+
# src = torch.tensor(tokenizer.encode(query)).unsqueeze(0).to(device)
|
| 99 |
+
# tgt = torch.tensor([[1]]).to(device) # <SOS>
|
| 100 |
+
# for _ in range(max_length):
|
| 101 |
+
# output = model(src, tgt)
|
| 102 |
+
# next_word = output.argmax(-1)[:, -1].unsqueeze(1)
|
| 103 |
+
# tgt = torch.cat([tgt, next_word], dim=1)
|
| 104 |
+
# if next_word.item() == 2: # <EOS>
|
| 105 |
+
# break
|
| 106 |
+
# return tokenizer.decode(tgt.squeeze(0).tolist())
|
| 107 |
+
|
| 108 |
+
def generate_response(model, query, max_length=200):
|
| 109 |
+
model.eval()
|
| 110 |
+
with torch.no_grad(): # Disable gradient tracking
|
| 111 |
+
src = torch.tensor(tokenizer.encode(query)).unsqueeze(0).to(device)
|
| 112 |
+
tgt = torch.tensor([[1]]).to(device) # <SOS>
|
| 113 |
+
|
| 114 |
+
for _ in range(max_length):
|
| 115 |
+
output = model(src, tgt)
|
| 116 |
+
next_token = output[:, -1, :].argmax(dim=-1, keepdim=True)
|
| 117 |
+
tgt = torch.cat([tgt, next_token], dim=1)
|
| 118 |
+
if next_token.item() == 2: # <EOS>
|
| 119 |
+
break
|
| 120 |
+
|
| 121 |
+
return tokenizer.decode(tgt.squeeze(0).tolist())
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# Flask App
|
| 125 |
+
app = Flask(__name__)
|
| 126 |
+
|
| 127 |
+
@app.route("/")
|
| 128 |
+
def home():
|
| 129 |
+
return {"message": "Transformer-based Response Generator API is running!"}
|
| 130 |
+
|
| 131 |
+
@app.route("/intent")
|
| 132 |
+
def intents():
|
| 133 |
+
return jsonify({"intents" :list(set(df['intent'].dropna()))})
|
| 134 |
+
|
| 135 |
+
@app.route("/query", methods=["POST"])
|
| 136 |
+
def query_model():
|
| 137 |
+
data = request.get_json()
|
| 138 |
+
query = data.get("query", "")
|
| 139 |
+
if not query:
|
| 140 |
+
return jsonify({"error": "Query cannot be empty"}), 400
|
| 141 |
+
start = time.time()
|
| 142 |
+
response = generate_response(model, query)
|
| 143 |
+
end = time.time()
|
| 144 |
+
return jsonify({"query": query, "response": response,"response_time":(end-start)})
|