File size: 2,472 Bytes
f020c4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import urllib
import warnings
from pathlib import Path
import os
import gradio as gr
from langchain import PromptTemplate
from langchain.chains.question_answering import load_qa_chain
from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_google_genai import ChatGoogleGenerativeAI
import google.generativeai as genai
import pandas as pd

from dotenv import load_dotenv
load_dotenv()  # take environment variables from .env.


# Fungsi untuk inisialisasi
def initialize(link, question):

    # Konfigurasikan kunci API
    os.getenv("GOOGLE_API_KEY")
    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"])

    # Download PDF dari URL yang diberikan
    pdf_file = "downloaded_paper.pdf"
    urllib.request.urlretrieve(link, pdf_file)

    # Load the PDF
    pdf_loader = PyPDFLoader(pdf_file)
    pages = pdf_loader.load_and_split()

    # Process the file content and use it as the context
    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']

# Membuat antarmuka pengguna
with gr.Blocks() as demo:
    gr.Markdown('# RAG Q&A Bot with Gemini - Pro')
    gr.Markdown('### Hands-On LLM')
    
    link_input = gr.Textbox(label="Input Link Paper atau PDF", placeholder="Paste PDF disini")
    question_input = gr.Textbox(label="Tanyakan Dokumen", placeholder="Tanyakan Dokumen:")
    chatbot = gr.Textbox(label="Answer - GeminiPro")

    ask_button = gr.Button("Ask Question")
    ask_button.click(initialize, inputs=[link_input, question_input], outputs=[chatbot])

# Meluncurkan antarmuka pengguna
demo.queue().launch(debug=True)