File size: 33,849 Bytes
c29cd9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b807cd3
 
16561ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c29cd9c
16561ba
 
 
 
 
 
 
 
0af226f
16561ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c29cd9c
b807cd3
 
 
 
 
 
7e408ac
 
 
 
b807cd3
 
7e408ac
 
 
 
 
b807cd3
 
 
 
 
 
7e408ac
 
 
 
b807cd3
 
08f9319
b807cd3
 
 
 
 
 
 
83f0821
b807cd3
 
 
 
 
 
 
 
 
 
 
 
 
67854a5
b807cd3
 
 
 
 
 
08f9319
b807cd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2fe968
b807cd3
 
 
 
 
7e408ac
 
 
 
2df683c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e408ac
 
213818c
7e408ac
 
 
 
 
 
 
 
b78a176
7e408ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b78a176
7e408ac
 
58cb9c0
 
 
 
 
 
 
 
 
7e408ac
8eee8ac
7e408ac
3d65dc9
213818c
3d65dc9
213818c
3d65dc9
 
 
 
 
213818c
3d65dc9
 
 
 
 
 
 
7e408ac
ce46e64
 
 
7e408ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58cb9c0
9afdc38
 
 
 
 
 
 
 
37bca9a
d1d4390
9afdc38
 
2bd190f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a9125
58cb9c0
 
6156310
e9a9125
58cb9c0
 
7e408ac
58cb9c0
 
 
 
 
 
7e408ac
58cb9c0
 
 
 
 
 
 
7e408ac
58cb9c0
 
 
 
 
 
7e408ac
58cb9c0
 
 
7e408ac
58cb9c0
 
7e408ac
58cb9c0
 
 
 
 
 
 
 
7e408ac
58cb9c0
 
 
7e408ac
 
 
 
 
 
 
 
 
 
 
b78a176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e408ac
 
 
 
 
 
 
 
 
 
8eee8ac
7e408ac
 
 
2df683c
 
 
 
 
65f031c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2df683c
65f031c
 
 
 
 
 
 
 
2df683c
65f031c
 
 
2df683c
65f031c
 
 
 
2df683c
 
65f031c
 
 
 
 
 
 
 
 
 
2df683c
65f031c
 
 
 
 
 
 
 
 
 
 
 
2df683c
65f031c
 
 
2df683c
65f031c
 
 
 
 
 
2df683c
65f031c
 
 
 
 
 
 
2df683c
65f031c
 
 
 
 
 
 
2df683c
65f031c
 
 
2df683c
65f031c
 
 
 
 
 
 
 
 
 
2df683c
65f031c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2df683c
65f031c
 
2df683c
2c2aa04
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


# # # # # from langchain_google_genai import ChatGoogleGenerativeAI



# # # # # llm = ChatGoogleGenerativeAI(
# # # # #     model="gemini-1.5-flash",
# # # # #     google_api_key='AIzaSyC7Rhv4L6_oNl-nW3Qeku2SPRkxL5hhtoE',
# # # # #     temperature=0.2)

# # # # # poem = llm.invoke("Write a poem on love for burger")
# # # # # print(poem)


# # # # import streamlit as st
# # # # from langchain_google_genai import ChatGoogleGenerativeAI

# # # # # Set up the AI model
# # # # llm = ChatGoogleGenerativeAI(
# # # #     model="gemini-1.5-flash",  # Free model
# # # #     google_api_key="AIzaSyC7Rhv4L6_oNl-nW3Qeku2SPRkxL5hhtoE",
# # # #     temperature=0.5
# # # # )

# # # # # Streamlit UI
# # # # st.title("๐Ÿฉบ Healthcare AI Assistant")
# # # # st.write("Ask me anything about health, symptoms, diet, or general medical advice!")

# # # # # User Input
# # # # user_question = st.text_input("Enter your health-related question:")

# # # # # Process User Query
# # # # if st.button("Get Recommendation"):
# # # #     if user_question.strip():
# # # #         with st.spinner("Analyzing..."):
# # # #             response = llm.invoke(user_question)
# # # #         st.success("Recommendation:")
# # # #         st.write(response)
# # # #     else:
# # # #         st.warning("Please enter a question!")

# # # # # Footer
# # # # st.markdown("---")
# # # # st.markdown("๐Ÿ’ก *Disclaimer: This AI assistant provides general health information. Always consult a doctor for medical concerns.*")



# # # import streamlit as st
# # # from langchain_google_genai import ChatGoogleGenerativeAI

# # # # Set up AI model
# # # llm = ChatGoogleGenerativeAI(
# # #     model="gemini-1.5-flash",  # Free model
# # #     google_api_key="AIzaSyC7Rhv4L6_oNl-nW3Qeku2SPRkxL5hhtoE",
# # #     temperature=0.5
# # # )

# # # # Streamlit UI
# # # st.title("๐Ÿฉบ AI Healthcare Learning Assistant")
# # # st.write("Ask me anything about healthcare, symptoms, diet, or medical learning!")

# # # # User Input
# # # user_question = st.text_input("Enter your healthcare question:")

# # # # Function to filter AI disclaimers
# # # def is_valid_response(response):
# # #     disclaimers = [
# # #         "I am an AI and cannot give medical advice",
# # #         "Seek medical attention",
# # #         "Consult a doctor",
# # #         "Contact your doctor",
# # #         "Go to an emergency room",
# # #     ]
# # #     return not any(phrase.lower() in response.lower() for phrase in disclaimers)

# # # # Process User Query
# # # if st.button("Get Information"):
# # #     if user_question.strip():
# # #         with st.spinner("Analyzing..."):
# # #             response = llm.invoke(user_question)
        
# # #         # Check if response is valid
# # #         if is_valid_response(response):
# # #             st.success("Here is the relevant information:")
# # #             st.write(response)
# # #         else:
# # #             st.warning("AI provided a disclaimer. Trying again...")
# # #             # Modify prompt to avoid disclaimers
# # #             better_prompt = f"Give a well-explained answer for educational purposes only: {user_question}"
# # #             retry_response = llm.invoke(better_prompt)

# # #             # Display the retried response if it's valid
# # #             if is_valid_response(retry_response):
# # #                 st.success("Here is the refined information:")
# # #                 st.write(retry_response)
# # #             else:
# # #                 st.error("Unable to get a useful response. Try rephrasing your question.")

# # #     else:
# # #         st.warning("Please enter a question!")

# # # # Footer
# # # st.markdown("---")
# # # st.markdown("๐Ÿ’ก *This AI provides learning-based medical insights, not actual medical advice.*")



# # import streamlit as st
# # from langchain_google_genai import ChatGoogleGenerativeAI

# # # Set up AI model
# # llm = ChatGoogleGenerativeAI(
# #     model="gemini-1.5-flash",  # Free model
# #     google_api_key="AIzaSyC7Rhv4L6_oNl-nW3Qeku2SPRkxL5hhtoE",
# #     temperature=0.5
# # )

# # # Streamlit UI
# # st.title("๐Ÿฉบ AI Healthcare Learning Assistant")
# # st.write("Ask me anything about healthcare, symptoms, diet, or medical learning!")

# # # User Input
# # user_question = st.text_input("Enter your healthcare question:")

# # # Function to filter AI disclaimers
# # def is_valid_response(response_text):
# #     disclaimers = [
# #         "I am an AI and cannot give medical advice",
# #         "Seek medical attention",
# #         "Consult a doctor",
# #         "Contact your doctor",
# #         "Go to an emergency room",
# #     ]
# #     return not any(phrase.lower() in response_text.lower() for phrase in disclaimers)

# # # Process User Query
# # if st.button("Get Information"):
# #     if user_question.strip():
# #         with st.spinner("Analyzing..."):
# #             response = llm.invoke(user_question)

# #         # Extract the text content from AIMessage
# #         response_text = response.content if hasattr(response, "content") else str(response)

# #         # Check if response is valid
# #         if is_valid_response(response_text):
# #             st.success("Here is the relevant information:")
# #             st.write(response_text)
# #         else:
# #             st.warning("AI provided a disclaimer. Trying again...")
# #             # Modify prompt to avoid disclaimers
# #             better_prompt = f"Give a well-explained answer for educational purposes only: {user_question}"
# #             retry_response = llm.invoke(better_prompt)

# #             # Extract text from the retried response
# #             retry_response_text = retry_response.content if hasattr(retry_response, "content") else str(retry_response)

# #             # Display the retried response if it's valid
# #             if is_valid_response(retry_response_text):
# #                 st.success("Here is the refined information:")
# #                 st.write(retry_response_text)
# #             else:
# #                 st.error("Unable to get a useful response. Try rephrasing your question.")

# #     else:
# #         st.warning("Please enter a question!")

# # # Footer
# # st.markdown("---")
# # st.markdown("๐Ÿ’ก *This AI provides learning-based medical insights, not actual medical advice.*")




# import streamlit as st
# from langchain_google_genai import ChatGoogleGenerativeAI

# # Set up AI model
# llm = ChatGoogleGenerativeAI(
#     model="gemini-1.5-flash",  # Free model
#     google_api_key="AIzaSyC7Rhv4L6_oNl-nW3Qeku2SPRkxL5hhtoE",
#     temperature=0.5
# )

# # Streamlit UI
# st.title("๐Ÿฉบ AI Healthcare Learning Assistant")
# st.write("Ask about symptoms, medicines, and alternative treatments.")

# # User Input
# user_question = st.text_input("Enter your health-related query:")

# # Function to filter AI disclaimers
# def is_valid_response(response_text):
#     disclaimers = [
#         "I am an AI and cannot give medical advice",
#         "Seek medical attention",
#         "Consult a doctor",
#         "Contact your doctor",
#         "Go to an emergency room",
#     ]
#     return not any(phrase.lower() in response_text.lower() for phrase in disclaimers)

# # Process User Query
# if st.button("Get Recommendation"):
#     if user_question.strip():
#         # Modify user input to ensure the model focuses on learning-based insights
#         formatted_question = f"Without any disclaimer, recommend me medicine for {user_question}. Only for learning purposes, not for treatment. Also, suggest some different ways to cure it."

#         with st.spinner("Analyzing..."):
#             response = llm.invoke(formatted_question)

#         # Extract text content
#         response_text = response.content if hasattr(response, "content") else str(response)

#         # # Check if response is valid
#         if is_valid_response(response_text):
#             st.success("Here is the relevant information:")
#             st.write(response_text)
#         else:
#             st.warning("AI provided a disclaimer. Trying again...")
#             # Retry with a refined prompt
#             better_prompt = f"Its only for leaning purpose not for treatment provide medicine names and alternative treatments for: {user_question}"
#             retry_response = llm.invoke(better_prompt)

#             # Extract text from retry response
#             retry_response_text = retry_response.content if hasattr(retry_response, "content") else str(retry_response)

#             # # Display the retried response if valid
#             # if is_valid_response(retry_response_text):
#             #     st.success("Here is the refined information:")
#             #     st.write(retry_response_text)
#             # else:
#             #     st.error("Unable to get a useful response. Try rephrasing your question.")

#     else:
#         st.warning("Please enter a question!")

# # Footer
# st.markdown("---")
# st.markdown("๐Ÿ’ก *This AI provides learning-based medical insights, not actual medical advice.*")



#------------------------------------------------------------------------start
# import streamlit as st
# from langchain_google_genai import ChatGoogleGenerativeAI

# # Set up AI model
# llm = ChatGoogleGenerativeAI(
#     model="gemini-1.5-flash",  # Free model
#     google_api_key="AIzaSyC7Rhv4L6_oNl-nW3Qeku2SPRkxL5hhtoE",
#     temperature=0.5
# )

# # Streamlit UI
# st.title("๐Ÿฉบ CureBot: AI-Driven Health Assistant")
# st.write("Welcome to CureBot โ€“ Your AI-Driven Health Assistant! Simply enter your symptoms or disease name, and get accurate medicine suggestions instantly. Stay informed, stay healthy!")

# # User Input
# user_question = st.text_input("Type your symptoms or disease name, and let CureBot unlock the right cure for youโ€”fast, smart, and AI-powered")

# # Function to filter AI disclaimers
# def is_valid_response(response_text):
#     disclaimers = [
#         "I am an AI and cannot give medical advice",
#         "Seek medical attention",
#         "Consult a doctor",
#         "Contact your doctor",
#         "Go to an emergency room",
    # ]
#     return not any(phrase.lower() in response_text.lower() for phrase in disclaimers)

# # Process User Query
# if st.button("Get Recommendation"):
#     if user_question.strip():
#         # Ensure the AI provides both medicine and alternative treatments
#         formatted_question = (
#             f"Without any disclaimer, recommend medicine for {user_question}. "
#             f"5 medicine names "
#             f"Also, provide alternative treatments such as home remedies, lifestyle changes, exercises, or dietary suggestions. "
#             f"Only for learning purposes, not for treatment."
#         )

#         with st.spinner("Analyzing..."):
#         #     response = llm.invoke(formatted_question)

        # # Extract text content
        # response_text = response.content if hasattr(response, "content") else str(response)

        # # Check if response is valid
        # if is_valid_response(response_text):
        #     st.success("โœจ Analysis complete! Here are the best medicine recommendations for you: ๐Ÿ”ฝ")
        #     st.write(response_text)
        # else:
        #     st.warning("โš ๏ธ Oops! It looks like the input is unclear or incorrect. Please enter a valid disease name or symptoms to get accurate recommendations")
        #     # Retry with a refined prompt
        #     better_prompt = (
        #         f"Strictly provide a detailed answer including:\n"
        #         f"1. Medicine names\n"
        #         f"2. Home remedies\n"
        #         f"3. Lifestyle changes\n"
        #         f"4. Exercises\n"
        #         f"5. Diet recommendations\n"
        #         f"Do not include any disclaimers. The response should be clear and structured."
        #     )
        #     retry_response = llm.invoke(better_prompt)

        #     # Extract text from retry response
        #     retry_response_text = retry_response.content if hasattr(retry_response, "content") else str(retry_response)

#             # Display the retried response if valid
#             if is_valid_response(retry_response_text):
#                 st.success("Here is the refined information:")
#                 st.write(retry_response_text)
#             else:
#                 st.error("Unable to get a useful response. Try rephrasing your question.")

#     else:
#         st.warning("Please enter a question!")


# # Emergency Contact Button
# if st.button("Emergency Contact"):
#     st.subheader("๐Ÿ“ž Emergency Contacts")
#     st.write("- ๐Ÿš‘ *Ambulance:* 102")
#     st.write("- ๐Ÿฅ *LPU Hospital:* 18001024432")
#     st.write("- ๐Ÿฅ *National Health Helpline:* 108")
#     st.write("- โ˜Ž *COVID-19 Helpline:*ย 1075")
#     st.write("- ๐Ÿš“ *Police:* 100")

# # Footer
# st.markdown("---")

# st.markdown("๐Ÿ”น Powered by Mayank, Wasim, Pravishank โ€“ Innovating Healthcare with AI! ๐Ÿ’ก Your Health, Our Mission. ๐Ÿš€")



#------------------------------------------------------------------------end



# 
# 
# 
# 


# 
# 
# 
# 
# 









'''
import streamlit as st
import speech_recognition as sr
from deep_translator import GoogleTranslator
from langchain_google_genai import ChatGoogleGenerativeAI
import matplotlib.pyplot as plt
import numpy as np

# Set up AI model
llm = ChatGoogleGenerativeAI(
    model="gemini-1.5-flash",
    google_api_key="AIzaSyC7Rhv4L6_oNl-nW3Qeku2SPRkxL5hhtoE",
    temperature=0.5
)

# Custom CSS
st.markdown("""
    <style>
        .big-font { font-size:20px !important; }
        .stButton>button { background-color: #ff4b4b; color: white; font-size: 18px; }
        .stTextInput>div>div>input { font-size: 16px; }
    </style>
""", unsafe_allow_html=True)

# UI Setup
# st.image("healthcare_logo.png", width=150)
st.title("๐Ÿฉบ CureBot: AI-Driven Health Assistant")
st.write("Empowering healthcare with AI-driven insights and recommendations!")

# Sidebar Navigation
st.sidebar.title("๐Ÿ” Navigation")
option = st.sidebar.radio("Select an option:", ["Home", "Symptom Checker", "Doctor Connect", "Health Stats"])
translator = GoogleTranslator(source='auto', target='en')

if option == "Home":
    user_question = st.text_input("Type your symptoms or disease name:")
    
    if st.button("๐ŸŽค Speak Symptoms"):
        recognizer = sr.Recognizer()
        with sr.Microphone() as source:
            st.info("Listening...")
            try:
                audio = recognizer.listen(source)
                user_question = recognizer.recognize_google(audio)
                st.success(f"Recognized: {user_question}")
            except sr.UnknownValueError:
                st.error("Could not understand audio")
            except sr.RequestError:
                st.error("Error in speech recognition service")
    
    lang = st.selectbox("Select Language", ["English", "Hindi", "Spanish"])
    if lang != "English":
        user_question = translator.translate(user_question, src="en", dest=lang.lower()).text
    
    if st.button("Get Recommendation"):
        if user_question.strip():
            formatted_question = (
                f"Provide medicine and alternative treatments for {user_question}. "
                f"List medicines, home remedies, lifestyle changes, exercises, and diet suggestions."
            )
            
            with st.spinner("Analyzing..."):
                response = llm.invoke(formatted_question)
            response_text = response.content if hasattr(response, "content") else str(response)
            st.success("โœจ Analysis complete! Here are your recommendations:")
            st.markdown(response_text)
        else:
            st.warning("Please enter a symptom or disease name!")
    
elif option == "Symptom Checker":
    st.subheader("๐Ÿ”Ž AI Symptom Checker")
    st.write("Find possible diseases based on symptoms.")
    symptoms = st.text_area("Enter symptoms separated by commas:")
    if st.button("Check Symptoms"):
        symptom_query = f"Analyze these symptoms: {symptoms}. List possible diseases."
        response = llm.invoke(symptom_query)
        st.write(response.content if hasattr(response, "content") else str(response))

elif option == "Doctor Connect":
    st.subheader("๐Ÿฅ Find a Doctor Near You")
    st.write("Using Google Maps API to find the nearest hospitals and doctors.")
    st.write("(Feature Under Development)")

elif option == "Health Stats":
    st.subheader("๐Ÿ“Š Health Trends & Data")
    
    diseases = ['Diabetes', 'Hypertension', 'Heart Disease', 'Asthma', 'Obesity']
    cases = np.random.randint(5000, 20000, size=len(diseases))
    
    fig, ax = plt.subplots()
    ax.barh(diseases, cases, color=['blue', 'green', 'red', 'purple', 'orange'])
    ax.set_xlabel("Number of Cases")
    ax.set_title("Disease Prevalence Statistics")
    st.pyplot(fig)

# Emergency Contact Section
st.sidebar.markdown("---")
st.sidebar.subheader("๐Ÿ“ž Emergency Contacts")
st.sidebar.write("- ๐Ÿš‘ *Ambulance:* 102")
st.sidebar.write("- ๐Ÿฅ *LPU Hospital:* 18001024432")
st.sidebar.write("- ๐Ÿฅ *National Health Helpline:* 108")
st.sidebar.write("- โ˜Ž *COVID-19 Helpline:* 1075")
st.sidebar.write("- ๐Ÿš“ *Police:* 1000")

st.markdown("---")
st.markdown("๐Ÿ”น Powered by Mayank, Wasim, Pravishank โ€“ Innovating Healthcare with AI! ๐Ÿ’ก Your Health, Our Mission. ๐Ÿš€")



'''




















import streamlit as st
import speech_recognition as sr
# import sounddevice as sd
from deep_translator import GoogleTranslator
from langchain_google_genai import ChatGoogleGenerativeAI
import matplotlib.pyplot as plt
import numpy as np
import folium
from streamlit_folium import folium_static
from geopy.geocoders import Nominatim
from geopy.distance import geodesic
import requests

# Set up AI model
llm = ChatGoogleGenerativeAI(
    model="gemini-1.5-flash",
    google_api_key="AIzaSyC7Rhv4L6_oNl-nW3Qeku2SPRkxL5hhtoE",
    temperature=0.5
)

# Custom CSS
st.markdown("""
    <style>
        .big-font { font-size:20px !important; }
        .stButton>button { background-color: #ff4b4b; color: white; font-size: 18px; }
        .stTextInput>div>div>input { font-size: 16px; }
    </style>
""", unsafe_allow_html=True)

# UI Setup
st.title("๐Ÿฉบ CureBot: AI-Driven Health Assistant")
st.write("Empowering healthcare with AI-driven insights and recommendations!")

# Sidebar Navigation
st.sidebar.title("๐Ÿ” Navigation")
option = st.sidebar.radio("Select an option:", ["Home", "Symptom Checker", "Doctor Connect", "Health Stats", "Health Risk Calculator"])
translator = GoogleTranslator(source='auto', target='en')

# Function to Get User Location
def get_user_location():
    try:
        response = requests.get("https://ipinfo.io/json").json()
        location = response["loc"].split(",")
        return float(location[0]), float(location[1])
    except:
        return None, None

if option == "Home":
    user_question = st.text_input("Type your disease name:")
    
#     st.title("๐ŸŽค AI Health Assistant - Speech to Text")

# uploaded_file = st.file_uploader("Upload an audio file (.wav)", type=["wav"])

# if uploaded_file:
#     recognizer = sr.Recognizer()
#     with sr.AudioFile(uploaded_file) as source:
#         st.info("Processing audio...")
#         audio = recognizer.record(source)
    
#     try:
#         text = recognizer.recognize_google(audio)
#         st.success(f"Recognized Text: {text}")
#     except sr.UnknownValueError:
#         st.error("Could not understand the audio")
#     except sr.RequestError:
#         st.error("Error with the speech recognition service")
    
    # lang = st.selectbox("Select Language", ["English", "Hindi", "Spanish"])
    # if lang != "English":
    #     user_question = translator.translate(user_question, src="en", dest=lang.lower()).text
    
    if st.button("Get Recommendation"):
        if user_question.strip():
            formatted_question = (
                f"Provide medicine and alternative treatments for {user_question}. "
                f"List medicines, home remedies, lifestyle changes, exercises, and diet suggestions."
            )
            
            with st.spinner("Analyzing..."):
                response = llm.invoke(formatted_question)
            response_text = response.content if hasattr(response, "content") else str(response)
            st.success("โœจ Analysis complete! Here are your recommendations:")
            st.markdown(response_text)
        else:
            st.warning("Please enter a symptom or disease name!")
    
elif option == "Symptom Checker":
    st.subheader("๐Ÿ”Ž AI Symptom Checker")
    st.write("Find possible diseases based on symptoms.")
    symptoms = st.text_area("Enter symptoms separated by commas:")
    if st.button("Check Symptoms"):
        symptom_query = f"Analyze these symptoms: {symptoms}. List possible diseases."
        response = llm.invoke(symptom_query)
        st.write(response.content if hasattr(response, "content") else str(response))


elif option == "Symptom Checker":
    st.subheader("๐Ÿ”Ž AI Symptom Checker")
    st.write("Find possible diseases based on symptoms.")
    symptoms = st.text_area("Enter symptoms separated by commas:")
    if st.button("Check Symptoms"):
        symptom_query = f"Analyze these symptoms: {symptoms}. List possible diseases."
        response = llm.invoke(symptom_query)
        st.write(response.content if hasattr(response, "content") else str(response))


elif option == "Doctor Connect":
    st.subheader("๐Ÿฅ Find a Doctor Near You")

    address = st.text_input("Enter your location (City, State or Latitude, Longitude):")

    if address:
        geolocator = Nominatim(user_agent="geoapi")
        location = geolocator.geocode(address)
        if location:
            lat, lon = location.latitude, location.longitude
            st.success(f"๐Ÿ“ Location detected: {location.address} ({lat}, {lon})")

            map_ = folium.Map(location=[lat, lon], zoom_start=13)
            folium.Marker([lat, lon], popup="You are here!", icon=folium.Icon(color="blue")).add_to(map_)
            folium_static(map_)
        else:
            st.error("โŒ Invalid address! Please try a different one.")
    else:
        st.info("โ„น๏ธ Please enter a location to view it on the map.")





# elif option == "Doctor Connect":
#     st.subheader("๐Ÿ“ Doctor Connect - Find Nearby Hospitals")
    
#     def get_user_location():
#         geolocator = Nominatim(user_agent="geoapi")
#         location = geolocator.geocode("Phagwara")  # Replace with dynamic location if needed
#         if location:
#             return location.latitude, location.longitude
#         return None
    
    # def find_nearby_hospitals(user_location):
    #     hospitals = [
    #         {"name": "Apollo Hospital", "location": (30.7333, 76.7794)},
    #         {"name": "Fortis Hospital", "location": (30.7194, 76.7644)},
    #         {"name": "Max Hospital", "location": (30.7086, 76.7853)},
    #         {"name": "AIIMS Hospital", "location": (30.7500, 76.7800)}
    #     ]
        
    #     nearby_hospitals = []
    #     for hospital in hospitals:
    #         distance = geodesic(user_location, hospital["location"]).km
    #         if distance <= 10:
    #             nearby_hospitals.append(hospital)
    #     return nearby_hospitals
    
    # user_location = get_user_location()
    # if user_location:
    #     st.success(f"๐Ÿ“ Your Location: {user_location}")
        
    #     m = folium.Map(location=user_location, zoom_start=13)
    #     folium.Marker(user_location, tooltip="Your Location", icon=folium.Icon(color="blue")).add_to(m)
        
    #     hospitals = find_nearby_hospitals(user_location)
    #     if hospitals:
    #         st.write("๐Ÿฅ Nearby Hospitals:")
    #         for hospital in hospitals:
    #             st.write(f"๐Ÿ”น {hospital['name']}")
    #             folium.Marker(hospital["location"], tooltip=hospital["name"], icon=folium.Icon(color="red")).add_to(m)
    #     else:
    #         st.write("โš ๏ธ No nearby hospitals found within 10 km.")
        
    #     folium_static(m)
    # else:
    #     st.error("โš ๏ธ Unable to fetch location. Please allow location access or enter manually.")
    
elif option == "Health Stats":
    st.subheader("๐Ÿ“Š Health Trends & Data")
    diseases = ['Diabetes', 'Hypertension', 'Heart Disease', 'Asthma', 'Obesity']
    cases = np.random.randint(5000, 20000, size=len(diseases))
    fig, ax = plt.subplots()
    ax.barh(diseases, cases, color=['blue', 'green', 'red', 'purple', 'orange'])
    ax.set_xlabel("Number of Cases")
    ax.set_title("Disease Prevalence Statistics")
    st.pyplot(fig)

elif option == "Health Risk Calculator":
    st.subheader("๐Ÿงฎ Health Risk Calculator")
    tabs = st.tabs(["๐Ÿ‹๏ธ BMI Calculator", "โค๏ธ Heart Risk Estimator", "๐Ÿฉธ Diabetes Risk Score"])

    # --- BMI CALCULATOR ---
    with tabs[0]:
        st.markdown("### ๐Ÿ‹๏ธ Body Mass Index (BMI) Calculator")
        height_cm = st.number_input("Enter height (in cm):", min_value=50.0, max_value=250.0, step=0.1)
        weight_kg = st.number_input("Enter weight (in kg):", min_value=10.0, max_value=300.0, step=0.1)

        if st.button("Calculate BMI"):
            if height_cm > 0:
                height_m = height_cm / 100
                bmi = weight_kg / (height_m ** 2)
                st.success(f"Your BMI is: **{bmi:.2f}**")
                if bmi < 18.5:
                    st.info("Underweight")
                elif 18.5 <= bmi < 24.9:
                    st.success("Normal weight")
                elif 25 <= bmi < 29.9:
                    st.warning("Overweight")
                else:
                    st.error("Obese")
            else:
                st.warning("Height must be greater than 0.")

    # --- HEART ATTACK RISK ---
    with tabs[1]:
        st.markdown("### โค๏ธ Heart Attack Risk Estimator")
        age = st.slider("Age", 18, 100, 30)
        gender = st.radio("Gender", ["Male", "Female"])
        smoker = st.radio("Do you smoke?", ["Yes", "No"])
        systolic_bp = st.slider("Systolic Blood Pressure (mmHg)", 80, 200, 120)
        cholesterol = st.slider("Cholesterol Level (mg/dL)", 100, 400, 200)

        if st.button("Estimate Heart Attack Risk"):
            risk_score = 0
            if age > 45: risk_score += 1
            if smoker == "Yes": risk_score += 1
            if systolic_bp > 140: risk_score += 1
            if cholesterol > 240: risk_score += 1
            if gender == "Male": risk_score += 0.5

            if risk_score <= 1:
                st.success("Low Risk โœ…")
            elif 2 <= risk_score <= 3:
                st.warning("Moderate Risk โš ๏ธ")
            else:
                st.error("High Risk โŒ")

    # --- DIABETES RISK ---
    with tabs[2]:
        st.markdown("### ๐Ÿฉธ Diabetes Risk Score Estimator")
        age_d = st.slider("Age", 10, 100, 30, key="d1")
        bmi_d = st.slider("BMI", 10.0, 50.0, 22.0, step=0.1, key="d2")
        family_history = st.radio("Family History of Diabetes?", ["Yes", "No"], key="d3")
        physical_activity = st.radio("Do you exercise regularly?", ["Yes", "No"], key="d4")
        diet = st.radio("Do you consume sugary or high-carb food often?", ["Yes", "No"], key="d5")

        if st.button("Estimate Diabetes Risk"):
            d_score = 0
            if age_d > 45: d_score += 1
            if bmi_d > 30: d_score += 1
            if family_history == "Yes": d_score += 1
            if physical_activity == "No": d_score += 1
            if diet == "Yes": d_score += 1

            if d_score <= 1:
                st.success("Low Risk โœ…")
            elif 2 <= d_score <= 3:
                st.warning("Moderate Risk โš ๏ธ")
            else:
                st.error("High Risk โŒ")       
# Emergency Contact Section
st.sidebar.markdown("---")
st.sidebar.subheader("๐Ÿ“ž Emergency Contacts")
st.sidebar.write("- ๐Ÿš‘ *Ambulance:* 102")
st.sidebar.write("- ๐Ÿฅ *LPU Hospital:* 18001024432")
st.sidebar.write("- ๐Ÿฅ *National Health Helpline:* 108")
st.sidebar.write("- โ˜Ž *COVID-19 Helpline:* 1075")
st.sidebar.write("- ๐Ÿš“ *Police:* 100")

st.markdown("---")
st.markdown("๐Ÿ”น Powered by Mayank, Wasim, Pravisank, Ananya โ€“ Innovating Healthcare with AI! ๐Ÿ’ก Your Health, Our Mission. ๐Ÿš€")








# '''
# import streamlit as st
# import speech_recognition as sr
# from deep_translator import GoogleTranslator
# from langchain_google_genai import ChatGoogleGenerativeAI
# import matplotlib.pyplot as plt
# import numpy as np
# import folium
# from streamlit_folium import folium_static
# import requests
# from geopy.geocoders import Nominatim

# # Initialize AI Model
# llm = ChatGoogleGenerativeAI(
#     model="gemini-1.5-flash",
#     google_api_key="YOUR_GOOGLE_API_KEY",
#     temperature=0.5
# )

# # Custom CSS
# st.markdown("""
#     <style>
#         .big-font { font-size:20px !important; }
#         .stButton>button { background-color: #ff4b4b; color: white; font-size: 18px; }
#         .stTextInput>div>div>input { font-size: 16px; }
#     </style>
# """, unsafe_allow_html=True)

# # App Title & Description
# st.title("๐Ÿฉบ CureBot: AI-Driven Health Assistant")
# st.write("Empowering healthcare with AI-driven insights and recommendations!")

# # Sidebar Navigation
# st.sidebar.title("๐Ÿ” Navigation")
# option = st.sidebar.radio("Select an option:", ["Home", "Symptom Checker", "Doctor Connect", "Health Stats"])
# translator = GoogleTranslator(source='auto', target='en')

# Function to Get User Location
# def get_user_location():
#     try:
#         response = requests.get("https://ipinfo.io/json").json()
#         location = response["loc"].split(",")
#         return float(location[0]), float(location[1])
#     except:
#         return None, None

# if option == "Home":
#     user_question = st.text_input("Type your symptoms or disease name:")
    
#     if st.button("๐ŸŽค Speak Symptoms"):
#         recognizer = sr.Recognizer()
#         with sr.Microphone() as source:
#             st.info("Listening...")
#             try:
#                 audio = recognizer.listen(source)
#                 user_question = recognizer.recognize_google(audio)
#                 st.success(f"Recognized: {user_question}")
#             except sr.UnknownValueError:
#                 st.error("Could not understand audio")
#             except sr.RequestError:
#                 st.error("Error in speech recognition service")
    
#     lang = st.selectbox("Select Language", ["English", "Hindi", "Spanish"])
#     if lang != "English":
#         user_question = translator.translate(user_question, src="en", dest=lang.lower())
    
#     if st.button("Get Recommendation"):
#         if user_question.strip():
#             formatted_question = (
#                 f"Provide medicine and alternative treatments for {user_question}. "
#                 f"List medicines, home remedies, lifestyle changes, exercises, and diet suggestions."
#             )
            
#             with st.spinner("Analyzing..."):
#                 response = llm.invoke(formatted_question)
#             response_text = response.content if hasattr(response, "content") else str(response)
#             st.success("โœจ Analysis complete! Here are your recommendations:")
#             st.markdown(response_text)
#         else:
#             st.warning("Please enter a symptom or disease name!")
    
# elif option == "Symptom Checker":
#     st.subheader("๐Ÿ”Ž AI Symptom Checker")
#     symptoms = st.text_area("Enter symptoms separated by commas:")
#     if st.button("Check Symptoms"):
#         symptom_query = f"Analyze these symptoms: {symptoms}. List possible diseases."
#         response = llm.invoke(symptom_query)
#         st.write(response.content if hasattr(response, "content") else str(response))

# elif option == "Doctor Connect":
#     st.subheader("๐Ÿฅ Find a Doctor Near You")
#     lat, lon = get_user_location()
    
    # if lat is None or lon is None:
#         st.warning("Unable to fetch location. Please allow location access or enter manually.")
#         address = st.text_input("Enter your location (City, State or Latitude, Longitude):")
#         if address:
#             geolocator = Nominatim(user_agent="geoapi")
#             location = geolocator.geocode(address)
#             if location:
#                 lat, lon = location.latitude, location.longitude
#             else:
#                 st.error("Invalid address! Try again.")
    
#     if lat and lon:
#         st.success(f"๐Ÿ“ Location detected: {lat}, {lon}")
#         map_ = folium.Map(location=[lat, lon], zoom_start=13)
#         folium.Marker([lat, lon], popup="You are here!", icon=folium.Icon(color="blue")).add_to(map_)
#         folium_static(map_)

# elif option == "Health Stats":
#     st.subheader("๐Ÿ“Š Health Trends & Data")
#     diseases = ['Diabetes', 'Hypertension', 'Heart Disease', 'Asthma', 'Obesity']
#     cases = np.random.randint(5000, 20000, size=len(diseases))
#     fig, ax = plt.subplots()
#     ax.barh(diseases, cases, color=['blue', 'green', 'red', 'purple', 'orange'])
#     ax.set_xlabel("Number of Cases")
#     ax.set_title("Disease Prevalence Statistics")
#     st.pyplot(fig)

# # Emergency Contacts
# st.sidebar.markdown("---")
# st.sidebar.subheader("๐Ÿ“ž Emergency Contacts")
# st.sidebar.write("- ๐Ÿš‘ *Ambulance:* 102")
# st.sidebar.write("- ๐Ÿฅ *LPU Hospital:* 18001024432")
# st.sidebar.write("- ๐Ÿฅ *National Health Helpline:* 108")
# st.sidebar.write("- โ˜Ž *COVID-19 Helpline:* 1075")
# st.sidebar.write("- ๐Ÿš“ *Police:* 1000")

# st.markdown("---")
# st.markdown("๐Ÿ”น Powered by Mayank, Wasim, Pravishank โ€“ Innovating Healthcare with AI! ๐Ÿ’ก Your Health, Our Mission. ๐Ÿš€")

# '''