MahatirTusher commited on
Commit
5acccc4
·
verified ·
1 Parent(s): 62ebd13

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -0
app.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ import gradio as gr
4
+ from langchain_community.vectorstores import FAISS
5
+ from langchain_huggingface import HuggingFaceEmbeddings
6
+ from langchain_groq import ChatGroq
7
+ from langchain.prompts import PromptTemplate
8
+ from langchain.chains import RetrievalQA
9
+ from langchain_core.documents import Document
10
+
11
+ # Hardcoded Groq API key
12
+ GROK_API_KEY = "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"
13
+
14
+ # Initialize LLM (Grok)
15
+ def initialize_llm():
16
+ return ChatGroq(
17
+ temperature=0.7,
18
+ groq_api_key=GROK_API_KEY,
19
+ model_name="llama-3.3-70b-versatile"
20
+ )
21
+
22
+ llm = initialize_llm()
23
+
24
+ # Load and prepare the CSV dataset, then create or load FAISS index
25
+ def create_or_load_faiss_index():
26
+ index_path = "faiss_index"
27
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
28
+
29
+ if os.path.exists(index_path):
30
+ vector_db = FAISS.load_local(index_path, embeddings, allow_dangerous_deserialization=True)
31
+ else:
32
+ csv_path = "A_Z_medicines_dataset_of_India.csv"
33
+ if not os.path.exists(csv_path):
34
+ raise FileNotFoundError(f"Dataset not found at: {csv_path}")
35
+
36
+ df = pd.read_csv(csv_path)
37
+ documents = [
38
+ Document(
39
+ page_content=row["name"],
40
+ metadata={"short_composition1": row["short_composition1"]}
41
+ )
42
+ for _, row in df.iterrows()
43
+ if pd.notna(row["name"]) and pd.notna(row["short_composition1"])
44
+ ]
45
+
46
+ vector_db = FAISS.from_documents(documents, embeddings)
47
+ vector_db.save_local(index_path)
48
+
49
+ return vector_db
50
+
51
+ vector_db = create_or_load_faiss_index()
52
+
53
+ # Set up QA chain
54
+ retriever = vector_db.as_retriever(search_kwargs={"k": 1})
55
+ prompt_template = """You are DrugScan, a medical assistant that explains drug compositions. Provide a detailed explanation of the drug based on its active ingredient and dosage, including its uses, mechanism of action, potential side effects, and any relevant precautions. Be empathetic and clear in your response.
56
+
57
+ Drug Composition: {context}
58
+ User Query: {question}
59
+ DrugScan: """
60
+ PROMPT = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
61
+ qa_chain = RetrievalQA.from_chain_type(
62
+ llm=llm,
63
+ chain_type="stuff",
64
+ retriever=retriever,
65
+ chain_type_kwargs={"prompt": PROMPT},
66
+ return_source_documents=True
67
+ )
68
+
69
+ # Suggested drugs
70
+ suggested_drugs = [
71
+ "Azirox",
72
+ "Augmentin",
73
+ "Ascoril LS",
74
+ "Allepra 120",
75
+ "Amoxycillin",
76
+ ]
77
+
78
+ # Function to handle drug query
79
+ def query_drug(drug_name, chat_history):
80
+ if not drug_name.strip():
81
+ return chat_history + [[None, "Please enter a drug name."]]
82
+
83
+ try:
84
+ result = qa_chain.invoke({"query": drug_name})
85
+ if not result["source_documents"]:
86
+ response = "Drug not found in the dataset. Please try another drug name."
87
+ else:
88
+ composition = result["source_documents"][0].metadata["short_composition1"]
89
+ response = f"{result['result']}\n\n**Drug Composition:** {composition}"
90
+ except Exception as e:
91
+ error_msg = str(e)
92
+ if "rate limit" in error_msg.lower() or "quota" in error_msg.lower():
93
+ response = "Error: Rate limit or quota exceeded for the Groq API. Please try again later."
94
+ elif "connection" in error_msg.lower() or "network" in error_msg.lower():
95
+ response = "Error: Network issue while connecting to the Groq API. Please check your internet connection."
96
+ else:
97
+ response = f"Error: An unexpected error occurred: {error_msg}"
98
+
99
+ return chat_history + [[drug_name, response]]
100
+
101
+ # Gradio Interface
102
+ with gr.Blocks(title="DrugScan") as demo:
103
+ gr.Markdown("# DrugScan")
104
+ gr.Markdown("Enter the name of a drug to learn about its active ingredients, uses, mechanism of action, side effects, and more.")
105
+
106
+ # Display logo
107
+ logo_url = "https://i.postimg.cc/gJ9Z0RGS/bc20af1b-8ee6-4e1c-8748-eba44e2780c1-removalai-preview.png"
108
+ gr.Image(logo_url, width=150)
109
+
110
+ # Chat interface
111
+ chatbot = gr.Chatbot(label="Results")
112
+ drug_input = gr.Textbox(placeholder="Enter a drug name (e.g., 'Azirox')", label="Drug Name")
113
+
114
+ # Suggested drugs buttons
115
+ gr.Markdown("### Try These Drugs")
116
+ with gr.Row():
117
+ for drug in suggested_drugs:
118
+ gr.Button(drug).click(
119
+ fn=query_drug,
120
+ inputs=[drug, chatbot],
121
+ outputs=chatbot
122
+ )
123
+
124
+ # Search button
125
+ drug_input.submit(
126
+ fn=query_drug,
127
+ inputs=[drug_input, chatbot],
128
+ outputs=chatbot
129
+ )
130
+
131
+ # Disclaimer
132
+ gr.Markdown("### Important Disclaimer")
133
+ gr.Markdown(
134
+ "DrugScan provides explanations of drug compositions based on available data. It is not a substitute for professional medical advice or diagnosis. Always consult a qualified healthcare provider for personal health concerns."
135
+ )
136
+
137
+ # Launch the app
138
+ demo.launch()