Update app.py to allow api calls to the site

#2
by Code0ut - opened
Files changed (1) hide show
  1. app.py +19 -59
app.py CHANGED
@@ -11,17 +11,12 @@ from torch.nn.functional import cosine_similarity
11
  from sentence_transformers import SentenceTransformer
12
  import gradio as gr
13
 
14
- # ---------------------
15
- # 1. Download NLTK Data
16
- # ---------------------
17
  nltk.download('punkt')
18
- nltk.download('punkt_tab')
19
  nltk.download('stopwords')
20
  nltk.download('wordnet')
21
 
22
- # ---------------------
23
- # 2. Load Dataset
24
- # ---------------------
25
  dataset_path = "dataset.json"
26
  if not os.path.exists(dataset_path):
27
  raise FileNotFoundError(f"{dataset_path} not found. Please ensure the file is in the current directory.")
@@ -29,42 +24,28 @@ if not os.path.exists(dataset_path):
29
  with open(dataset_path, "r") as f:
30
  data = json.load(f)
31
 
32
- # Convert dataset into a dictionary: disease name -> details
33
  disease_data = {d["name"]: d for d in data["diseases"]}
34
- print("Sample Disease (Acne):")
35
- print(json.dumps(disease_data.get("Acne", {}), indent=2))
36
 
37
- # ---------------------
38
- # 3. Advanced Preprocessing Functions
39
- # ---------------------
40
  lemmatizer = WordNetLemmatizer()
41
  stop_words = set(stopwords.words('english'))
42
 
43
- # Mapping for common medical synonyms to standardize terminology
44
  medical_synonyms = {
45
- "itchy": "itch",
46
- "pruritic": "itch",
47
- "rash": "eruption",
48
- "redness": "red",
49
- "swollen": "swelling",
50
- "bumps": "lesion"
51
  }
52
 
 
53
  def advanced_preprocess_text(text):
54
- # Lowercase and remove unwanted characters (retain only letters and spaces)
55
  text = text.lower()
56
  text = re.sub(r'[^a-zA-Z\s]', ' ', text)
57
  tokens = word_tokenize(text)
58
- # Replace tokens using the medical synonym mapping
59
  tokens = [medical_synonyms.get(token, token) for token in tokens]
60
- # Remove stopwords and lemmatize
61
  tokens = [lemmatizer.lemmatize(token) for token in tokens if token not in stop_words]
62
  return " ".join(tokens)
63
 
64
- # ---------------------
65
- # 4. Prepare Disease Descriptions & Embeddings Using BERT
66
- # ---------------------
67
- # For each disease, combine symptoms, causes, cure, and home remedies into a detailed description.
68
  disease_names = []
69
  disease_descriptions = []
70
 
@@ -82,51 +63,33 @@ for disease_name, details in disease_data.items():
82
  processed_desc = advanced_preprocess_text(description)
83
  disease_descriptions.append(processed_desc)
84
 
85
- # Initialize SentenceTransformer (BERT-based model)
86
  bert_model = SentenceTransformer('all-MiniLM-L6-v2')
87
- # Compute embeddings for each disease description (as torch tensors)
88
  disease_embeddings = bert_model.encode(disease_descriptions, convert_to_tensor=True)
89
- print("Computed disease embeddings for", len(disease_embeddings), "diseases.")
90
-
91
- # ---------------------
92
- # 5. Detailed User Input Collection
93
- # ---------------------
94
- def get_detailed_user_input(primary_symptom, location, associated_symptoms, duration, severity, additional_info):
95
- # Combine all responses into one detailed description.
96
- combined_input = " ".join([primary_symptom, location, associated_symptoms, duration, severity, additional_info])
97
- return combined_input
98
-
99
- # ---------------------
100
- # 6. Chatbot Prediction Function Using BERT Similarity
101
- # ---------------------
102
- def chatbot_response(user_input):
103
  processed_input = advanced_preprocess_text(user_input)
104
  user_embedding = bert_model.encode(processed_input, convert_to_tensor=True)
105
  similarities = cosine_similarity(user_embedding, disease_embeddings)
106
  best_match_idx = torch.argmax(similarities).item()
107
  predicted_disease = disease_names[best_match_idx]
108
- return predicted_disease
109
 
110
- # ---------------------
111
- # 7. Gradio Chatbot Function
112
- # ---------------------
113
- def gradio_chatbot(primary_symptom, location, associated_symptoms, duration, severity, additional_info):
114
- detailed_input = get_detailed_user_input(primary_symptom, location, associated_symptoms, duration, severity, additional_info)
115
- predicted = chatbot_response(detailed_input)
116
- details = disease_data.get(predicted, {})
117
  causes = ", ".join(details.get("causes", ["Not available"]))
118
  cure = ", ".join(details.get("cure", ["Not available"]))
119
  home_remedies = ", ".join(details.get("home_remedies", ["Not available"]))
120
-
121
- response = (f"🩺 **Predicted Disease:** {predicted}\n\n"
122
  f"**Causes:** {causes}\n\n"
123
  f"**Cure:** {cure}\n\n"
124
  f"**Home Remedies:** {home_remedies}")
125
  return response
126
 
127
- # ---------------------
128
- # 8. Gradio Interface Setup
129
- # ---------------------
130
  iface = gr.Interface(
131
  fn=gradio_chatbot,
132
  inputs=[
@@ -142,7 +105,4 @@ iface = gr.Interface(
142
  description="Answer a few questions about your symptoms and get a predicted skin disease along with recommended solutions."
143
  )
144
 
145
- # ---------------------
146
- # 9. Launch the Gradio App on Hugging Face Spaces
147
- # ---------------------
148
  iface.launch()
 
11
  from sentence_transformers import SentenceTransformer
12
  import gradio as gr
13
 
14
+ # Download necessary NLTK data
 
 
15
  nltk.download('punkt')
 
16
  nltk.download('stopwords')
17
  nltk.download('wordnet')
18
 
19
+ # Load dataset
 
 
20
  dataset_path = "dataset.json"
21
  if not os.path.exists(dataset_path):
22
  raise FileNotFoundError(f"{dataset_path} not found. Please ensure the file is in the current directory.")
 
24
  with open(dataset_path, "r") as f:
25
  data = json.load(f)
26
 
 
27
  disease_data = {d["name"]: d for d in data["diseases"]}
 
 
28
 
29
+ # Preprocessing
 
 
30
  lemmatizer = WordNetLemmatizer()
31
  stop_words = set(stopwords.words('english'))
32
 
 
33
  medical_synonyms = {
34
+ "itchy": "itch", "pruritic": "itch", "rash": "eruption",
35
+ "redness": "red", "swollen": "swelling", "bumps": "lesion"
 
 
 
 
36
  }
37
 
38
+
39
  def advanced_preprocess_text(text):
 
40
  text = text.lower()
41
  text = re.sub(r'[^a-zA-Z\s]', ' ', text)
42
  tokens = word_tokenize(text)
 
43
  tokens = [medical_synonyms.get(token, token) for token in tokens]
 
44
  tokens = [lemmatizer.lemmatize(token) for token in tokens if token not in stop_words]
45
  return " ".join(tokens)
46
 
47
+
48
+ # Prepare disease descriptions
 
 
49
  disease_names = []
50
  disease_descriptions = []
51
 
 
63
  processed_desc = advanced_preprocess_text(description)
64
  disease_descriptions.append(processed_desc)
65
 
66
+ # Load BERT model
67
  bert_model = SentenceTransformer('all-MiniLM-L6-v2')
 
68
  disease_embeddings = bert_model.encode(disease_descriptions, convert_to_tensor=True)
69
+
70
+
71
+ def gradio_chatbot(primary_symptom, location, associated_symptoms, duration, severity, additional_info):
72
+ user_input = " ".join([
73
+ primary_symptom, location, associated_symptoms, duration, severity, additional_info
74
+ ])
 
 
 
 
 
 
 
 
75
  processed_input = advanced_preprocess_text(user_input)
76
  user_embedding = bert_model.encode(processed_input, convert_to_tensor=True)
77
  similarities = cosine_similarity(user_embedding, disease_embeddings)
78
  best_match_idx = torch.argmax(similarities).item()
79
  predicted_disease = disease_names[best_match_idx]
80
+ details = disease_data.get(predicted_disease, {})
81
 
 
 
 
 
 
 
 
82
  causes = ", ".join(details.get("causes", ["Not available"]))
83
  cure = ", ".join(details.get("cure", ["Not available"]))
84
  home_remedies = ", ".join(details.get("home_remedies", ["Not available"]))
85
+
86
+ response = (f"🩺 **Predicted Disease:** {predicted_disease}\n\n"
87
  f"**Causes:** {causes}\n\n"
88
  f"**Cure:** {cure}\n\n"
89
  f"**Home Remedies:** {home_remedies}")
90
  return response
91
 
92
+
 
 
93
  iface = gr.Interface(
94
  fn=gradio_chatbot,
95
  inputs=[
 
105
  description="Answer a few questions about your symptoms and get a predicted skin disease along with recommended solutions."
106
  )
107
 
 
 
 
108
  iface.launch()