File size: 2,458 Bytes
7df44cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06c97f0
7df44cb
 
 
 
 
 
 
 
 
48467d2
7df44cb
 
 
 
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
import os
import streamlit as st
from langchain import PromptTemplate
from langchain.chains.question_answering import load_qa_chain
from langchain.document_loaders import PyPDFLoader
from langchain_google_genai import ChatGoogleGenerativeAI
import google.generativeai as genai

# Load environment variables from .env file
from dotenv import load_dotenv
load_dotenv()

# Fungsi untuk inisialisasi
def initialize(file_path, question):
    genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
    model = genai.GenerativeModel('gemini-pro')
    model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
    prompt_template = """Answer the question as precise as possible using the provided context. If the answer is
                          not contained in the context, say "answer not available in context" \n\n
                          Context: \n {context}?\n
                          Question: \n {question} \n
                          Answer:
                        """
    prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
    if os.path.exists(file_path):
        pdf_loader = PyPDFLoader(file_path)
        pages = pdf_loader.load_and_split()
        context = "\n".join(str(page.page_content) for page in pages[:30])
        stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
        stuff_answer = stuff_chain({"input_documents": pages, "question": question, "context": context}, return_only_outputs=True)
        return stuff_answer['output_text']
    else:
        return None

# Membuat antarmuka pengguna dengan Streamlit
st.title('RAG Q&A Bot with Gemini - Pro')

# Layout untuk input dan tombol di sebelah kiri
st.sidebar.title("Input")
file_upload = st.sidebar.file_uploader("Upload PDF", type=["pdf"])
question_input = st.sidebar.text_input("Tanyakan Dokumen", "Apa isi dokumennya?")
ask_button = st.sidebar.button("Ask Question")

# Jika tombol "Ask Question" ditekan
if ask_button:
    if file_upload is not None:
        with open("uploaded_pdf.pdf", "wb") as f:
            f.write(file_upload.getbuffer())
        chatbot_answer = initialize("uploaded_pdf.pdf", question_input)
        if chatbot_answer:
            st.text_area("Answer - GeminiPro", value=chatbot_answer, height=500)
        else:
            st.error("Terjadi kesalahan saat memproses dokumen. Pastikan file PDF valid.")
    else:
        st.error("Mohon unggah file PDF untuk melanjutkan.")