harris1 commited on
Commit
4e1b4b6
·
verified ·
1 Parent(s): 5e54bfd

Upload healthhive.py

Browse files
Files changed (1) hide show
  1. healthhive.py +227 -0
healthhive.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ import os
3
+ from docx import Document
4
+ from llama_index.llms.together import TogetherLLM
5
+ from llama_index.core.llms import ChatMessage, MessageRole
6
+ from Bio import Entrez
7
+ import ssl
8
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
9
+ import streamlit as st
10
+ from googleapiclient.discovery import build
11
+ from typing import List, Optional
12
+
13
+ load_dotenv()
14
+ # 995d5f1a8de125c5b39bb48c2613e85f57d53c0e498a87d1ff33f0ec89a26ec7
15
+ os.environ["TOGETHER_API"] = os.getenv("TOGETHER_API")
16
+ os.environ["GOOGLE_SEARCH_API_KEY"] = os.getenv("GOOGLE_SEARCH_API_KEY")
17
+
18
+ def search_pubmed(query: str) -> Optional[List[str]]:
19
+ """
20
+ Searches PubMed for a given query and returns a list of formatted results
21
+ (or None if no results are found).
22
+ """
23
+ Entrez.email = "harisellahi888@gmail.com" # Replace with your email
24
+
25
+ try:
26
+ ssl._create_default_https_context = ssl._create_unverified_context
27
+
28
+ handle = Entrez.esearch(db="pubmed", term=query, retmax=3)
29
+ record = Entrez.read(handle)
30
+ id_list = record["IdList"]
31
+
32
+ if not id_list:
33
+ return None
34
+
35
+ handle = Entrez.efetch(db="pubmed", id=id_list, retmode="xml")
36
+ articles = Entrez.read(handle)
37
+
38
+ results = []
39
+ for article in articles['PubmedArticle']:
40
+ try:
41
+ medline_citation = article['MedlineCitation']
42
+ article_data = medline_citation['Article']
43
+ title = article_data['ArticleTitle']
44
+ abstract = article_data.get('Abstract', {}).get('AbstractText', [""])[0]
45
+
46
+ result = f"**Title:** {title}\n**Abstract:** {abstract}\n"
47
+ result += f"**Link:** https://pubmed.ncbi.nlm.nih.gov/{medline_citation['PMID']} \n\n"
48
+ results.append(result)
49
+ except KeyError as e:
50
+ print(f"Error parsing article: {article}, Error: {e}")
51
+
52
+ return results
53
+
54
+ except Exception as e:
55
+ print(f"Error accessing PubMed: {e}")
56
+ return None
57
+
58
+ def chat_with_pubmed(article_text, article_link):
59
+ """
60
+ Engages in a chat-like interaction with a PubMed article using TogetherLLM.
61
+ """
62
+ try:
63
+ llm = TogetherLLM(model="QWEN/QWEN1.5-14B-CHAT", api_key=os.environ['TOGETHER_API'])
64
+ messages = [
65
+ ChatMessage(role=MessageRole.SYSTEM, content="You are a helpful AI assistant summarizing and answering questions about the following medical research article: " + article_link),
66
+ ChatMessage(role=MessageRole.USER, content=article_text)
67
+ ]
68
+ response = llm.chat(messages)
69
+ return str(response) if response else "I'm sorry, I couldn't generate a summary for this article."
70
+ except Exception as e:
71
+ print(f"Error in chat_with_pubmed: {e}")
72
+ return "An error occurred while generating a summary."
73
+
74
+ def search_web(query: str, num_results: int = 3) -> Optional[List[str]]:
75
+ """
76
+ Searches the web using the Google Search API and returns a list of formatted results
77
+ (or None if no results are found).
78
+ """
79
+ try:
80
+ service = build("customsearch", "v1", developerKey=os.environ["GOOGLE_SEARCH_API_KEY"])
81
+
82
+ # Execute the search request
83
+ res = service.cse().list(q=query, cx="e31a5857f45ef4d2a", num=num_results).execute()
84
+
85
+ if "items" not in res:
86
+ return None
87
+
88
+ results = []
89
+ for item in res["items"]:
90
+ title = item["title"]
91
+ link = item["link"]
92
+ snippet = item["snippet"]
93
+ result = f"**Title:** {title}\n**Link:** {link} \n**Snippet:** {snippet}\n\n"
94
+ results.append(result)
95
+
96
+ return results
97
+
98
+ except Exception as e:
99
+ print(f"Error performing web search: {e}")
100
+ return None
101
+
102
+
103
+ from together import Together
104
+ def medmind_chatbot(user_input, chat_history=None):
105
+ """
106
+ Processes user input, interacts with various resources, and generates a response.
107
+ Handles potential errors, maintains chat history,
108
+ """
109
+ if chat_history is None:
110
+ chat_history = []
111
+
112
+ response_parts = [] # Collect responses from different sources
113
+ final_response = "";
114
+
115
+ try:
116
+ # PubMed Search and Chat
117
+ pubmed_results = search_pubmed(user_input)
118
+ if pubmed_results:
119
+ for article_text in pubmed_results:
120
+ title, abstract, link = article_text.split("\n")[:3]
121
+ # print(article_text)
122
+ response_parts.append(f"{title}\n{abstract}\n{link}\n")
123
+ else:
124
+ response_parts.append("No relevant PubMed articles found.")
125
+
126
+ # Web Search
127
+ web_results = search_web(user_input)
128
+ if web_results:
129
+ response_parts.append("\n\n**Web Search Results:**")
130
+ response_parts.extend(web_results)
131
+ else:
132
+ response_parts.append("No relevant web search results found.")
133
+
134
+ # Combine response parts into a single string
135
+ response_text = "\n\n".join(response_parts)
136
+
137
+ prompt = f"""You are a Health Assistant AI designed to provide detailed responses to health-related questions.
138
+ Based on the information retrieved from the PubMed and Web Search below, answer the user's query appropriately.
139
+
140
+ - If the user's query is health-related, provide a detailed and helpful response based on the retrieved information. Or if there is
141
+ some previous conversation then answer the health by seeing the previous conversation also.
142
+ - If the query is a general greeting (e.g., 'Hello', 'Hi'), respond as a friendly assistant.
143
+ - If the query is irrelevant or unrelated to health, respond with: 'I am a health assistant. Please ask only health-related questions.'
144
+ - Don't mention in response that where you reterived the information.
145
+ Previous Conversation:
146
+ {chat_history}
147
+
148
+ User's Query: {user_input}
149
+
150
+ Information retrieved from PubMed and Web Search:
151
+ {response_text}
152
+
153
+ Your response:"""
154
+
155
+ client = Together(api_key=os.environ.get('TOGETHER_API'))
156
+
157
+ response = client.chat.completions.create(
158
+ model="meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",
159
+ messages=[{"role": "user", "content": prompt}],
160
+ )
161
+
162
+ final_response = response.choices[0].message.content
163
+
164
+ except Exception as e:
165
+ print(f"Error in chatbot: {e}")
166
+ response_text = "An error occurred. Please try again later."
167
+
168
+ chat_history.append((user_input, final_response))
169
+ return final_response, chat_history
170
+
171
+ medmind_chatbot("What are the symptoms of COVID-19?")
172
+
173
+ import gradio as gr
174
+
175
+ def show_info_popup():
176
+ info = """
177
+ **HealthHive is an AI-powered chatbot designed to assist with medical information.**
178
+ ...
179
+ """
180
+ return info
181
+
182
+
183
+ def main():
184
+ # Initialize Gradio Interface
185
+ with gr.Blocks() as demo:
186
+ gr.Markdown("# HealthHive Chatbot")
187
+ gr.Markdown("Ask your medical questions and get reliable information!")
188
+
189
+ # Example Questions (Sidebar)
190
+ gr.Markdown("### Example Questions")
191
+ example_questions = [
192
+ "What are the symptoms of COVID-19?",
193
+ "How can I manage my diabetes?",
194
+ "What are the potential side effects of ibuprofen?",
195
+ "What lifestyle changes can help prevent heart disease?"
196
+ ]
197
+ for question in example_questions:
198
+ gr.Markdown(f"- {question}")
199
+
200
+ # Chat History and User Input
201
+ with gr.Row():
202
+ user_input = gr.Textbox(label="You:", placeholder="Type your medical question here...", lines=2)
203
+ chat_history = gr.State([])
204
+
205
+ # Output Container
206
+ with gr.Row():
207
+ response = gr.Textbox(label="HealthHive:", placeholder="Response will appear here...", interactive=False, lines=10)
208
+ def clear_chat():
209
+ return "", ""
210
+
211
+ # Define function to update chat history and response
212
+ def on_submit(user_input, chat_history):
213
+ result, updated_history = medmind_chatbot(user_input, chat_history)
214
+ info = show_info_popup()
215
+ return result, updated_history, info
216
+
217
+ # Link the submit button to the chatbot function
218
+ gr.Button("Submit").click(on_submit, inputs=[user_input, chat_history], outputs=[response, chat_history])
219
+ # gr.Button("Start New Chat").click(lambda: [], outputs=[chat_history])
220
+ gr.Button("Start New Chat").click(clear_chat, outputs=[user_input, response])
221
+
222
+
223
+ demo.launch()
224
+
225
+ if __name__ == "__main__":
226
+ main()
227
+