|
import gradio as gr |
|
from gpt import GPTLanguageModel |
|
import torch |
|
import config as cfg |
|
|
|
torch.manual_seed(1337) |
|
|
|
|
|
with open('input.txt', 'r', encoding='utf-8') as f: |
|
text = f.read() |
|
|
|
|
|
chars = sorted(list(set(text))) |
|
vocab_size = len(chars) |
|
|
|
stoi = { ch:i for i,ch in enumerate(chars) } |
|
itos = { i:ch for i,ch in enumerate(chars) } |
|
|
|
encode = lambda s: [stoi[c] for c in s] |
|
|
|
decode = lambda l: ''.join([itos[i] for i in l]) |
|
|
|
model = GPTLanguageModel(vocab_size) |
|
model.load_state_dict(torch.load('gpt_model_saved.pth', map_location=cfg.device)) |
|
m = model.to(cfg.device) |
|
|
|
def inference(InputContext, DesiredCharacterCount): |
|
encoded_text = [encode(InputContext)] |
|
count = int(DesiredCharacterCount) |
|
context = torch.tensor(encoded_text, dtype=torch.long, device=cfg.device) |
|
|
|
out_text = decode(m.generate(context, max_new_tokens=count)[0].tolist()) |
|
return out_text |
|
|
|
title = "GPT Application : GPT built from scratch and trained on mini Shakespeare dataset" |
|
description = "A simple Gradio interface based application that accepts a context, and character count and generates Shakespeare data like text " |
|
examples = [["Edward","200"], |
|
["Buckingham","200"], |
|
["Margaret", "200"] |
|
] |
|
|
|
|
|
|
|
demo = gr.Interface( |
|
inference, |
|
inputs = [gr.Textbox(placeholder="Enter starting characters"), gr.Textbox(placeholder="Enter number of characters you want to generate")], |
|
outputs = [gr.Textbox(label="Shakespeare data like generated text")], |
|
title = title, |
|
description = description, |
|
examples = examples |
|
) |
|
|
|
demo.launch() |
|
|
|
|