File size: 1,996 Bytes
652d3a1
 
cea5647
9e5ce24
6fab346
9e5ce24
 
 
6fab346
cea5647
9e5ce24
787c124
9e5ce24
 
 
 
787c124
9e5ce24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
787c124
9e5ce24
 
787c124
 
9e5ce24
787c124
 
 
9e5ce24
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from transformers import pipeline

# Load the Question Answering pipeline with a better model
qa_pipeline = pipeline(
    "question-answering", 
    model="deepset/roberta-base-squad2",  # Try a more accurate model
    top_k=3  # Get top 3 answers
)

# Define the function to get the answer with confidence check
def answer_question(context, question):
    if not context or not question:
        return "Please provide both a context and a question."
    
    # Get the answer
    result = qa_pipeline(question=question, context=context)
    
    # If using top_k=3, you can get multiple answers
    if isinstance(result, list):
        # Return the highest confidence answer
        best_answer = result[0]
        confidence = best_answer["score"] * 100
        answer = best_answer["answer"]
    else:
        confidence = result["score"] * 100
        answer = result["answer"]
    
    # Only return answers with reasonable confidence
    if confidence < 10:
        return "I couldn't find a reliable answer to this question in the provided context."
    
    return f"{answer} (Confidence: {confidence:.1f}%)"

# Define Gradio interface with examples
iface = gr.Interface(
    fn=answer_question,
    inputs=[
        gr.Textbox(lines=6, label="Context (Paragraph)"),
        gr.Textbox(lines=1, label="Question")
    ],
    outputs="text",
    title="Hugging Face QA App",
    description="Enter a paragraph and ask a question about it. The model will find the answer.",
    examples=[
        ["The Eiffel Tower is located in Paris, France. It was built in 1889 by Gustave Eiffel. The tower is 324 meters tall and was initially criticized by some French artists.", 
         "Where is the Eiffel Tower located?"],
        ["Python is a programming language created by Guido van Rossum in 1991. It emphasizes code readability and allows programmers to express concepts in fewer lines of code.",
         "Who created Python?"]
    ]
)

# Launch the app
iface.launch()