Downloads · 30 days
0
keval159/question-answering
question-answering is a machine learning model from keval159. Use it for the machine learning task on the model card, and read the license before you ship it in a product.
Downloads · 30 days
0
Access
Public
Updated Mar 12, 2025
Repo size
—
Likes
0
Public
Click a slice to open those files.
.py2.1 KB · 37%
From the Hugging Face model README
from transformers import pipeline
model_name = "deepset/roberta-base-squad2"
nlp = pipeline("question-answering", model=model_name, tokenizer=model_name)
def load_context(file_path): try: with open(file_path, 'r', encoding='utf-8') as file: return file.read() except FileNotFoundError: print(f"Error: Context file not found: {file_path}") return ""
def split_text_into_chunks(text, chunk_size=500): words = text.split() return [' '.join(words[i:i + chunk_size]) for i in range(0, len(words), chunk_size)]
def get_best_answer(question, context_chunks): best_answer = None best_score = 0
for chunk in context_chunks:
QA_input = {'question': question, 'context': chunk}
try:
res = nlp(QA_input)
answer = res.get('answer', 'No answer found')
confidence = res.get('score', 0)
# Keep track of the best answer
if confidence > best_score:
best_score = confidence
best_answer = answer.strip()
except Exception as e:
print(f"Error processing chunk: {str(e)}")
# Return the best answer found or a default message
return best_answer if best_answer and best_score > 0.3 else "Sorry, I couldn't find a reliable answer."
context_file_path = 'information.txt'
full_context = load_context(context_file_path) context_chunks = split_text_into_chunks(full_context)
while True: question = input("\nEnter your question (or type 'exit' to quit): ") if question.lower() == "exit": break answer = get_best_answer(question, context_chunks) print(f"Answer: {answer}")