Team Ai
Apppublic

virtual-assistant/implementation

sourceHugging Facemitupdated 2y agoView on Hugging Face
0likes
app.py207 linesDownload Raw Back to root
1import streamlit as st
2import pickle
3import pandas as pd
4from sklearn.feature_extraction.text import TfidfVectorizer
5from nltk.tokenize import word_tokenize
6from nltk.corpus import stopwords
7from nltk.stem import WordNetLemmatizer
8import nltk
9nltk.download('punkt')
10nltk.download('stopwords')
11nltk.download('wordnet')
12
13#from imblearn.over_sampling import SMOTE
14tab_1, tab_2 = st.tabs(['Diagnose','Health Information'])
15
16with open('rforest.pkl', 'rb') as file:
17        forest = pickle.load(file)
18with open('mlogreg.pkl', 'rb') as file:
19        logreg = pickle.load(file)
20count_vect = TfidfVectorizer(stop_words= 'english')
21
22option = st.sidebar.selectbox("Choose the action to perform in the application",('Diagnose','Health Information'))
23    
24if option == 'Diagnose' :
25
26    df = pd.read_csv("diseases.csv")
27    symptoms = tab_1.chat_input("How do you feel like")
28    
29    if symptoms :
30        tab_1.chat_message("user").write(symptoms)
31        sy = symptoms.lower()
32        sy_list = sy.split()
33        def convert_lower(text) :
34             text = text.lower()
35             return text
36        df['text'] = df['text'].apply(convert_lower)
37        def remove_stopwords(text) :
38             new_list = []
39             words = word_tokenize(text)
40             sw = stopwords.words('english')
41             sw.extend(["'ve",'discomfort'])
42             for word in words:
43                  if word not in sw:
44                       new_list.append(word)
45             return " ".join(new_list)
46        df['text'] = df['text'].apply(remove_stopwords)
47        def lemma(text):
48             lemmatize_text = []
49             words = word_tokenize(text)
50             for word in words :
51                  lemmatize_text.append(WordNetLemmatizer().lemmatize(word))
52             return " ".join(lemmatize_text)
53        df['text'] = df['text'].apply(lemma)
54        X = df['text']
55        y = df['label']
56        X_count_vect = count_vect.fit_transform(X)
57        #smote = SMOTE()
58        #X_resampled, y_resampled = smote.fit_resample(X_count_vect,y)
59        symptoms = convert_lower(symptoms)
60        symptoms = remove_stopwords(symptoms)
61        symptoms = lemma(symptoms)
62        data_vec = count_vect.fit_transform([symptoms])
63        df_count = pd.DataFrame(X_count_vect)
64        DF = []
65        for i in range(140) :
66            if i in df_count :
67                if i != 0 :
68                    DF.append(i)
69                else :
70                    DF.append(0)
71            else :
72                DF.append(0)
73        df_conv = pd.DataFrame([DF])  
74
75        pred = forest.predict(df_conv)
76        pred_proba = forest.predict_proba(df_conv)
77        if len(sy_list) < 8 :
78             tab_1.chat_message("assistant").write("""You are normal and not infected with any of malaria or typhoid.
79                             """)
80             tab_2.chat_message("assistant").write("""
81               You are free from both malaria and typhoid but should visit the doctor to discuss more about how you feel. 
82               So that you can get more detailed health information.               
83               """)
84        elif "cyclic fever" or "anemia" or "jaundice" in symptoms :
85             tab_1.chat_message("assistant").write("""You are infected with malaria you need to see the doctor for 
86                             medicine prescription
87                             """)
88             tab_2.chat_message("assistant").write("""
89               The treatment for malaria typically involves taking antimalarial medications, as prescribed by the doctor,
90               depending on the specific type of malaria and its resistance patterns.
91               It is important to start treatment as soon as possible after diagnosis to prevent complications and ensure a quick recovery.
92               In severe cases, hospitalization may be necessary for intravenous medications and supportive care.
93               Additionally, maintaining hydration, getting adequate rest,
94               and following up with healthcare providers for monitoring and further evaluation are essential components of the treatment plan.
95                                                       
96               """)
97        else :
98          if i in pred == "Malaria":
99               tab_1.chat_message("assistant").write("""You are infected with malaria you need to see the doctor for 
100                              medicine prescription
101                              """)
102               tab_2.chat_message("assistant").write("""
103               The treatment for malaria typically involves taking antimalarial medications, as prescribed by the doctor,
104               depending on the specific type of malaria and its resistance patterns.
105               It is important to start treatment as soon as possible after diagnosis to prevent complications and ensure a quick recovery.
106               In severe cases, hospitalization may be necessary for intravenous medications and supportive care.
107               Additionally, maintaining hydration, getting adequate rest,
108               and following up with healthcare providers for monitoring and further evaluation are essential components of the treatment plan.
109                                                       
110               """) 
111          #elif i in pred == "Typhoid":
112          else :
113               tab_1.chat_message("assistant").write("""You are infected with typhoid you need to see the doctor for 
114                              medicine prescription
115                              """)
116               tab_2.chat_message("assistant").write("""
117               The primary cure for typhoid fever involves antibiotics,That will be prescribed by the doctor,
118               .Additionally,supportive treatments such as hydration, rest, and proper nutrition are important to aid recovery.
119               In addition to taking antibiotics, it is crucial to stay well-hydrated by drinking plenty of fluids to prevent dehydration caused by fever and diarrhea.
120               Getting ample rest is essential to help your body fight off the infection and recover more quickly.
121               Maintaining proper nutrition by eating light, easily digestible foods such as soups, fruits, and boiled vegetables supports the immune system.
122
123               Practicing good personal hygiene, including regular handwashing with soap and water, helps prevent the spread of the infection to others.
124               It is important to consume only safe, well-cooked food and drink purified or bottled water to avoid re-infection.
125               Attending follow-up appointments with your healthcare provider ensures the infection is completely cleared and monitors for any potential complications.
126               Finally, consider getting vaccinated against typhoid fever if you live in or plan to travel to areas where the disease is common.
127                                                       
128               """)
129        #else :
130             #tab_1.chat_message("assistant").write("""The diagnosis isnt you need to see the doctor for 
131                             
132              #               """)
133             #tab_2.chat_message("assistant").write("""
134          #The diagnosis is neither malaria nor typhoid, you are advised to contact the doctor for further test.                                       
135         # """)
136        #tab_1.chat_message("assistant").write(f"Echo: {pred}, {pred_proba}")
137
138else :
139     info_option = st.sidebar.selectbox("Choose the health information needed",('Malaria','Typhoid'))
140     if info_option == "Malaria" :
141          tab_2.title("Malaria Health Information")
142          tab_2.write(
143          """
144          Malaria is a very old disease, with references found in ancient Chinese, Greek, and Roman texts,
145          and for a long time, people believed it was caused by bad air from swamps.
146          In the late 1800s, a scientist named Charles Louis Alphonse Laveran discovered that malaria is actually caused by tiny parasites.
147          Later, Ronald Ross found that these parasites are spread by mosquitoes, specifically female Anopheles mosquitoes,
148          which bite humans and pass the parasites into their bloodstream.
149
150          Malaria is caused by parasites called Plasmodium,
151          with five types that can infect humans: Plasmodium falciparum, P. vivax, P. malariae, P. ovale, and P. knowlesi.
152          These parasites enter the body when an infected mosquito bites a person, travel to the liver to grow and multiply,
153          and then move into the bloodstream to infect red blood cells.
154
155          The symptoms of malaria usually start 10-15 days after an infected mosquito bite.
156          Common symptoms include high fever, severe chills, persistent headaches, heavy sweating,
157          extreme tiredness, aching muscles and joints, nausea and vomiting,
158          stomach pain, frequent loose bowel movements, low red blood cell count (anemia) causing paleness and shortness of breath,
159          and yellowing of the skin and eyes (jaundice). In severe cases, malaria can cause confusion, seizures, and organ failure, which can be life-threatening.
160
161          To prevent malaria, several steps can be taken:
162          use insect repellents containing DEET or picaridin to keep mosquitoes away,
163          sleep under insecticide-treated mosquito nets to avoid bites at night,
164          wear long sleeves and pants especially during dawn and dusk when mosquitoes are most active,
165          and spray the inside of homes with insecticides to kill mosquitoes. Additionally, eliminate standing water around your home where mosquitoes can breed,
166          take preventive antimalarial medications if you are traveling to a high-risk area, and consider getting vaccinated with the RTS,S/AS01 (Mosquirix) vaccine,
167          especially if you live in or are traveling to regions where malaria is common.
168
169     """ )
170     else :
171          tab_2.title("Typhoid Information")
172          tab_2.write(
173          """
174               Typhoid fever is a disease that has been known for many centuries.
175               It was first clearly described in the early 19th century, but the bacteria that cause it, Salmonella Typhi, were discovered by Karl Joseph Eberth in 1880.
176               Before the development of modern sanitation and antibiotics, typhoid fever caused many outbreaks and was a significant cause of illness and death.
177
178     Cause
179     Typhoid fever is caused by the bacteria Salmonella Typhi. People get infected by consuming food or water that has been contaminated with the feces of an infected person.
180     This can happen when proper hygiene practices, like washing hands with soap, are not followed, or when sewage contaminates drinking water.
181
182     Symptoms
183     Symptoms of typhoid fever usually appear 1-3 weeks after exposure to the bacteria. Common symptoms include:
184
185     Fever: A high, sustained fever that can reach up to 104°F (40°C).
186     Weakness: Feeling very weak and tired.
187     Stomach pain: Pain or discomfort in the abdominal area.
188     Headache: Persistent pain in the head.
189     Loss of appetite: Not feeling hungry and eating less than usual.
190     Diarrhea or constipation: Some people may have diarrhea, while others may experience constipation.
191     Rash: Some people may develop a rash of flat, rose-colored spots.
192     If not treated, typhoid fever can become very serious, leading to complications such as intestinal bleeding or perforation, which can be life-threatening.
193
194     Preventive Measures
195     To prevent typhoid fever, follow these steps:
196
197     Good Hygiene: Always wash your hands thoroughly with soap and water, especially before eating and after using the toilet.
198     Safe Drinking Water: Drink only boiled or bottled water. Avoid ice cubes unless you are sure they are made from safe water.
199     Proper Food Handling: Eat food that is thoroughly cooked and still hot. Avoid raw fruits and vegetables unless you can peel them yourself.
200     Avoid Street Food: Be cautious with food from street vendors, as it might not be prepared under hygienic conditions.
201     Vaccination: Get vaccinated against typhoid fever, especially if you are traveling to areas where the disease is common.
202     There are two main types of vaccines: an injection given as a single dose and an oral vaccine taken in multiple doses over several days.
203     Sanitation: Ensure proper sanitation practices are in place to prevent contamination of food and water sources.
204     By following these preventive measures, you can significantly reduce your risk of getting typhoid fever.
205
206     """ 
207          )