File size: 8,732 Bytes
dd765b2 c53d978 00eb76e 0fd97ae 4f2bd66 dd765b2 c53d978 00eb76e dd765b2 07f9cb7 00eb76e dd765b2 00eb76e 4f2bd66 00eb76e 4f2bd66 dd765b2 4f2bd66 00eb76e dd765b2 4f2bd66 dd765b2 00eb76e 4f2bd66 dd765b2 4f2bd66 dd765b2 0fd97ae 4f2bd66 00eb76e 0fd97ae 00eb76e 0fd97ae 00eb76e 0fd97ae 00eb76e 0fd97ae dd765b2 4f2bd66 dd765b2 0fd97ae dd765b2 0fd97ae 00eb76e 0fd97ae dd765b2 00eb76e dd765b2 00eb76e dd765b2 00eb76e dd765b2 00eb76e dd765b2 00eb76e dd765b2 00eb76e dd765b2 00eb76e dd765b2 00eb76e dd765b2 00eb76e dd765b2 00eb76e dd765b2 00eb76e dd765b2 00eb76e dd765b2 00eb76e e4efe09 0fd97ae dd765b2 00eb76e 0fd97ae 00eb76e 4f2bd66 0fd97ae 4f2bd66 0fd97ae c53d978 dd765b2 0fd97ae 00eb76e 0fd97ae dd765b2 00eb76e 0fd97ae c53d978 dd765b2 4f2bd66 0fd97ae 00eb76e dd765b2 00eb76e dd765b2 00eb76e e4efe09 dd765b2 0fd97ae dd765b2 4f2bd66 0fd97ae dd765b2 0fd97ae dd765b2 00eb76e 0fd97ae 00eb76e dd765b2 0fd97ae dd765b2 0fd97ae 00eb76e e4efe09 00eb76e 4f2bd66 0fd97ae dd765b2 |
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 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
import os
os.environ['HF_HUB_ENABLE_HF_TRANSFER'] = '0'
import gradio as gr
from sentence_transformers import SentenceTransformer
import numpy as np
from pypdf import PdfReader
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import re
# Global variables
chunks = []
embeddings = []
model = None
tokenizer = None
embed_model = None
text_cache = ""
def initialize_models():
"""Initialize models on startup with optimizations"""
global model, tokenizer, embed_model
print("Loading models...")
# Use smaller, faster embedding model
embed_model = SentenceTransformer(
'sentence-transformers/paraphrase-MiniLM-L3-v2', # Faster, smaller model
device='cpu'
)
# Use smaller, faster language model
model_name = "microsoft/phi-1_5" # Much faster than TinyLlama, better quality
# Alternative: "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
tokenizer = AutoTokenizer.from_pretrained(
model_name,
trust_remote_code=True
)
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float32,
low_cpu_mem_usage=True,
trust_remote_code=True
)
# Set padding token
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
print("Models loaded successfully!")
def smart_chunk_text(text, chunk_size=500, overlap=100):
"""Smarter chunking that respects sentence boundaries"""
# Split into sentences
sentences = re.split(r'[.!?]+', text)
chunks = []
current_chunk = ""
for sentence in sentences:
sentence = sentence.strip()
if not sentence:
continue
# If adding this sentence exceeds chunk size, save current chunk
if len(current_chunk) + len(sentence) > chunk_size and current_chunk:
chunks.append(current_chunk)
# Start new chunk with overlap
words = current_chunk.split()
current_chunk = " ".join(words[-20:]) + " " + sentence
else:
current_chunk += " " + sentence
# Add the last chunk
if current_chunk:
chunks.append(current_chunk.strip())
return chunks
def process_pdf(pdf_file):
"""Process PDF and create embeddings - OPTIMIZED"""
global chunks, embeddings, embed_model, text_cache
if pdf_file is None:
return "β Please upload a PDF file!", None
try:
# Read PDF
pdf_reader = PdfReader(pdf_file.name)
text = ""
for page in pdf_reader.pages:
text += page.extract_text() + "\n"
if not text.strip():
return "β Could not extract text from PDF!", None
text_cache = text # Cache for faster reprocessing
# Smart chunking (smaller chunks = faster embedding)
chunks = smart_chunk_text(text, chunk_size=500, overlap=100)
# Batch encode for speed
print(f"Creating embeddings for {len(chunks)} chunks...")
embeddings = embed_model.encode(
chunks,
batch_size=32, # Process multiple chunks at once
show_progress_bar=False,
convert_to_numpy=True
)
return f"β
PDF processed! Created {len(chunks)} chunks. You can now ask questions!", None
except Exception as e:
print(f"Error processing PDF: {str(e)}")
return f"β Error: {str(e)}", None
def find_relevant_chunks(query, top_k=2): # Reduced from 3 to 2 for speed
"""Find most relevant chunks - OPTIMIZED"""
global chunks, embeddings, embed_model
if not chunks or len(embeddings) == 0:
return []
# Encode query
query_embedding = embed_model.encode(
[query],
convert_to_numpy=True,
show_progress_bar=False
)[0]
# Fast cosine similarity using numpy
embeddings_norm = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)
query_norm = query_embedding / np.linalg.norm(query_embedding)
similarities = np.dot(embeddings_norm, query_norm)
# Get top k indices
top_indices = np.argsort(similarities)[-top_k:][::-1]
return [chunks[i] for i in top_indices]
def generate_response(question, context):
"""Generate response - OPTIMIZED"""
global model, tokenizer
# Shorter, more efficient prompt
prompt = f"""Context: {context[:800]}
Question: {question}
Answer:"""
inputs = tokenizer(
prompt,
return_tensors="pt",
truncation=True,
max_length=1024 # Reduced from 2048
)
# Faster generation settings
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=150, # Reduced from 300
temperature=0.7,
top_p=0.9,
do_sample=True,
pad_token_id=tokenizer.eos_token_id,
num_beams=1, # Greedy search for speed
early_stopping=True
)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Extract answer
if "Answer:" in response:
response = response.split("Answer:")[-1].strip()
# Clean up response
response = response.split("\n")[0].strip() # Take first line
return response
def chat(message, history):
"""Handle chat - OPTIMIZED"""
global chunks
if not chunks:
return history + [[message, "β οΈ Please upload and process a PDF first!"]]
if not message.strip():
return history
try:
# Find relevant context (reduced chunks)
relevant_chunks = find_relevant_chunks(message, top_k=2)
context = " ".join(relevant_chunks)
# Generate response
response = generate_response(message, context)
# Ensure response is not empty
if not response or len(response) < 10:
response = "I found relevant information but couldn't generate a clear answer. Please try rephrasing your question."
return history + [[message, response]]
except Exception as e:
print(f"Error in chat: {str(e)}")
return history + [[message, f"β Error: {str(e)}"]]
def clear_all():
"""Clear everything"""
global chunks, embeddings, text_cache
chunks = []
embeddings = []
text_cache = ""
return None, "Ready to process a new PDF"
# Create UI with better styling
with gr.Blocks(title="Chat with PDF - Fast", theme=gr.themes.Soft()) as demo:
gr.Markdown("# β‘ Chat with PDF - Optimized Fast Version")
gr.Markdown("*Using lightweight models for faster responses*")
with gr.Row():
with gr.Column(scale=1):
pdf_input = gr.File(
label="π Upload PDF",
file_types=[".pdf"]
)
process_btn = gr.Button(
"π Process PDF",
variant="primary",
size="lg"
)
status = gr.Textbox(
label="Status",
lines=2,
interactive=False
)
gr.Markdown("### Tips:")
gr.Markdown("""
- Processing is much faster now!
- Ask specific questions
- Keep questions concise
""")
clear_all_btn = gr.Button("ποΈ Clear All", variant="stop")
with gr.Column(scale=2):
chatbot = gr.Chatbot(
label="π¬ Chat",
height=450,
bubble_full_width=False
)
msg = gr.Textbox(
label="Question",
placeholder="Ask a question about the PDF...",
lines=2
)
with gr.Row():
send_btn = gr.Button("π€ Send", variant="primary")
clear_btn = gr.Button("Clear Chat")
# Events
process_btn.click(
process_pdf,
inputs=[pdf_input],
outputs=[status, chatbot]
)
msg.submit(
chat,
inputs=[msg, chatbot],
outputs=[chatbot]
).then(
lambda: "",
None,
[msg]
)
send_btn.click(
chat,
inputs=[msg, chatbot],
outputs=[chatbot]
).then(
lambda: "",
None,
[msg]
)
clear_btn.click(lambda: None, None, [chatbot])
clear_all_btn.click(clear_all, None, [chatbot, status])
# Initialize on startup
initialize_models()
if __name__ == "__main__":
demo.queue() # Enable queuing for better performance
demo.launch(share=False) |