# qna_webapp.py
# pip install transformers torch nltk streamlit

import streamlit as st
import nltk
from transformers import pipeline

nltk.download("punkt")
# Download required tokenizers
nltk.download("punkt_tab")
from nltk.tokenize import sent_tokenize

# Load QA model (fast + stable)
qa_pipeline = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")

def generate_qna(paragraph, num_questions=5):
    sentences = sent_tokenize(paragraph)
    qna_list = []

    for sent in sentences[:num_questions]:
        words = sent.split()

        # Simple heuristic question generator
        if len(words) > 3:
            question = "What is " + " ".join(words[:4]) + "?"
        else:
            question = "What does this mean?"

        try:
            answer = qa_pipeline(question=question, context=paragraph)["answer"]
            qna_list.append({"question": question, "answer": answer})
        except:
            continue

    return qna_list


# Streamlit UI
st.title("📘 Paragraph QnA Generator (Stable Version)")
paragraph = st.text_area("Enter your paragraph here:")
num_q = st.slider("How many questions?", 1, 10, 5)

if st.button("Generate Q&A"):
    if paragraph.strip():
        qna = generate_qna(paragraph, num_questions=num_q)
        st.subheader("Generated Questions & Answers:")
        for i, qa in enumerate(qna, 1):
            st.write(f"**Q{i}:** {qa['question']}")
            st.write(f"**A{i}:** {qa['answer']}\n")
    else:
        st.warning("Please enter a paragraph.")
