Muhammad Haris
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,63 +1,82 @@
|
|
1 |
-
import
|
2 |
import pandas as pd
|
|
|
3 |
from sklearn.metrics.pairwise import cosine_similarity
|
4 |
-
import
|
5 |
-
import
|
6 |
-
import
|
7 |
import gdown
|
8 |
-
|
|
|
9 |
|
10 |
-
# Download the file
|
11 |
file_id = '1P3Nz6f3KG0m0kO_2pEfnVIhgP8Bvkl4v'
|
12 |
url = f'https://drive.google.com/uc?id={file_id}'
|
13 |
excel_file_path = os.path.join(os.path.expanduser("~"), 'medical_data.csv')
|
14 |
|
15 |
-
|
16 |
-
|
17 |
-
# Read the CSV file into a DataFrame using 'latin1' encoding
|
18 |
try:
|
19 |
medical_df = pd.read_csv(excel_file_path, encoding='utf-8')
|
20 |
except UnicodeDecodeError:
|
21 |
medical_df = pd.read_csv(excel_file_path, encoding='latin1')
|
22 |
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
model
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
import pandas as pd
|
3 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
4 |
from sklearn.metrics.pairwise import cosine_similarity
|
5 |
+
from transformers import GPT2Tokenizer, GPT2LMHeadModel
|
6 |
+
from sentence_transformers import SentenceTransformer, util
|
7 |
+
import torch
|
8 |
import gdown
|
9 |
+
import os
|
10 |
+
|
11 |
|
|
|
12 |
file_id = '1P3Nz6f3KG0m0kO_2pEfnVIhgP8Bvkl4v'
|
13 |
url = f'https://drive.google.com/uc?id={file_id}'
|
14 |
excel_file_path = os.path.join(os.path.expanduser("~"), 'medical_data.csv')
|
15 |
|
16 |
+
# Read the CSV file
|
|
|
|
|
17 |
try:
|
18 |
medical_df = pd.read_csv(excel_file_path, encoding='utf-8')
|
19 |
except UnicodeDecodeError:
|
20 |
medical_df = pd.read_csv(excel_file_path, encoding='latin1')
|
21 |
|
22 |
+
# TF-IDF Vectorization
|
23 |
+
vectorizer = TfidfVectorizer(stop_words='english')
|
24 |
+
X_tfidf = vectorizer.fit_transform(medical_df['Questions'])
|
25 |
+
|
26 |
+
# Load pre-trained GPT-2 model and tokenizer
|
27 |
+
model_name = "sshleifer/tiny-gpt2"
|
28 |
+
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
|
29 |
+
model = GPT2LMHeadModel.from_pretrained(model_name)
|
30 |
+
|
31 |
+
# Load pre-trained Sentence Transformer model
|
32 |
+
sbert_model_name = "paraphrase-MiniLM-L6-v2"
|
33 |
+
sbert_model = SentenceTransformer(sbert_model_name)
|
34 |
+
|
35 |
+
|
36 |
+
# Function to answer medical questions using a combination of TF-IDF, LLM, and semantic similarity
|
37 |
+
def get_medical_response(question, vectorizer, X_tfidf, model, tokenizer, sbert_model, medical_df):
|
38 |
+
# TF-IDF Cosine Similarity
|
39 |
+
question_vector = vectorizer.transform([question])
|
40 |
+
tfidf_similarities = cosine_similarity(question_vector, X_tfidf).flatten()
|
41 |
+
|
42 |
+
# Find the most similar question using semantic similarity
|
43 |
+
question_embedding = sbert_model.encode(question, convert_to_tensor=True)
|
44 |
+
similarities = util.pytorch_cos_sim(question_embedding, sbert_model.encode(medical_df['Questions'].tolist(), convert_to_tensor=True)).flatten()
|
45 |
+
max_sim_index = similarities.argmax().item()
|
46 |
+
|
47 |
+
# LLM response generation
|
48 |
+
input_text = "DiBot: " + medical_df.iloc[max_sim_index]['Questions']
|
49 |
+
input_ids = tokenizer.encode(input_text, return_tensors="pt")
|
50 |
+
attention_mask = torch.ones(input_ids.shape, dtype=torch.long)
|
51 |
+
pad_token_id = tokenizer.eos_token_id
|
52 |
+
lm_output = model.generate(input_ids, max_length=150, num_return_sequences=1, no_repeat_ngram_size=2, attention_mask=attention_mask, pad_token_id=pad_token_id)
|
53 |
+
lm_generated_response = tokenizer.decode(lm_output[0], skip_special_tokens=True)
|
54 |
+
|
55 |
+
# Compare similarities and choose the best response
|
56 |
+
if tfidf_similarities.max() > 0.5:
|
57 |
+
tfidf_index = tfidf_similarities.argmax()
|
58 |
+
return medical_df.iloc[tfidf_index]['Answers']
|
59 |
+
else:
|
60 |
+
return lm_generated_response
|
61 |
+
|
62 |
+
# Streamlit UI
|
63 |
+
st.title("DiBot")
|
64 |
+
|
65 |
+
if "messages" not in st.session_state:
|
66 |
+
st.session_state.messages = []
|
67 |
+
|
68 |
+
for message in st.session_state.messages:
|
69 |
+
with st.chat_message(message["role"]):
|
70 |
+
st.markdown(message["content"])
|
71 |
+
|
72 |
+
user_input = st.chat_input("You:")
|
73 |
+
|
74 |
+
if user_input:
|
75 |
+
response = get_medical_response(user_input, vectorizer, X_tfidf, model, tokenizer, sbert_model, medical_df)
|
76 |
+
st.session_state.messages.append({"role": "user", "content": user_input})
|
77 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
78 |
+
|
79 |
+
# Display the chat messages
|
80 |
+
for message in st.session_state.messages:
|
81 |
+
with st.chat_message(message["role"]):
|
82 |
+
st.markdown(message["content"])
|