Spaces:
Sleeping
Sleeping
File size: 21,203 Bytes
11bfceb e4e5c5c 11bfceb 8eb71cf 11bfceb bbe6774 11bfceb 8eb71cf 11bfceb fc8e85d 8208e45 fc8e85d 66455d8 fc8e85d f8f85bd 66455d8 fc8e85d f8f85bd 11bfceb f8f85bd 11bfceb b954e3d f8f85bd 66455d8 fc8e85d f8f85bd fc8e85d 66455d8 f8f85bd fc8e85d b954e3d fc8e85d 66455d8 fc8e85d 66455d8 fc8e85d 66455d8 fc8e85d 66455d8 fc8e85d 87a3c7e fc8e85d 66455d8 fc8e85d 66455d8 8208e45 66455d8 fc8e85d b954e3d fc8e85d 66455d8 fc8e85d 11bfceb fc8e85d e4e5c5c 66455d8 fc8e85d 11bfceb fc8e85d 11bfceb fc8e85d 11bfceb 87a3c7e f8f85bd 87a3c7e f8f85bd 11bfceb 87a3c7e b954e3d 87a3c7e b954e3d 87a3c7e f8f85bd 87a3c7e 0a4cbab 87a3c7e b954e3d 4503fbd 87a3c7e 4503fbd 5d2977e eae52d7 5d2977e 87a3c7e 5d2977e c1a952d eae52d7 5d2977e 11bfceb 66455d8 fc8e85d 11bfceb b954e3d 66455d8 3e7de78 f8f85bd 66455d8 f8f85bd 3e7de78 66455d8 f8f85bd b954e3d 66455d8 3e7de78 1582a08 f8f85bd 66455d8 b954e3d f8f85bd fc8e85d 66455d8 5d2977e eae52d7 66455d8 4503fbd 66455d8 4503fbd 87a3c7e 4503fbd 87a3c7e 11bfceb fc8e85d 11bfceb fc8e85d 8eb71cf 11bfceb fc8e85d 11bfceb |
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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 |
# app.py
import os
import gradio as gr
from langchain.vectorstores import FAISS
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.document_loaders import TextLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain.chains import RetrievalQA
from langchain.llms import HuggingFacePipeline
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline, AutoModelForCausalLM
from langchain.document_loaders import PyPDFLoader, PyMuPDFLoader
import pypdf
from langchain.prompts import PromptTemplate
from huggingface_hub import upload_folder
from huggingface_hub import HfApi, upload_file
from huggingface_hub import hf_hub_download
from huggingface_hub import (
file_exists,
upload_file,
repo_exists,
create_repo,
hf_hub_download
)
import shutil
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
from langchain_huggingface import HuggingFacePipeline
# Optional: Set HF Token if needed-allWrite
os.environ['HUGGINGFACEHUB_API_TOKEN'] = os.getenv("HF_TOKEN")
api = HfApi(token=os.getenv("HF_TOKEN")) # Replace with your token
# Initialize embedding model
embedding_model = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
# Store the vraiables globally (across UI events)
qa_chain = None
qa_chain1 = None
llm=None
llm1=None
repo_id=os.getenv("reposit_id")
#=============================================google/flan-t5-small
# Load HF model (lightweight for CPU)
model_name = "google/flan-t5-small"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
# Wrap in pipeline
#pipe1 = pipeline("text2text-generation", model=model, tokenizer=tokenizer, max_length=512)
pipe1 = pipeline("text2text-generation", model=model, tokenizer=tokenizer, max_length=512)
if llm1 is None:
llm1 = HuggingFacePipeline(pipeline=pipe1)
#=============================================TinyLlama/TinyLlama-1.1B-Chat-v1.0
# Create optimized pipeline for TinyLlama
pipe = pipeline(
"text-generation",
model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
tokenizer=AutoTokenizer.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0"),
device_map="auto" if torch.cuda.is_available() else None,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
max_new_tokens=512,
temperature=0.7,
top_p=0.95,
do_sample=True,
repetition_penalty=1.15,
pad_token_id=tokenizer.eos_token_id if 'tokenizer' in locals() else 128001,
trust_remote_code=True
)
# Build LangChain LLM wrapper
if llm is None:
llm = HuggingFacePipeline(pipeline=pipe)
#=============================================
def format_as_bullets(text):
"""Convert answer to bullet points"""
lines = text.strip().split('\n')
bullet_lines = [f"β’ {line.strip()}" for line in lines if line.strip()]
return '\n'.join(bullet_lines) if bullet_lines else text
#=============================================
def create_faiss_index(repo_id, file, embedding_model="sentence-transformers/all-MiniLM-L6-v2"):
"""Create FAISS index from PDF and upload to HF dataset repo"""
message = "Index creation started"
try:
# Step 1: Create proper embeddings object (CRITICAL FIX)
embeddings = HuggingFaceEmbeddings(model_name=embedding_model)
# Step 2: Clean temp directory
if os.path.exists("temp_faiss"):
shutil.rmtree("temp_faiss")
# Step 3: Try PyPDFLoader first
loader = PyPDFLoader(file)
documents = loader.load()
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
new_docs = text_splitter.split_documents(documents)
db = FAISS.from_documents(new_docs, embeddings)
db.save_local("temp_faiss")
# After db.save_local("temp_faiss")...
# Step 4: Upload to HF Hub
api = HfApi(token=os.getenv("HF_TOKEN"))
api.upload_file(path_or_fileobj=file, path_in_repo=f"docs/{os.path.basename(file)}", repo_id=repo_id, repo_type="dataset")
api.upload_file(path_or_fileobj="temp_faiss/index.faiss", path_in_repo="index.faiss", repo_id=repo_id, repo_type="dataset")
api.upload_file(path_or_fileobj="temp_faiss/index.pkl", path_in_repo="index.pkl", repo_id=repo_id, repo_type="dataset")
message = "β
Index created successfully with PyPDFLoader and uploaded to repo"
except Exception as e1:
try:
print(f"PyPDFLoader failed: {e1}")
# Step 5: Fallback to PyMuPDFLoader
loader = PyMuPDFLoader(file)
documents = loader.load()
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
new_docs = text_splitter.split_documents(documents)
# Use same embeddings instance
embeddings = HuggingFaceEmbeddings(model_name=embedding_model)
db = FAISS.from_documents(new_docs, embeddings)
db.save_local("temp_faiss")
# Upload
api = HfApi(token=os.getenv("HF_TOKEN"))
api.upload_file(path_or_fileobj=file, path_in_repo=f"docs/{os.path.basename(file)}", repo_id=repo_id, repo_type="dataset")
api.upload_file(path_or_fileobj="temp_faiss/index.faiss", path_in_repo="index.faiss", repo_id=repo_id, repo_type="dataset")
api.upload_file(path_or_fileobj="temp_faiss/index.pkl", path_in_repo="index.pkl", repo_id=repo_id, repo_type="dataset")
message = f"β
PyPDFLoader failed ({e1}), PyMuPDFLoader succeeded and uploaded to repo"
except Exception as e2:
message = f"β Both loaders failed. PyPDF: {e1}, PyMuPDF: {e2}"
finally:
# Cleanup
if os.path.exists("temp_faiss"):
shutil.rmtree("temp_faiss")
return message
# Usage
#result = create_faiss_index("your_username/your-dataset", "path/to/your/file.pdf")
#print(result)
#=============
def update_faiss_from_hf(repo_id, file, embedding_model="sentence-transformers/all-MiniLM-L6-v2"):
"""Load existing FAISS from HF, add new docs, push updated version."""
message = ""
try:
# Step 1: Create embeddings
embeddings = HuggingFaceEmbeddings(model_name=embedding_model)
# Step 2: Download existing FAISS files
print("Downloading existing FAISS index...")
faiss_path = hf_hub_download(repo_id=repo_id, filename="index.faiss", repo_type="dataset")
pkl_path = hf_hub_download(repo_id=repo_id, filename="index.pkl", repo_type="dataset")
# Step 3: Load existing vectorstore
folder_path = os.path.dirname(faiss_path)
vectorstore = FAISS.load_local(
folder_path=folder_path,
embeddings=embeddings,
allow_dangerous_deserialization=True
)
message += f"β
Loaded existing index with {vectorstore.index.ntotal} vectors\n"
# Step 4: Load new document with fallback
documents = None
loaders = [
("PyPDFLoader", PyPDFLoader),
("PyMuPDFLoader", PyMuPDFLoader)
]
for loader_name, LoaderClass in loaders:
try:
print(f"Trying {loader_name}...")
loader = LoaderClass(file)
documents = loader.load()
message += f"β
Loaded {len(documents)} pages with {loader_name}\n"
break
except Exception as e:
message += f"β {loader_name} failed: {str(e)[:100]}...\n"
continue
if documents is None:
return "β All PDF loaders failed"
# Step 5: Split documents
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
new_docs = text_splitter.split_documents(documents)
message += f"β
Created {len(new_docs)} chunks from new document\n"
# Step 6: Add new documents to existing index
vectorstore.add_documents(new_docs)
message += f"β
Added to index. New total: {vectorstore.index.ntotal} vectors\n"
# Step 7: Save updated index
temp_dir = "temp_faiss_update"
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
vectorstore.save_local(temp_dir)
# Step 8: Upload updated files
api = HfApi(token=os.getenv("HF_TOKEN")) # Replace with your token
api.upload_file(
path_or_fileobj=file,
path_in_repo=f"docs/{os.path.basename(file)}",
repo_id=repo_id,
repo_type="dataset"
)
api.upload_file(
path_or_fileobj=f"{temp_dir}/index.faiss",
path_in_repo="index.faiss",
repo_id=repo_id,
repo_type="dataset"
)
api.upload_file(
path_or_fileobj=f"{temp_dir}/index.pkl",
path_in_repo="index.pkl",
repo_id=repo_id,
repo_type="dataset"
)
message += f"β
Successfully updated repo with {len(new_docs)} new chunks!"
except Exception as e:
message += f"β Update failed: {str(e)}"
finally:
# Cleanup
if os.path.exists("temp_faiss_update"):
shutil.rmtree("temp_faiss_update")
return message
# Usage
# result = update_faiss_from_hf("yourusername/my-faiss-store", "new_document.pdf")
# print(result)
#====================
def upload_and_prepare(file, user):
mm = ""
pdf_links = "**No PDFs**"
if user != os.getenv("uploading_password"):
return "β Unauthorized User", pdf_links
try:
if file_exists(repo_id=repo_id, filename="index.faiss", repo_type="dataset"):
mm = update_faiss_from_hf(repo_id, file)
else:
mm = create_faiss_index(repo_id, file)
# NOW this runs - generate PDF list
api = HfApi(token=os.getenv("HF_TOKEN"))
pdf_files = api.list_repo_files(repo_id, repo_type="dataset")
pdf_links = "\n".join([f"β’ [π {f}](https://huggingface.co/datasets/{repo_id}/resolve/main/{f})"
for f in pdf_files if f.endswith('.pdf')])
except Exception as e:
mm += f"\nβ Error: {e}"
return mm, pdf_links
#============
def upload_and_prepare_old(file,user):
#==============================
#=============================
# Load & split document
mm=""
if user == os.getenv("uploading_password"):
if file_exists(repo_id=repo_id, filename="index.faiss", repo_type="dataset"):
mm=update_faiss_from_hf(repo_id, file)
#mm="β
Document processed. New index added. You can now ask questions!"
if not file_exists(repo_id=repo_id, filename="index.faiss", repo_type="dataset"):
mm=create_faiss_index(repo_id, file)
#mm="β
Document processed. New index created. You can now ask questions!"
else:
mm="β Unauthorized User"
# After successful upload
api = HfApi(token=os.getenv("HF_TOKEN")) # Replace with your token
pdf_files = api.list_repo_files(repo_id, repo_type="dataset")
pdf_links = "\n".join([f"β’ [π {f}](https://huggingface.co/datasets/{repo_id}/resolve/main/{f})"
for f in pdf_files if f.endswith('.pdf')])
return mm, pdf_links # Update both outputs
#return mm
#create_faiss_index(repo_id, file_input)
#======================================================================
def generate_qa_chain(repo_id, embedding_model="sentence-transformers/all-MiniLM-L6-v2", llm=None):
"""
Generate QA chain from HF dataset repo FAISS index
"""
try:
# Step 1: Create embeddings (FIX: was missing)
embeddings = HuggingFaceEmbeddings(model_name=embedding_model)
# Step 2: Download FAISS files from HF Hub
faiss_path = hf_hub_download(
repo_id=repo_id,
filename="index.faiss",
repo_type="dataset"
)
pkl_path = hf_hub_download(
repo_id=repo_id,
filename="index.pkl",
repo_type="dataset"
)
# Step 3: Load FAISS vectorstore (FIX: pass embeddings object, not string)
folder_path = os.path.dirname(faiss_path)
vectorstore = FAISS.load_local(
folder_path=folder_path,
embeddings=embeddings, # FIXED: was 'embedding_model' string
allow_dangerous_deserialization=True
)
# Step 4: Create retriever
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
# Step 5: Custom prompt template
prompt_template = PromptTemplate(
input_variables=["context", "question"],
template="""
Answer strictly based on the context below.
Mention rule number / circular reference and **PAGE NUMBER**..
Add interpretation.
If answer is not found, say "Not available in the provided context".
Question: {question}
Context: {context}
Answer (include page references):
"""
)
# Step 6: Setup RetrievalQA chain
qa_chain = RetrievalQA.from_chain_type(
llm=llm, # Make sure llm is passed or defined globally
chain_type="stuff",
chain_type_kwargs={"prompt": prompt_template},
retriever=retriever,
return_source_documents=True
)
except Exception as e:
print(f"Error in generate_qa_chain: {e}")
return None
return qa_chain
# Usage example:
# llm = HuggingFacePipeline(...) # Your LLM setup
# qa = generate_qa_chain("your_username/your-dataset", llm=llm)
# result = qa.invoke({"query": "What is the main rule?"})
# print(result["result"])
#============================
def bePrepare():
global qa_chain
qa_chain = generate_qa_chain(repo_id,llm=llm)
return "I am ready, ask me questions with model tiny Lama."
def bePrepare1():
global qa_chain1
qa_chain1 = generate_qa_chain(repo_id,llm=llm1)
return "I am ready, ask me questions with model google flan-t5."
def ask_question(query):
if not query or not qa_chain:
return "β Please click prepare button first and check whether question is empty"
response = qa_chain.invoke({"query": query})
result = response["result"]
bullet_result = format_as_bullets(result)
sources = response.get("source_documents", [])
source_info = ""
for i, doc in enumerate(sources[:3]):
page_num = doc.metadata.get('page', 'Unknown')
filename = os.path.basename(doc.metadata.get('source', 'Unknown'))
repo_url = f"https://huggingface.co/datasets/{repo_id}/resolve/main/docs/{filename}"
source_info += f"\n**Source {i+1}:** [{filename} (Page {page_num})]({repo_url})"
return f"{result}\n\n In bullet form \n{bullet_result}\n\n**π Sources:**{source_info}"
def ask_question1(query):
if not query or not qa_chain1:
return "β Please click prepare button first and check whether question is empty"
response = qa_chain1.invoke({"query": query})
result = response["result"]
bullet_result = format_as_bullets(result)
sources = response.get("source_documents", [])
source_info = ""
for i, doc in enumerate(sources[:3]):
page_num = doc.metadata.get('page', 'Unknown')
filename = os.path.basename(doc.metadata.get('source', 'Unknown'))
repo_url = f"https://huggingface.co/datasets/{repo_id}/resolve/main/docs/{filename}"
source_info += f"\n**Source {i+1}:** [{filename} (Page {page_num})]({repo_url})"
return f"{result}\n\n In bullet form \n{bullet_result}\n\n**π Sources:**{source_info}"
#===============================================
#delete entire repo
def delete_entire_repo(user):
mx="Unauthorized user."
repo=os.getenv("reposit_id")
if user != os.getenv("uploading_password"):
return "β Unauthorized user"
try:
api = HfApi(token=os.getenv("HF_TOKEN"))
api.delete_repo(repo_id=repo, repo_type="dataset")
api.create_repo(repo_id=repo, repo_type="dataset", private=False)
return f"β
Repo {repo_id} reset successfully"
except Exception as e:
mx=f"β error during deletetion & creation of repo: {e} "
#===============================================
# β Static (never updates)
# pdf_list = gr.Markdown("**No documents loaded yet.**")
# β
Dynamic function
def get_pdf_list():
repo_id=os.getenv("reposit_id")
try:
api = HfApi(token=os.getenv("HF_TOKEN"))
files = api.list_repo_files(repo_id, repo_type="dataset")
pdf_files = [f for f in files if f.endswith('.pdf')]
if not pdf_files:
return "**No PDF documents in repo yet.**"
links = []
for pdf in pdf_files:
url = f"https://huggingface.co/datasets/{repo_id}/resolve/main/{pdf}"
links.append(f"β’ [π {os.path.basename(pdf)}]({url})")
return f"**π Uploaded PDFs ({len(pdf_files)}):**\n" + "\n".join(links)
except Exception as ee:
print (ee)
return f"**β Cannot load PDF list**error: {ee}"
#===============================================
# Gradio UI
with gr.Blocks(title="N R L C H A T B O T - for commercial procurement - Supply", css="""
#blue-col { background: linear-gradient(135deg, #667eea, #764ba2); padding: 20px; border-radius: 10px; }
#green-col { background: #4ecdc4; padding: 20px; border-radius: 10px; }
""") as demo:
gr.Markdown("## π§ For use of NRL procurement department Only")
with gr.Row():
# LEFT COLUMN: TinyLama Model
with gr.Column(elem_id="blue-col",scale=1):
gr.Markdown("## π§ Using heavy TinyLama Model")
with gr.Row():
Index_processing_output=gr.Textbox(label="π Status for tiny lama", interactive=False)
with gr.Row():
Index_processing_btn = gr.Button("π Clik to get the udated resources with tiny Lama")
Index_processing_btn.click(bePrepare, inputs=None, outputs=Index_processing_output)
with gr.Row():
query_input = gr.Textbox(label="β Your Question pls")
with gr.Row():
query_btn = gr.Button("π§ Get Answer")
with gr.Row():
answer_output = gr.Textbox(
label="β
Answer with Document Links",
lines=8
)
query_btn.click(ask_question, inputs=query_input, outputs=answer_output)
# RIGHT COLUMN: google\flan-t5
with gr.Column(elem_id="green-col",scale=2):
gr.Markdown("## π§ Using ligth model - google flan-t5")
Index_processing_output1=gr.Textbox(label="π Status for google flan-t5", interactive=False)
Index_processing_btn1 = gr.Button("π Clik to get the udated resources with google flan-t5")
Index_processing_btn1.click(bePrepare1, inputs=None, outputs=Index_processing_output1)
query_input1 = gr.Textbox(label="β Your Question pls")
query_btn1 = gr.Button("π§ Get Answer")
answer_output1 = gr.Textbox(
label="β
Answer with Document Links",
lines=8
)
summary_output = gr.Markdown("**Summary will appear here**")
query_btn1.click(
ask_question1,
inputs=query_input1,
outputs=answer_output1
)
with gr.Row():
# LEFT COLUMN: Document Management
with gr.Column(elem_id="green-col",scale=1):
gr.Markdown("## π Uploaded Documents")
with gr.Row():
pdf_list = gr.Markdown("**No documents loaded yet.**")
refresh_btn = gr.Button("π Refresh")
refresh_btn.click(get_pdf_list,inputs=None,outputs=pdf_list)
with gr.Column(elem_id="blue-col",scale=1):
gr.Markdown("## π§ For uploading new PDF documents.")
with gr.Row():
output_msg = gr.Textbox(label="π Authorization Message", interactive=False)
with gr.Row():
file_input = gr.File(label="π Upload .pdf File by only authorized user", type="filepath")
with gr.Row():
authorized_user=gr.Textbox(label="Write the password to upload new Circular Doc.")
with gr.Row():
upload_btn = gr.Button("π Process Doc")
upload_btn.click(upload_and_prepare, inputs=[file_input,authorized_user], outputs=[output_msg,pdf_list])
with gr.Row():
delete_btn = gr.Button("π Delete complete repo")
delete_btn.click(delete_entire_repo, inputs=authorized_user, outputs=output_msg)
# For local dev use: demo.launch()
# For HF Spaces
if __name__ == "__main__":
demo.launch()
|