File size: 1,830 Bytes
9a6f34b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re

import gradio as gr
import requests
import xmltodict
from transformers import AutoModelForQuestionAnswering, AutoTokenizer, pipeline
from transformers.pipelines.question_answering import QuestionAnsweringPipeline

QA_MODEL_NAME = "ixa-ehu/SciBERT-SQuAD-QuAC"


def clean_text(text: str) -> str:
    text = re.sub("\n", " ", text)
    return text


def get_paper_summary(arxiv_id: str) -> str:
    paper_url = f"http://export.arxiv.org/api/query?id_list={arxiv_id}"
    response = requests.get(paper_url)
    paper_dict = xmltodict.parse(response.content)["feed"]["entry"]
    return clean_text(paper_dict["summary"])


def get_qa_pipeline(qa_model_name: str = QA_MODEL_NAME) -> QuestionAnsweringPipeline:
    tokenizer = AutoTokenizer.from_pretrained(qa_model_name)
    model = AutoModelForQuestionAnswering.from_pretrained(qa_model_name)
    qa_pipeline = pipeline("question-answering", model=model, tokenizer=tokenizer)
    return qa_pipeline


def get_answer(question: str, context: str) -> str:
    qa_pipeline = get_qa_pipeline()
    prediction = qa_pipeline(question=question, context=context)
    return prediction["answer"]


demo = gr.Blocks()


with demo:
    gr.Markdown("# Document QA")

    # Retrieve paper
    arxiv_id = gr.Textbox(
        label="arXiv Paper ID", placeholder="Insert here the ID of a paper on arXiv"
    )
    paper_summary = gr.Textbox(label="Paper summary")
    fetch_document_button = gr.Button("Get Summary")
    fetch_document_button.click(
        fn=get_paper_summary, inputs=arxiv_id, outputs=paper_summary
    )

    # QA on paper
    question = gr.Textbox(label="Ask a question about the paper:")
    answer = gr.Textbox("Answer:")
    ask_button = gr.Button("Ask me 🤖")
    ask_button.click(fn=get_answer, inputs=[question, paper_summary], outputs=answer)


demo.launch()