Bandipreethamreddy commited on
Commit
da796d2
β€’
1 Parent(s): cfb4e09

Upload 4 files

Browse files
Files changed (4) hide show
  1. .env +4 -0
  2. lamagemini.py +1036 -0
  3. llama-2-7b-chat.ggmlv3.q8_0.bin +3 -0
  4. requirements.txt +9 -0
.env ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # GOOGLE_API_KEY="AIzaSyABTnz36FuTsNFgbQJXxpjPsig4PlguS-U"
2
+ #AIzaSyCfHbPRrEQRcTfPL4UXZJmuRmtbtDoM-GE
3
+ GOOGLE_API_KEY="AIzaSyBGtDA9R9qVv6fi-XaOTK4GTfsnN33Mm48"
4
+ GROQ_API_KEY="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"
lamagemini.py ADDED
@@ -0,0 +1,1036 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # from langchain.prompts import PromptTemplate
3
+ # from langchain_community.llms import CTransformers
4
+ # import streamlit as st
5
+ # from PyPDF2 import PdfReader
6
+ # from langchain.text_splitter import RecursiveCharacterTextSplitter
7
+ # import os
8
+ # from langchain_google_genai import GoogleGenerativeAIEmbeddings
9
+ # import google.generativeai as genai
10
+
11
+ # from langchain_community.vectorstores import FAISS
12
+ # from langchain_google_genai import ChatGoogleGenerativeAI
13
+ # from langchain.chains.question_answering import load_qa_chain
14
+ # from langchain.prompts import PromptTemplate
15
+ # from dotenv import load_dotenv
16
+
17
+ # load_dotenv()
18
+ # os.getenv("GOOGLE_API_KEY")
19
+ # genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
20
+
21
+
22
+
23
+
24
+ # def get_pdf_text(pdf_docs):
25
+ # text = ""
26
+ # for pdf in pdf_docs:
27
+ # pdf_reader = PdfReader(pdf)
28
+ # for page in pdf_reader.pages:
29
+ # text += page.extract_text() or ""
30
+ # return text
31
+
32
+ # def get_text_chunks(text):
33
+ # text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
34
+ # chunks = text_splitter.split_text(text)
35
+ # return chunks
36
+
37
+ # def get_vector_store(text_chunks):
38
+ # embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
39
+ # vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
40
+ # vector_store.save_local("faiss_index")
41
+
42
+ # def get_conversational_chain():
43
+ # prompt_template = """
44
+ # Answer the question as detailed as possible from the provided context, make sure to provide all the details, if the answer is not in
45
+ # provided context just say, "answer is not available in the context", don't provide the wrong answer\n\n
46
+ # Context:\n {context}?\n
47
+ # Question: \n{question}\n
48
+
49
+ # Answer:
50
+ # """
51
+ # model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
52
+ # prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
53
+ # chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
54
+ # return chain
55
+
56
+ # def getLLamaresponse(input_text, no_words, blog_style):
57
+ # llm = CTransformers(
58
+ # model='models/llama-2-7b-chat.ggmlv3.q8_0.bin',
59
+ # model_type='llama',
60
+ # config={'max_new_tokens': 256, 'temperature': 0.01}
61
+ # )
62
+
63
+ # template = """
64
+ # Explain about {input_text} for a {blog_style} blog within {no_words} words and ensure your information is accurate.
65
+ # """
66
+
67
+ # # Use PromptTemplate to format your prompt correctly
68
+ # prompt = PromptTemplate(
69
+ # input_variables=["input_text", "no_words", "blog_style"],
70
+ # template=template
71
+ # ).format(input_text=input_text, no_words=no_words, blog_style=blog_style)
72
+
73
+ # # Ensure the prompt is passed as a list
74
+ # response = llm.generate([prompt])
75
+ # return response
76
+
77
+
78
+ # def user_input(user_question):
79
+ # embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
80
+ # new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
81
+ # docs = new_db.similarity_search(user_question)
82
+
83
+ # gemini_chain = get_conversational_chain()
84
+ # gemini_response = gemini_chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
85
+ # initial_response = gemini_response["output_text"]
86
+
87
+ # if "answer is not available in the context" in initial_response:
88
+ # refined_response = getLLamaresponse(user_question, no_words=256, blog_style="detailed")
89
+ # st.write("Generated Reponse from LLaMA-2: ", refined_response)
90
+
91
+
92
+ # else:
93
+ # refined_response = getLLamaresponse(initial_response, no_words=256, blog_style="detailed")
94
+
95
+ # st.write("Refined Reply: ", refined_response)
96
+
97
+
98
+ # def main():
99
+
100
+ # st.set_page_config(page_title="Chat With AUTHOR", page_icon="πŸ“š", layout='centered')
101
+ # st.header("Enhance Understanding with Gemini and LLaMA-2 models πŸ€–")
102
+
103
+ # user_question = st.text_input("Ask a Question from the PDF Files uploaded")
104
+ # if user_question:
105
+ # user_input(user_question)
106
+
107
+ # with st.sidebar:
108
+ # st.title("Menu:")
109
+ # pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)
110
+ # if st.button("Submit & Process"):
111
+ # with st.spinner("Processing..."):
112
+ # raw_text = get_pdf_text(pdf_docs)
113
+ # text_chunks = get_text_chunks(raw_text)
114
+ # get_vector_store(text_chunks)
115
+ # st.success("Done")
116
+
117
+ # if __name__ == "__main__":
118
+ # main()
119
+ # import os
120
+ # import streamlit as st
121
+ # from PyPDF2 import PdfReader
122
+ # from langchain.text_splitter import RecursiveCharacterTextSplitter
123
+ # from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI #embeding model used for embeding the tokens
124
+ # import google.generativeai as genai
125
+ # from langchain_community.vectorstores import FAISS
126
+ # from langchain_community.llms import CTransformers
127
+ # from langchain.chains.question_answering import load_qa_chain
128
+ # from langchain.prompts import PromptTemplate
129
+ # from dotenv import load_dotenv
130
+
131
+ # load_dotenv() # this will load env variables
132
+ # google_api_key = os.getenv("GOOGLE_API_KEY")
133
+ # if not google_api_key:
134
+ # raise ValueError("Google API key not found. Please check your environment variables.")
135
+ # genai.configure(api_key=google_api_key)
136
+
137
+
138
+ # def get_pdf_text(pdf_docs):
139
+ # text = ""
140
+ # for pdf in pdf_docs:
141
+ # pdf_reader = PdfReader(pdf)
142
+ # for page in pdf_reader.pages:
143
+ # text += page.extract_text() or ""
144
+ # return text
145
+
146
+ # # Function to split text into manageable chunks
147
+ # def get_text_chunks(text):
148
+ # text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
149
+ # #using recursive text spliting we are spliting the text into the chunks.. and we mention its size and chunk over lap..
150
+ # return text_splitter.split_text(text)
151
+
152
+ # # Function to create a vector store for text chunks
153
+ # def get_vector_store(text_chunks):
154
+ # embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001") #we are using embedding-001 model from googleaiembeding
155
+ # vector_store = FAISS.from_texts(text_chunks, embedding=embeddings) #the vector data base is used for search and store mechanism
156
+ # vector_store.save_local("faiss_index")
157
+ # # facebook ai similarity search and it also stores the data into the vector
158
+
159
+ # # Function to load the conversational chain
160
+ # def get_conversational_chain():
161
+ # prompt_template = """
162
+ # Please provide a detailed answer based on the provided context. If the necessary information to answer the question is not present in the context, respond with 'The answer is not available in the context'
163
+
164
+ # Context:
165
+ # {context}
166
+
167
+ # Question:
168
+ # {question}
169
+
170
+ # Answer:
171
+ # """
172
+ # model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3) #chat google generative ai is used to get the LLM model
173
+ # prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"]) # we will give prompt to the LLm model which has both context and the User question
174
+ # x=load_qa_chain(model, chain_type="stuff", prompt=prompt)
175
+ # print(x) #load qa will generate the response from the llm model
176
+ # return x
177
+
178
+
179
+ # def get_llama_response(input_text, no_words, blog_style):
180
+ # llm = CTransformers(
181
+ # model='models/llama-2-7b-chat.ggmlv3.q8_0.bin',
182
+ # model_type='llama',
183
+ # config={'max_new_tokens': 256, 'temperature': 0.01}
184
+ # )#we use CT transformers which is langchain library to use LLama2 model in our project
185
+
186
+ # prompt_template = """
187
+ # Given some information of '{input_text}', provide a concise summary suitable for a {blog_style} blog post in approximately {no_words} words. Focus on key aspects and provide accurate information.
188
+ # """
189
+
190
+ # prompt = PromptTemplate(input_variables=["input_text", "no_words", "blog_style"], template=prompt_template)
191
+ # formatted_prompt = prompt.format(input_text=input_text, no_words=no_words, blog_style=blog_style)
192
+
193
+
194
+ # print("Formatted Prompt:", formatted_prompt)
195
+
196
+ # response = llm.generate([formatted_prompt])
197
+
198
+
199
+ # return response
200
+
201
+
202
+ # from sklearn.feature_extraction.text import TfidfVectorizer
203
+ # from sklearn.metrics.pairwise import cosine_similarity
204
+ # import PyPDF2
205
+
206
+ # import nltk
207
+ # from nltk.corpus import stopwords
208
+
209
+ # nltk.download('stopwords')
210
+ # stop_words = stopwords.words('english')
211
+ # custom_stopwords = ["what", "is", "how", "who", "explain", "about","?","please","hey","whatsup","can u explain"]
212
+ # stop_words.extend(custom_stopwords)
213
+
214
+ # def calculate_cosine_similarity(text,user_question):
215
+ # vectorizer = TfidfVectorizer(stop_words=stop_words)
216
+
217
+ # tfidf_matrix=vectorizer.fit_transform([text,user_question])
218
+ # cos_similarity=cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]
219
+ # return cos_similarity
220
+
221
+ # # def user_input(user_question,raw_text):
222
+ # embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
223
+ # new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
224
+ # docs = new_db.similarity_search(user_question)
225
+
226
+ # gemini_chain = get_conversational_chain()
227
+ # gemini_response = gemini_chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
228
+ # initial_response = gemini_response["output_text"]
229
+ # print(initial_response)
230
+ # similarity_score = calculate_cosine_similarity(raw_text, user_question)
231
+ # st.write(similarity_score)
232
+ # if "The answer is not available in the context" or "The provided context does not contain any information" in initial_response:
233
+
234
+ # if(similarity_score>0.00125):
235
+ # refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
236
+ # st.write("Generated Response from LLaMA-2:", refined_response)
237
+ # else:
238
+ # st.write("oops I'm sorry, I cannot answer this question based on the provided context.")
239
+ # st.write("wait for more info about your question.......llama2 model is ready to give me u the iformation...")
240
+ # refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
241
+ # st.write("Generated Response from LLaMA-2:", refined_response)
242
+ # else:
243
+
244
+ # refined_response = get_llama_response(initial_response, no_words=256, blog_style="detailed")
245
+ # st.write("Refined Reply:", refined_response)
246
+ # def user_input(user_question, raw_text):
247
+ # embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
248
+ # new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
249
+ # docs = new_db.similarity_search(user_question)
250
+
251
+ # gemini_chain=get_conversational_chain()
252
+ # gemini_response=gemini_chain({"input_documents":docs, "question": user_question}, return_only_outputs=True)
253
+ # initial_response=gemini_response["output_text"]
254
+
255
+ # similarity_score=calculate_cosine_similarity(raw_text, user_question)
256
+ # st.write("Cosine similarity score: ", similarity_score)
257
+
258
+ # if "The answer is not available in the context" in initial_response or "The provided context does not contain any information" in initial_response:
259
+ # if similarity_score > 0.00125:
260
+ # refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
261
+ # st.write("Generated Response from LLaMA-2:", refined_response)
262
+ # else:
263
+ # st.write("I'm sorry, I cannot answer this question based on the provided context.")
264
+ # st.write("Waiting for more info about your question... LLaMA-2 model is preparing to provide the information...")
265
+ # refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
266
+ # st.write("Generated Response from LLaMA-2:", refined_response)
267
+ # else:
268
+ # refined_response = get_llama_response(initial_response, no_words=256, blog_style="detailed")
269
+ # st.write("Refined Reply:", refined_response)
270
+
271
+ # def main():
272
+ # st.set_page_config(page_title="Chat With AUTHOR", page_icon="πŸ“š", layout='centered')
273
+ # st.header("Enhance Understanding with Gemini and LLaMA-2 models πŸ€–")
274
+
275
+ # user_question = st.text_input("Ask a Question from the PDF Files uploaded")
276
+
277
+ # with st.sidebar:
278
+ # st.title("Menu:")
279
+ # pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)
280
+ # if st.button("Submit & Process"):
281
+ # with st.spinner("Processing..."):
282
+ # raw_text = get_pdf_text(pdf_docs)
283
+ # text_chunks = get_text_chunks(raw_text)
284
+ # get_vector_store(text_chunks)
285
+ # st.success("Done")
286
+ # if user_question:
287
+ # raw_text = get_pdf_text(pdf_docs)
288
+ # text_chunks = get_text_chunks(raw_text)
289
+ # get_vector_store(text_chunks)
290
+ # user_input(user_question,raw_text)
291
+ # if __name__ == "__main__":
292
+ # main()
293
+
294
+
295
+ # import os
296
+ # import streamlit as st
297
+ # from PyPDF2 import PdfReader
298
+ # from langchain.text_splitter import RecursiveCharacterTextSplitter
299
+ # from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
300
+ # import google.generativeai as genai
301
+ # from langchain_community.vectorstores import FAISS
302
+ # from langchain_community.llms import CTransformers
303
+ # from langchain.chains.question_answering import load_qa_chain
304
+ # from langchain.prompts import PromptTemplate
305
+ # from dotenv import load_dotenv
306
+ # import pyttsx3
307
+
308
+ # load_dotenv() # this will load env variables
309
+ # google_api_key = os.getenv("GOOGLE_API_KEY")
310
+ # if not google_api_key:
311
+ # raise ValueError("Google API key not found. Please check your environment variables.")
312
+ # genai.configure(api_key=google_api_key)
313
+
314
+ # def get_pdf_text(pdf_docs):
315
+ # text = ""
316
+ # for pdf in pdf_docs:
317
+ # pdf_reader = PdfReader(pdf)
318
+ # for page in pdf_reader.pages:
319
+ # text += page.extract_text() or ""
320
+ # return text
321
+
322
+ # # Function to split text into manageable chunks
323
+ # def get_text_chunks(text):
324
+ # text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
325
+ # return text_splitter.split_text(text)
326
+
327
+ # # Function to create a vector store for text chunks
328
+ # def get_vector_store(text_chunks):
329
+ # embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
330
+ # vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
331
+ # vector_store.save_local("faiss_index")
332
+
333
+ # # Function to load the conversational chain
334
+ # def get_conversational_chain():
335
+ # prompt_template = """
336
+ # Please provide a detailed answer based on the provided context. If the necessary information to answer the question is not present in the context, respond with 'The answer is not available in the context'
337
+
338
+ # Context:
339
+ # {context}
340
+
341
+ # Question:
342
+ # {question}
343
+
344
+ # Answer:
345
+ # """
346
+ # model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
347
+ # prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
348
+ # return load_qa_chain(model, chain_type="stuff", prompt=prompt)
349
+
350
+ # def get_llama_response(input_text, no_words, blog_style):
351
+ # llm = CTransformers(
352
+ # model='models/llama-2-7b-chat.ggmlv3.q8_0.bin',
353
+ # model_type='llama',
354
+ # config={'max_new_tokens': 256, 'temperature': 0.01}
355
+ # )
356
+ # prompt_template = """
357
+ # Given some information of '{input_text}', provide a concise summary suitable for a {blog_style} blog post in approximately {no_words} words. Focus on key aspects and provide accurate information.
358
+ # """
359
+ # prompt = PromptTemplate(input_variables=["input_text", "no_words", "blog_style"], template=prompt_template)
360
+ # formatted_prompt = prompt.format(input_text=input_text, no_words=no_words, blog_style=blog_style)
361
+
362
+ # response = llm.generate([formatted_prompt])
363
+ # return response
364
+
365
+ # from sklearn.feature_extraction.text import TfidfVectorizer
366
+ # from sklearn.metrics.pairwise import cosine_similarity
367
+ # import PyPDF2
368
+
369
+ # import nltk
370
+ # from nltk.corpus import stopwords
371
+
372
+ # nltk.download('stopwords')
373
+ # stop_words = stopwords.words('english')
374
+ # custom_stopwords = ["what", "is", "how", "who", "explain", "about", "?", "please", "hey", "whatsup", "can u explain"]
375
+ # stop_words.extend(custom_stopwords)
376
+
377
+ # def calculate_cosine_similarity(text, user_question):
378
+ # vectorizer = TfidfVectorizer(stop_words=stop_words)
379
+ # tfidf_matrix = vectorizer.fit_transform([text, user_question])
380
+ # cos_similarity = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]
381
+ # return cos_similarity
382
+
383
+ # def user_input(user_question, raw_text, engine, language):
384
+ # embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
385
+ # new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
386
+ # docs = new_db.similarity_search(user_question)
387
+
388
+ # gemini_chain = get_conversational_chain()
389
+ # gemini_response = gemini_chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
390
+ # initial_response = gemini_response["output_text"]
391
+
392
+ # similarity_score = calculate_cosine_similarity(raw_text, user_question)
393
+ # st.write("Cosine similarity score: ", similarity_score)
394
+
395
+ # if "The answer is not available in the context" in initial_response or "The provided context does not contain any information" in initial_response:
396
+ # if similarity_score > 0.00125:
397
+ # refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
398
+ # st.write("Generated Response from LLaMA-2:", refined_response)
399
+ # speak_text(engine, refined_response, language)
400
+ # else:
401
+ # st.write("I'm sorry, I cannot answer this question based on the provided context.")
402
+ # st.write("Waiting for more info about your question... LLaMA-2 model is preparing to provide the information...")
403
+ # refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
404
+ # st.write("Generated Response from LLaMA-2:", refined_response)
405
+ # speak_text(engine, refined_response, language)
406
+ # else:
407
+ # refined_response = get_llama_response(initial_response, no_words=256, blog_style="detailed")
408
+ # st.write("Refined Reply:", refined_response)
409
+ # speak_text(engine, refined_response, language)
410
+
411
+ # def speak_text(engine, text, language):
412
+ # voices = engine.getProperty('voices')
413
+ # # Select the appropriate voice based on the language
414
+ # for voice in voices:
415
+ # if language in voice.languages:
416
+ # engine.setProperty('voice', voice.id)
417
+ # break
418
+ # engine.say(text)
419
+ # engine.runAndWait()
420
+
421
+ # def stop_speech(engine):
422
+ # engine.stop()
423
+
424
+ # def main():
425
+ # st.set_page_config(page_title="Chat With AUTHOR", page_icon="πŸ“š", layout='centered')
426
+ # st.header("Enhance Understanding with Gemini and LLaMA-2 models πŸ€–")
427
+
428
+ # engine = pyttsx3.init()
429
+
430
+ # user_question = st.text_input("Ask a Question from the PDF Files uploaded")
431
+ # language = st.selectbox("Select Language", ["en", "es", "fr", "de"]) # Example languages
432
+
433
+ # with st.sidebar:
434
+ # st.title("Menu:")
435
+ # pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)
436
+ # if st.button("Submit & Process"):
437
+ # with st.spinner("Processing..."):
438
+ # raw_text = get_pdf_text(pdf_docs)
439
+ # text_chunks = get_text_chunks(raw_text)
440
+ # get_vector_store(text_chunks)
441
+ # st.success("Done")
442
+
443
+ # if user_question:
444
+ # raw_text = get_pdf_text(pdf_docs)
445
+ # text_chunks = get_text_chunks(raw_text)
446
+ # get_vector_store(text_chunks)
447
+ # user_input(user_question, raw_text, engine, language)
448
+
449
+
450
+
451
+ # if __name__ == "__main__":
452
+ # main()
453
+
454
+ # import os
455
+ # import streamlit as st
456
+ # from PyPDF2 import PdfReader
457
+ # from langchain.text_splitter import RecursiveCharacterTextSplitter
458
+ # from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
459
+ # import google.generativeai as genai
460
+ # from langchain_community.vectorstores import FAISS
461
+ # from langchain_community.llms import CTransformers
462
+ # from langchain.chains.question_answering import load_qa_chain
463
+ # from langchain.prompts import PromptTemplate
464
+ # from dotenv import load_dotenv
465
+ # import pyttsx3
466
+
467
+ # try:
468
+ # import speech_recognition as sr
469
+ # except ImportError:
470
+ # sr = None
471
+
472
+ # load_dotenv() # this will load env variables
473
+ # google_api_key = os.getenv("GOOGLE_API_KEY")
474
+ # if not google_api_key:
475
+ # raise ValueError("Google API key not found. Please check your environment variables.")
476
+ # genai.configure(api_key=google_api_key)
477
+
478
+ # def get_pdf_text(pdf_docs):
479
+ # text = ""
480
+ # for pdf in pdf_docs:
481
+ # pdf_reader = PdfReader(pdf)
482
+ # for page in pdf_reader.pages:
483
+ # text += page.extract_text() or ""
484
+ # return text
485
+
486
+ # # Function to split text into manageable chunks
487
+ # def get_text_chunks(text):
488
+ # text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
489
+ # return text_splitter.split_text(text)
490
+
491
+ # # Function to create a vector store for text chunks
492
+ # def get_vector_store(text_chunks):
493
+ # embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
494
+ # vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
495
+ # vector_store.save_local("faiss_index")
496
+
497
+ # # Function to load the conversational chain
498
+ # def get_conversational_chain():
499
+ # prompt_template = """
500
+ # Please provide a detailed answer based on the provided context. If the necessary information to answer the question is not present in the context, respond with 'The answer is not available in the context'
501
+
502
+ # Context:
503
+ # {context}
504
+
505
+ # Question:
506
+ # {question}
507
+
508
+ # Answer:
509
+ # """
510
+ # model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
511
+ # prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
512
+ # return load_qa_chain(model, chain_type="stuff", prompt=prompt)
513
+
514
+ # def get_llama_response(input_text, no_words, blog_style):
515
+ # llm = CTransformers(
516
+ # model='models/llama-2-7b-chat.ggmlv3.q8_0.bin',
517
+ # model_type='llama',
518
+ # config={'max_new_tokens': 256, 'temperature': 0.01}
519
+ # )
520
+ # prompt_template = """
521
+ # Given some information of '{input_text}', provide a concise summary suitable for a {blog_style} blog post in approximately {no_words} words. Focus on key aspects and provide accurate information.
522
+ # """
523
+ # prompt = PromptTemplate(input_variables=["input_text", "no_words", "blog_style"], template=prompt_template)
524
+ # formatted_prompt = prompt.format(input_text=input_text, no_words=no_words, blog_style=blog_style)
525
+
526
+ # response = llm.generate([formatted_prompt])
527
+ # return response
528
+
529
+ # from sklearn.feature_extraction.text import TfidfVectorizer
530
+ # from sklearn.metrics.pairwise import cosine_similarity
531
+ # import PyPDF2
532
+
533
+ # import nltk
534
+ # from nltk.corpus import stopwords
535
+
536
+ # nltk.download('stopwords')
537
+ # stop_words = stopwords.words('english')
538
+ # custom_stopwords = ["what", "is", "how", "who", "explain", "about", "?", "please", "hey", "whatsup", "can u explain"]
539
+ # stop_words.extend(custom_stopwords)
540
+
541
+ # def calculate_cosine_similarity(text, user_question):
542
+ # vectorizer = TfidfVectorizer(stop_words=stop_words)
543
+ # tfidf_matrix = vectorizer.fit_transform([text, user_question])
544
+ # cos_similarity = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]
545
+ # return cos_similarity
546
+
547
+ # def user_input(user_question, raw_text, engine, language):
548
+ # embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
549
+ # new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
550
+ # docs = new_db.similarity_search(user_question)
551
+
552
+ # gemini_chain = get_conversational_chain()
553
+ # gemini_response = gemini_chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
554
+ # initial_response = gemini_response["output_text"]
555
+
556
+ # similarity_score = calculate_cosine_similarity(raw_text, user_question)
557
+ # st.write("Cosine similarity score: ", similarity_score)
558
+
559
+ # if "The answer is not available in the context" in initial_response or "The provided context does not contain any information" in initial_response:
560
+ # if similarity_score > 0.00125:
561
+ # refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
562
+ # st.write("Generated Response from LLaMA-2:", refined_response)
563
+ # speak_text(engine, refined_response, language)
564
+ # else:
565
+ # st.write("I'm sorry, I cannot answer this question based on the provided context.")
566
+ # st.write("Waiting for more info about your question... LLaMA-2 model is preparing to provide the information...")
567
+ # refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
568
+ # st.write("Generated Response from LLaMA-2:", refined_response)
569
+ # speak_text(engine, refined_response, language)
570
+ # else:
571
+ # refined_response = get_llama_response(initial_response, no_words=256, blog_style="detailed")
572
+ # st.write("Refined Reply:", refined_response)
573
+ # speak_text(engine, refined_response, language)
574
+
575
+ # def speak_text(engine, text, language):
576
+ # voices = engine.getProperty('voices')
577
+ # # Select the appropriate voice based on the language
578
+ # for voice in voices:
579
+ # if language in voice.languages:
580
+ # engine.setProperty('voice', voice.id)
581
+ # break
582
+ # engine.say(text)
583
+ # engine.runAndWait()
584
+
585
+ # def stop_speech(engine):
586
+ # engine.stop()
587
+
588
+ # def main():
589
+ # st.set_page_config(page_title="Chat With AUTHOR", page_icon="πŸ“š", layout='centered')
590
+ # st.header("Enhance Understanding with Gemini and LLaMA-2 models πŸ€–")
591
+
592
+ # engine = pyttsx3.init()
593
+
594
+ # user_question = st.text_input("Ask a Question from the PDF Files uploaded")
595
+ # language = st.selectbox("Select Language", ["en", "es", "fr", "de"]) # Example languages
596
+
597
+ # with st.sidebar:
598
+ # st.title("Menu:")
599
+ # pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)
600
+ # if st.button("Submit & Process"):
601
+ # with st.spinner("Processing..."):
602
+ # raw_text = get_pdf_text(pdf_docs)
603
+ # text_chunks = get_text_chunks(raw_text)
604
+ # get_vector_store(text_chunks)
605
+ # st.success("Done")
606
+
607
+ # if sr and st.button("Use Voice Input to Query"):
608
+ # recognizer = sr.Recognizer()
609
+ # with sr.Microphone() as source:
610
+ # # st.write("Listening...")
611
+ # audio = recognizer.listen(source)
612
+ # if(audio==true){
613
+ # st.write("listening")
614
+ # }else{
615
+ # st.write("")
616
+ # }
617
+ # try:
618
+ # user_question = recognizer.recognize_google(audio)
619
+
620
+ # st.write(f"You said: {user_question}")
621
+ # except sr.UnknownValueError:
622
+ # st.write("Sorry, I could not understand your speech.")
623
+ # except sr.RequestError:
624
+ # st.write("Could not request results; check your network connection.")
625
+ # elif not sr:
626
+ # st.write("Speech recognition module not available. Please install it to use voice input.")
627
+
628
+ # if user_question:
629
+ # raw_text = get_pdf_text(pdf_docs)
630
+ # text_chunks = get_text_chunks(raw_text)
631
+ # get_vector_store(text_chunks)
632
+ # user_input(user_question, raw_text, engine, language)
633
+
634
+ # if __name__ == "__main__":
635
+ # main()
636
+
637
+
638
+
639
+ # import os
640
+ # import streamlit as st
641
+ # from PyPDF2 import PdfReader
642
+ # from langchain.text_splitter import RecursiveCharacterTextSplitter
643
+ # from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
644
+ # import google.generativeai as genai
645
+ # from langchain_community.vectorstores import FAISS
646
+ # from langchain.chains.question_answering import load_qa_chain
647
+ # from langchain.prompts import PromptTemplate
648
+ # from dotenv import load_dotenv
649
+ # from gtts import gTTS
650
+ # import speech_recognition as sr
651
+ # import pyttsx3
652
+ # import tempfile
653
+ # from sklearn.feature_extraction.text import TfidfVectorizer
654
+ # from sklearn.metrics.pairwise import cosine_similarity
655
+ # import nltk
656
+ # from nltk.corpus import stopwords
657
+ # from langchain_community.llms import CTransformers
658
+
659
+ # # Load environment variables
660
+ # load_dotenv()
661
+ # google_api_key = os.getenv("GOOGLE_API_KEY")
662
+ # if not google_api_key:
663
+ # raise ValueError("Google API key not found. Please check your environment variables.")
664
+ # genai.configure(api_key=google_api_key)
665
+
666
+ # # Download stopwords
667
+ # nltk.download('stopwords')
668
+ # stop_words = stopwords.words('english')
669
+ # custom_stopwords = ["what", "is", "how", "who", "explain", "about", "?", "please", "hey", "whatsup", "can u explain"]
670
+ # stop_words.extend(custom_stopwords)
671
+
672
+ # def get_pdf_text(pdf_docs):
673
+ # text = ""
674
+ # for pdf in pdf_docs:
675
+ # pdf_reader = PdfReader(pdf)
676
+ # for page in pdf_reader.pages:
677
+ # text += page.extract_text() or ""
678
+ # return text
679
+
680
+ # def get_text_chunks(text):
681
+ # text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
682
+ # return text_splitter.split_text(text)
683
+
684
+ # def get_vector_store(text_chunks):
685
+ # try:
686
+ # embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
687
+ # vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
688
+ # vector_store.save_local("faiss_index")
689
+ # except Exception as e:
690
+ # st.error(f"Error during embedding: {e}")
691
+
692
+ # def get_conversational_chain():
693
+ # prompt_template = """
694
+ # Please provide a detailed answer based on the provided context. If the necessary information to answer the question is not present in the context, respond with 'The answer is not available in the context'
695
+
696
+ # Context:
697
+ # {context}
698
+
699
+ # Question:
700
+ # {question}
701
+
702
+ # Answer:
703
+ # """
704
+ # model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
705
+ # prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
706
+ # return load_qa_chain(model, chain_type="stuff", prompt=prompt)
707
+
708
+ # def get_llama_response(input_text, no_words, blog_style):
709
+ # llm = CTransformers(
710
+ # model='models/llama-2-7b-chat.ggmlv3.q8_0.bin',
711
+ # model_type='llama',
712
+ # config={'max_new_tokens': 256, 'temperature': 0.01}
713
+ # )
714
+ # prompt_template = """
715
+ # Given some information of '{input_text}', provide a concise summary suitable for a {blog_style} blog post in approximately {no_words} words explain me in telugu language i mean cob=nvert it to telugu. Focus on key aspects and provide accurate information.
716
+ # """
717
+ # prompt=PromptTemplate(input_variables=["input_text", "no_words", "blog_style"], template=prompt_template)
718
+ # formatted_prompt = prompt.format(input_text=input_text, no_words=no_words, blog_style=blog_style)
719
+
720
+ # response = llm.generate([formatted_prompt])
721
+ # return response
722
+
723
+ # def calculate_cosine_similarity(text, user_question):
724
+ # vectorizer = TfidfVectorizer(stop_words=list(stop_words))
725
+ # tfidf_matrix = vectorizer.fit_transform([text, user_question])
726
+ # cos_similarity = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]
727
+ # return cos_similarity
728
+
729
+ # def user_input(user_question, raw_text, engine, language):
730
+ # try:
731
+ # embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
732
+ # new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
733
+ # docs = new_db.similarity_search(user_question)
734
+
735
+ # gemini_chain = get_conversational_chain()
736
+ # gemini_response = gemini_chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
737
+ # initial_response = gemini_response["output_text"]
738
+ # except Exception as e:
739
+ # st.error(f"Error during question answering: {e}")
740
+ # initial_response = "The provided context does not contain any information"
741
+
742
+ # similarity_score = calculate_cosine_similarity(raw_text, user_question)
743
+ # st.write("Cosine similarity score: ", similarity_score)
744
+
745
+ # if "The answer is not available in the context" in initial_response or "The provided context does not contain any information" in initial_response:
746
+ # if similarity_score > 0.00125:
747
+ # refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
748
+ # st.write("Generated Response from LLaMA-2:", refined_response)
749
+ # speak_text(engine, refined_response, language)
750
+ # else:
751
+ # st.write("I'm sorry, I cannot answer this question based on the provided context.")
752
+ # st.write("Waiting for more info about your question... LLaMA-2 model is preparing to provide the information...")
753
+ # refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
754
+ # st.write("Generated Response from LLaMA-2:", refined_response)
755
+ # speak_text(engine, refined_response, language)
756
+ # else:
757
+ # refined_response = get_llama_response(initial_response, no_words=256, blog_style="detailed")
758
+ # st.write("Refined Reply:", refined_response)
759
+ # speak_text(engine, refined_response, language)
760
+
761
+ # def speak_text(engine, text, language):
762
+ # try:
763
+ # if language == 'en':
764
+ # # Use pyttsx3 for English
765
+ # engine.say(text)
766
+ # engine.runAndWait()
767
+ # else:
768
+ # # Use gTTS for other languages
769
+ # with tempfile.NamedTemporaryFile(delete=True) as fp:
770
+ # tts = gTTS(text=text, lang=language)
771
+ # tts.save(fp.name)
772
+ # os.system(f"start {fp.name}")
773
+ # except Exception as e:
774
+ # st.error(f"Error occurred during text-to-speech: {e}")
775
+
776
+ # def stop_speech(engine):
777
+ # engine.stop()
778
+
779
+ # def main():
780
+ # st.set_page_config(page_title="Chat With AUTHOR", page_icon="πŸ“š", layout='centered')
781
+ # st.header("Enhance Understanding with Gemini and LLaMA-2 models πŸ€–")
782
+
783
+ # engine = pyttsx3.init()
784
+
785
+ # user_question = st.text_input("Ask a Question from the PDF Files uploaded")
786
+ # language = st.selectbox("Select Language", ["en", "es", "fr", "de", "te"]) # Example languages, including Telugu (te)
787
+
788
+ # if st.button("Use Voice Input to Query"):
789
+ # recognizer = sr.Recognizer()
790
+ # with sr.Microphone() as source:
791
+ # st.write("Listening...")
792
+ # audio = recognizer.listen(source)
793
+ # st.write("Listening stopped")
794
+ # try:
795
+ # user_question = recognizer.recognize_google(audio)
796
+ # st.write(f"You said: {user_question}")
797
+ # except sr.UnknownValueError:
798
+ # st.write("Sorry, I could not understand your speech.")
799
+ # except sr.RequestError:
800
+ # st.write("Could not request results; check your network connection.")
801
+
802
+ # with st.sidebar:
803
+ # st.title("Menu:")
804
+ # pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)
805
+ # if st.button("Submit & Process"):
806
+ # with st.spinner("Processing..."):
807
+ # raw_text = get_pdf_text(pdf_docs)
808
+ # text_chunks = get_text_chunks(raw_text)
809
+ # get_vector_store(text_chunks)
810
+ # st.success("Done")
811
+
812
+ # if user_question:
813
+ # raw_text = get_pdf_text(pdf_docs)
814
+ # text_chunks = get_text_chunks(raw_text)
815
+ # get_vector_store(text_chunks)
816
+ # user_input(user_question, raw_text, engine, language)
817
+
818
+ # if __name__ == "__main__":
819
+ # main()
820
+
821
+
822
+ import os
823
+ import streamlit as st
824
+ from PyPDF2 import PdfReader
825
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
826
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
827
+ import google.generativeai as genai
828
+ from langchain_community.vectorstores import FAISS
829
+ from langchain.chains.question_answering import load_qa_chain
830
+ from langchain.prompts import PromptTemplate
831
+ from dotenv import load_dotenv
832
+ from gtts import gTTS
833
+ import speech_recognition as sr
834
+ import pyttsx3
835
+ import tempfile
836
+ from sklearn.feature_extraction.text import TfidfVectorizer
837
+ from sklearn.metrics.pairwise import cosine_similarity
838
+ import nltk
839
+ from nltk.corpus import stopwords
840
+ from langchain_community.llms import CTransformers
841
+ from googletrans import Translator
842
+
843
+ # Load environment variables
844
+ load_dotenv()
845
+ google_api_key = os.getenv("GOOGLE_API_KEY")
846
+ if not google_api_key:
847
+ raise ValueError("Google API key not found. Please check your environment variables.")
848
+ genai.configure(api_key=google_api_key)
849
+
850
+ # Download stopwords
851
+ nltk.download('stopwords')
852
+ stop_words = stopwords.words('english')
853
+ custom_stopwords = ["what", "is", "how", "who", "explain", "about", "?", "please", "hey", "whatsup", "can u explain"]
854
+ stop_words.extend(custom_stopwords)
855
+
856
+ def get_pdf_text(pdf_docs):
857
+ text = ""
858
+ for pdf in pdf_docs:
859
+ pdf_reader = PdfReader(pdf)
860
+ for page in pdf_reader.pages:
861
+ text += page.extract_text() or ""
862
+ return text
863
+
864
+ def get_text_chunks(text):
865
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
866
+ return text_splitter.split_text(text)
867
+
868
+ def get_vector_store(text_chunks):
869
+ try:
870
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
871
+ vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
872
+ vector_store.save_local("faiss_index")
873
+ except Exception as e:
874
+ st.error(f"Error during embedding: {e}")
875
+
876
+ def get_conversational_chain():
877
+ prompt_template = """
878
+ Please provide a detailed answer based on the provided context. If the necessary information to answer the question is not present in the context, respond with 'The answer is not available in the context'
879
+
880
+ Context:
881
+ {context}
882
+
883
+ Question:
884
+ {question}
885
+
886
+ Answer:
887
+ """
888
+ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
889
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
890
+ return load_qa_chain(model, chain_type="stuff", prompt=prompt)
891
+
892
+ def get_llama_response(input_text, no_words, blog_style, response_language):
893
+ llm = CTransformers(
894
+ model='models/llama-2-7b-chat.ggmlv3.q8_0.bin',
895
+ model_type='llama',
896
+ config={'max_new_tokens': 500, 'temperature': 0.01}
897
+ )
898
+ template = """
899
+ Given some information of '{input_text}', provide a concise summary suitable for a {blog_style} blog post in approximately {no_words} words. The total response should be in {response_language} language. Focus on key aspects and provide accurate information.
900
+ """
901
+
902
+ prompt = PromptTemplate(input_variables=["blog_style", "input_text", 'no_words', 'response_language'],
903
+ template=template)
904
+
905
+ response = llm(prompt.format(input_text=input_text, no_words=no_words, blog_style=blog_style, response_language=response_language))
906
+ return response
907
+
908
+ def calculate_cosine_similarity(text, user_question):
909
+ vectorizer = TfidfVectorizer(stop_words=list(stop_words))
910
+ tfidf_matrix = vectorizer.fit_transform([text, user_question])
911
+ cos_similarity = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]
912
+ return cos_similarity
913
+
914
+ def translate_text(text, dest_language):
915
+ translator = Translator()
916
+ translation = translator.translate(text, dest=dest_language)
917
+ return translation.text
918
+
919
+ def user_input(user_question, raw_text, response_language):
920
+ try:
921
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
922
+ new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
923
+ docs = new_db.similarity_search(user_question)
924
+
925
+ gemini_chain = get_conversational_chain()
926
+ gemini_response = gemini_chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
927
+ initial_response = gemini_response["output_text"]
928
+ except Exception as e:
929
+ # st.error(f"Error during question answering: {e}")
930
+ initial_response = "The provided context does not contain any information"
931
+
932
+ similarity_score = calculate_cosine_similarity(raw_text, user_question)
933
+ st.write("Cosine similarity score: ", similarity_score)
934
+
935
+ if "The answer is not available in the context" in initial_response or "The provided context does not contain any information" in initial_response:
936
+ if similarity_score > 0.00125:
937
+ refined_response = get_llama_response(user_question, no_words=500, blog_style="detailed", response_language="english")
938
+ else:
939
+ refined_response = "I'm sorry, I cannot answer this question based on the provided context."
940
+ else:
941
+ refined_response = get_llama_response(initial_response, no_words=500, blog_style="detailed", response_language="english")
942
+
943
+ translated_response = translate_text(refined_response, response_language)
944
+ st.write("Generated Response:", translated_response)
945
+
946
+ st.session_state.refined_response = translated_response
947
+
948
+ # def speak_text(engine, text, language):
949
+ # try:
950
+ # if language == 'en':
951
+ # # Use pyttsx3 for English
952
+ # engine.say(text)
953
+ # engine.runAndWait()
954
+ # else:
955
+ # # Use gTTS for other languages
956
+ # with tempfile.NamedTemporaryFile(delete=True) as fp:
957
+ # tts = gTTS(text=text, lang=language)
958
+ # tts.save(fp.name)
959
+ # os.system(f"start {fp.name}")
960
+ # except Exception as e:
961
+ # st.error(f"Error occurred during text-to-speech: {e}")
962
+ # import os
963
+ # import tempfile
964
+ # import pyttsx3
965
+ # from gtts import gTTS
966
+ # from pydub import AudioSegment
967
+ # from pydub.playback import play
968
+
969
+ # def speak_text(engine, text, language):
970
+ # if language == 'en':
971
+ # # Use pyttsx3 for English
972
+ # engine.say(text)
973
+ # engine.runAndWait()
974
+ # else:
975
+ # # Use gTTS for other languages
976
+ # tts = gTTS(text=text, lang=language)
977
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
978
+ # tts.save(fp.name)
979
+ # # Use Pydub to play the audio
980
+ # audio = AudioSegment.from_file(fp.name)
981
+ # play(audio)
982
+ # os.remove(fp.name)
983
+
984
+ # Example usage
985
+ # engine = pyttsx3.init()
986
+
987
+ def stop_speech(engine):
988
+ engine.stop()
989
+
990
+ def main():
991
+ st.set_page_config(page_title="Chat With AUTHOR", page_icon="πŸ“š", layout='centered')
992
+ st.header("Enhance Understanding with Gemini and LLaMA-2 models πŸ€–")
993
+
994
+ engine = pyttsx3.init()
995
+
996
+ user_question = st.text_input("Ask a Question from the PDF Files uploaded")
997
+ if st.button("πŸŽ™"):
998
+ recognizer = sr.Recognizer()
999
+ with sr.Microphone() as source:
1000
+ st.write("Listening...")
1001
+ audio = recognizer.listen(source)
1002
+ st.write("Listening stopped")
1003
+ try:
1004
+ user_question = recognizer.recognize_google(audio)
1005
+ st.write(f"You said: {user_question}")
1006
+ except sr.UnknownValueError:
1007
+ st.write("Sorry, I could not understand your speech.")
1008
+ except sr.RequestError:
1009
+ st.write("Could not request results; check your network connection.")
1010
+
1011
+ response_language = st.selectbox("Select Response Language", ["en", "es", "fr", "de", "te"]) # Example languages, including Telugu (te)
1012
+
1013
+
1014
+
1015
+ with st.sidebar:
1016
+ st.title("Menu:")
1017
+ pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)
1018
+ if st.button("Submit & Process"):
1019
+ with st.spinner("Processing..."):
1020
+ raw_text = get_pdf_text(pdf_docs)
1021
+ text_chunks = get_text_chunks(raw_text)
1022
+ get_vector_store(text_chunks)
1023
+ st.success("Done")
1024
+
1025
+ if user_question:
1026
+ raw_text = get_pdf_text(pdf_docs)
1027
+ text_chunks = get_text_chunks(raw_text)
1028
+ get_vector_store(text_chunks)
1029
+ user_input(user_question, raw_text, response_language)
1030
+
1031
+ # if "refined_response" in st.session_state:
1032
+ # if st.button("Speak"):
1033
+ # speak_text(engine, st.session_state.translated_response, response_language)
1034
+
1035
+ if __name__ == "__main__":
1036
+ main()
llama-2-7b-chat.ggmlv3.q8_0.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3bfdde943555c78294626a6ccd40184162d066d39774bd2c98dae24943d32cc3
3
+ size 7160799872
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ google-generativeai
3
+ python-dotenv
4
+ langchain
5
+ PyPDF2
6
+ chromadb
7
+ faiss-cpu
8
+ langchain_google_genai
9
+ langchain-community