KalooAI commited on
Commit
2b45b01
·
verified ·
1 Parent(s): f300733

Upload RAG chatbot files

Browse files

Firest version of granite 3.0 8b

Files changed (2) hide show
  1. app.py +155 -0
  2. requirements.txt +9 -0
app.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from ibm_watsonx_ai.foundation_models import ModelInference
2
+ # from ibm_watsonx_ai.metanames import GenTextParamsMetaNames as GenParams
3
+ # from ibm_watsonx_ai.metanames import EmbedTextParamsMetaNames
4
+ # from ibm_watsonx_ai import Credentials
5
+ # from langchain_ibm import WatsonxLLM, WatsonxEmbeddings
6
+ # from langchain.text_splitter import RecursiveCharacterTextSplitter
7
+ # from langchain_text_splitters import RecursiveCharacterTextSplitter
8
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
9
+ from langchain_community.vectorstores import Chroma
10
+ from langchain_community.document_loaders import PyPDFLoader
11
+ # from langchain.chains import RetrievalQA
12
+ from langchain_classic.chains import RetrievalQA
13
+ from langchain_community.llms import HuggingFacePipeline
14
+ from langchain_community.embeddings import HuggingFaceEmbeddings
15
+ from langchain_huggingface import HuggingFacePipeline
16
+ import torch
17
+
18
+ from huggingface_hub import HfFolder
19
+ import gradio as gr
20
+
21
+ from transformers import AutoTokenizer, AutoModelForCausalLM, Pipeline, BitsAndBytesConfig
22
+
23
+ ## You can use this section to suppress warnings generated by your code:
24
+ def warn(*args, **kwargs):
25
+ pass
26
+ import warnings
27
+ warnings.warn = warn
28
+ warnings.filterwarnings('ignore')
29
+
30
+ ## LLM
31
+ # def get_llm():
32
+ # model_id = 'ibm/granite-3-2-8b-instruct'
33
+ # parameters = {
34
+ # GenParams.MAX_NEW_TOKENS: 256, # This controls the maximum number of tokens in the generated output
35
+ # GenParams.TEMPERATURE: 0.5, # This controls randomness or creativity of the model's responses
36
+ # }
37
+ # project_id = 'skills-network'
38
+ # watsonx_llm = WatsonxLLM(
39
+ # model_id = model_id,
40
+ # url="https://us-south.ml.cloud.ibm.com",
41
+ # project_id = project_id,
42
+ # params = parameters,
43
+ # )
44
+ # return watsonx_llm
45
+
46
+ def get_llm():
47
+ model_id = 'ibm-granite/granite-3.0-8b-instruct'
48
+
49
+ # Configuration for 4-bit compression
50
+ quantization_config = BitsAndBytesConfig(
51
+ load_in_4bit=True,
52
+ bnb_4bit_compute_dtype=torch.float16,
53
+ bnb_4bit_quant_type="nf4",
54
+ bnb_4bit_use_double_quant=True,
55
+ )
56
+
57
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
58
+ model = AutoModelForCausalLM.from_pretrained(
59
+ model_id,
60
+ quantization_config=quantization_config,
61
+ device_map='cpu',
62
+ torch_dtype='float32',
63
+ )
64
+
65
+ pipeline = Pipeline(
66
+ model=model,
67
+ tokenizer=tokenizer,
68
+ max_new_tokens=256,
69
+ temperature= 0.3,
70
+ do_sample= True
71
+ )
72
+
73
+ return HuggingFacePipeline(pipeline=pipeline)
74
+
75
+ ## Document loader
76
+ def document_loader(file):
77
+ loader = PyPDFLoader(file)
78
+ loaded_document = loader.load()
79
+ return loaded_document
80
+ ## Text splitter
81
+ def text_splitter(data):
82
+ text_splitter = RecursiveCharacterTextSplitter(
83
+ chunk_size = 1000,
84
+ chunk_overlap = 50,
85
+ length_function = len,
86
+ )
87
+ chuncks = text_splitter.split_documents(data)
88
+ return chuncks
89
+ ## Embedding model
90
+
91
+
92
+ # def watsonx_embedding():
93
+ # embed_params = {
94
+ # EmbedTextParamsMetaNames.TRUNCATE_INPUT_TOKENS: 256,
95
+ # EmbedTextParamsMetaNames.RETURN_OPTIONS: {'input_text': True},
96
+ # }
97
+
98
+ # watsonx_embedding = WatsonxEmbeddings(
99
+ # model_id = "ibm/slate-125m-english-rtrvr-v2",
100
+ # url="https://us-south.ml.cloud.ibm.com",
101
+ # project_id = "skills-network",
102
+ # params = embed_params,
103
+ # )
104
+ # return watsonx_embedding
105
+ def watsonx_embedding():
106
+ model_id = 'sentence-transformers/all-MiniLM-L6-v2'
107
+ embedding_model = HuggingFaceEmbeddings(model_name=model_id)
108
+ return embedding_model
109
+
110
+ ## Vector db
111
+ def vector_database(chunks):
112
+
113
+ chunks = [
114
+ c for c in chunks
115
+ if c.page_content and c.page_content.strip() and len(c.page_content.strip()) > 10
116
+ ]
117
+ embedding_model = watsonx_embedding()
118
+ vectordb = Chroma.from_documents(chunks, embedding_model)
119
+ return vectordb
120
+ ## Retriever
121
+ def retriever(file):
122
+ splits = document_loader(file)
123
+ chunks = text_splitter(splits)
124
+ vectordb = vector_database(chunks)
125
+ retriever = vectordb.as_retriever()
126
+
127
+ return retriever
128
+ ## QA Chain
129
+ def retriever_qa(file, query):
130
+ llm = get_llm()
131
+ retriever_obj = retriever(file)
132
+ qa = RetrievalQA.from_chain_type(
133
+ llm = llm,
134
+ chain_type = 'stuff',
135
+ retriever = retriever_obj,
136
+ return_source_documents = False
137
+ )
138
+ response = qa.invoke(query)
139
+ return response['result']
140
+
141
+ ## Create Gradio interface
142
+ rag_application = gr.Interface(
143
+ fn = retriever_qa,
144
+ # allow_flagging = 'never',
145
+ flagging_mode = 'never',
146
+ inputs = [
147
+ gr.File(label = 'Upload PDF File', file_count = 'single', file_types = ['.pdf'], type ='filepath'), # Drag and drop file upload
148
+ gr.Textbox(label= 'Input Query', lines = 2, placeholder = 'Type your question here...')
149
+ ],
150
+ outputs = gr.Textbox(label = 'Ouput'),
151
+ title= 'PDF QA Chatbot',
152
+ description = 'Upload a PDF document and ask any question. The chatbot will try to answer using the provided document.'
153
+ )
154
+ # Launch the app
155
+ rag_application.launch(server_name= '127.0.0.1', server_port= 7860)
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ transformers
2
+ torch
3
+ sentence-transformers
4
+ langchain
5
+ langchain-community
6
+ chromadb
7
+ pypdf
8
+ gradio
9
+ accelerate