import os
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfig
import gradio as gr
from threading import Thread
MODEL_PATH = r"C:\Users\shermanhonsf\Desktop\Python\llama_develop\model\Llama3.2-1B-Instruct-HF-Model" #Your model path
TITLE = """
Llama 3.2 1B
"""
PLACEHOLDER = """
Hi, I'm Llama. Ask me anything.
"""
CSS = """
.duplicate-button {
margin: auto !important;
color: white !important;
background: black !important;
border-radius: 100vh !important;
}
h3 {
text-align: center;
}
"""
Set the device to "cuda" if you have a compatible GPU, otherwise "cpu"
device = "cuda" if torch.cuda.is_available() else "cpu"
with gr.Blocks(css=CSS) as demo:
gr.HTML(TITLE)
gr.ChatInterface(
fn=stream_chat,
chatbot=chatbot,
fill_height=True,
additional_inputs_accordion=gr.Accordion(
label="⚙️ Parameters",
open=False,
render=False
),
code
additional_inputs=[
gr.Textbox(
value="You are a helpful assistant",
label="System Prompt",
render=False,
),
gr.Slider(
minimum=0,
maximum=1,
step=0.1,
value=0.8,
label="Temperature",
render=False,
),
gr.Slider(
minimum=128,
maximum=8192,
step=1,
value=1024,
label="Max new tokens",
render=False,
),
gr.Slider(
minimum=0.0,
maximum=1.0,
step=0.1,
value=1.0,
label="Top_p",
render=False,
),
gr.Slider(
minimum=1,
maximum=20,
step=1,
value=20,
label="Top_k",
render=False,
),
gr.Slider(
minimum=0.0,
maximum=2.0,
step=0.1,
value=1.2,
label="Repetition penalty",
render=False,
)
],
examples=[
["Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option."],
["What are 5 creative things I could do with my kids' art? I don't want to throw them away, but it's also so much clutter."],
["Tell me a random fun fact about the Roman Empire."],
["Show me a code snippet of a website's sticky header in CSS and JavaScript."],
],
cache_examples=False,
)
if name == "main":
demo.launch(debug=True)
"
I want to add the input pdf function so the user can input the pdf and ask question about the pdf.
You can take the following code as reference:
"
import gradio as gr
import os
api_token = os.getenv("HF_TOKEN")
from langchain_community.vectorstores import FAISS
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import Chroma
from langchain.chains import ConversationalRetrievalChain
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.llms import HuggingFacePipeline
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain_community.llms import HuggingFaceEndpoint
import torch
list_llm = ["meta-llama/Meta-Llama-3-8B-Instruct", "mistralai/Mistral-7B-Instruct-v0.2"]
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
Load and split PDF document
def load_doc(list_file_path):
# Processing for one document only
# loader = PyPDFLoader(file_path)
# pages = loader.load()
loaders = [PyPDFLoader(x) for x in list_file_path]
pages = []
for loader in loaders:
pages.extend(loader.load())
text_splitter = RecursiveCharacterTextSplitter(
chunk_size = 1024,
chunk_overlap = 64
)
doc_splits = text_splitter.split_documents(pages)
return doc_splits
def initialize_database(list_file_obj, progress=gr.Progress()):
# Create a list of documents (when valid)
list_file_path = [x.name for x in list_file_obj if x is not None]
# Load document and create splits
doc_splits = load_doc(list_file_path)
# Create or load vector database
vector_db = create_db(doc_splits)
return vector_db, "Database created!"
def upload_file(file_obj):
list_file_path = []
for idx, file in enumerate(file_obj):
file_path = file_obj.name
list_file_path.append(file_path)
return list_file_path
def demo():
# with gr.Blocks(theme=gr.themes.Default(primary_hue="sky")) as demo:
with gr.Blocks(theme=gr.themes.Default(primary_hue="red", secondary_hue="pink", neutral_hue = "sky")) as demo:
vector_db = gr.State()
qa_chain = gr.State()
gr.HTML("RAG PDF chatbot")
gr.Markdown("""Query your PDF documents! This AI agent is designed to perform retrieval augmented generation (RAG) on PDF documents. The app is hosted on Hugging Face Hub for the sole purpose of demonstration.
Please do not upload confidential documents.
""")
with gr.Row():
with gr.Column(scale = 86):
gr.Markdown("Step 1 - Upload PDF documents and Initialize RAG pipeline")
with gr.Row():
document = gr.Files(height=300, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload PDF documents")
with gr.Row():
db_btn = gr.Button("Create vector database")
with gr.Row():
db_progress = gr.Textbox(value="Not initialized", show_label=False) # label="Vector database status",
gr.Markdown("body { font-size: 16px; }Select Large Language Model (LLM) and input parameters")
with gr.Row():
llm_btn = gr.Radio(list_llm_simple, label="Available LLMs", value = list_llm_simple[0], type="index") # info="Select LLM", show_label=False
with gr.Row():
with gr.Accordion("LLM input parameters", open=False):
with gr.Row():
slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.5, step=0.1, label="Temperature", info="Controls randomness in token generation", interactive=True)
with gr.Row():
slider_maxtokens = gr.Slider(minimum = 128, maximum = 9192, value=4096, step=128, label="Max New Tokens", info="Maximum number of tokens to be generated",interactive=True)
with gr.Row():
slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k", info="Number of tokens to select the next token from", interactive=True)
with gr.Row():
qachain_btn = gr.Button("Initialize Question Answering Chatbot")
with gr.Row():
llm_progress = gr.Textbox(value="Not initialized", show_label=False) # label="Chatbot status",
if name == "main":
demo()
"
No need to include advanced function.
To integrate the functionality for users to upload a PDF file and ask questions about the content of the PDF, we can modify your existing Gradio code for the Llama model inference.
We will add the necessary components for PDF loading and text extraction using a simple implementation. This will include functions to handle the PDF upload and retrieval of text content that will be processed by the Llama model. The example assumes you already have the PyPDFLoader from langchain and the necessary embedding/vector store utilities set up.
Here’s how to modify your code:
First, make sure you have all necessary imports, and we will extend the Gradio interface to include PDF uploading and question answering.
Modified Code
python
import os
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfig
import gradio as gr
from threading import Thread
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
MODEL_PATH = r"C:\Users\shermanhonsf\Desktop\Python\llama_develop\model\Llama3.2-1B-Instruct-HF-Model"
# Other constants remain the same...
# Set the device to "cuda" if you have a compatible GPU, otherwise "cpu"
device = "cuda" if torch.cuda.is_available() else "cpu"
# Load the tokenizer and model from the local directory
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
model = AutoModelForCausalLM.from_pretrained(
MODEL_PATH,
torch_dtype=torch.bfloat16,
device_map="auto",
)
model.to(device)
# Load and split PDF documents
def load_pdf(file_paths):
pages = []
for file_path in file_paths:
loader = PyPDFLoader(file_path)
pages.extend(loader.load())
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1024, chunk_overlap=64)
doc_splits = text_splitter.split_documents(pages)
return doc_splits
# Create vector database
def create_vector_db(docs):
embeddings = HuggingFaceEmbeddings()
vectordb = FAISS.from_documents(docs, embeddings)
return vectordb
# Stream chat function will need adaptations for PDF queries
def stream_chat(message: str, history: list, pdf_db=None, system_prompt='You are a helpful assistant'):
# If pdf_db exists, handle query against PDF documents here
if pdf_db:
# Here you would implement the query logic against the vector database
# For instance, retrieving relevant documents and feeding them into the model
return "Query logic not implemented yet."
# continue with the existing chat logic below...
conversation = [{"role": "system", "content": system_prompt}]
for prompt, answer in history:
conversation.append({"role": "user", "content": prompt})
conversation.append({"role": "assistant", "content": answer})
conversation.append({"role": "user", "content": message})
# Your existing logic for preparing input IDs and generating responses...
# ...
# Stream functions handling chat and PDF interactions
def handle_pdf(inputs):
file_paths = [doc.name for doc in inputs]
docs = load_pdf(file_paths)
pdf_db = create_vector_db(docs)
return "PDF loaded and processed successfully", pdf_db
# Gradio Blocks Interface
with gr.Blocks() as demo:
with gr.Row():
gr.Markdown("## PDF Assistant with Llama")
document_upload = gr.Files(file_types=["pdf"], label="Upload PDF Document")
pdf_load_btn = gr.Button("Load PDF and Create Vector DB")
pdf_status = gr.Textbox(value="", label="PDF Processing Status", interactive=False)
# Here, we will have the chatbot interface
chatbot = gr.Chatbot(height=600)
user_input = gr.Textbox(placeholder="Ask a question about the PDF...")
document_upload.change(fn=handle_pdf, inputs=document_upload, outputs=[pdf_status])
# Connect chat message submission
user_input.submit(fn=stream_chat, inputs=[user_input, chatbot], outputs=[chatbot])
demo.launch(debug=True)
Explanation of Changes
PDF Loader: We created a function load_pdf() that handles the loading of PDF files, extracts text, and splits the content into manageable chunks for processing.
Vector Database Creation: The create_vector_db() function generates a vector store (using FAISS) from the loaded documents.
Chat Handling: The stream_chat() function is modified to optionally handle user inputs regarding the PDFs. Depending on whether a PDF database is available, it will respond appropriately.
Gradio Interface: The layout is adjusted to include a PDF upload button and status updates. We allow users to upload PDFs and initiate the loading process via a button.
PDF Query Handling: This basic implementation requires an extension to actually query the vector database and return relevant results to the model, which you may want to implement based on your specific requirements.
This setup should allow users to upload a PDF document and prepare it for interaction with the Llama model for questions about its content. You can expand the PDF query logic as needed!
If you want to keep it simple and not use Retrieval-Augmented Generation (RAG) or advanced document processing techniques, we can just focus on extracting text from the PDF and then using that text as the context for the Llama model to answer questions.
We'll implement a straightforward way for users to upload a PDF, extract its text, and then ask questions. The answer generation will solely depend on the Llama model and given text without utilizing a vector store or embeddings.
Here's an updated version of your code, streamlined to simply handle PDF uploads and use extracted text for inference:
Updated Code for Simple PDF Querying
python
import os
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
import gradio as gr
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from threading import Thread
MODEL_PATH = r"C:\Users\shermanhonsf\Desktop\Python\llama_develop\model\Llama3.2-1B-Instruct-HF-Model"
# Set the device to "cuda" if you have a compatible GPU, otherwise "cpu"
device = "cuda" if torch.cuda.is_available() else "cpu"
# Load the tokenizer and model from the local directory
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
model = AutoModelForCausalLM.from_pretrained(
MODEL_PATH,
torch_dtype=torch.bfloat16,
device_map="auto",
)
model.to(device)
# Load and split PDF documents
def load_pdf(file_paths):
text_content = ""
for file_path in file_paths:
loader = PyPDFLoader(file_path)
pages = loader.load()
for page in pages:
text_content += page.page_content + "\n"
return text_content
# Stream chat function with PDF context
def stream_chat(message: str, history: list, pdf_text: str, system_prompt='You are a helpful assistant'):
conversation = [{"role": "system", "content": system_prompt}]
for prompt, answer in history:
conversation.append({"role": "user", "content": prompt})
conversation.append({"role": "assistant", "content": answer})
# Append PDF context before the user's message
conversation.append({"role": "user", "content": pdf_text + "\n" + message})
# Prepare the input IDs
input_ids = tokenizer.encode(pdf_text + "\n" + message, return_tensors="pt").to(device)
streamer = TextIteratorStreamer(tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
# Generate response
with torch.no_grad():
thread = Thread(target=model.generate, kwargs={
"input_ids": input_ids,
"max_new_tokens": 256,
"do_sample": True,
"temperature": 0.7,
"streamer": streamer,
})
thread.start()
buffer = ""
for new_text in streamer:
buffer += new_text
yield buffer
# Gradio Blocks Interface
with gr.Blocks() as demo:
with gr.Row():
gr.Markdown("## PDF Assistant with Llama")
document_upload = gr.Files(file_types=["pdf"], label="Upload PDF Document", file_count="single")
pdf_load_btn = gr.Button("Load PDF")
pdf_status = gr.Textbox(value="", label="PDF Content", interactive=False, placeholder="Content of the PDF will appear here...")
# Chat Interface
chatbot = gr.Chatbot(height=600)
user_input = gr.Textbox(placeholder="Ask a question about the PDF...")
def handle_pdf(file):
# Load the PDF and extract text
if file:
pdf_text = load_pdf([file.name])
return pdf_text
document_upload.change(
fn=handle_pdf,
inputs=document_upload,
outputs=pdf_status
)
# Connect chat message submission
user_input.submit(fn=stream_chat, inputs=[user_input, chatbot, pdf_status], outputs=[chatbot])
demo.launch(debug=True)
Key Changes Made:
Simple PDF Loading: The load_pdf() function reads the uploaded PDF and concatenates the text into a single string.
Text Context in Chat: The chat function stream_chat() now accepts the entire extracted PDF text as context for the model's response, appending it to the user message.
Gradio Interface Adjustments: The Gradio interface allows users to upload a single PDF file, extracts the content upon upload, and displays it. Users can then ask questions based on the content.
Streamlined Logic: Removed any reference to RAG or complex vector stores, focusing solely on using the text extracted from the PDF.
This setup enables users to upload a PDF, get its text processed, and interactively ask questions about that text directly from the Llama model without the complexities of RAG. If the PDF is lengthy, you may want to implement further chunking or summarization to manage the context better; as it stands, the extracted text will be used directly.