Spaces:
Runtime error
Runtime error
File size: 4,150 Bytes
8e5bb9e 7c59cdd af44808 8e5bb9e 6e18097 a7c96e0 6e18097 8e5bb9e af44808 6e18097 19b6aec 6e18097 a7c96e0 6e18097 7d531ce 6e18097 8e5bb9e 6e18097 8e5bb9e 6e18097 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
import gradio as gr
from transformers import (
BartForConditionalGeneration,
BartTokenizer
)
import torch
import json
def read_json_file_2_dict(filename, store_dir='.'):
with open(f'{store_dir}/{filename}', 'r', encoding='utf-8') as file:
return json.load(file)
def get_device():
# If there's a GPU available...
if torch.cuda.is_available():
device = torch.device("cuda")
n_gpus = torch.cuda.device_count()
first_gpu = torch.cuda.get_device_name(0)
print(f'There are {n_gpus} GPU(s) available.')
print(f'GPU gonna be used: {first_gpu}')
else:
print('No GPU available, using the CPU instead.')
device = torch.device("cpu")
return device
model_name = 'unlisboa/bart_qa_assistant'
tokenizer = BartTokenizer.from_pretrained(model_name)
device = get_device()
model = BartForConditionalGeneration.from_pretrained(model_name).to(device)
model.eval()
def run_bart(question, censor):
print(question, censor)
if censor:
bad_words = read_json_file_2_dict('bad_words_file.json')
bad_words_ids = tokenizer(bad_words, add_prefix_space=True, add_special_tokens=False).get('input_ids')
else:
bad_words_ids = None
model_input = tokenizer(question, truncation=True, padding=True, return_tensors="pt")
generated_answers_encoded = model.generate(input_ids=model_input["input_ids"].to(device),
attention_mask=model_input["attention_mask"].to(device),
#bad_words_ids=bad_words_ids,
force_words_ids=None,
min_length=1,
max_length=100,
do_sample=True,
bad_words_ids=bad_words_ids,
early_stopping=True,
num_beams=4,
temperature=1.0,
top_k=None,
top_p=None,
# eos_token_id=tokenizer.eos_token_id,
no_repeat_ngram_size=2,
num_return_sequences=1,
return_dict_in_generate=True,
output_scores=True)
response = tokenizer.batch_decode(generated_answers_encoded['sequences'], skip_special_tokens=True,clean_up_tokenization_spaces=True)[0]
return response
examples = [["What's the meaning of life?", True]]
checkbox = gr.Checkbox(value=True, label="should censor output")
question_input = gr.Textbox(lines=2, label='Question:')
answer_output = gr.Textbox(lines=2, label='Answer:')
gr.Interface(fn=run_bart, inputs=[question_input, checkbox], outputs=[answer_output], allow_flagging="never", examples=examples).launch() |