Fredaaaaaa commited on
Commit
80f4e12
·
verified ·
1 Parent(s): 62ce45c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -21
app.py CHANGED
@@ -1,16 +1,19 @@
 
1
  import pickle
2
  import requests
 
3
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
  import torch
 
5
  import gradio as gr
6
 
7
- # Load label encoder
8
- label_encoder_path = 'Fredaaaaaa/hybrid_model/label_encoder.pkl' # Path to the uploaded label encoder
9
  with open(label_encoder_path, 'rb') as f:
10
  label_encoder = pickle.load(f)
11
 
12
- # Load model and tokenizer from Hugging Face model directory
13
- model_name = "Fredaaaaaa/hybrid_model"
14
  model = AutoModelForSequenceClassification.from_pretrained(model_name)
15
  tokenizer = AutoTokenizer.from_pretrained(model_name)
16
 
@@ -18,7 +21,7 @@ tokenizer = AutoTokenizer.from_pretrained(model_name)
18
  def get_drug_features(drug1, drug2):
19
  api_url = f'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{drug1}/property/SMILES,Pharmacology,Toxicity,Mechanism-of-action,Route-of-elimination,Metabolism/JSON'
20
  response = requests.get(api_url)
21
-
22
  if response.status_code == 200:
23
  data = response.json()
24
  drug_features = {
@@ -31,48 +34,72 @@ def get_drug_features(drug1, drug2):
31
  }
32
  return drug_features
33
  else:
34
- return None
35
 
36
- # Function to predict severity based on drug interactions
37
- def predict_severity(drug1, drug2):
38
- # Check if drugs are present in the dataset
39
  if drug1 in df['Drug 1_normalized'].values and drug2 in df['Drug 2_normalized'].values:
40
- # Predict severity based on the dataset (your logic for prediction)
41
- # Add your prediction logic based on the dataset here
42
- severity = "Predicted severity based on dataset logic"
43
- return severity
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  else:
45
- # If drugs not found in dataset, call the external API to fetch their features
46
  drug_features = get_drug_features(drug1, drug2)
47
 
48
  if not drug_features:
49
  return "Error: Could not fetch drug features from the API."
50
 
51
  # Preprocess text data (interaction description)
52
- interaction_description = f"{drug1} interacts with {drug2}"
53
  inputs = tokenizer(interaction_description, return_tensors="pt", padding=True, truncation=True, max_length=128)
54
- input_ids = inputs['input_ids'].to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
55
- attention_mask = inputs['attention_mask'].to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
56
 
57
  # Process drug features (SMILES, pharmacology, toxicity, etc.)
58
  drug_feature_values = [drug_features['SMILES'], drug_features['pharmacology'], drug_features['toxicity']]
59
- drug_features_tensor = torch.tensor(drug_feature_values, dtype=torch.float32).unsqueeze(0).to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
60
 
61
  # Run the model to get predictions
62
  model.eval()
63
  with torch.no_grad():
64
- outputs = model(input_ids, attention_mask)
65
 
66
  # Get the predicted class
67
- prediction = torch.argmax(outputs.logits, dim=1).item()
68
 
69
  # Map the predicted class index to the severity label
70
  severity_labels = ["No interaction", "Mild", "Moderate", "Severe"]
71
  return severity_labels[prediction]
72
 
 
 
 
 
73
  # Gradio Interface
74
  interface = gr.Interface(
75
- fn=predict_severity,
76
  inputs=[gr.Textbox(label="Drug 1"), gr.Textbox(label="Drug 2")],
77
  outputs="text",
78
  live=True
@@ -80,3 +107,4 @@ interface = gr.Interface(
80
 
81
  # Launch the interface
82
  interface.launch()
 
 
1
+ import os
2
  import pickle
3
  import requests
4
+ from huggingface_hub import hf_hub_download
5
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
6
  import torch
7
+ import torch.nn.functional as F
8
  import gradio as gr
9
 
10
+ # Function to download the label encoder from Hugging Face
11
+ label_encoder_path = hf_hub_download(repo_id="Fredaaaaaa/hybrid_model", filename="label_encoder.pkl")
12
  with open(label_encoder_path, 'rb') as f:
13
  label_encoder = pickle.load(f)
14
 
15
+ # Load the model and tokenizer
16
+ model_name = "Fredaaaaaa/hybrid_model" # Update with the correct model repo
17
  model = AutoModelForSequenceClassification.from_pretrained(model_name)
18
  tokenizer = AutoTokenizer.from_pretrained(model_name)
19
 
 
21
  def get_drug_features(drug1, drug2):
22
  api_url = f'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{drug1}/property/SMILES,Pharmacology,Toxicity,Mechanism-of-action,Route-of-elimination,Metabolism/JSON'
23
  response = requests.get(api_url)
24
+
25
  if response.status_code == 200:
26
  data = response.json()
27
  drug_features = {
 
34
  }
35
  return drug_features
36
  else:
37
+ return None # If no data is returned, handle the missing values gracefully
38
 
39
+ # Function to check if the drugs are in the dataset
40
+ def check_drugs_in_dataset(drug1, drug2, df):
 
41
  if drug1 in df['Drug 1_normalized'].values and drug2 in df['Drug 2_normalized'].values:
42
+ return True
43
+ return False
44
+
45
+ # Function to process the input and predict severity
46
+ def predict_severity(drug1, drug2, df):
47
+ # Check if drugs are in the dataset first
48
+ if check_drugs_in_dataset(drug1, drug2, df):
49
+ # Preprocess text data (interaction description)
50
+ interaction_description = f"{drug1} interacts with {drug2}" # Example interaction description
51
+ inputs = tokenizer(interaction_description, return_tensors="pt", padding=True, truncation=True, max_length=128)
52
+ input_ids = inputs['input_ids'].to(device)
53
+ attention_mask = inputs['attention_mask'].to(device)
54
+
55
+ # Run the model to get predictions
56
+ model.eval()
57
+ with torch.no_grad():
58
+ outputs = model(input_ids, attention_mask=attention_mask)
59
+
60
+ # Get the predicted class
61
+ prediction = torch.argmax(outputs.logits, dim=1).item()
62
+
63
+ # Map the predicted class index to the severity label
64
+ severity_labels = ["No interaction", "Mild", "Moderate", "Severe"]
65
+ return severity_labels[prediction]
66
+
67
  else:
68
+ # Fetch drug features from the external API if not in the dataset
69
  drug_features = get_drug_features(drug1, drug2)
70
 
71
  if not drug_features:
72
  return "Error: Could not fetch drug features from the API."
73
 
74
  # Preprocess text data (interaction description)
75
+ interaction_description = f"{drug1} interacts with {drug2}" # Example interaction description
76
  inputs = tokenizer(interaction_description, return_tensors="pt", padding=True, truncation=True, max_length=128)
77
+ input_ids = inputs['input_ids'].to(device)
78
+ attention_mask = inputs['attention_mask'].to(device)
79
 
80
  # Process drug features (SMILES, pharmacology, toxicity, etc.)
81
  drug_feature_values = [drug_features['SMILES'], drug_features['pharmacology'], drug_features['toxicity']]
82
+ drug_features_tensor = torch.tensor(drug_feature_values, dtype=torch.float32).unsqueeze(0).to(device)
83
 
84
  # Run the model to get predictions
85
  model.eval()
86
  with torch.no_grad():
87
+ outputs = model(input_ids, attention_mask, drug_features_tensor)
88
 
89
  # Get the predicted class
90
+ prediction = torch.argmax(outputs, dim=1).item()
91
 
92
  # Map the predicted class index to the severity label
93
  severity_labels = ["No interaction", "Mild", "Moderate", "Severe"]
94
  return severity_labels[prediction]
95
 
96
+ # Set device
97
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
98
+ print(f"🚀 Device: {device}")
99
+
100
  # Gradio Interface
101
  interface = gr.Interface(
102
+ fn=lambda drug1, drug2: predict_severity(drug1, drug2, df), # Pass dataset to the prediction function
103
  inputs=[gr.Textbox(label="Drug 1"), gr.Textbox(label="Drug 2")],
104
  outputs="text",
105
  live=True
 
107
 
108
  # Launch the interface
109
  interface.launch()
110
+