Question Answering with transformers

Answer questions from a context with a Hugging Face question-answering pipeline.

1 min read Updated

A few lines of Python that load a Hugging Face question-answering pipeline and extract an answer from a context window. The script is below.

qa.py

python
from transformers import pipeline

class QuestionAnswering:
  def __init__(self, context: str):
    model_name = 'Nadav/bert-base-french-europeana-cased-squad-fr'
    model_name = 'etalab-ia/camembert-base-squadFR-fquad-piaf'

    self._model = pipeline('question-answering', model=model_name, tokenizer=model_name)
    self._context = context

  def ask(self, question: str, threshold: float = 0.2):
    answer = self._model(question = question, context = self._context)

    return answer['answer'] if answer['score'] > threshold and answer['answer'] else None

Search articles

Type to filter articles. Use the arrow keys to move through results and Enter to open one. Press Escape to close.