File size: 2,181 Bytes
ff77f23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import streamlit as st
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_huggingface import HuggingFaceEmbeddings
from langchain.vectorstores import Chroma
from langchain.prompts import ChatPromptTemplate
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.runnables import RunnablePassthrough
import tempfile


# --- Streamlit App Title ---
st.title("📄 Medical Education Visual Aid - PDF RAG Chatbot")

# --- File Uploader ---
uploaded_file = st.file_uploader("Upload a PDF document", type=["pdf"])

# Check if a file is uploaded
if uploaded_file:
    # Save uploaded file to a temporary path
    with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
        tmp_file.write(uploaded_file.read())
        temp_pdf_path = tmp_file.name

    # Load and process the PDF
    loader = PyPDFLoader(temp_pdf_path)
    pages = loader.load()

    splitter = RecursiveCharacterTextSplitter(
        chunk_size=100,
        chunk_overlap=20
    )
    split = splitter.split_documents(pages)

    # Create embeddings and vector store
    hfembedding = HuggingFaceEmbeddings()
    db = Chroma.from_documents(documents=split, embedding=hfembedding)

    # Prompt template
    template_string = """
    You are a smart medical assistant. Use the provided context to answer the question.
    context: {context}
    question: {question}
    """
    prompt_template = ChatPromptTemplate.from_template(template_string)

    # LLM initialization (replace with your key or env variable)
    GOOGLE_API_KEY = "AIzaSyDA1zZ006f4krgUDjhdju_RcwZNwNPOJwI"
    llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash-latest", api_key=GOOGLE_API_KEY)

        # RAG chain
    retriever = db.as_retriever()
    chain = (
            {"context": retriever, "question": RunnablePassthrough()}
            | prompt_template
            | llm
        )

        # User query
    query = st.text_input("💬 Ask a question about the uploaded PDF:")
    if query:
          response = chain.invoke(query)
          st.subheader("Answer")
          st.write(response.content)