Spaces:
Runtime error
Runtime error
Walid Aissa commited on
Commit ·
41cb046
1
Parent(s): 22eefa0
bert question answering model trained on squad added
Browse files1234567891011121313 unmodified lines272829303132333418 unmodified lines5354555657583 unmodified lines62636465666768697071import osimport gradio as grimport wikipediaapi as wkfrom transformers import (TokenClassificationPipeline,AutoModelForTokenClassification,AutoTokenizer,)from transformers.pipelines import AggregationStrategyimport numpy as np# =====[ DEFINE PIPELINE ]===== #class KeyphraseExtractionPipeline(TokenClassificationPipeline):13 unmodified linesreturn np.unique([result.get("word").strip() for result in results])# =====[ LOAD PIPELINE ]===== #model_name = "ml6team/keyphrase-extraction-kbir-inspec"extractor = KeyphraseExtractionPipeline(model=model_name)#TODO: add further preprocessingdef keyphrases_extraction(text: str) -> str:18 unmodified linesreturn page.summaryexcept:return "I cannot answer this question"# =====[ DEFINE INTERFACE ]===== #'title = "Azza Chatbot"3 unmodified lines]demo = gr.Interface(title = title,fn=wikipedia_search,inputs = "text",outputs = "text",1234567891011121314151613 unmodified lines3031323334353637383918 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271283 unmodified lines132133134135136137138139140141142import osimport gradio as grimport numpy as npimport wikipediaapi as wkfrom transformers import (TokenClassificationPipeline,AutoModelForTokenClassification,AutoTokenizer,)import torchfrom transformers.pipelines import AggregationStrategyfrom transformers import BertForQuestionAnsweringfrom transformers import BertTokenizer# =====[ DEFINE PIPELINE ]===== #class KeyphraseExtractionPipeline(TokenClassificationPipeline):13 unmodified linesreturn np.unique([result.get("word").strip() for result in results])# =====[ LOAD PIPELINE ]===== #keyPhraseExtractionModel = "ml6team/keyphrase-extraction-kbir-inspec"extractor = KeyphraseExtractionPipeline(model=keyPhraseExtractionModel)model = BertForQuestionAnswering.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')tokenizer = BertTokenizer.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')#TODO: add further preprocessingdef keyphrases_extraction(text: str) -> str:18 unmodified linesreturn page.summaryexcept:return "I cannot answer this question"def answer_question(question):context = wikipedia_search(question)if context == "I cannot answer this question":return context# ======== Tokenize ========# Apply the tokenizer to the input text, treating them as a text-pair.input_ids = tokenizer.encode(question, context)# Report how long the input sequence is. if longer than 512 tokens, make it shorterwhile(len(input_ids) > 512):input_ids.pop()print('Query has {:,} tokens.\n'.format(len(input_ids)))# ======== Set Segment IDs ========# Search the input_ids for the first instance of the `[SEP]` token.sep_index = input_ids.index(tokenizer.sep_token_id)# The number of segment A tokens includes the [SEP] token istelf.num_seg_a = sep_index + 1# The remainder are segment B.num_seg_b = len(input_ids) - num_seg_a# Construct the list of 0s and 1s.segment_ids = [0]*num_seg_a + [1]*num_seg_b# There should be a segment_id for every input token.assert len(segment_ids) == len(input_ids)# ======== Evaluate ========# Run our example through the model.outputs = model(torch.tensor([input_ids]), # The tokens representing our input text.token_type_ids=torch.tensor([segment_ids]), # The segment IDs to differentiate question from answer_textreturn_dict=True)start_scores = outputs.start_logitsend_scores = outputs.end_logits# ======== Reconstruct Answer ========# Find the tokens with the highest `start` and `end` scores.answer_start = torch.argmax(start_scores)answer_end = torch.argmax(end_scores)# Get the string versions of the input tokens.tokens = tokenizer.convert_ids_to_tokens(input_ids)# Start with the first token.answer = tokens[answer_start]# Select the remaining answer tokens and join them with whitespace.for i in range(answer_start + 1, answer_end + 1):# If it's a subword token, then recombine it with the previous token.if tokens[i][0:2] == '##':answer += tokens[i][2:]# Otherwise, add a space then the token.else:answer += ' ' + tokens[i]return 'Answer: "' + answer + '"'# =====[ DEFINE INTERFACE ]===== #'title = "Azza Chatbot"3 unmodified lines]demo = gr.Interface(title = title,fn=answer_question,inputs = "text",outputs = "text",
app.py+75-4