Spaces:
Sleeping
Sleeping
Update app.py
Browse filesUpdate for the 2026 hugging face compatibility
app.py
CHANGED
|
@@ -1,134 +1,82 @@
|
|
| 1 |
-
|
| 2 |
-
# from ibm_watsonx_ai.foundation_models import ModelInference
|
| 3 |
-
# from ibm_watsonx_ai.metanames import GenTextParamsMetaNames as GenParams
|
| 4 |
-
# from ibm_watsonx_ai.metanames import EmbedTextParamsMetaNames
|
| 5 |
-
# from ibm_watsonx_ai import Credentials
|
| 6 |
-
# from langchain_ibm import WatsonxLLM, WatsonxEmbeddings
|
| 7 |
-
|
| 8 |
import os
|
| 9 |
import uuid
|
|
|
|
| 10 |
from langchain_huggingface import HuggingFaceEndpoint
|
| 11 |
-
|
| 12 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 13 |
from langchain_community.vectorstores import Chroma
|
| 14 |
from langchain_community.document_loaders import PyPDFLoader
|
| 15 |
-
from langchain.chains import RetrievalQA
|
| 16 |
-
#from huggingface_hub import HfFolder
|
| 17 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 18 |
-
from
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
## You can use this section to suppress warnings generated by your code:
|
| 22 |
-
def warn(*args, **kwargs):
|
| 23 |
-
pass
|
| 24 |
-
import warnings
|
| 25 |
-
warnings.warn = warn
|
| 26 |
-
warnings.filterwarnings('ignore')
|
| 27 |
-
|
| 28 |
-
## LLM
|
| 29 |
-
# def get_llm():
|
| 30 |
-
# model_id = 'ibm/granite-3-2-8b-instruct'
|
| 31 |
-
# parameters = {
|
| 32 |
-
# GenParams.MAX_NEW_TOKENS: 256, # This controls the maximum number of tokens in the generated output
|
| 33 |
-
# GenParams.TEMPERATURE: 0.5, # This controls randomness or creativity of the model's responses
|
| 34 |
-
# }
|
| 35 |
-
# project_id = 'skills-network'
|
| 36 |
-
# watsonx_llm = WatsonxLLM(
|
| 37 |
-
# model_id = model_id,
|
| 38 |
-
# url="https://us-south.ml.cloud.ibm.com",
|
| 39 |
-
# project_id = project_id,
|
| 40 |
-
# params = parameters,
|
| 41 |
-
# )
|
| 42 |
-
# return watsonx_llm
|
| 43 |
|
|
|
|
| 44 |
def get_llm():
|
| 45 |
-
|
| 46 |
-
# You don't need Ollama for this!
|
| 47 |
-
llm = HuggingFaceEndpoint(
|
| 48 |
repo_id="ibm-granite/granite-3.1-8b-instruct",
|
| 49 |
task="text-generation",
|
| 50 |
max_new_tokens=512,
|
| 51 |
temperature=0.1,
|
| 52 |
-
huggingfacehub_api_token=os.getenv("HF_TOKEN")
|
| 53 |
)
|
| 54 |
-
return llm
|
| 55 |
|
| 56 |
-
#
|
| 57 |
-
def
|
| 58 |
-
loader = PyPDFLoader(
|
| 59 |
-
|
| 60 |
-
return loaded_document
|
| 61 |
-
## Text splitter
|
| 62 |
-
def text_splitter(data):
|
| 63 |
-
text_splitter = RecursiveCharacterTextSplitter(
|
| 64 |
-
chunk_size = 1000,
|
| 65 |
-
chunk_overlap = 50,
|
| 66 |
-
length_function = len,
|
| 67 |
-
)
|
| 68 |
-
chuncks = text_splitter.split_documents(data)
|
| 69 |
-
return chuncks
|
| 70 |
-
## Embedding model
|
| 71 |
-
# def watsonx_embedding():
|
| 72 |
-
# embed_params = {
|
| 73 |
-
# EmbedTextParamsMetaNames.TRUNCATE_INPUT_TOKENS: 256,
|
| 74 |
-
# EmbedTextParamsMetaNames.RETURN_OPTIONS: {'input_text': True},
|
| 75 |
-
# }
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
#
|
| 81 |
-
|
| 82 |
-
# )
|
| 83 |
-
# return watsonx_embedding
|
| 84 |
-
|
| 85 |
-
def watsonx_embedding():
|
| 86 |
-
return HuggingFaceEmbeddings(
|
| 87 |
-
model_name="sentence-transformers/all-MiniLM-L6-v2"
|
| 88 |
-
)
|
| 89 |
-
|
| 90 |
-
## Vector db
|
| 91 |
-
def vector_database(chunks):
|
| 92 |
|
| 93 |
-
|
| 94 |
-
c for c in chunks
|
| 95 |
-
if c.page_content and c.page_content.strip() and len(c.page_content.strip()) > 10
|
| 96 |
-
]
|
| 97 |
-
embedding_model = watsonx_embedding()
|
| 98 |
-
vectordb = Chroma.from_documents(chunks, embedding_model)
|
| 99 |
-
return vectordb
|
| 100 |
-
## Retriever
|
| 101 |
-
def retriever(file):
|
| 102 |
-
splits = document_loader(file)
|
| 103 |
-
chunks = text_splitter(splits)
|
| 104 |
-
vectordb = vector_database(chunks)
|
| 105 |
-
retriever = vectordb.as_retriever()
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
def retriever_qa(file, query):
|
|
|
|
|
|
|
|
|
|
| 110 |
llm = get_llm()
|
| 111 |
-
retriever_obj =
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
)
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
rag_application = gr.Interface(
|
| 123 |
-
fn
|
| 124 |
-
flagging_mode
|
| 125 |
-
inputs
|
| 126 |
-
gr.File(label
|
| 127 |
-
gr.Textbox(label=
|
| 128 |
],
|
| 129 |
-
outputs
|
| 130 |
-
title=
|
| 131 |
-
description = 'Upload a PDF document and ask any question. The chatbot will try to answer using the provided document.'
|
| 132 |
)
|
| 133 |
-
|
| 134 |
-
rag_application.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import uuid
|
| 3 |
+
import gradio as gr
|
| 4 |
from langchain_huggingface import HuggingFaceEndpoint
|
|
|
|
| 5 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 6 |
from langchain_community.vectorstores import Chroma
|
| 7 |
from langchain_community.document_loaders import PyPDFLoader
|
|
|
|
|
|
|
| 8 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 9 |
+
from langchain.chains.combine_documents import create_stuff_documents_chain
|
| 10 |
+
from langchain.chains import create_retrieval_chain
|
| 11 |
+
from langchain_core.prompts import ChatPromptTemplate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
# 1. LLM SETUP (Using Granite via HF API)
|
| 14 |
def get_llm():
|
| 15 |
+
return HuggingFaceEndpoint(
|
|
|
|
|
|
|
| 16 |
repo_id="ibm-granite/granite-3.1-8b-instruct",
|
| 17 |
task="text-generation",
|
| 18 |
max_new_tokens=512,
|
| 19 |
temperature=0.1,
|
| 20 |
+
huggingfacehub_api_token=os.getenv("HF_TOKEN")
|
| 21 |
)
|
|
|
|
| 22 |
|
| 23 |
+
# 2. DOCUMENT PROCESSING
|
| 24 |
+
def process_pdf(file_path):
|
| 25 |
+
loader = PyPDFLoader(file_path)
|
| 26 |
+
data = loader.load()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=50)
|
| 29 |
+
chunks = text_splitter.split_documents(data)
|
| 30 |
+
|
| 31 |
+
# Clean empty chunks
|
| 32 |
+
chunks = [c for c in chunks if len(c.page_content.strip()) > 10]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
# We use a unique collection name to prevent memory crossover
|
| 37 |
+
vectordb = Chroma.from_documents(
|
| 38 |
+
documents=chunks,
|
| 39 |
+
embedding=embeddings,
|
| 40 |
+
collection_name=f"pdf_{uuid.uuid4().hex}"
|
| 41 |
+
)
|
| 42 |
+
return vectordb.as_retriever()
|
| 43 |
+
|
| 44 |
+
# 3. QA CHAIN (The 2026 Modern Way)
|
| 45 |
def retriever_qa(file, query):
|
| 46 |
+
if file is None:
|
| 47 |
+
return "Please upload a PDF first."
|
| 48 |
+
|
| 49 |
llm = get_llm()
|
| 50 |
+
retriever_obj = process_pdf(file)
|
| 51 |
+
|
| 52 |
+
# Define the Prompt
|
| 53 |
+
system_prompt = (
|
| 54 |
+
"Use the following pieces of retrieved context to answer the question. "
|
| 55 |
+
"If you don't know the answer, say you don't know. \n\n {context}"
|
| 56 |
)
|
| 57 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 58 |
+
("system", system_prompt),
|
| 59 |
+
("human", "{input}"),
|
| 60 |
+
])
|
| 61 |
+
|
| 62 |
+
# Create the modern retrieval chain
|
| 63 |
+
combine_docs_chain = create_stuff_documents_chain(llm, prompt)
|
| 64 |
+
rag_chain = create_retrieval_chain(retriever_obj, combine_docs_chain)
|
| 65 |
+
|
| 66 |
+
# Invoke and return result
|
| 67 |
+
response = rag_chain.invoke({"input": query})
|
| 68 |
+
return response["answer"] # Note: 'answer' instead of 'result'
|
| 69 |
+
|
| 70 |
+
# 4. GRADIO INTERFACE
|
| 71 |
rag_application = gr.Interface(
|
| 72 |
+
fn=retriever_qa,
|
| 73 |
+
flagging_mode='never',
|
| 74 |
+
inputs=[
|
| 75 |
+
gr.File(label='Upload PDF', file_types=['.pdf'], type='filepath'),
|
| 76 |
+
gr.Textbox(label='Your Question', lines=2)
|
| 77 |
],
|
| 78 |
+
outputs=gr.Textbox(label='AI Answer'),
|
| 79 |
+
title='Granite PDF Chatbot'
|
|
|
|
| 80 |
)
|
| 81 |
+
|
| 82 |
+
rag_application.launch()
|