File size: 27,264 Bytes
2cd7bf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# import os
# import streamlit as st
# from dotenv import load_dotenv
# import google.generativeai as gen_ai
#
#
# # Load environvent variables
# load_dotenv()
#
# # Configure Streamlit page settings
# st.set_page_config(
#     page_title="Chat with Gemini-Pro!",
#     page_icon=":brain:", # Favicon emoji
#     layout="centered", # Page layout option
# )
#
# Google_API_Key = os.getenv("Google_API_Key")
#
# # Set up Google Gemni-Pro AI Model
# gen_ai.configure(api_key=Google_API_Key)
# model = gen_ai.GenerativeModel('gemini-pro')
#
# # Function to translate roles between Gemini-Pro and streamlit terminology
#
# def translate_role_for_streamlit(user_role):
#     if user_role == 'model':
#         return 'assistant'
#     else: return user_role
#
# # Initialize chat session in streamlit if not already present
# if "chat_session" not in st.session_state:
#     st.session_state.chat_session = model.start_chat(history=[])
#
# # Display the chatbot's title on the page
# st.title("πŸ€– Gemini Pro - ChatBot")
#
# # Display the chat history
# for message in st.session_state.chat_session.history:
#     with st.chat_message(translate_role_for_streamlit(message.role)):
#         st.markdown(message.parts[0].text)
#
#
# # Input field for user's message
# user_prompt = st.chat_input("Ask Gemini Pro...")
#
# if user_prompt:
#     # Add user's message to chat and display it
#     st.chat_message("user").markdown(user_prompt)
#
#     # Send user's message to chat and display it
#     gemini_response = st.session_state.chat_session.send_message(user_prompt)
#
#     # Display Gemini-Pro's response
#     with st.chat_message('assistant'):
#         st.markdown(gemini_response.text)






#
# import os
# import json
# import streamlit as st
# import google.generativeai as gen_ai
# from dotenv import load_dotenv
# import speech_recognition as sr
# import pyttsx3
#
# # Load environment variables
# load_dotenv()
# Google_API_Key = os.getenv("Google_API_Key")
#
# # Configure Streamlit page settings
# st.set_page_config(
#     page_title="Chat with Gemini-Pro!",
#     page_icon="πŸ€–",
#     layout="wide",
# )
#
# # Set up Google Gemini-Pro AI Model
# gen_ai.configure(api_key=Google_API_Key)
# model = gen_ai.GenerativeModel('gemini-pro')
#
# # Initialize chatbot memory
# if "chat_history" not in st.session_state:
#     try:
#         with open("chat_history.json", "r") as f:
#             st.session_state.chat_history = json.load(f)
#     except FileNotFoundError:
#         st.session_state.chat_history = []
#
#
# # Save chat history
# def save_chat_history():
#     with open("chat_history.json", "w") as f:
#         json.dump(st.session_state.chat_history, f)
#
#
# # Sidebar settings
# with st.sidebar:
#     st.subheader("βš™οΈ Settings")
#
#     # Theme selection
#     theme = st.radio("Select Theme", ["🌞 Light", "πŸŒ™ Dark"])
#
#     # Clear chat history button
#     if st.button("πŸ—‘οΈ Clear Chat History"):
#         st.session_state.chat_history = []
#         save_chat_history()
#         st.experimental_rerun()
#
# # Apply dark mode styling
# if theme == "πŸŒ™ Dark":
#     st.markdown(
#         """
#         <style>
#         body {background-color: #333; color: white;}
#         .stChatMessage {background-color: #444; color: white;}
#         </style>
#         """,
#         unsafe_allow_html=True
#     )
#
# # Display chatbot title
# st.title("πŸ€– Gemini Pro - ChatBot")
#
# # Display chat history
# for message in st.session_state.chat_history:
#     with st.chat_message(message["role"]):
#         st.markdown(message["content"])
#
# # Speech recognition & text-to-speech setup
# recognizer = sr.Recognizer()
# engine = pyttsx3.init()
#
# # Voice input button
# if st.button("🎀 Speak"):
#     with sr.Microphone() as source:
#         st.write("Listening...")
#         audio = recognizer.listen(source)
#         try:
#             user_prompt = recognizer.recognize_google(audio)
#             st.chat_message("user").markdown(user_prompt)
#         except:
#             st.error("Could not understand. Try again.")
#
# # Text input
# user_prompt = st.chat_input("Ask Gemini Pro...")
#
# if user_prompt:
#     # Add user message to chat history
#     st.session_state.chat_history.append({"role": "user", "content": user_prompt})
#
#     # Display user message
#     st.chat_message("user").markdown(user_prompt)
#
#     # Get response from Gemini-Pro
#     gemini_response = model.generate_content(user_prompt)
#
#     # Add chatbot response to history
#     st.session_state.chat_history.append({"role": "assistant", "content": gemini_response.text})
#
#     # Display chatbot response
#     with st.chat_message("assistant"):
#         st.markdown(gemini_response.text)
#
#     # Save chat history
#     save_chat_history()
#
#     # Text-to-Speech response
#     engine.say(gemini_response.text)
#     engine.runAndWait()





# import os
# import json
# import streamlit as st
# import google.generativeai as gen_ai
# from dotenv import load_dotenv
# import speech_recognition as sr
# import pyttsx3
#
# # Load environment variables
# load_dotenv()
# Google_API_Key = os.getenv("Google_API_Key")
#
# # Configure Streamlit page settings
# st.set_page_config(
#     page_title="Chat with Gemini-Pro!",
#     page_icon="πŸ€–",
#     layout="wide",
# )
#
# # Apply custom CSS for UI/UX improvements
# st.markdown(
#     """
#     <style>
#     .stChatMessage { padding: 10px; border-radius: 10px; margin: 5px 0; }
#     .user { background-color: #DCF8C6; }
#     .assistant { background-color: #E3E3E3; }
#     .sidebar .sidebar-content { background-color: #f0f2f6; }
#     .chat-container { max-width: 700px; margin: auto; }
#     </style>
#     """,
#     unsafe_allow_html=True
# )
#
# # Set up Google Gemini-Pro AI Model
# gen_ai.configure(api_key=Google_API_Key)
# model = gen_ai.GenerativeModel('gemini-pro')
#
# # Initialize chatbot memory
# if "chat_history" not in st.session_state:
#     try:
#         with open("chat_history.json", "r") as f:
#             st.session_state.chat_history = json.load(f)
#     except (FileNotFoundError, json.JSONDecodeError):
#         st.session_state.chat_history = []
#
#
# # Save chat history
# def save_chat_history():
#     with open("chat_history.json", "w") as f:
#         json.dump(st.session_state.chat_history, f)
#
#
# # Sidebar settings
# with st.sidebar:
#     st.subheader("βš™οΈ Settings")
#
#     # Theme selection
#     theme = st.radio("Select Theme", ["🌞 Light", "πŸŒ™ Dark"])
#
#     # Clear chat history button
#     if st.button("πŸ—‘οΈ Clear Chat History"):
#         st.session_state.chat_history = []
#         save_chat_history()
#         st.experimental_rerun()
#
# # Apply dark mode styling
# if theme == "πŸŒ™ Dark":
#     st.markdown(
#         """
#         <style>
#         body {background-color: #1e1e1e; color: white;}
#         .stChatMessage {background-color: #444; color: white;}
#         .sidebar .sidebar-content {background-color: #333;}
#         .stTextInput, .stButton, .stRadio {background-color: #333; color: white;}
#         </style>
#         """,
#         unsafe_allow_html=True
#     )
#
# # Display chatbot title
# st.title("πŸ€– Gemini Pro - AI ChatBot")
#
# # Chat container
# st.markdown('<div class="chat-container">', unsafe_allow_html=True)
#
# # Display chat history
# for message in st.session_state.chat_history:
#     role = message["role"]
#     avatar = "πŸ‘€" if role == "user" else "πŸ€–"
#     bg_color = "user" if role == "user" else "assistant"
#
#     with st.chat_message(role):
#         st.markdown(f'<div class="{bg_color} stChatMessage">{avatar} {message["content"]}</div>',
#                     unsafe_allow_html=True)
#
# # Speech recognition & text-to-speech setup
# recognizer = sr.Recognizer()
# # engine = pyttsx3.init()
# engine = pyttsx3.init()
# engine.setProperty('rate', 150)  # Adjust speech rate
# engine.setProperty('voice', engine.getProperty('voices')[0].id)  # Set a specific voice
#
# # Voice input button
# if st.button("🎀 Speak"):
#     with sr.Microphone() as source:
#         st.write("Listening...")
#         audio = recognizer.listen(source)
#         try:
#             user_prompt = recognizer.recognize_google(audio)
#             st.session_state.chat_history.append({"role": "user", "content": user_prompt})
#             st.chat_message("user").markdown(user_prompt)
#             # Trigger chatbot response
#             gemini_response = model.generate_content(user_prompt)
#             st.session_state.chat_history.append({"role": "assistant", "content": gemini_response.text})
#             st.chat_message("assistant").markdown(gemini_response.text)
#             save_chat_history()
#             engine.say(gemini_response.text)
#             engine.runAndWait()
#         except sr.UnknownValueError:
#             st.error("Sorry, I could not understand the audio.")
#         except sr.RequestError:
#             st.error("Could not request results from the speech recognition service.")
# # Text input
# user_prompt = st.chat_input("Ask Gemini Pro...")
#
# if user_prompt:
#     # Add user message to chat history
#     st.session_state.chat_history.append({"role": "user", "content": user_prompt})
#
#     # Display user message
#     st.chat_message("user").markdown(user_prompt)
#
#     # Get response from Gemini-Pro
#     # gemini_response = model.generate_content(user_prompt)
#     try:
#         gemini_response = model.generate_content(user_prompt)
#     except Exception as e:
#         st.error(f"An error occurred: {e}")
#         gemini_response = type('Object', (), {'text': 'Sorry, I could not generate a response.'})
#
#     # Add chatbot response to history
#     st.session_state.chat_history.append({"role": "assistant", "content": gemini_response.text})
#
#     # Display chatbot response
#     with st.chat_message("assistant"):
#         st.markdown(gemini_response.text)
#
#     # Save chat history
#     save_chat_history()
#
#     # Text-to-Speech response
#     engine.say(gemini_response.text)
#     engine.runAndWait()
#
# st.markdown('</div>', unsafe_allow_html=True)
#










# import os
# import streamlit as st
# import google.generativeai as gen_ai
# import pyttsx3
# import threading
# from dotenv import load_dotenv
#
# # Load environment variables
# load_dotenv()
#
# # Configure Streamlit page settings
# st.set_page_config(
#     page_title="Gemini-Pro ChatBot",
#     page_icon="πŸ€–",  # Favicon emoji
#     layout="centered",  # Page layout option
# )
#
# # Retrieve Google API Key
# Google_API_Key = os.getenv("Google_API_Key")
#
# # Set up Google Gemini-Pro AI Model
# gen_ai.configure(api_key=Google_API_Key)
# model = gen_ai.GenerativeModel('gemini-pro')
#
# # Function to translate roles between Gemini-Pro and Streamlit terminology
# def translate_role_for_streamlit(user_role):
#     return "assistant" if user_role == "model" else user_role
#
# # Function to handle text-to-speech (TTS) in a separate thread
# def speak_text(text):
#     engine = pyttsx3.init()
#     engine.say(text)
#     engine.runAndWait()
#
# # Initialize chat session in Streamlit if not already present
# if "chat_session" not in st.session_state:
#     st.session_state.chat_session = model.start_chat(history=[])
#
# # Display chatbot title and description
# st.markdown("<h1 style='text-align: center; color: #4A90E2;'>πŸ€– Gemini-Pro ChatBot</h1>", unsafe_allow_html=True)
# st.markdown("<p style='text-align: center; font-size: 16px;'>Ask me anything! I'm powered by Gemini-Pro AI.</p>", unsafe_allow_html=True)
#
# # Display chat history
# for message in st.session_state.chat_session.history:
#     with st.chat_message(translate_role_for_streamlit(message.role)):
#         st.markdown(message.parts[0].text)
#
# # User input field
# user_prompt = st.chat_input("Ask Gemini Pro...")
#
# # If user enters a prompt
# if user_prompt:
#     # Display user's message
#     st.chat_message("user").markdown(user_prompt)
#
#     # Show a loading indicator while waiting for a response
#     with st.spinner("Thinking..."):
#         gemini_response = st.session_state.chat_session.send_message(user_prompt)
#
#     # Display Gemini-Pro's response
#     with st.chat_message("assistant"):
#         st.markdown(gemini_response.text)
#
#     # Run text-to-speech in the background
#     threading.Thread(target=speak_text, args=(gemini_response.text,), daemon=True).start()






#
#
#
#
#
#
#
#
#
#
# import os
# import streamlit as st
# import google.generativeai as gen_ai
# import pyttsx3
# import threading
# from dotenv import load_dotenv
#
# # Load environment variables
# load_dotenv()
#
# # Configure Streamlit page settings
# st.set_page_config(
#     page_title="Gemini-Pro ChatBot",
#     page_icon="πŸ€–",
#     layout="centered",
# )
#
# # Retrieve Google API Key
# Google_API_Key = os.getenv("Google_API_Key")
#
# # Set up Google Gemini-Pro AI Model
# gen_ai.configure(api_key=Google_API_Key)
# model = gen_ai.GenerativeModel('gemini-pro')
#
# # Function to translate roles between Gemini-Pro and Streamlit terminology
# def translate_role_for_streamlit(user_role):
#     return "assistant" if user_role == "model" else user_role
#
# # Initialize text-to-speech engine
# if "tts_engine" not in st.session_state:
#     st.session_state.tts_engine = pyttsx3.init()
#
# def stop_speech():
#     """Stop the current speech if running."""
#     st.session_state.tts_engine.stop()
#
# def speak_text(text):
#     """Stop previous speech and start speaking new text."""
#     stop_speech()  # Stop any ongoing speech
#     st.session_state.tts_engine.say(text)
#     st.session_state.tts_engine.runAndWait()
#
# # Initialize chat session in Streamlit if not already present
# if "chat_session" not in st.session_state:
#     st.session_state.chat_session = model.start_chat(history=[])
#
# # Display chatbot title and description
# st.markdown("<h1 style='text-align: center; color: #4A90E2;'>πŸ€– Gemini-Pro ChatBot</h1>", unsafe_allow_html=True)
# st.markdown("<p style='text-align: center; font-size: 16px;'>Ask me anything! I'm powered by Gemini-Pro AI.</p>", unsafe_allow_html=True)
#
# # Display chat history
# for message in st.session_state.chat_session.history:
#     with st.chat_message(translate_role_for_streamlit(message.role)):
#         st.markdown(message.parts[0].text)
#
# # User input field
# user_prompt = st.chat_input("Ask Gemini Pro...")
#
# # If user enters a prompt
# if user_prompt:
#     # Display user's message
#     st.chat_message("user").markdown(user_prompt)
#
#     # Show a loading indicator while waiting for a response
#     with st.spinner("Thinking..."):
#         gemini_response = st.session_state.chat_session.send_message(user_prompt)
#
#     # Display Gemini-Pro's response
#     with st.chat_message("assistant"):
#         st.markdown(gemini_response.text)
#
#     # Run text-to-speech in the background (stopping previous speech first)
#     threading.Thread(target=speak_text, args=(gemini_response.text,), daemon=True).start()


# import os
# import streamlit as st
# import google.generativeai as gen_ai
# import pyttsx3
# import threading
# from dotenv import load_dotenv
#
# # Load environment variables
# load_dotenv()
#
# # Configure Streamlit page settings
# st.set_page_config(
#     page_title="Gemini-Pro ChatBot",
#     page_icon="πŸ€–",
#     layout="centered",
# )
#
# # Retrieve Google API Key
# Google_API_Key = os.getenv("Google_API_Key")
#
# # Set up Google Gemini-Pro AI Model
# gen_ai.configure(api_key=Google_API_Key)
# model = gen_ai.GenerativeModel('gemini-pro')
#
# # Function to translate roles between Gemini-Pro and Streamlit terminology
# def translate_role_for_streamlit(user_role):
#     return "assistant" if user_role == "model" else user_role
#
# # Initialize text-to-speech engine
# if "tts_engine" not in st.session_state:
#     st.session_state.tts_engine = pyttsx3.init()
#
# # Initialize threading event for speech control
# if "speech_event" not in st.session_state:
#     st.session_state.speech_event = threading.Event()
#
# def stop_speech():
#     """Stop the current speech if running."""
#     st.session_state.speech_event.set()  # Set the event to stop speech
#     st.session_state.tts_engine.stop()
#
# def speak_text(text):
#     """Stop previous speech and start speaking new text."""
#     stop_speech()  # Stop any ongoing speech
#     st.session_state.speech_event.clear()  # Clear the event for new speech
#     st.session_state.tts_engine.say(text)
#     st.session_state.tts_engine.runAndWait()
#
# # Initialize chat session in Streamlit if not already present
# if "chat_session" not in st.session_state:
#     st.session_state.chat_session = model.start_chat(history=[])
#
# # Display chatbot title and description
# st.markdown("<h1 style='text-align: center; color: #4A90E2;'>πŸ€– Gemini-Pro ChatBot</h1>", unsafe_allow_html=True)
# st.markdown("<p style='text-align: center; font-size: 16px;'>Ask me anything! I'm powered by Gemini-Pro AI.</p>", unsafe_allow_html=True)
#
# # Display chat history
# for message in st.session_state.chat_session.history:
#     with st.chat_message(translate_role_for_streamlit(message.role)):
#         st.markdown(message.parts[0].text)
#
# # User input field
# user_prompt = st.chat_input("Ask Gemini Pro...")
#
# # If user enters a prompt
# if user_prompt:
#     # Display user's message
#     st.chat_message("user").markdown(user_prompt)
#
#     # Show a loading indicator while waiting for a response
#     with st.spinner("Thinking..."):
#         gemini_response = st.session_state.chat_session.send_message(user_prompt)
#
#     # Display Gemini-Pro's response
#     with st.chat_message("assistant"):
#         st.markdown(gemini_response.text)
#
#     # Run text-to-speech in the background (stopping previous speech first)
#     threading.Thread(target=speak_text, args=(gemini_response.text,), daemon=True).start()






#
# import os
# import streamlit as st
# import google.generativeai as gen_ai
# import pyttsx3
# import threading
# from dotenv import load_dotenv
#
# # Load environment variables
# load_dotenv()
#
# # Configure Streamlit page settings
# st.set_page_config(
#     page_title="Gemini-Pro ChatBot",
#     page_icon="πŸ€–",
#     layout="centered",
# )
#
# # Retrieve Google API Key
# Google_API_Key = os.getenv("Google_API_Key")
#
# # Set up Google Gemini-Pro AI Model
# gen_ai.configure(api_key=Google_API_Key)
# model = gen_ai.GenerativeModel('gemini-pro')
#
# # Function to translate roles between Gemini-Pro and Streamlit terminology
# def translate_role_for_streamlit(user_role):
#     return "assistant" if user_role == "model" else user_role
#
# # Initialize text-to-speech engine
# if "tts_engine" not in st.session_state:
#     st.session_state.tts_engine = pyttsx3.init()
#
# def stop_speech():
#     """Stop the current speech if running."""
#     st.session_state.tts_engine.stop()
#
# def speak_text(text):
#     """Stop previous speech and start speaking new text."""
#     stop_speech()  # Stop any ongoing speech
#     st.session_state.tts_engine.say(text)
#     st.session_state.tts_engine.runAndWait()
#
# # Initialize chat session in Streamlit if not already present
# if "chat_session" not in st.session_state:
#     st.session_state.chat_session = model.start_chat(history=[])
#
# # Display chatbot title and description
# st.markdown("<h1 style='text-align: center; color: #4A90E2;'>πŸ€– Gemini-Pro ChatBot</h1>", unsafe_allow_html=True)
# st.markdown("<p style='text-align: center; font-size: 16px;'>Ask me anything! I'm powered by Gemini-Pro AI.</p>", unsafe_allow_html=True)
#
# # Display chat history
# for message in st.session_state.chat_session.history:
#     with st.chat_message(translate_role_for_streamlit(message.role)):
#         st.markdown(message.parts[0].text)
#
# # User input field
# user_prompt = st.chat_input("Ask Gemini Pro...")
#
# # If user enters a prompt
# if user_prompt:
#     # Display user's message
#     st.chat_message("user").markdown(user_prompt)
#
#     # Show a loading indicator while waiting for a response
#     with st.spinner("Thinking..."):
#         gemini_response = st.session_state.chat_session.send_message(user_prompt)
#
#     # Display Gemini-Pro's response
#     with st.chat_message("assistant"):
#         st.markdown(gemini_response.text)
#
#     # Run text-to-speech in the background (stopping previous speech first)
#     threading.Thread(target=speak_text, args=(gemini_response.text,), daemon=True).start()
#
#
#
#













#
#
# import os
# import streamlit as st
# import google.generativeai as gen_ai
# import pyttsx3
# import threading
# from dotenv import load_dotenv
# import speech_recognition as sr
#
# # Load environment variables
# load_dotenv()
#
# # Configure Streamlit page settings
# st.set_page_config(
#     page_title="Gemini-Pro ChatBot",
#     page_icon="πŸ€–",  # Favicon emoji
#     layout="centered",  # Page layout option
# )
#
# # Retrieve Google API Key
# Google_API_Key = os.getenv("Google_API_Key")
#
# # Set up Google Gemini-Pro AI Model
# gen_ai.configure(api_key=Google_API_Key)
# model = gen_ai.GenerativeModel('gemini-pro')
#
# # Initialize text-to-speech engine
# if "tts_engine" not in st.session_state:
#     st.session_state.tts_engine = pyttsx3.init()
#
# # Speech-to-text function
# def listen_for_input():
#     recognizer = sr.Recognizer()
#     with sr.Microphone() as source:
#         print("Listening...")
#         audio = recognizer.listen(source)
#         try:
#             return recognizer.recognize_google(audio)
#         except sr.UnknownValueError:
#             return "Sorry, I did not catch that."
#         except sr.RequestError:
#             return "Sorry, there was an error with the speech recognition service."
#
# # Stop previous speech and speak the new text
# def speak_text(text):
#     stop_speech()  # Stop any ongoing speech
#     st.session_state.tts_engine.say(text)
#     st.session_state.tts_engine.runAndWait()
#
# # Stop ongoing speech
# def stop_speech():
#     st.session_state.tts_engine.stop()
#
# # Function to translate roles between Gemini-Pro and Streamlit terminology
# def translate_role_for_streamlit(user_role):
#     return "assistant" if user_role == "model" else user_role
#
# # Initialize chat session in Streamlit if not already present
# if "chat_session" not in st.session_state:
#     st.session_state.chat_session = model.start_chat(history=[])
#
# # Display chatbot title and description
# st.markdown("<h1 style='text-align: center; color: #4A90E2;'>πŸ€– Gemini-Pro ChatBot</h1>", unsafe_allow_html=True)
# st.markdown("<p style='text-align: center; font-size: 16px;'>Ask me anything! I'm powered by Gemini-Pro AI.</p>", unsafe_allow_html=True)
#
# # Display chat history
# for message in st.session_state.chat_session.history:
#     with st.chat_message(translate_role_for_streamlit(message.role)):
#         st.markdown(message.parts[0].text)
#
# # User input field (with optional speech-to-text input)
# user_prompt = st.chat_input("Ask Gemini Pro...")
#
# if st.button("Use Voice Input"):
#     user_prompt = listen_for_input()
#
# # If user enters a prompt
# if user_prompt:
#     # Display user's message
#     st.chat_message("user").markdown(user_prompt)
#
#     # Show a loading indicator while waiting for a response
#     with st.spinner("Thinking..."):
#         gemini_response = st.session_state.chat_session.send_message(user_prompt)
#
#     # Display Gemini-Pro's response
#     with st.chat_message("assistant"):
#         st.markdown(gemini_response.text)
#
#     # Run text-to-speech in the background
#     threading.Thread(target=speak_text, args=(gemini_response.text,), daemon=True).start()








import os
import streamlit as st
import google.generativeai as gen_ai
import pyttsx3
import threading
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configure Streamlit page settings
st.set_page_config(
    page_title="Gemini-Pro ChatBot",
    page_icon="πŸ€–",  # Favicon emoji
    layout="centered",  # Page layout option
)

# Retrieve Google API Key
Google_API_Key = os.getenv("Google_API_Key")

# Set up Google Gemini-Pro AI Model
gen_ai.configure(api_key=Google_API_Key)
model = gen_ai.GenerativeModel('gemini-pro')

# Function to translate roles between Gemini-Pro and Streamlit terminology
def translate_role_for_streamlit(user_role):
    return "assistant" if user_role == "model" else user_role

# Initialize the TTS engine if not already present in session state
if "tts_engine" not in st.session_state:
    st.session_state.tts_engine = pyttsx3.init()

# Function to stop speech if any ongoing speech is happening
def stop_speech():
    if hasattr(st.session_state, "tts_engine"):
        st.session_state.tts_engine.stop()

# Function to handle text-to-speech (TTS) in a separate thread
def speak_text(text):
    try:
        stop_speech()  # Stop any ongoing speech
        st.session_state.tts_engine.say(text)
        st.session_state.tts_engine.runAndWait()
    except Exception as e:
        st.error(f"Error in TTS: {e}")

# Initialize chat session in Streamlit if not already present
if "chat_session" not in st.session_state:
    st.session_state.chat_session = model.start_chat(history=[])

# Display chatbot title and description
st.markdown("<h1 style='text-align: center; color: #4A90E2;'>πŸ€– Gemini-Pro ChatBot</h1>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center; font-size: 16px;'>Ask me anything! I'm powered by Gemini-Pro AI.</p>", unsafe_allow_html=True)

# Display chat history
for message in st.session_state.chat_session.history:
    with st.chat_message(translate_role_for_streamlit(message.role)):
        st.markdown(message.parts[0].text)

# User input field
user_prompt = st.chat_input("Ask Gemini Pro...")

# If user enters a prompt
if user_prompt:
    # Display user's message
    st.chat_message("user").markdown(user_prompt)

    # Show a loading indicator while waiting for a response
    with st.spinner("Thinking..."):
        gemini_response = st.session_state.chat_session.send_message(user_prompt)

    # Display Gemini-Pro's response
    with st.chat_message("assistant"):
        st.markdown(gemini_response.text)

    # Run text-to-speech in the background
    threading.Thread(target=speak_text, args=(gemini_response.text,), daemon=True).start()