Hackaton / app.py
akazmi's picture
Update app.py
0dcfe8b verified
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
import gradio as gr
# Sample medicine data
data = {
'drug_name': ['Paracetamol', 'Ibuprofen', 'Aspirin', 'Amoxicillin', 'Ciprofloxacin', 'Lisinopril'],
'composition': [
'Paracetamol 500mg',
'Ibuprofen 200mg',
'Aspirin 100mg',
'Amoxicillin 500mg',
'Ciprofloxacin 500mg',
'Lisinopril 10mg'
],
'description': [
'Used for pain relief and fever reduction.',
'Nonsteroidal anti-inflammatory drug (NSAID).',
'Used to reduce pain, fever, or inflammation.',
'Antibiotic used to treat bacterial infections.',
'Antibiotic used to treat a variety of bacterial infections.',
'Used to treat high blood pressure.'
]
}
# Create a DataFrame from the sample data
medicines_df = pd.DataFrame(data)
# Create the TF-IDF matrix for finding similar medicines
tfidf = TfidfVectorizer(stop_words='english')
tfidf_matrix = tfidf.fit_transform(medicines_df['composition'].fillna(''))
# Compute the cosine similarity matrix
cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)
# Function to get recommendations based on drug name or composition
def get_alternatives(drug_name, cosine_sim=cosine_sim):
if drug_name not in medicines_df['drug_name'].values:
return pd.DataFrame(columns=['drug_name', 'composition']) # Return empty DataFrame if not found
idx = medicines_df.index[medicines_df['drug_name'] == drug_name][0]
sim_scores = list(enumerate(cosine_sim[idx]))
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
sim_scores = sim_scores[1:4] # Get top 3 alternatives
alternative_indices = [i[0] for i in sim_scores]
return medicines_df.iloc[alternative_indices][['drug_name', 'composition']]
# Define the recommend_alternative function for Gradio
def recommend_alternative(selected_drug):
alternatives = get_alternatives(selected_drug)
return alternatives
# Create the Gradio interface
drug_names = medicines_df['drug_name'].dropna().tolist() # List of drug names
interface = gr.Interface(
fn=recommend_alternative,
inputs=gr.Dropdown(choices=drug_names, label="Select a Drug"),
outputs="dataframe",
title="Medicine Alternative Recommendation System",
description="Select a medicine to see alternative drugs with similar compositions."
)
# Launch the interface
if __name__ == "__main__":
interface.launch()