Spaces:
Sleeping

File size: 2,151 Bytes
396482d
 
 
 
 
 
 
9d86639
39dfb8a
 
 
396482d
 
 
 
63abafe
 
 
396482d
 
 
f01aeef
396482d
 
 
9d86639
 
f01aeef
9d86639
8c7c907
396482d
8c7c907
396482d
9d86639
 
8c7c907
 
396482d
8c7c907
 
 
 
 
39dfb8a
396482d
 
 
9d86639
e67500e
63abafe
 
 
 
e67500e
9d86639
396482d
8c7c907
396482d
e67500e
9d86639
39dfb8a
 
 
 
8c7c907
e67500e
39dfb8a
 
396482d
 
e67500e
9d86639
e67500e
8c7c907
e67500e
9d86639
e67500e
 
 
9d86639
8c7c907
39dfb8a
8c7c907
396482d
39dfb8a
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
82
83
84
85
import gradio as gr
from pypdf import PdfReader
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np

embed_model = SentenceTransformer('all-MiniLM-L6-v2')

index = None
chunks = None

def load_pdf(file):
    reader = PdfReader(file)
    text = ""
    for page in reader.pages:
        page_text = page.extract_text()
        if page_text:
            text += page_text
    return text

def split_text(text, chunk_size=500):
    return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]

def create_vector_store(chunks):
    embeddings = embed_model.encode(chunks)
    embeddings = np.array(embeddings).astype("float32")

    index = faiss.IndexFlatL2(embeddings.shape[1])
    index.add(embeddings)
    return index

def retrieve(query, index, chunks):
    query_vec = embed_model.encode([query])
    query_vec = np.array(query_vec).astype("float32")

    D, I = index.search(query_vec, 1)
    return chunks[I[0][0]]

def answer_question(query):
    global index, chunks
    if index is None:
        return "❌ Upload and process PDF first."
    result = retrieve(query, index, chunks)
    return result[:500]

def process_pdf(file):
    global index, chunks
    if file is None:
        return "❌ Upload PDF"

    text = load_pdf(file)

    if len(text) == 0:
        return "❌ PDF has no readable text"

    chunks = split_text(text)
    index = create_vector_store(chunks)

    return "βœ… PDF processed!"

def respond(message, history):
    if history is None:
        history = []

    reply = answer_question(message)
    history.append((message, reply))  # βœ… correct

    return "", history

with gr.Blocks() as app:
    gr.Markdown("# πŸ“š Course Chatbot")

    file_input = gr.File()
    btn = gr.Button("Process PDF")
    status = gr.Textbox()

    chatbot = gr.Chatbot()  # βœ… correct for your version
    msg = gr.Textbox()
    clear = gr.Button("Clear")

    btn.click(process_pdf, inputs=file_input, outputs=status)
    msg.submit(respond, inputs=[msg, chatbot], outputs=[msg, chatbot])
    clear.click(lambda: [], None, chatbot)

app.launch(server_name="0.0.0.0", server_port=7860)