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()