filius-Dei commited on
Commit
5c7cb56
verified
1 Parent(s): 5f4d78c

RAG is working well as expected

Files changed (1) hide show
  1. cipe_test3.py +410 -0
cipe_test3.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """CiPE_Test3
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1oqx4e49lscGSUJGejVF43AbKWlNJf5IU
8
+ """
9
+
10
+ # Om Maa
11
+
12
+ !pip install langchain predictionguard lancedb html2text sentence-transformers PyPDF2
13
+ ! pip install huggingface_hub
14
+ ! pip install transformers
15
+ ! pip install sentencepiece
16
+
17
+
18
+
19
+ import os
20
+ import urllib.request
21
+
22
+ import html2text
23
+ import predictionguard as pg
24
+ from langchain import PromptTemplate, FewShotPromptTemplate
25
+ from langchain.text_splitter import CharacterTextSplitter
26
+ from sentence_transformers import SentenceTransformer
27
+ import numpy as np
28
+ import lancedb
29
+ from lancedb.embeddings import with_embeddings
30
+ import pandas as pd
31
+
32
+
33
+ os.environ['PREDICTIONGUARD_TOKEN'] = "q1VuOjnffJ3NO2oFN8Q9m8vghYc84ld13jaqdF7E"
34
+
35
+ # # Chaining
36
+
37
+ # template = """### Instruction:
38
+ # Decide if the following input message is an informational question, a general chat message, or a request for code generation.
39
+ # If the message is an informational question, answer it based on the informational context provided below.
40
+ # If the message is a general chat message, respond in a kind and friendly manner based on the coversation context provided below.
41
+ # If the message is a request for code generation, respond with a code snippet.
42
+
43
+ # ### Input:
44
+ # Message: {query}
45
+
46
+ # 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.
47
+
48
+ # Conversational Context:
49
+ # Human - "Hello, how are you?"
50
+ # AI - "I'm good, what can I help you with?"
51
+ # Human - "What is the captital of California?"
52
+ # AI - "Sacramento"
53
+ # Human - "Thanks!"
54
+ # AI - "You are welcome!"
55
+
56
+ # ### Response:
57
+ # """
58
+
59
+ # prompt = PromptTemplate(
60
+ # input_variables=["query"],
61
+ # template=template,
62
+ # )
63
+
64
+ # result = pg.Completion.create(
65
+ # model="Nous-Hermes-Llama2-13B",
66
+ # prompt=prompt.format(query="What is the population of LA?")
67
+ # )
68
+
69
+ # print(result['choices'][0]['text'])
70
+
71
+ # # Let's get the html off of a website.
72
+ # fp = urllib.request.urlopen("https://docs.kernel.org/process/submitting-patches.html")
73
+ # mybytes = fp.read()
74
+ # html = mybytes.decode("utf8")
75
+ # fp.close()
76
+
77
+ # # And convert it to text.
78
+ # h = html2text.HTML2Text()
79
+ # h.ignore_links = True
80
+ # text = h.handle(html)
81
+
82
+ # print(text)
83
+
84
+ from PyPDF2 import PdfReader
85
+
86
+ # Replace 'path_to_your_pdf_file.pdf' with the path to your PDF file
87
+ pdf_path = '/content/data/drug_side_effects_summary_cleaned.pdf'
88
+ reader = PdfReader(pdf_path)
89
+
90
+ # Initialize an empty string to accumulate text
91
+ text = ''
92
+
93
+ # Iterate over each page in the PDF
94
+ for page in reader.pages:
95
+ # Extract text from the page and append it to the text string
96
+ text += page.extract_text() + "\n"
97
+
98
+ # Now, `text` contains the text content of the PDF. You can print it or process it further.
99
+ print(text[:500]) # Example: print the first 500 characters to understand the structure
100
+
101
+
102
+ # from PyPDF2 import PdfReader
103
+
104
+ # # Open the PDF file
105
+ # pdf_path = '/content/data/drug_side_effects_summary_cleaned.pdf'
106
+ # reader = PdfReader(pdf_path)
107
+
108
+ # # Read each page and extract text
109
+ # text = ''
110
+ # for page in reader.pages:
111
+ # text += page.extract_text() + "\n"
112
+
113
+ # # Show the first 500 characters to understand the structure
114
+ # text[:500]
115
+
116
+ # # Clean things up just a bit.
117
+ # text = text.split("### This Page")[1]
118
+ # text = text.split("## References")[0]
119
+
120
+ # # Chunk the text into smaller pieces for injection into LLM prompts.
121
+ # text_splitter = CharacterTextSplitter(chunk_size=700, chunk_overlap=50)
122
+ # docs = text_splitter.split_text(text)
123
+
124
+ # # Let's checkout some of the chunks!
125
+ # for i in range(0, 3):
126
+ # print("Chunk", str(i+1))
127
+ # print("----------------------------")
128
+ # print(docs[i])
129
+ # print("")
130
+
131
+ import re
132
+
133
+ # Function to clean the extracted text
134
+ def clean_text(text):
135
+ # Correcting unwanted line breaks and spaces
136
+ text = re.sub(r'-\n', '', text) # Remove hyphenation
137
+ text = re.sub(r'\n', ' ', text) # Replace new lines with space
138
+ text = re.sub(r'\s+', ' ', text) # Replace multiple spaces with single space
139
+ text = text.strip() # Remove leading and trailing spaces
140
+ return text
141
+
142
+ # Clean the extracted text
143
+ cleaned_text = clean_text(text)
144
+
145
+ # Return a portion of the cleaned text to verify the cleaning
146
+ cleaned_text[:500]
147
+
148
+ # Define a function to chunk text with specified size and overlap using standard Python
149
+ def chunk_text(text, chunk_size=700, overlap=50):
150
+ chunks = []
151
+ start = 0
152
+ while start < len(text):
153
+ # If we're not at the beginning, move back 'overlap' characters for context
154
+ if start > 0:
155
+ start -= overlap
156
+ end = start + chunk_size
157
+ chunks.append(text[start:end])
158
+ start += chunk_size
159
+ return chunks
160
+
161
+ # Chunk the cleaned text into smaller pieces for LLM input
162
+ docs_alternative = chunk_text(cleaned_text, chunk_size=700, overlap=50)
163
+
164
+ # Prepare to display the first few chunks to verify the result
165
+ chunks_to_display_alt = 3
166
+ chunks_preview_alt = [docs_alternative[i] for i in range(min(len(docs_alternative), chunks_to_display_alt))]
167
+
168
+ chunks_preview_alt
169
+
170
+
171
+ # from PyPDF2 import PdfReader
172
+ # import re
173
+ # from langchain.text_splitter import CharacterTextSplitter
174
+
175
+ # # Load and clean the PDF text
176
+ # pdf_path = '/content/data/drug_side_effects_summary_cleaned.pdf'
177
+ # reader = PdfReader(pdf_path)
178
+ # text = ''
179
+ # for page in reader.pages:
180
+ # text += page.extract_text() + "\n"
181
+
182
+ # # Basic cleaning function
183
+ # def clean_text(text):
184
+ # text = re.sub(r'-\n', '', text) # Remove hyphenation
185
+ # text = re.sub(r'\n', ' ', text) # Replace new lines with space
186
+ # text = re.sub(r'\s+', ' ', text) # Replace multiple spaces with single space
187
+ # return text.strip()
188
+
189
+ # cleaned_text = clean_text(text)
190
+
191
+
192
+ # # Assuming you have specific sections to remove, adjust these lines accordingly
193
+ # # cleaned_text = cleaned_text.split("Your Start Marker")[1]
194
+ # # cleaned_text = cleaned_text.split("Your End Marker")[0]
195
+
196
+ # # Chunk the cleaned text
197
+ # chunk_size = 700 # Customize based on your LLM's token limit
198
+ # chunk_overlap = 50 # Optional overlap to maintain context between chunks
199
+ # text_splitter = CharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
200
+ # docs = text_splitter.split_text(cleaned_text)
201
+
202
+ # # Example to print the first few chunks
203
+ # for i, doc in enumerate(docs[:3]):
204
+ # print(f"Chunk {i+1}:")
205
+ # print(doc)
206
+ # print("----------------------------")
207
+
208
+
209
+
210
+
211
+ # import re
212
+
213
+ # # Split the text based on a pattern that seems to mark new entries
214
+ # # Assuming each entry starts with a numeral followed by ".", as seen in "1. This particular disease..."
215
+ # chunks = re.split(r'\n\d+\.', text)
216
+
217
+ # # Remove any leading or trailing whitespace and unwanted characters from each chunk
218
+ # chunks_cleaned = [chunk.strip().replace('\n', ' ').replace('#', '-') for chunk in chunks if chunk.strip()]
219
+
220
+ # # Show the number of chunks and the first 3 chunks as examples
221
+ # len(chunks_cleaned), chunks_cleaned[:3]
222
+
223
+ # # Let's take care of some of the formatting so it doesn't conflict with our
224
+ # # typical prompt template structure
225
+ # docs = [x.replace('#', '-') for x in docs]
226
+
227
+
228
+ # # Now we need to embed these documents and put them into a "vector store" or
229
+ # # "vector db" that we will use for semantic search and retrieval.
230
+
231
+ # # Embeddings setup
232
+ # name="all-MiniLM-L12-v2"
233
+ # model = SentenceTransformer(name)
234
+
235
+ # def embed_batch(batch):
236
+ # return [model.encode(sentence) for sentence in batch]
237
+
238
+ # def embed(sentence):
239
+ # return model.encode(sentence)
240
+
241
+ # # LanceDB setup
242
+ # os.mkdir(".lancedb")
243
+ # uri = ".lancedb"
244
+ # db = lancedb.connect(uri)
245
+
246
+ # # Create a dataframe with the chunk ids and chunks
247
+ # metadata = []
248
+ # for i in range(len(docs)):
249
+ # metadata.append([
250
+ # i,
251
+ # docs[i]
252
+ # ])
253
+ # doc_df = pd.DataFrame(metadata, columns=["chunk", "text"])
254
+
255
+ # # Embed the documents
256
+ # data = with_embeddings(embed_batch, doc_df)
257
+
258
+ # # Create the DB table and add the records.
259
+ # db.create_table("linux", data=data)
260
+ # table = db.open_table("linux")
261
+ # table.add(data=data)
262
+
263
+ # Format the chunks to avoid prompt template conflicts
264
+ chunks_preview_alt = [x.replace('#', '-') for x in chunks_preview_alt]
265
+
266
+ # Embeddings setup
267
+ name = "all-MiniLM-L12-v2"
268
+ model = SentenceTransformer(name)
269
+
270
+ # Embedding functions
271
+ def embed_batch(batch):
272
+ return [model.encode(sentence, show_progress_bar=True) for sentence in batch]
273
+
274
+ def embed(sentence):
275
+ return model.encode(sentence)
276
+
277
+ # Ensure the LanceDB directory does not exist already to avoid errors
278
+ lancedb_dir = ".lancedb"
279
+ if not os.path.exists(lancedb_dir):
280
+ os.mkdir(lancedb_dir)
281
+ uri = lancedb_dir
282
+ db = lancedb.connect(uri)
283
+
284
+ # Prepare metadata for embedding
285
+ metadata = [[i, chunks_preview_alt] for i, chunks_preview_alt in enumerate(chunks_preview_alt)]
286
+ doc_df = pd.DataFrame(metadata, columns=["chunk", "text"])
287
+
288
+ # Embed the documents
289
+ data = with_embeddings(embed_batch, doc_df)
290
+
291
+ # LanceDB operations
292
+ # if not db.has_table("pdf_data"):
293
+ db.create_table("pdf_data", data=data)
294
+ table = db.open_table("pdf_data")
295
+ table.add(data=data)
296
+
297
+ # Note: Adjust the 'create_table' and 'open_table' to match your dataset/table names
298
+
299
+ # # Let's try to match a query to one of our documents.
300
+ # message = "How many problems should be solved per patch?"
301
+ # results = table.search(embed(message)).limit(5).to_df()
302
+ # results.head()
303
+
304
+ message = "What are the side effects of doxycycline for treating Acne?"
305
+ results = table.search(embed(message)).limit(5).to_pandas()
306
+ print(results.head())
307
+
308
+
309
+ message = "What are the side effects of doxycycline for treating Acne?"
310
+ results = table.search(embed(message)).limit(5).to_pandas()
311
+ print(results.head())
312
+
313
+ # # Now let's augment our Q&A prompt with this external knowledge on-the-fly!!!
314
+ # template = """### Instruction:
315
+ # 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."
316
+
317
+ # ### Input:
318
+ # Context: {context}
319
+
320
+ # Question: {question}
321
+
322
+ # ### Response:
323
+ # """
324
+ # qa_prompt = PromptTemplate(
325
+ # input_variables=["context", "question"],
326
+ # template=template,
327
+ # )
328
+
329
+ # def rag_answer(message):
330
+
331
+ # # Search the for relevant context
332
+ # results = table.search(embed(message)).limit(5).to_df()
333
+ # results.sort_values(by=['_distance'], inplace=True, ascending=True)
334
+ # doc_use = results['text'].values[0]
335
+
336
+ # # Augment the prompt with the context
337
+ # prompt = qa_prompt.format(context=doc_use, question=message)
338
+
339
+ # # Get a response
340
+ # result = pg.Completion.create(
341
+ # model="Nous-Hermes-Llama2-13B",
342
+ # prompt=prompt
343
+ # )
344
+
345
+ # return result['choices'][0]['text']
346
+
347
+ # response = rag_answer("How many problems should be solved in a single patch?")
348
+
349
+ # print('')
350
+ # print("RESPONSE:", response)
351
+
352
+
353
+
354
+ # Assuming the setup for embeddings, LanceDB, and the PromptTemplate are already in place
355
+
356
+ def rag_answer_drug_side_effects(drug_name):
357
+ # Formulate a question related to drug side effects
358
+ message = f"What are the side effects of {drug_name}?"
359
+
360
+ # Search the database for relevant context
361
+ results = table.search(embed(message)).limit(5).to_pandas() # Adjust based on the correct API call
362
+ results.sort_values(by=['_distance'], inplace=True, ascending=True)
363
+ context = results['text'].iloc[0] # Use the most relevant document
364
+
365
+ # Define the prompt template
366
+ template = """### Instruction:
367
+ 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."
368
+
369
+ ### Input:
370
+ Context: {context}
371
+
372
+ Question: {question}
373
+
374
+ ### Response:
375
+ """
376
+
377
+ # Augment the prompt with the retrieved context
378
+ prompt = template.format(context=context, question=message)
379
+
380
+ # Get a response
381
+ result = pg.Completion.create(
382
+ model="Neural-Chat-7B",
383
+ prompt = prompt
384
+ )
385
+
386
+ # # Here you would call your LLM or any other model to generate an answer based on the prompt
387
+ # # Since we cannot execute dynamic model calls in this environment, we'll simulate a response
388
+ # simulated_response = "Sorry, I can't find an answer, but you might try looking in the following resource."
389
+
390
+ return result['choices'][0]['text']
391
+
392
+ # Example usage
393
+ drug_name = "doxycycline" # Specify the drug of interest
394
+ response = rag_answer_drug_side_effects(drug_name)
395
+
396
+ print("RESPONSE:", response)
397
+
398
+ from huggingface_hub import notebook_login, Repository
399
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
400
+
401
+ notebook_login()
402
+
403
+ # # Save the model and tokenizer
404
+ # model_name_on_hub = "CiPE"
405
+ # model.save_pretrained(model_name_on_hub)
406
+ # tokenizer.save_pretrained(model_name_on_hub)
407
+
408
+ # # Push to the hub
409
+ # model.push_to_hub(model_name_on_hub)
410
+ # tokenizer.push_to_hub(model_name_on_hub)