AIChatPro commited on
Commit
c8ba9dd
·
verified ·
1 Parent(s): 76bc541

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -147
app.py DELETED
@@ -1,147 +0,0 @@
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
- chat_history.append({"role": "assistant", "content": "Please enter a drug name."})
82
- return chat_history
83
-
84
- try:
85
- result = qa_chain.invoke({"query": drug_name})
86
- if not result["source_documents"]:
87
- response = "Drug not found in the dataset. Please try another drug name."
88
- else:
89
- composition = result["source_documents"][0].metadata["short_composition1"]
90
- response = f"{result['result']}\n\n**Drug Composition:** {composition}"
91
- except Exception as e:
92
- error_msg = str(e)
93
- if "rate limit" in error_msg.lower() or "quota" in error_msg.lower():
94
- response = "Error: Rate limit or quota exceeded for the Groq API. Please try again later."
95
- elif "connection" in error_msg.lower() or "network" in error_msg.lower():
96
- response = "Error: Network issue while connecting to the Groq API. Please check your internet connection."
97
- else:
98
- response = f"Error: An unexpected error occurred: {error_msg}"
99
-
100
- chat_history.append({"role": "user", "content": drug_name})
101
- chat_history.append({"role": "assistant", "content": response})
102
- return chat_history
103
-
104
- # Function to handle suggested drug buttons
105
- def query_suggested_drug(drug_name, chat_history):
106
- return query_drug(drug_name, chat_history)
107
-
108
- # Gradio Interface
109
- with gr.Blocks(title="DrugScan") as demo:
110
- gr.Markdown("# DrugScan")
111
- gr.Markdown("Enter the name of a drug to learn about its active ingredients, uses, mechanism of action, side effects, and more.")
112
-
113
- # Display logo
114
- logo_url = "https://i.postimg.cc/gJ9Z0RGS/bc20af1b-8ee6-4e1c-8748-eba44e2780c1-removalai-preview.png"
115
- gr.Image(logo_url, width=150)
116
-
117
- # Chat interface
118
- chatbot = gr.Chatbot(label="Results", type="messages")
119
- drug_input = gr.Textbox(placeholder="Enter a drug name (e.g., 'Azirox')", label="Drug Name")
120
-
121
- # Search button
122
- search_btn = gr.Button("Search")
123
- search_btn.click(
124
- fn=query_drug,
125
- inputs=[drug_input, chatbot],
126
- outputs=chatbot
127
- )
128
-
129
- # Suggested drugs buttons
130
- gr.Markdown("### Try These Drugs")
131
- with gr.Row():
132
- for drug in suggested_drugs:
133
- btn = gr.Button(drug)
134
- btn.click(
135
- fn=query_suggested_drug,
136
- inputs=[gr.State(value=drug), chatbot],
137
- outputs=chatbot
138
- )
139
-
140
- # Disclaimer
141
- gr.Markdown("### Important Disclaimer")
142
- gr.Markdown(
143
- "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."
144
- )
145
-
146
- # Launch the app
147
- demo.launch()