File size: 2,091 Bytes
fb0136e
24aba9a
dc63593
24aba9a
eccea84
 
13017f6
eccea84
5d4b634
dc63593
5d4b634
dc63593
 
c9dbb4b
dc63593
13017f6
 
eccea84
13017f6
eccea84
13017f6
 
 
 
 
eeeab4a
13017f6
 
 
 
 
 
 
 
eccea84
 
13017f6
eccea84
5d4b634
13017f6
eccea84
13017f6
 
 
 
 
 
 
526135f
13017f6
 
526135f
13017f6
 
526135f
13017f6
 
 
eccea84
526135f
13017f6
526135f
eccea84
5d4b634
eccea84
5d4b634
13017f6
c727022
eccea84
 
c727022
5d4b634
 
dc63593
 
c727022
5d4b634
eeeab4a
cb883ca
526135f
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import os
import gradio as gr
from transformers import pipeline
from langchain_text_splitters import RecursiveCharacterTextSplitter

# =========================
# LOAD DOCUMENT
# =========================
def load_text(path="ai-geoth.txt"):
    if not os.path.exists(path):
        raise FileNotFoundError("ai-geoth.txt not found")

    with open(path, "r", encoding="utf-8") as f:
        return f.read()

text = load_text()

# =========================
# SPLIT DOCUMENT
# =========================
splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,
    chunk_overlap=100
)
chunks = splitter.split_text(text)

# =========================
# EXTRACTIVE QA (LIGHTWEIGHT)
# =========================
qa = pipeline(
    "question-answering",
    model="distilbert-base-uncased-distilled-squad",
    device=-1
)

# =========================
# SMART LONG ANSWER
# =========================
def answer_question(question):
    answers = []

    for chunk in chunks:
        try:
            result = qa(question=question, context=chunk)
            if result["score"] > 0.25 and result["answer"].strip():
                answers.append(result["answer"].strip())
        except Exception:
            continue

    if not answers:
        return "No detailed answer found in the document."

    # 🔹 Combine answers into detailed response
    unique_answers = list(dict.fromkeys(answers))  # remove duplicates

    detailed_answer = (
        "Based on the document, the following points are relevant:\n\n"
        + "\n- ".join(unique_answers)
    )

    return detailed_answer

# =========================
# GRADIO UI
# =========================
with gr.Blocks() as demo:
    gr.Markdown("## 📄 Smart TXT Chatbot (Detailed & Stable)")

    chat = gr.Chatbot(height=500)
    box = gr.Textbox(placeholder="Ask a detailed question about the document...")

    def chat_fn(msg, history):
        reply = answer_question(msg)
        history.append((msg, reply))
        return "", history

    box.submit(chat_fn, [box, chat], [box, chat])

if __name__ == "__main__":
    demo.launch()