File size: 7,217 Bytes
f615b93 df2b51a f615b93 df2b51a 2f96c18 df2b51a f615b93 3d0f58b f615b93 df2b51a f615b93 df2b51a f615b93 df2b51a 2f96c18 df2b51a f615b93 2f96c18 f615b93 df2b51a f615b93 df2b51a f615b93 921780e f615b93 921780e f615b93 df2b51a 921780e df2b51a 2f96c18 f615b93 921780e df2b51a 2f96c18 f615b93 2f96c18 df2b51a 2f96c18 df2b51a f615b93 921780e df2b51a 921780e df2b51a f615b93 df2b51a f615b93 2f96c18 df2b51a 921780e f615b93 921780e f615b93 921780e f615b93 2f96c18 f615b93 df2b51a f615b93 df2b51a |
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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
import os
import faiss
import gradio as gr
import numpy as np
import requests
from pypdf import PdfReader
from sentence_transformers import SentenceTransformer
################################################################################
# 1. PDF Parsing and Chunking
################################################################################
def extract_pdf_text(pdf_file) -> str:
reader = PdfReader(pdf_file)
all_text = []
for page in reader.pages:
text = page.extract_text() or ""
all_text.append(text.strip())
return "\n".join(all_text)
def chunk_text(text, chunk_size=300, overlap=50):
words = text.split()
chunks = []
start = 0
while start < len(words):
end = start + chunk_size
chunk = words[start:end]
chunks.append(" ".join(chunk))
start += (chunk_size - overlap)
return chunks
################################################################################
# 2. Embedding Model
################################################################################
embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
################################################################################
# 3. Build FAISS Index
################################################################################
def build_faiss_index(chunks):
chunk_embeddings = embedding_model.encode(chunks, show_progress_bar=False)
chunk_embeddings = np.array(chunk_embeddings, dtype='float32')
dimension = chunk_embeddings.shape[1]
index = faiss.IndexFlatL2(dimension)
index.add(chunk_embeddings)
return index, chunk_embeddings
################################################################################
# 4. Retrieval Function
################################################################################
def retrieve_chunks(query, index, chunks, top_k=3):
query_embedding = embedding_model.encode([query], show_progress_bar=False)
query_embedding = np.array(query_embedding, dtype='float32')
distances, indices = index.search(query_embedding, top_k)
return [chunks[i] for i in indices[0]]
################################################################################
# 5. Gemini LLM Integration
################################################################################
def gemini_generate(prompt):
gemini_api_key = os.environ.get("GEMINI_API_KEY", "")
if not gemini_api_key:
return "Error: No GEMINI_API_KEY found in environment variables."
url = (
"https://generativelanguage.googleapis.com/"
"v1beta/models/gemini-1.5-flash:generateContent"
f"?key={gemini_api_key}"
)
data = {
"contents": [
{
"parts": [
{"text": prompt}
]
}
]
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, headers=headers, json=data)
if response.status_code != 200:
return f"Error {response.status_code}: {response.text}"
r_data = response.json()
try:
return r_data["candidates"][0]["content"]["parts"][0]["text"]
except Exception:
return f"Parsing error or unexpected response structure: {r_data}"
################################################################################
# 6. RAG QA Function
################################################################################
def answer_question_with_RAG(user_question, index, chunks):
relevant_chunks = retrieve_chunks(user_question, index, chunks, top_k=3)
context = "\n\n".join(relevant_chunks)
prompt = f"""
You are an AI assistant that knows the details from the uploaded research paper.
Answer the user's question accurately using the context below.
If something is not in the context, say you don't know.
Context:
{context}
User's question: {user_question}
Answer:
"""
return gemini_generate(prompt)
################################################################################
# 7. Gradio Interface
################################################################################
def process_pdf(pdf_file):
if pdf_file is None:
return None, "Please upload a PDF file."
text = extract_pdf_text(pdf_file.name)
if not text:
return None, "No text found in PDF."
chunks = chunk_text(text, chunk_size=300, overlap=50)
if not chunks:
return None, "No valid text to chunk."
faiss_index, _ = build_faiss_index(chunks)
return (faiss_index, chunks), "PDF processed successfully!"
def chat_with_paper(query, state):
if not state:
return "Please upload and process a PDF first."
faiss_index, doc_chunks = state
if not query or not query.strip():
return "Please enter a valid question."
return answer_question_with_RAG(query, faiss_index, doc_chunks)
demo_theme = gr.themes.Soft(primary_hue="slate")
css_code = """
body {
background-color: #E6F7FF !important; /* Lightest blue */
margin: 0;
padding: 0;
}
.block > .inside {
margin: auto !important;
max-width: 900px !important;
border: 4px solid black !important;
border-radius: 10px !important;
background-color: #FFFFFF !important;
padding: 20px !important;
}
#icon-container {
text-align: center !important;
margin-top: 1rem !important;
margin-bottom: 1rem !important;
}
#app-title {
text-align: center !important;
font-size: 3rem !important;
font-weight: 900 !important;
margin-bottom: 0.5rem !important;
margin-top: 0.5rem !important;
}
#app-welcome {
text-align: center !important;
font-size: 1.5rem !important;
color: #444 !important;
margin-bottom: 25px !important;
font-weight: 700 !important;
}
button {
background-color: #3CB371 !important;
color: #ffffff !important;
border: none !important;
font-weight: 600 !important;
cursor: pointer;
}
button:hover {
background-color: #2E8B57 !important;
}
textarea, input[type="text"] {
text-align: center !important;
}
"""
with gr.Blocks(theme=demo_theme, css=css_code) as demo:
gr.Markdown("""
<div id="icon-container">
<img src="https://i.ibb.co/3Wp3yBZ/ai-icon.png" alt="AI icon" style="width:100px;">
</div>
""")
gr.Markdown("<div id='app-title'>AI-Powered Personal Research Assistant</div>")
gr.Markdown("<div id='app-welcome'>Welcome! How may I help you?</div>")
state = gr.State()
with gr.Row():
pdf_input = gr.File(label="Upload your research paper (PDF)", file_types=[".pdf"])
process_button = gr.Button("Process PDF")
status_output = gr.Textbox(label="Status", interactive=False)
process_button.click(
fn=process_pdf,
inputs=pdf_input,
outputs=[state, status_output]
)
with gr.Row():
user_query = gr.Textbox(label="Ask a question about your research paper:")
ask_button = gr.Button("Get Answer")
answer_output = gr.Textbox(label="Answer")
ask_button.click(
fn=chat_with_paper,
inputs=[user_query, state],
outputs=answer_output
)
demo.launch()
|