File size: 13,434 Bytes
5c7cb56 |
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 |
# -*- coding: utf-8 -*-
"""CiPE_Test3
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1oqx4e49lscGSUJGejVF43AbKWlNJf5IU
"""
# Om Maa
!pip install langchain predictionguard lancedb html2text sentence-transformers PyPDF2
! pip install huggingface_hub
! pip install transformers
! pip install sentencepiece
import os
import urllib.request
import html2text
import predictionguard as pg
from langchain import PromptTemplate, FewShotPromptTemplate
from langchain.text_splitter import CharacterTextSplitter
from sentence_transformers import SentenceTransformer
import numpy as np
import lancedb
from lancedb.embeddings import with_embeddings
import pandas as pd
os.environ['PREDICTIONGUARD_TOKEN'] = "q1VuOjnffJ3NO2oFN8Q9m8vghYc84ld13jaqdF7E"
# # Chaining
# template = """### Instruction:
# Decide if the following input message is an informational question, a general chat message, or a request for code generation.
# If the message is an informational question, answer it based on the informational context provided below.
# If the message is a general chat message, respond in a kind and friendly manner based on the coversation context provided below.
# If the message is a request for code generation, respond with a code snippet.
# ### Input:
# Message: {query}
# Informational Context: The Greater Los Angeles and San Francisco Bay areas in California are the nation's second and fifth-most populous urban regions, respectively. Greater Los Angeles has over 18.7 million residents and the San Francisco Bay Area has over 9.6 million residents. Los Angeles is state's most populous city and the nation's second-most populous city. San Francisco is the second-most densely populated major city in the country. Los Angeles County is the country's most populous county, and San Bernardino County is the nation's largest county by area. Sacramento is the state's capital.
# Conversational Context:
# Human - "Hello, how are you?"
# AI - "I'm good, what can I help you with?"
# Human - "What is the captital of California?"
# AI - "Sacramento"
# Human - "Thanks!"
# AI - "You are welcome!"
# ### Response:
# """
# prompt = PromptTemplate(
# input_variables=["query"],
# template=template,
# )
# result = pg.Completion.create(
# model="Nous-Hermes-Llama2-13B",
# prompt=prompt.format(query="What is the population of LA?")
# )
# print(result['choices'][0]['text'])
# # Let's get the html off of a website.
# fp = urllib.request.urlopen("https://docs.kernel.org/process/submitting-patches.html")
# mybytes = fp.read()
# html = mybytes.decode("utf8")
# fp.close()
# # And convert it to text.
# h = html2text.HTML2Text()
# h.ignore_links = True
# text = h.handle(html)
# print(text)
from PyPDF2 import PdfReader
# Replace 'path_to_your_pdf_file.pdf' with the path to your PDF file
pdf_path = '/content/data/drug_side_effects_summary_cleaned.pdf'
reader = PdfReader(pdf_path)
# Initialize an empty string to accumulate text
text = ''
# Iterate over each page in the PDF
for page in reader.pages:
# Extract text from the page and append it to the text string
text += page.extract_text() + "\n"
# Now, `text` contains the text content of the PDF. You can print it or process it further.
print(text[:500]) # Example: print the first 500 characters to understand the structure
# from PyPDF2 import PdfReader
# # Open the PDF file
# pdf_path = '/content/data/drug_side_effects_summary_cleaned.pdf'
# reader = PdfReader(pdf_path)
# # Read each page and extract text
# text = ''
# for page in reader.pages:
# text += page.extract_text() + "\n"
# # Show the first 500 characters to understand the structure
# text[:500]
# # Clean things up just a bit.
# text = text.split("### This Page")[1]
# text = text.split("## References")[0]
# # Chunk the text into smaller pieces for injection into LLM prompts.
# text_splitter = CharacterTextSplitter(chunk_size=700, chunk_overlap=50)
# docs = text_splitter.split_text(text)
# # Let's checkout some of the chunks!
# for i in range(0, 3):
# print("Chunk", str(i+1))
# print("----------------------------")
# print(docs[i])
# print("")
import re
# Function to clean the extracted text
def clean_text(text):
# Correcting unwanted line breaks and spaces
text = re.sub(r'-\n', '', text) # Remove hyphenation
text = re.sub(r'\n', ' ', text) # Replace new lines with space
text = re.sub(r'\s+', ' ', text) # Replace multiple spaces with single space
text = text.strip() # Remove leading and trailing spaces
return text
# Clean the extracted text
cleaned_text = clean_text(text)
# Return a portion of the cleaned text to verify the cleaning
cleaned_text[:500]
# Define a function to chunk text with specified size and overlap using standard Python
def chunk_text(text, chunk_size=700, overlap=50):
chunks = []
start = 0
while start < len(text):
# If we're not at the beginning, move back 'overlap' characters for context
if start > 0:
start -= overlap
end = start + chunk_size
chunks.append(text[start:end])
start += chunk_size
return chunks
# Chunk the cleaned text into smaller pieces for LLM input
docs_alternative = chunk_text(cleaned_text, chunk_size=700, overlap=50)
# Prepare to display the first few chunks to verify the result
chunks_to_display_alt = 3
chunks_preview_alt = [docs_alternative[i] for i in range(min(len(docs_alternative), chunks_to_display_alt))]
chunks_preview_alt
# from PyPDF2 import PdfReader
# import re
# from langchain.text_splitter import CharacterTextSplitter
# # Load and clean the PDF text
# pdf_path = '/content/data/drug_side_effects_summary_cleaned.pdf'
# reader = PdfReader(pdf_path)
# text = ''
# for page in reader.pages:
# text += page.extract_text() + "\n"
# # Basic cleaning function
# def clean_text(text):
# text = re.sub(r'-\n', '', text) # Remove hyphenation
# text = re.sub(r'\n', ' ', text) # Replace new lines with space
# text = re.sub(r'\s+', ' ', text) # Replace multiple spaces with single space
# return text.strip()
# cleaned_text = clean_text(text)
# # Assuming you have specific sections to remove, adjust these lines accordingly
# # cleaned_text = cleaned_text.split("Your Start Marker")[1]
# # cleaned_text = cleaned_text.split("Your End Marker")[0]
# # Chunk the cleaned text
# chunk_size = 700 # Customize based on your LLM's token limit
# chunk_overlap = 50 # Optional overlap to maintain context between chunks
# text_splitter = CharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
# docs = text_splitter.split_text(cleaned_text)
# # Example to print the first few chunks
# for i, doc in enumerate(docs[:3]):
# print(f"Chunk {i+1}:")
# print(doc)
# print("----------------------------")
# import re
# # Split the text based on a pattern that seems to mark new entries
# # Assuming each entry starts with a numeral followed by ".", as seen in "1. This particular disease..."
# chunks = re.split(r'\n\d+\.', text)
# # Remove any leading or trailing whitespace and unwanted characters from each chunk
# chunks_cleaned = [chunk.strip().replace('\n', ' ').replace('#', '-') for chunk in chunks if chunk.strip()]
# # Show the number of chunks and the first 3 chunks as examples
# len(chunks_cleaned), chunks_cleaned[:3]
# # Let's take care of some of the formatting so it doesn't conflict with our
# # typical prompt template structure
# docs = [x.replace('#', '-') for x in docs]
# # Now we need to embed these documents and put them into a "vector store" or
# # "vector db" that we will use for semantic search and retrieval.
# # Embeddings setup
# name="all-MiniLM-L12-v2"
# model = SentenceTransformer(name)
# def embed_batch(batch):
# return [model.encode(sentence) for sentence in batch]
# def embed(sentence):
# return model.encode(sentence)
# # LanceDB setup
# os.mkdir(".lancedb")
# uri = ".lancedb"
# db = lancedb.connect(uri)
# # Create a dataframe with the chunk ids and chunks
# metadata = []
# for i in range(len(docs)):
# metadata.append([
# i,
# docs[i]
# ])
# doc_df = pd.DataFrame(metadata, columns=["chunk", "text"])
# # Embed the documents
# data = with_embeddings(embed_batch, doc_df)
# # Create the DB table and add the records.
# db.create_table("linux", data=data)
# table = db.open_table("linux")
# table.add(data=data)
# Format the chunks to avoid prompt template conflicts
chunks_preview_alt = [x.replace('#', '-') for x in chunks_preview_alt]
# Embeddings setup
name = "all-MiniLM-L12-v2"
model = SentenceTransformer(name)
# Embedding functions
def embed_batch(batch):
return [model.encode(sentence, show_progress_bar=True) for sentence in batch]
def embed(sentence):
return model.encode(sentence)
# Ensure the LanceDB directory does not exist already to avoid errors
lancedb_dir = ".lancedb"
if not os.path.exists(lancedb_dir):
os.mkdir(lancedb_dir)
uri = lancedb_dir
db = lancedb.connect(uri)
# Prepare metadata for embedding
metadata = [[i, chunks_preview_alt] for i, chunks_preview_alt in enumerate(chunks_preview_alt)]
doc_df = pd.DataFrame(metadata, columns=["chunk", "text"])
# Embed the documents
data = with_embeddings(embed_batch, doc_df)
# LanceDB operations
# if not db.has_table("pdf_data"):
db.create_table("pdf_data", data=data)
table = db.open_table("pdf_data")
table.add(data=data)
# Note: Adjust the 'create_table' and 'open_table' to match your dataset/table names
# # Let's try to match a query to one of our documents.
# message = "How many problems should be solved per patch?"
# results = table.search(embed(message)).limit(5).to_df()
# results.head()
message = "What are the side effects of doxycycline for treating Acne?"
results = table.search(embed(message)).limit(5).to_pandas()
print(results.head())
message = "What are the side effects of doxycycline for treating Acne?"
results = table.search(embed(message)).limit(5).to_pandas()
print(results.head())
# # Now let's augment our Q&A prompt with this external knowledge on-the-fly!!!
# template = """### Instruction:
# Read the below input context and respond with a short answer to the given question. Use only the information in the below input to answer the question. If you cannot answer the question, respond with "Sorry, I can't find an answer, but you might try looking in the following resource."
# ### Input:
# Context: {context}
# Question: {question}
# ### Response:
# """
# qa_prompt = PromptTemplate(
# input_variables=["context", "question"],
# template=template,
# )
# def rag_answer(message):
# # Search the for relevant context
# results = table.search(embed(message)).limit(5).to_df()
# results.sort_values(by=['_distance'], inplace=True, ascending=True)
# doc_use = results['text'].values[0]
# # Augment the prompt with the context
# prompt = qa_prompt.format(context=doc_use, question=message)
# # Get a response
# result = pg.Completion.create(
# model="Nous-Hermes-Llama2-13B",
# prompt=prompt
# )
# return result['choices'][0]['text']
# response = rag_answer("How many problems should be solved in a single patch?")
# print('')
# print("RESPONSE:", response)
# Assuming the setup for embeddings, LanceDB, and the PromptTemplate are already in place
def rag_answer_drug_side_effects(drug_name):
# Formulate a question related to drug side effects
message = f"What are the side effects of {drug_name}?"
# Search the database for relevant context
results = table.search(embed(message)).limit(5).to_pandas() # Adjust based on the correct API call
results.sort_values(by=['_distance'], inplace=True, ascending=True)
context = results['text'].iloc[0] # Use the most relevant document
# Define the prompt template
template = """### Instruction:
Read the below input context and respond with a short answer to the given question. Use only the information in the below input to answer the question. If you cannot answer the question, respond with "Sorry, I can't find an answer, but you might try looking in the following resource."
### Input:
Context: {context}
Question: {question}
### Response:
"""
# Augment the prompt with the retrieved context
prompt = template.format(context=context, question=message)
# Get a response
result = pg.Completion.create(
model="Neural-Chat-7B",
prompt = prompt
)
# # Here you would call your LLM or any other model to generate an answer based on the prompt
# # Since we cannot execute dynamic model calls in this environment, we'll simulate a response
# simulated_response = "Sorry, I can't find an answer, but you might try looking in the following resource."
return result['choices'][0]['text']
# Example usage
drug_name = "doxycycline" # Specify the drug of interest
response = rag_answer_drug_side_effects(drug_name)
print("RESPONSE:", response)
from huggingface_hub import notebook_login, Repository
from transformers import AutoModelForSequenceClassification, AutoTokenizer
notebook_login()
# # Save the model and tokenizer
# model_name_on_hub = "CiPE"
# model.save_pretrained(model_name_on_hub)
# tokenizer.save_pretrained(model_name_on_hub)
# # Push to the hub
# model.push_to_hub(model_name_on_hub)
# tokenizer.push_to_hub(model_name_on_hub) |