File size: 45,892 Bytes
97b1658
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037

# from langchain.prompts import PromptTemplate
# from langchain_community.llms import CTransformers
# import streamlit as st
# from PyPDF2 import PdfReader
# from langchain.text_splitter import RecursiveCharacterTextSplitter
# import os
# from langchain_google_genai import GoogleGenerativeAIEmbeddings
# import google.generativeai as genai

# from langchain_community.vectorstores import FAISS
# from langchain_google_genai import ChatGoogleGenerativeAI
# from langchain.chains.question_answering import load_qa_chain
# from langchain.prompts import PromptTemplate
# from dotenv import load_dotenv

# load_dotenv()
# os.getenv("GOOGLE_API_KEY")
# genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))




# def get_pdf_text(pdf_docs):
#     text = ""  
#     for pdf in pdf_docs:
#         pdf_reader = PdfReader(pdf)
#         for page in pdf_reader.pages:
#             text += page.extract_text() or ""
#     return text

# def get_text_chunks(text):
#     text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
#     chunks = text_splitter.split_text(text)
#     return chunks

# def get_vector_store(text_chunks):
#     embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
#     vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
#     vector_store.save_local("faiss_index")

# def get_conversational_chain():
#     prompt_template = """
#         Answer the question as detailed as possible from the provided context, make sure to provide all the details, if the answer is not in
#         provided context just say, "answer is not available in the context", don't provide the wrong answer\n\n
#         Context:\n {context}?\n
#         Question: \n{question}\n

#         Answer:
#     """
#     model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
#     prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
#     chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
#     return chain

# def getLLamaresponse(input_text, no_words, blog_style):
#     llm = CTransformers(
#         model='models/llama-2-7b-chat.ggmlv3.q8_0.bin',
#         model_type='llama',
#         config={'max_new_tokens': 256, 'temperature': 0.01}
#     )

#     template = """
#         Explain about {input_text} for a {blog_style} blog within {no_words} words and ensure your information is accurate.
#     """

#     # Use PromptTemplate to format your prompt correctly
#     prompt = PromptTemplate(
#         input_variables=["input_text", "no_words", "blog_style"],
#         template=template
#     ).format(input_text=input_text, no_words=no_words, blog_style=blog_style)

#     # Ensure the prompt is passed as a list
#     response = llm.generate([prompt])
#     return response


# def user_input(user_question):
#     embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
#     new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
#     docs = new_db.similarity_search(user_question)

#     gemini_chain = get_conversational_chain()
#     gemini_response = gemini_chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
#     initial_response = gemini_response["output_text"]
    
#     if "answer is not available in the context" in initial_response:
#             refined_response = getLLamaresponse(user_question, no_words=256, blog_style="detailed")
#             st.write("Generated Reponse from LLaMA-2: ", refined_response)
    
     
#     else:
#         refined_response = getLLamaresponse(initial_response, no_words=256, blog_style="detailed")
       
#         st.write("Refined Reply: ", refined_response)


# def main():
    
#     st.set_page_config(page_title="Chat With AUTHOR", page_icon="πŸ“š", layout='centered')
#     st.header("Enhance Understanding with Gemini and LLaMA-2 models πŸ€–")

#     user_question = st.text_input("Ask a Question from the PDF Files uploaded")
#     if user_question:
#         user_input(user_question)

#     with st.sidebar:
#         st.title("Menu:")
#         pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)
#         if st.button("Submit & Process"):
#             with st.spinner("Processing..."):
#                 raw_text = get_pdf_text(pdf_docs)
#                 text_chunks = get_text_chunks(raw_text)
#                 get_vector_store(text_chunks)
#                 st.success("Done")

# if __name__ == "__main__":
#     main()
# import os
# import streamlit as st
# from PyPDF2 import PdfReader
# from langchain.text_splitter import RecursiveCharacterTextSplitter
# from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI #embeding model used for embeding the tokens
# import google.generativeai as genai
# from langchain_community.vectorstores import FAISS
# from langchain_community.llms import CTransformers
# from langchain.chains.question_answering import load_qa_chain
# from langchain.prompts import PromptTemplate
# from dotenv import load_dotenv

# load_dotenv() # this will load env variables
# google_api_key = os.getenv("GOOGLE_API_KEY")
# if not google_api_key:
#     raise ValueError("Google API key not found. Please check your environment variables.")
# genai.configure(api_key=google_api_key)


# def get_pdf_text(pdf_docs):
#     text = ""
#     for pdf in pdf_docs:
#         pdf_reader = PdfReader(pdf)
#         for page in pdf_reader.pages:
#             text += page.extract_text() or ""
#     return text

# # Function to split text into manageable chunks
# def get_text_chunks(text):
#     text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
#     #using recursive text spliting we are spliting the text into the chunks.. and we mention its size and chunk over lap.. 
#     return text_splitter.split_text(text)

# # Function to create a vector store for text chunks
# def get_vector_store(text_chunks):
#     embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001") #we are using embedding-001 model from googleaiembeding
#     vector_store = FAISS.from_texts(text_chunks, embedding=embeddings) #the vector data base is used for search and store mechanism 
#     vector_store.save_local("faiss_index")
# # facebook ai similarity search  and it also stores the data into the vector 

# # Function to load the conversational chain
# def get_conversational_chain():
#     prompt_template = """
#     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'
    
#     Context:
#     {context}
    
#     Question:
#     {question}
    
#     Answer:
#     """
#     model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3) #chat google generative ai is used to get the LLM model
#     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
#     x=load_qa_chain(model, chain_type="stuff", prompt=prompt)
#     print(x) #load qa will generate the response from the llm model
#     return x


# def get_llama_response(input_text, no_words, blog_style):
#     llm = CTransformers(
#         model='models/llama-2-7b-chat.ggmlv3.q8_0.bin',
#         model_type='llama',
#         config={'max_new_tokens': 256, 'temperature': 0.01}
#     )#we use CT transformers which is langchain library to use LLama2 model in our project
    
#     prompt_template = """
#     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.
#     """
    
#     prompt = PromptTemplate(input_variables=["input_text", "no_words", "blog_style"], template=prompt_template)
#     formatted_prompt = prompt.format(input_text=input_text, no_words=no_words, blog_style=blog_style)
 

#     print("Formatted Prompt:", formatted_prompt)
    
#     response = llm.generate([formatted_prompt])
    
    
#     return response


# from sklearn.feature_extraction.text import TfidfVectorizer
# from sklearn.metrics.pairwise import cosine_similarity
# import PyPDF2

# import nltk
# from nltk.corpus import stopwords

# nltk.download('stopwords')
# stop_words = stopwords.words('english')
# custom_stopwords = ["what", "is", "how", "who", "explain", "about","?","please","hey","whatsup","can u explain"] 
# stop_words.extend(custom_stopwords)

# def calculate_cosine_similarity(text,user_question):
#     vectorizer = TfidfVectorizer(stop_words=stop_words) 

#     tfidf_matrix=vectorizer.fit_transform([text,user_question])
#     cos_similarity=cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]
#     return cos_similarity

# # def user_input(user_question,raw_text):
#     embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
#     new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
#     docs = new_db.similarity_search(user_question)
    
#     gemini_chain = get_conversational_chain()
#     gemini_response = gemini_chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
#     initial_response = gemini_response["output_text"]
#     print(initial_response)
#     similarity_score = calculate_cosine_similarity(raw_text, user_question)
#     st.write(similarity_score)
#     if "The answer is not available in the context" or "The provided context does not contain any information" in initial_response:
        
#         if(similarity_score>0.00125):
#             refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
#             st.write("Generated Response from LLaMA-2:", refined_response)
#         else:
#             st.write("oops I'm sorry, I cannot answer this question based on the provided context.")
#             st.write("wait for more info about your question.......llama2 model is ready to give me u the iformation...")
#             refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
#             st.write("Generated Response from LLaMA-2:", refined_response)
#     else:
        
#         refined_response = get_llama_response(initial_response, no_words=256, blog_style="detailed")
#         st.write("Refined Reply:", refined_response)
# def user_input(user_question, raw_text):
#     embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
#     new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
#     docs = new_db.similarity_search(user_question)
    
#     gemini_chain=get_conversational_chain()
#     gemini_response=gemini_chain({"input_documents":docs, "question": user_question}, return_only_outputs=True)
#     initial_response=gemini_response["output_text"]
    
#     similarity_score=calculate_cosine_similarity(raw_text, user_question)
#     st.write("Cosine similarity score: ", similarity_score)
    
#     if "The answer is not available in the context" in initial_response or "The provided context does not contain any information" in initial_response:
#         if similarity_score > 0.00125:
#             refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
#             st.write("Generated Response from LLaMA-2:", refined_response)
#         else:
#             st.write("I'm sorry, I cannot answer this question based on the provided context.")
#             st.write("Waiting for more info about your question... LLaMA-2 model is preparing to provide the information...")
#             refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
#             st.write("Generated Response from LLaMA-2:", refined_response)
#     else:
#         refined_response = get_llama_response(initial_response, no_words=256, blog_style="detailed")
#         st.write("Refined Reply:", refined_response)

# def main():
#     st.set_page_config(page_title="Chat With AUTHOR", page_icon="πŸ“š", layout='centered')
#     st.header("Enhance Understanding with Gemini and LLaMA-2 models πŸ€–")

#     user_question = st.text_input("Ask a Question from the PDF Files uploaded")
    
#     with st.sidebar:
#         st.title("Menu:")
#         pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)
#         if st.button("Submit & Process"):
#             with st.spinner("Processing..."):
#                 raw_text = get_pdf_text(pdf_docs)
#                 text_chunks = get_text_chunks(raw_text)
#                 get_vector_store(text_chunks)
#                 st.success("Done")
#     if user_question:
#         raw_text = get_pdf_text(pdf_docs)
#         text_chunks = get_text_chunks(raw_text)
#         get_vector_store(text_chunks)
#         user_input(user_question,raw_text)
# if __name__ == "__main__":
#     main()


# import os
# import streamlit as st
# from PyPDF2 import PdfReader
# from langchain.text_splitter import RecursiveCharacterTextSplitter
# from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
# import google.generativeai as genai
# from langchain_community.vectorstores import FAISS
# from langchain_community.llms import CTransformers
# from langchain.chains.question_answering import load_qa_chain
# from langchain.prompts import PromptTemplate
# from dotenv import load_dotenv
# import pyttsx3

# load_dotenv()  # this will load env variables
# google_api_key = os.getenv("GOOGLE_API_KEY")
# if not google_api_key:
#     raise ValueError("Google API key not found. Please check your environment variables.")
# genai.configure(api_key=google_api_key)

# def get_pdf_text(pdf_docs):
#     text = ""
#     for pdf in pdf_docs:
#         pdf_reader = PdfReader(pdf)
#         for page in pdf_reader.pages:
#             text += page.extract_text() or ""
#     return text

# # Function to split text into manageable chunks
# def get_text_chunks(text):
#     text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
#     return text_splitter.split_text(text)

# # Function to create a vector store for text chunks
# def get_vector_store(text_chunks):
#     embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
#     vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
#     vector_store.save_local("faiss_index")

# # Function to load the conversational chain
# def get_conversational_chain():
#     prompt_template = """
#     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'
    
#     Context:
#     {context}
    
#     Question:
#     {question}
    
#     Answer:
#     """
#     model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
#     prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
#     return load_qa_chain(model, chain_type="stuff", prompt=prompt)

# def get_llama_response(input_text, no_words, blog_style):
#     llm = CTransformers(
#         model='models/llama-2-7b-chat.ggmlv3.q8_0.bin',
#         model_type='llama',
#         config={'max_new_tokens': 256, 'temperature': 0.01}
#     )
#     prompt_template = """
#     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.
#     """
#     prompt = PromptTemplate(input_variables=["input_text", "no_words", "blog_style"], template=prompt_template)
#     formatted_prompt = prompt.format(input_text=input_text, no_words=no_words, blog_style=blog_style)

#     response = llm.generate([formatted_prompt])
#     return response

# from sklearn.feature_extraction.text import TfidfVectorizer
# from sklearn.metrics.pairwise import cosine_similarity
# import PyPDF2

# import nltk
# from nltk.corpus import stopwords

# nltk.download('stopwords')
# stop_words = stopwords.words('english')
# custom_stopwords = ["what", "is", "how", "who", "explain", "about", "?", "please", "hey", "whatsup", "can u explain"]
# stop_words.extend(custom_stopwords)

# def calculate_cosine_similarity(text, user_question):
#     vectorizer = TfidfVectorizer(stop_words=stop_words)
#     tfidf_matrix = vectorizer.fit_transform([text, user_question])
#     cos_similarity = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]
#     return cos_similarity

# def user_input(user_question, raw_text, engine, language):
#     embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
#     new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
#     docs = new_db.similarity_search(user_question)
    
#     gemini_chain = get_conversational_chain()
#     gemini_response = gemini_chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
#     initial_response = gemini_response["output_text"]
    
#     similarity_score = calculate_cosine_similarity(raw_text, user_question)
#     st.write("Cosine similarity score: ", similarity_score)
    
#     if "The answer is not available in the context" in initial_response or "The provided context does not contain any information" in initial_response:
#         if similarity_score > 0.00125:
#             refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
#             st.write("Generated Response from LLaMA-2:", refined_response)
#             speak_text(engine, refined_response, language)
#         else:
#             st.write("I'm sorry, I cannot answer this question based on the provided context.")
#             st.write("Waiting for more info about your question... LLaMA-2 model is preparing to provide the information...")
#             refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
#             st.write("Generated Response from LLaMA-2:", refined_response)
#             speak_text(engine, refined_response, language)
#     else:
#         refined_response = get_llama_response(initial_response, no_words=256, blog_style="detailed")
#         st.write("Refined Reply:", refined_response)
#         speak_text(engine, refined_response, language)

# def speak_text(engine, text, language):
#     voices = engine.getProperty('voices')
#     # Select the appropriate voice based on the language
#     for voice in voices:
#         if language in voice.languages:
#             engine.setProperty('voice', voice.id)
#             break
#     engine.say(text)
#     engine.runAndWait()

# def stop_speech(engine):
#     engine.stop()

# def main():
#     st.set_page_config(page_title="Chat With AUTHOR", page_icon="πŸ“š", layout='centered')
#     st.header("Enhance Understanding with Gemini and LLaMA-2 models πŸ€–")

#     engine = pyttsx3.init()

#     user_question = st.text_input("Ask a Question from the PDF Files uploaded")
#     language = st.selectbox("Select Language", ["en", "es", "fr", "de"])  # Example languages

#     with st.sidebar:
#         st.title("Menu:")
#         pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)
#         if st.button("Submit & Process"):
#             with st.spinner("Processing..."):
#                 raw_text = get_pdf_text(pdf_docs)
#                 text_chunks = get_text_chunks(raw_text)
#                 get_vector_store(text_chunks)
#                 st.success("Done")
    
#     if user_question:
#         raw_text = get_pdf_text(pdf_docs)
#         text_chunks = get_text_chunks(raw_text)
#         get_vector_store(text_chunks)
#         user_input(user_question, raw_text, engine, language)
    
 

# if __name__ == "__main__":
#     main()

# import os
# import streamlit as st
# from PyPDF2 import PdfReader
# from langchain.text_splitter import RecursiveCharacterTextSplitter
# from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
# import google.generativeai as genai
# from langchain_community.vectorstores import FAISS
# from langchain_community.llms import CTransformers
# from langchain.chains.question_answering import load_qa_chain
# from langchain.prompts import PromptTemplate
# from dotenv import load_dotenv
# import pyttsx3

# try:
#     import speech_recognition as sr
# except ImportError:
#     sr = None

# load_dotenv()  # this will load env variables
# google_api_key = os.getenv("GOOGLE_API_KEY")
# if not google_api_key:
#     raise ValueError("Google API key not found. Please check your environment variables.")
# genai.configure(api_key=google_api_key)

# def get_pdf_text(pdf_docs):
#     text = ""
#     for pdf in pdf_docs:
#         pdf_reader = PdfReader(pdf)
#         for page in pdf_reader.pages:
#             text += page.extract_text() or ""
#     return text

# # Function to split text into manageable chunks
# def get_text_chunks(text):
#     text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
#     return text_splitter.split_text(text)

# # Function to create a vector store for text chunks
# def get_vector_store(text_chunks):
#     embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
#     vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
#     vector_store.save_local("faiss_index")

# # Function to load the conversational chain
# def get_conversational_chain():
#     prompt_template = """
#     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'
    
#     Context:
#     {context}
    
#     Question:
#     {question}
    
#     Answer:
#     """
#     model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
#     prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
#     return load_qa_chain(model, chain_type="stuff", prompt=prompt)

# def get_llama_response(input_text, no_words, blog_style):
#     llm = CTransformers(
#         model='models/llama-2-7b-chat.ggmlv3.q8_0.bin',
#         model_type='llama',
#         config={'max_new_tokens': 256, 'temperature': 0.01}
#     )
#     prompt_template = """
#     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.
#     """
#     prompt = PromptTemplate(input_variables=["input_text", "no_words", "blog_style"], template=prompt_template)
#     formatted_prompt = prompt.format(input_text=input_text, no_words=no_words, blog_style=blog_style)

#     response = llm.generate([formatted_prompt])
#     return response

# from sklearn.feature_extraction.text import TfidfVectorizer
# from sklearn.metrics.pairwise import cosine_similarity
# import PyPDF2

# import nltk
# from nltk.corpus import stopwords

# nltk.download('stopwords')
# stop_words = stopwords.words('english')
# custom_stopwords = ["what", "is", "how", "who", "explain", "about", "?", "please", "hey", "whatsup", "can u explain"]
# stop_words.extend(custom_stopwords)

# def calculate_cosine_similarity(text, user_question):
#     vectorizer = TfidfVectorizer(stop_words=stop_words)
#     tfidf_matrix = vectorizer.fit_transform([text, user_question])
#     cos_similarity = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]
#     return cos_similarity

# def user_input(user_question, raw_text, engine, language):
#     embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
#     new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
#     docs = new_db.similarity_search(user_question)
    
#     gemini_chain = get_conversational_chain()
#     gemini_response = gemini_chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
#     initial_response = gemini_response["output_text"]
    
#     similarity_score = calculate_cosine_similarity(raw_text, user_question)
#     st.write("Cosine similarity score: ", similarity_score)
    
#     if "The answer is not available in the context" in initial_response or "The provided context does not contain any information" in initial_response:
#         if similarity_score > 0.00125:
#             refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
#             st.write("Generated Response from LLaMA-2:", refined_response)
#             speak_text(engine, refined_response, language)
#         else:
#             st.write("I'm sorry, I cannot answer this question based on the provided context.")
#             st.write("Waiting for more info about your question... LLaMA-2 model is preparing to provide the information...")
#             refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
#             st.write("Generated Response from LLaMA-2:", refined_response)
#             speak_text(engine, refined_response, language)
#     else:
#         refined_response = get_llama_response(initial_response, no_words=256, blog_style="detailed")
#         st.write("Refined Reply:", refined_response)
#         speak_text(engine, refined_response, language)

# def speak_text(engine, text, language):
#     voices = engine.getProperty('voices')
#     # Select the appropriate voice based on the language
#     for voice in voices:
#         if language in voice.languages:
#             engine.setProperty('voice', voice.id)
#             break
#     engine.say(text)
#     engine.runAndWait()

# def stop_speech(engine):
#     engine.stop()

# def main():
#     st.set_page_config(page_title="Chat With AUTHOR", page_icon="πŸ“š", layout='centered')
#     st.header("Enhance Understanding with Gemini and LLaMA-2 models πŸ€–")

#     engine = pyttsx3.init()

#     user_question = st.text_input("Ask a Question from the PDF Files uploaded")
#     language = st.selectbox("Select Language", ["en", "es", "fr", "de"])  # Example languages

#     with st.sidebar:
#         st.title("Menu:")
#         pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)
#         if st.button("Submit & Process"):
#             with st.spinner("Processing..."):
#                 raw_text = get_pdf_text(pdf_docs)
#                 text_chunks = get_text_chunks(raw_text)
#                 get_vector_store(text_chunks)
#                 st.success("Done")
    
#     if sr and st.button("Use Voice Input to Query"):
#         recognizer = sr.Recognizer()
#         with sr.Microphone() as source:
#             # st.write("Listening...")
#             audio = recognizer.listen(source)
#             if(audio==true){
#                 st.write("listening")
#             }else{
#                 st.write("")
#             }
#             try:
#                 user_question = recognizer.recognize_google(audio)
                
#                 st.write(f"You said: {user_question}")
#             except sr.UnknownValueError:
#                 st.write("Sorry, I could not understand your speech.")
#             except sr.RequestError:
#                 st.write("Could not request results; check your network connection.")
#     elif not sr:
#         st.write("Speech recognition module not available. Please install it to use voice input.")

#     if user_question:
#         raw_text = get_pdf_text(pdf_docs)
#         text_chunks = get_text_chunks(raw_text)
#         get_vector_store(text_chunks)
#         user_input(user_question, raw_text, engine, language)

# if __name__ == "__main__":
#     main()



# import os
# import streamlit as st
# from PyPDF2 import PdfReader
# from langchain.text_splitter import RecursiveCharacterTextSplitter
# from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
# import google.generativeai as genai
# from langchain_community.vectorstores import FAISS
# from langchain.chains.question_answering import load_qa_chain
# from langchain.prompts import PromptTemplate
# from dotenv import load_dotenv
# from gtts import gTTS
# import speech_recognition as sr
# import pyttsx3
# import tempfile
# from sklearn.feature_extraction.text import TfidfVectorizer
# from sklearn.metrics.pairwise import cosine_similarity
# import nltk
# from nltk.corpus import stopwords
# from langchain_community.llms import CTransformers

# # Load environment variables
# load_dotenv()
# google_api_key = os.getenv("GOOGLE_API_KEY")
# if not google_api_key:
#     raise ValueError("Google API key not found. Please check your environment variables.")
# genai.configure(api_key=google_api_key)

# # Download stopwords
# nltk.download('stopwords')
# stop_words = stopwords.words('english')
# custom_stopwords = ["what", "is", "how", "who", "explain", "about", "?", "please", "hey", "whatsup", "can u explain"]
# stop_words.extend(custom_stopwords)

# def get_pdf_text(pdf_docs):
#     text = ""
#     for pdf in pdf_docs:
#         pdf_reader = PdfReader(pdf)
#         for page in pdf_reader.pages:
#             text += page.extract_text() or ""
#     return text

# def get_text_chunks(text):
#     text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
#     return text_splitter.split_text(text)

# def get_vector_store(text_chunks):
#     try:
#         embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
#         vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
#         vector_store.save_local("faiss_index")
#     except Exception as e:
#         st.error(f"Error during embedding: {e}")

# def get_conversational_chain():
#     prompt_template = """
#     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'
    
#     Context:
#     {context}
    
#     Question:
#     {question}
    
#     Answer:
#     """
#     model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
#     prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
#     return load_qa_chain(model, chain_type="stuff", prompt=prompt)

# def get_llama_response(input_text, no_words, blog_style):
#     llm = CTransformers(
#         model='models/llama-2-7b-chat.ggmlv3.q8_0.bin',
#         model_type='llama',
#         config={'max_new_tokens': 256, 'temperature': 0.01}
#     )
#     prompt_template = """
#     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.
#     """
#     prompt=PromptTemplate(input_variables=["input_text", "no_words", "blog_style"], template=prompt_template)
#     formatted_prompt = prompt.format(input_text=input_text, no_words=no_words, blog_style=blog_style)

#     response = llm.generate([formatted_prompt])
#     return response

# def calculate_cosine_similarity(text, user_question):
#     vectorizer = TfidfVectorizer(stop_words=list(stop_words))
#     tfidf_matrix = vectorizer.fit_transform([text, user_question])
#     cos_similarity = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]
#     return cos_similarity

# def user_input(user_question, raw_text, engine, language):
#     try:
#         embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
#         new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
#         docs = new_db.similarity_search(user_question)
        
#         gemini_chain = get_conversational_chain()
#         gemini_response = gemini_chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
#         initial_response = gemini_response["output_text"]
#     except Exception as e:
#         st.error(f"Error during question answering: {e}")
#         initial_response = "The provided context does not contain any information"
    
#     similarity_score = calculate_cosine_similarity(raw_text, user_question)
#     st.write("Cosine similarity score: ", similarity_score)
    
#     if "The answer is not available in the context" in initial_response or "The provided context does not contain any information" in initial_response:
#         if similarity_score > 0.00125:
#             refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
#             st.write("Generated Response from LLaMA-2:", refined_response)
#             speak_text(engine, refined_response, language)
#         else:
#             st.write("I'm sorry, I cannot answer this question based on the provided context.")
#             st.write("Waiting for more info about your question... LLaMA-2 model is preparing to provide the information...")
#             refined_response = get_llama_response(user_question, no_words=256, blog_style="detailed")
#             st.write("Generated Response from LLaMA-2:", refined_response)
#             speak_text(engine, refined_response, language)
#     else:
#         refined_response = get_llama_response(initial_response, no_words=256, blog_style="detailed")
#         st.write("Refined Reply:", refined_response)
#         speak_text(engine, refined_response, language)

# def speak_text(engine, text, language):
#     try:
#         if language == 'en':
#             # Use pyttsx3 for English
#             engine.say(text)
#             engine.runAndWait()
#         else:
#             # Use gTTS for other languages
#             with tempfile.NamedTemporaryFile(delete=True) as fp:
#                 tts = gTTS(text=text, lang=language)
#                 tts.save(fp.name)
#                 os.system(f"start {fp.name}")
#     except Exception as e:
#         st.error(f"Error occurred during text-to-speech: {e}")

# def stop_speech(engine):
#     engine.stop()

# def main():
#     st.set_page_config(page_title="Chat With AUTHOR", page_icon="πŸ“š", layout='centered')
#     st.header("Enhance Understanding with Gemini and LLaMA-2 models πŸ€–")

#     engine = pyttsx3.init()

#     user_question = st.text_input("Ask a Question from the PDF Files uploaded")
#     language = st.selectbox("Select Language", ["en", "es", "fr", "de", "te"])  # Example languages, including Telugu (te)

#     if st.button("Use Voice Input to Query"):
#         recognizer = sr.Recognizer()
#         with sr.Microphone() as source:
#             st.write("Listening...")
#             audio = recognizer.listen(source)
#             st.write("Listening stopped")
#             try:
#                 user_question = recognizer.recognize_google(audio)
#                 st.write(f"You said: {user_question}")
#             except sr.UnknownValueError:
#                 st.write("Sorry, I could not understand your speech.")
#             except sr.RequestError:
#                 st.write("Could not request results; check your network connection.")

#     with st.sidebar:
#         st.title("Menu:")
#         pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)
#         if st.button("Submit & Process"):
#             with st.spinner("Processing..."):
#                 raw_text = get_pdf_text(pdf_docs)
#                 text_chunks = get_text_chunks(raw_text)
#                 get_vector_store(text_chunks)
#                 st.success("Done")
    
#     if user_question:
#         raw_text = get_pdf_text(pdf_docs)
#         text_chunks = get_text_chunks(raw_text)
#         get_vector_store(text_chunks)
#         user_input(user_question, raw_text, engine, language)
    
# if __name__ == "__main__":
    # main()


import os
import streamlit as st
from PyPDF2 import PdfReader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
import google.generativeai as genai
from langchain_community.vectorstores import FAISS
from langchain.chains.question_answering import load_qa_chain
from langchain.prompts import PromptTemplate
from dotenv import load_dotenv
from gtts import gTTS
import speech_recognition as sr
import pyttsx3
import tempfile
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import nltk
from nltk.corpus import stopwords
from langchain_community.llms import CTransformers
from googletrans import Translator

# Load environment variables
load_dotenv()
google_api_key = os.getenv("GOOGLE_API_KEY")
if not google_api_key:
    raise ValueError("Google API key not found. Please check your environment variables.")
genai.configure(api_key=google_api_key)

# Download stopwords
nltk.download('stopwords')
stop_words = stopwords.words('english')
custom_stopwords = ["what", "is", "how", "who", "explain", "about", "?", "please", "hey", "whatsup", "can u explain"]
stop_words.extend(custom_stopwords)

def get_pdf_text(pdf_docs):
    text = ""
    for pdf in pdf_docs:
        pdf_reader = PdfReader(pdf)
        for page in pdf_reader.pages:
            text += page.extract_text() or ""
    return text

def get_text_chunks(text):
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
    return text_splitter.split_text(text)

def get_vector_store(text_chunks):
    try:
        embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
        vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
        vector_store.save_local("faiss_index")
    except Exception as e:
        st.error(f"Error during embedding: {e}")

def get_conversational_chain():
    prompt_template = """

    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'

    

    Context:

    {context}

    

    Question:

    {question}

    

    Answer:

    """
    model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
    prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
    return load_qa_chain(model, chain_type="stuff", prompt=prompt)

def get_llama_response(input_text, no_words, blog_style, response_language):
    llm = CTransformers(
        model='models/llama-2-7b-chat.ggmlv3.q8_0.bin',
        model_type='llama',
        config={'max_new_tokens': 500, 'temperature': 0.01}
    )
    template = """

          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.

    """
    
    prompt = PromptTemplate(input_variables=["blog_style", "input_text", 'no_words', 'response_language'],
                            template=template)
    
    response = llm(prompt.format(input_text=input_text, no_words=no_words, blog_style=blog_style, response_language=response_language))
    return response

def calculate_cosine_similarity(text, user_question):
    vectorizer = TfidfVectorizer(stop_words=list(stop_words))
    tfidf_matrix = vectorizer.fit_transform([text, user_question])
    cos_similarity = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]
    return cos_similarity

def translate_text(text, dest_language):
    translator = Translator()
    translation = translator.translate(text, dest=dest_language)
    return translation.text

def user_input(user_question, raw_text, response_language):
    try:
        embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
        new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
        docs = new_db.similarity_search(user_question)
        
        gemini_chain = get_conversational_chain()
        gemini_response = gemini_chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
        initial_response = gemini_response["output_text"]
    except Exception as e:
        # st.error(f"Error during question answering: {e}")
        initial_response = "The provided context does not contain any information"
    
    similarity_score = calculate_cosine_similarity(raw_text, user_question)
    st.write("Cosine similarity score: ", similarity_score)
    
    if "The answer is not available in the context" in initial_response or "The provided context does not contain any information" in initial_response:
        if similarity_score > 0.00125:
            refined_response = get_llama_response(user_question, no_words=500, blog_style="detailed", response_language="english")
        else:
            refined_response = "I'm sorry, I cannot answer this question based on the provided context."
    else:
        refined_response = get_llama_response(initial_response, no_words=500, blog_style="detailed", response_language="english")
    
    translated_response = translate_text(refined_response, response_language)
    st.write("Generated Response:", translated_response)
    
    st.session_state.refined_response = translated_response

# def speak_text(engine, text, language):
#     try:
#         if language == 'en':
#             # Use pyttsx3 for English
#             engine.say(text)
#             engine.runAndWait()
#         else:
#             # Use gTTS for other languages
#             with tempfile.NamedTemporaryFile(delete=True) as fp:
#                 tts = gTTS(text=text, lang=language)
#                 tts.save(fp.name)
#                 os.system(f"start {fp.name}")
#     except Exception as e:
#         st.error(f"Error occurred during text-to-speech: {e}")
# import os
# import tempfile
# import pyttsx3
# from gtts import gTTS
# from pydub import AudioSegment
# from pydub.playback import play

# def speak_text(engine, text, language):
#     if language == 'en':
#         # Use pyttsx3 for English
#         engine.say(text)
#         engine.runAndWait()
#     else:
#         # Use gTTS for other languages
#         tts = gTTS(text=text, lang=language)
#         with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
#             tts.save(fp.name)
#             # Use Pydub to play the audio
#             audio = AudioSegment.from_file(fp.name)
#             play(audio)
#             os.remove(fp.name)

# Example usage
# engine = pyttsx3.init()

def stop_speech(engine):
    engine.stop()

def main():
    st.set_page_config(page_title="Chat With AUTHOR", page_icon="πŸ“š", layout='centered')
    st.header("Enhance Understanding with Gemini and LLaMA-2 models πŸ€–")

    engine = pyttsx3.init()

    user_question = st.text_input("Ask a Question from the PDF Files uploaded")
    if st.button("πŸŽ™"):
        recognizer = sr.Recognizer()
        with sr.Microphone() as source:
            st.write("Listening...")
            audio = recognizer.listen(source)
            st.write("Listening stopped")
            try:
                user_question = recognizer.recognize_google(audio)
                st.write(f"You said: {user_question}")
            except sr.UnknownValueError:
                st.write("Sorry, I could not understand your speech.")
            except sr.RequestError:
                st.write("Could not request results; check your network connection.")
   
    response_language = st.selectbox("Select Response Language", ["en", "es", "fr", "de", "te"])  # Example languages, including Telugu (te)

   

    with st.sidebar:
        st.title("Menu:")
        pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)
        if st.button("Submit & Process"):
            with st.spinner("Processing..."):
                raw_text = get_pdf_text(pdf_docs)
                text_chunks = get_text_chunks(raw_text)
                get_vector_store(text_chunks)
                st.success("Done")
    
    if user_question:
        raw_text = get_pdf_text(pdf_docs)
        text_chunks = get_text_chunks(raw_text)
        get_vector_store(text_chunks)
        user_input(user_question, raw_text, response_language)
    
    # if "refined_response" in st.session_state:
    #     if st.button("Speak"):
    #         speak_text(engine, st.session_state.translated_response, response_language)
    
if __name__ == "__main__":
    main()