File size: 5,514 Bytes
f085c10
ddf266a
34ef142
f085c10
 
 
 
 
 
a80fb91
91bc905
ddf266a
f085c10
 
 
6692e0b
f085c10
 
 
 
 
6692e0b
f085c10
 
a80fb91
 
 
 
f085c10
 
 
6692e0b
f085c10
 
 
 
6692e0b
 
 
 
a80fb91
 
 
f085c10
a80fb91
6692e0b
ddf266a
f085c10
6692e0b
ddf266a
 
6692e0b
f085c10
6692e0b
f085c10
 
 
 
 
 
6692e0b
 
 
 
 
 
 
 
 
f085c10
6692e0b
ddf266a
 
 
6692e0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a80fb91
ddf266a
 
f085c10
6692e0b
 
 
f085c10
ddf266a
f085c10
 
 
 
 
 
 
ddf266a
 
f085c10
 
 
 
 
ddf266a
f085c10
 
 
 
 
 
 
 
 
6692e0b
ddf266a
f085c10
ddf266a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f085c10
6692e0b
f085c10
 
 
 
 
 
 
 
 
 
 
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import io
import streamlit as st
from PyPDF2 import PdfReader
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
from langchain.vectorstores import FAISS
from langchain.chains.question_answering import load_qa_chain
from langchain.llms import HuggingFacePipeline
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
from peft import PeftModel, PeftConfig

# Global variables
knowledge_base = None
qa_chain = None

# PDF ํŒŒ์ผ ๋กœ๋“œ ๋ฐ ํ…์ŠคํŠธ ์ถ”์ถœ
def load_pdf(pdf_file):
    pdf_reader = PdfReader(pdf_file)
    text = "".join(page.extract_text() for page in pdf_reader.pages)
    return text

# ํ…์ŠคํŠธ๋ฅผ ์ฒญํฌ๋กœ ๋ถ„ํ• 
def split_text(text):
    text_splitter = CharacterTextSplitter(
        separator="\n", 
        chunk_size=1000, 
        chunk_overlap=200, 
        length_function=len
    )
    return text_splitter.split_text(text)

# FAISS ๋ฒกํ„ฐ ์ €์žฅ์†Œ ์ƒ์„ฑ
def create_knowledge_base(chunks):
    embeddings = HuggingFaceEmbeddings()
    return FAISS.from_texts(chunks, embeddings)

# Hugging Face ๋ชจ๋ธ ๋กœ๋“œ
def load_model():
    model_name = "halyn/gemma2-2b-it-finetuned-paperqa"
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    config = PeftConfig.from_pretrained(model_name)
    model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path)
    model = PeftModel.from_pretrained(model, model_name)

    return pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=150, temperature=0.1)
# QA ์ฒด์ธ ์„ค์ •
def setup_qa_chain():
    global qa_chain
    pipe = load_model()
    llm = HuggingFacePipeline(pipeline=pipe)
    qa_chain = load_qa_chain(llm, chain_type="stuff")
    

# ๋ฉ”์ธ ํŽ˜์ด์ง€ UI
def main_page():
    st.title("Welcome to GemmaPaperQA")
    st.subheader("Upload Your Paper")

    paper = st.file_uploader("Upload Here!", type="pdf", label_visibility="hidden")
    if paper:
        st.write(f"Upload complete! File name: {paper.name}")
        # ํŒŒ์ผ ํฌ๊ธฐ ํ™•์ธ
        file_size = paper.size  # ํŒŒ์ผ ํฌ๊ธฐ๋ฅผ ํŒŒ์ผ ํฌ์ธํ„ฐ ์ด๋™ ์—†์ด ํ™•์ธ
        if file_size > 10 * 1024 * 1024:  # 10MB ์ œํ•œ
            st.error("File is too large! Please upload a file smaller than 10MB.")
            return

        # ์ค‘๊ฐ„ ํ™•์ธ ์ ˆ์ฐจ - PDF ๋‚ด์šฉ ๋ฏธ๋ฆฌ๋ณด๊ธฐ
        with st.spinner('Processing PDF...'):
            try:
                paper.seek(0)  # ํŒŒ์ผ ์ฝ๊ธฐ ํฌ์ธํ„ฐ๋ฅผ ์ฒ˜์Œ์œผ๋กœ ๋˜๋Œ๋ฆผ
                contents = paper.read()
                pdf_file = io.BytesIO(contents)
                text = load_pdf(pdf_file)

                # ํ…์ŠคํŠธ๊ฐ€ ์ถ”์ถœ๋˜์ง€ ์•Š์„ ๊ฒฝ์šฐ ์—๋Ÿฌ ์ฒ˜๋ฆฌ
                if len(text.strip()) == 0:
                    st.error("The PDF appears to have no extractable text. Please check the file and try again.")
                    return

                st.text_area("Preview of extracted text", text[:1000], height=200)
                st.write(f"Total characters extracted: {len(text)}")

                if st.button("Proceed with this file"):
                    chunks = split_text(text)
                    global knowledge_base
                    knowledge_base = create_knowledge_base(chunks)
                    
                    if knowledge_base is None:
                        st.error("Failed to create knowledge base.")
                        return
                    
                    st.session_state.paper_name = paper.name[:-4]
                    st.session_state.page = "chat"
                    setup_qa_chain()
                    st.success("PDF successfully processed! You can now ask questions.")

            except Exception as e:
                st.error(f"Failed to process the PDF: {str(e)}")



# ์ฑ„ํŒ… ํŽ˜์ด์ง€ UI
def chat_page():
    st.title(f"Ask anything about {st.session_state.paper_name}")

    if "messages" not in st.session_state:
        st.session_state.messages = []

    for message in st.session_state.messages:
        with st.chat_message(message["role"]):
            st.markdown(message["content"])

    if prompt := st.chat_input("Chat here!"):
        st.session_state.messages.append({"role": "user", "content": prompt})

        with st.chat_message("user"):
            st.markdown(prompt)

        response = get_response_from_model(prompt)

        with st.chat_message("assistant"):
            st.markdown(response)

        st.session_state.messages.append({"role": "assistant", "content": response})

    if st.button("Go back to main page"):
        st.session_state.page = "main"

# ๋ชจ๋ธ ์‘๋‹ต ์ฒ˜๋ฆฌ
def get_response_from_model(prompt):
    try:
        global knowledge_base, qa_chain
        if not knowledge_base:
            return "No PDF has been uploaded yet."
        if not qa_chain:
            return "QA chain is not initialized."

        docs = knowledge_base.similarity_search(prompt)
        response = qa_chain.run(input_documents=docs, question=prompt)

        if "Helpful Answer:" in response:
            response = response.split("Helpful Answer:")[1].strip()

        return response
    except Exception as e:
        return f"Error: {str(e)}"

# ํŽ˜์ด์ง€ ์„ค์ •
if "page" not in st.session_state:
    st.session_state.page = "main"

if "paper_name" not in st.session_state:
    st.session_state.paper_name = ""

# ํŽ˜์ด์ง€ ๋ Œ๋”๋ง
if st.session_state.page == "main":
    main_page()
elif st.session_state.page == "chat":
    chat_page()