I have written a code to create a PDF QA Bot. The code for it is - “”“import numpy as np…
- User
I have written a code to create a PDF QA Bot. The code for it is - “”“import numpy as np from langchain.embeddings import HuggingFaceEmbeddings from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.vectorstores import Chroma from langchain.document_loaders import PyPDFLoader from langchain import HuggingFacePipeline from langchain import PromptTemplate from langchain.chains import ConversationalRetrievalChain from langchain.memory import ConversationBufferWindowMemory from sentence_transformers import SentenceTransformer import gradio as gr from langchain_community.vectorstores import FAISS
#nltk.download() import torch from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, pipeline, TextStreamer
def create_multipage_pdf(text, filename=‘output.pdf’, font_size=12, margin=50):
Split text into chunks that fit on one page
chunks = [] chunk_size = 50 # Number of characters per chunk for i in range(0, len(text), chunk_size): chunks.append(text[i:i+chunk_size])
Create PDF
c = canvas.Canvas(filename, pagesize=letter) width, height = letter y = height - margin for chunk in chunks:
Draw text
text_object = c.beginText(margin, y) text_object.setFont(“Helvetica”, font_size) text_object.textLines(chunk) c.drawText(text_object)
Update y position
y -= (font_size + 4) # Adjust spacing between lines
Check if we need to start a new page
if y <= margin: c.showPage() y = height - margin
c.save()
Example usage
#create_multipage_pdf(text, filename=‘document.pdf’)
bnb_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type=“nf4”, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=False)
model_id = “meta-llama/Llama-2-7b-chat-hf”
tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config = bnb_config,device_map={”“:0})
import json import textwrap
B_INST, E_INST = “[INST]”, “[/INST]” B_SYS, E_SYS = “<>\n”, “\n<>\n\n” DEFAULT_SYSTEM_PROMPT = “””You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don’t know the answer to a question, please don’t share false information.“”“
def get_prompt(instruction, new_system_prompt=DEFAULT_SYSTEM_PROMPT ): SYSTEM_PROMPT = B_SYS + new_system_prompt + E_SYS prompt_template = B_INST + SYSTEM_PROMPT + instruction + E_INST return prompt_template
- Assistant