Spaces:
Runtime error
Runtime error
File size: 12,032 Bytes
1a8b103 0284c70 1a8b103 0284c70 1a8b103 0284c70 1a8b103 0284c70 1a8b103 0284c70 1a8b103 68c8d72 9f7d3b3 0284c70 1a8b103 0284c70 9f7d3b3 1a8b103 9f7d3b3 68c8d72 1a8b103 68c8d72 486c196 f005fdc 1a8b103 68c8d72 9f7d3b3 0284c70 e3a3202 0284c70 1a8b103 0284c70 e3a3202 0284c70 1a8b103 0284c70 1a8b103 0284c70 1a8b103 0284c70 1a8b103 0284c70 1a8b103 0284c70 f005fdc 486c196 1a8b103 |
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 |
# import gradio as gr
# from qdrant_client import models, QdrantClient
# from sentence_transformers import SentenceTransformer
# from PyPDF2 import PdfReader
# from langchain.text_splitter import RecursiveCharacterTextSplitter
# from langchain.callbacks.manager import CallbackManager
# from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
# # from langchain.llms import LlamaCpp
# from langchain.vectorstores import Qdrant
# from qdrant_client.http import models
# # from langchain.llms import CTransformers
# from ctransformers import AutoModelForCausalLM
# # loading the embedding model -
# encoder = SentenceTransformer('jinaai/jina-embedding-b-en-v1')
# print("embedding model loaded.............................")
# print("####################################################")
# # loading the LLM
# callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
# print("loading the LLM......................................")
# # llm = LlamaCpp(
# # model_path="TheBloke/Llama-2-7B-Chat-GGUF/llama-2-7b-chat.Q8_0.gguf",
# # n_ctx=2048,
# # f16_kv=True, # MUST set to True, otherwise you will run into problem after a couple of calls
# # callback_manager=callback_manager,
# # verbose=True,
# # )
# llm = AutoModelForCausalLM.from_pretrained("TheBloke/Llama-2-7B-Chat-GGUF",
# model_file="llama-2-7b-chat.Q8_0.gguf",
# model_type="llama",
# # config = ctransformers.hub.AutoConfig,
# # hf = True
# temperature = 0.2,
# max_new_tokens = 1024,
# stop = ['\n']
# )
# print("LLM loaded........................................")
# print("################################################################")
# def get_chunks(text):
# text_splitter = RecursiveCharacterTextSplitter(
# # seperator = "\n",
# chunk_size = 500,
# chunk_overlap = 100,
# length_function = len,
# )
# chunks = text_splitter.split_text(text)
# return chunks
# pdf_path = './100 Weird Facts About the Human Body.pdf'
# reader = PdfReader(pdf_path)
# text = ""
# num_of_pages = len(reader.pages)
# for page in range(num_of_pages):
# current_page = reader.pages[page]
# text += current_page.extract_text()
# chunks = get_chunks(text)
# print("Chunks are ready.....................................")
# print("######################################################")
# qdrant = QdrantClient(path = "./db")
# print("db created................................................")
# print("#####################################################################")
# qdrant.recreate_collection(
# collection_name="my_facts",
# vectors_config=models.VectorParams(
# size=encoder.get_sentence_embedding_dimension(), # Vector size is defined by used model
# distance=models.Distance.COSINE,
# ),
# )
# print("Collection created........................................")
# print("#########################################################")
# li = []
# for i in range(len(chunks)):
# li.append(i)
# dic = zip(li, chunks)
# dic= dict(dic)
# qdrant.upload_records(
# collection_name="my_facts",
# records=[
# models.Record(
# id=idx,
# vector=encoder.encode(dic[idx]).tolist(),
# payload= {dic[idx][:5] : dic[idx]}
# ) for idx in dic.keys()
# ],
# )
# print("Records uploaded........................................")
# print("###########################################################")
# def chat(question):
# # question = input("ask question from pdf.....")
# hits = qdrant.search(
# collection_name="my_facts",
# query_vector=encoder.encode(question).tolist(),
# limit=3
# )
# context = []
# for hit in hits:
# context.append(list(hit.payload.values())[0])
# context = context[0] + context[1] + context[2]
# system_prompt = """You are a helpful assistant, you will use the provided context to answer user questions.
# Read the given context before answering questions and think step by step. If you can not answer a user question based on
# the provided context, inform the user. Do not use any other information for answering user. Provide a detailed answer to the question."""
# B_INST, E_INST = "[INST]", "[/INST]"
# B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
# SYSTEM_PROMPT = B_SYS + system_prompt + E_SYS
# instruction = f"""
# Context: {context}
# User: {question}"""
# prompt_template = B_INST + SYSTEM_PROMPT + instruction + E_INST
# result = llm(prompt_template)
# return result
# gr.Interface(
# fn = chat,
# inputs = gr.Textbox(lines = 10, placeholder = "Enter your question here π"),
# outputs = gr.Textbox(lines = 10, placeholder = "Your answer will be here soon π"),
# title="Q&N with PDF π©π»βπ»πβπ»π‘",
# description="This app facilitates a conversation with PDFs available on https://www.delo.si/assets/media/other/20110728/100%20Weird%20Facts%20About%20the%20Human%20Body.pdfπ‘",
# theme="soft",
# examples=["Hello", "what is the speed of human nerve impulses?"],
# # cache_examples=True,
# ).launch()
import gradio as gr
from threading import Thread
from queue import SimpleQueue
from typing import Any, Dict, List, Union
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import LLMResult
from qdrant_client import models, QdrantClient
from sentence_transformers import SentenceTransformer
from PyPDF2 import PdfReader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from qdrant_client.models import PointStruct
import os
from langchain.callbacks.manager import CallbackManager
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
# from qdrant_client import QdrantClient
# from langchain import VectorDBQA - This is obsolete
from langchain.chains import RetrievalQA
from langchain.llms import LlamaCpp
# from PyPDF2 import PdfReader
from langchain.vectorstores import Qdrant
# from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import HuggingFaceBgeEmbeddings
from transformers import AutoModel
from qdrant_client.http import models
# from sentence_transformers import SentenceTransformer
from langchain.prompts import PromptTemplate
from ctransformers import AutoModelForCausalLM
# loading the embedding model -
encoder = SentenceTransformer("all-MiniLM-L6-v2")
print("embedding model loaded.............................")
print("####################################################")
# loading the LLM
callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
print("loading the LLM......................................")
# llm = LlamaCpp(
# model_path="/home/devangpagare/llm/models/llama-2-7b-chat.Q3_K_S.gguf",
# # n_gpu_layers=n_gpu_layers,
# # n_batch=n_batch,
# n_ctx=2048,
# f16_kv=True, # MUST set to True, otherwise you will run into problem after a couple of calls
# callback_manager=callback_manager,
# verbose=True,
# )
llm = AutoModelForCausalLM.from_pretrained("TheBloke/Llama-2-7B-Chat-GGUF",
model_file="llama-2-7b-chat.Q3_K_S.gguf",
model_type="llama",
# config = ctransformers.hub.AutoConfig,
# hf = True
temperature = 0.2,
# max_new_tokens = 1024,
# stop = ['\n']
)
print("LLM loaded........................................")
print("################################################################")
def get_chunks(text):
text_splitter = RecursiveCharacterTextSplitter(
# seperator = "\n",
chunk_size = 500,
chunk_overlap = 100,
length_function = len,
)
chunks = text_splitter.split_text(text)
return chunks
pdf_path = './100 Weird Facts About the Human Body.pdf'
reader = PdfReader(pdf_path)
text = ""
num_of_pages = len(reader.pages)
for page in range(num_of_pages):
current_page = reader.pages[page]
text += current_page.extract_text()
chunks = get_chunks(text)
print(chunks)
print("Chunks are ready.....................................")
print("######################################################")
qdrant = QdrantClient(path = "./db")
print("db created................................................")
print("#####################################################################")
qdrant.recreate_collection(
collection_name="my_facts",
vectors_config=models.VectorParams(
size=encoder.get_sentence_embedding_dimension(), # Vector size is defined by used model
distance=models.Distance.COSINE,
),
)
print("Collection created........................................")
print("#########################################################")
# starting a list of same size as chunks
li = []
for i in range(len(chunks)):
li.append(i)
# concantinating the li and chunks to create a dcitionary
dic = zip(li, chunks)
dic= dict(dic)
qdrant.upload_records(
collection_name="my_facts",
records=[
models.Record(
id=idx,
vector=encoder.encode(dic[idx]).tolist(),
payload= {dic[idx][:5] : dic[idx]}
## payload is always suppose to be a dictionary with both keys and values as strings. To do this, I used first 5 chars of
## every value as key to make the payload.
) for idx in dic.keys()
],
)
print("Records uploaded........................................")
print("###########################################################")
def chat(question):
# question = input("ask question from pdf.....")
hits = qdrant.search(
collection_name="my_facts",
query_vector=encoder.encode(question).tolist(),
limit=3
)
context = []
for hit in hits:
# print(hit.payload, "score:", hit.score)
context.append(list(hit.payload.values())[0])
# context += str(hit.payload[hit.payload.values()[:5]])
# print("##################################################################")
context = context[0] + context[1] + context[2]
system_prompt = """You are a helpful assistant, you will use the provided context to answer user questions.
Read the given context before answering questions and think step by step. If you can not answer a user question based on
the provided context, inform the user. Do not use any other information for answering user. Provide a detailed answer to the question."""
B_INST, E_INST = "[INST]", "[/INST]"
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
SYSTEM_PROMPT = B_SYS + system_prompt + E_SYS
instruction = f"""
Context: {context}
User: {question}"""
prompt_template = B_INST + SYSTEM_PROMPT + instruction + E_INST
result = llm(prompt_template)
return result
gr.Interface(
fn = chat,
inputs = gr.Textbox(lines = 10, placeholder = "Enter your question here π"),
outputs = gr.Textbox(lines = 10, placeholder = "Your answer will be here soon π"),
title="Q&N with PDF π©π»βπ»πβπ»π‘",
description="This app facilitates a conversation with PDFs available on https://www.delo.si/assets/media/other/20110728/100%20Weird%20Facts%20About%20the%20Human%20Body.pdfπ‘",
theme="soft",
examples=["Hello", "what is the speed of human nerve impulses?"],
# cache_examples=True,
).launch()
|