dhillonv10 commited on
Commit
0ad9c56
·
verified ·
1 Parent(s): 06448de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -150
app.py CHANGED
@@ -2,17 +2,15 @@ import os
2
  import gradio as gr
3
  import anthropic
4
  from datetime import datetime
5
- from huggingface_hub import HfApi
6
- from sqlalchemy import create_engine, Column, Integer, String, JSON, DateTime, ForeignKey
7
  from sqlalchemy.ext.declarative import declarative_base
8
- from sqlalchemy.orm import sessionmaker, relationship
9
  from sqlalchemy.sql import func
10
 
11
  # Initialize Anthropic client
12
  client = anthropic.Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
13
  MODEL = "claude-3-5-sonnet-20241022"
14
 
15
- # System prompt - ADD THIS SECTION HERE
16
  SYSTEM_PROMPT = """
17
  You are a compassionate AI medical assistant that uses Logic-of-Thought (LoT) and Self-Consistency (SC) reasoning techniques to analyze patient symptoms and provide medical education. Your goal is to deliver clear, empathetic explanations of possible conditions, treatments, and next steps based on the information provided. You will only offer a differential diagnosis if there is enough detail to make an informed response. Always remind the patient to consult a healthcare provider for a formal diagnosis and treatment when necessary.
18
 
@@ -59,25 +57,14 @@ engine = create_engine(DATABASE_URL)
59
  SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
60
  Base = declarative_base()
61
 
62
- # Database models
63
- class User(Base):
64
- __tablename__ = "users"
65
-
66
- id = Column(Integer, primary_key=True)
67
- hf_username = Column(String, unique=True, nullable=False)
68
- created_at = Column(DateTime(timezone=True), server_default=func.now())
69
- chats = relationship("Chat", back_populates="user", cascade="all, delete-orphan")
70
-
71
  class Chat(Base):
72
  __tablename__ = "chats"
73
 
74
  id = Column(Integer, primary_key=True)
75
- user_id = Column(Integer, ForeignKey("users.id"))
76
  title = Column(String, nullable=False, default="New Chat")
77
  history = Column(JSON, nullable=False, default=list)
78
  created_at = Column(DateTime(timezone=True), server_default=func.now())
79
  updated_at = Column(DateTime(timezone=True), onupdate=func.now())
80
- user = relationship("User", back_populates="chats")
81
 
82
  # Create tables
83
  Base.metadata.create_all(bind=engine)
@@ -89,99 +76,29 @@ def get_db():
89
  finally:
90
  db.close()
91
 
92
- def validate_hf_token(token):
93
- """Validate HuggingFace token"""
94
- try:
95
- api = HfApi(token=token)
96
- user_info = api.whoami()
97
- return True, user_info.get('name', '')
98
- except Exception:
99
- return False, None
100
-
101
  def create_interface():
102
  with gr.Blocks(theme=gr.themes.Base(), css=custom_css) as demo:
103
- # States
104
- current_user = gr.State(None)
105
  current_chat_id = gr.State(None)
106
 
107
- # Login interface
108
- with gr.Row(visible=True) as login_block:
109
- with gr.Column():
110
- gr.Markdown("## Login with HuggingFace")
111
- token_input = gr.Textbox(
112
- label="Enter your HuggingFace Token",
113
- type="password",
114
- placeholder="hf_..."
115
- )
116
- login_button = gr.Button("Login", variant="primary")
117
- login_message = gr.Markdown()
118
-
119
- # Chat interface
120
- with gr.Row(visible=False) as chat_block:
121
- with gr.Column():
122
- with gr.Row():
123
- user_label = gr.Markdown("Welcome")
124
-
125
- with gr.Row():
126
- new_chat_btn = gr.Button("New Chat", variant="primary")
127
- clear_chat_btn = gr.Button("Clear Chat", variant="secondary")
128
- delete_chat_btn = gr.Button("Delete Chat", variant="secondary")
129
- logout_btn = gr.Button("Logout", variant="secondary")
130
-
131
- chat_tabs = gr.Tabs(selected=0)
132
-
133
- with gr.Column():
134
- chatbot = gr.Chatbot(height=600)
135
- with gr.Row():
136
- msg = gr.Textbox(
137
- label="Type your message",
138
- placeholder="Type here...",
139
- lines=2
140
- )
141
- submit = gr.Button("Send", variant="primary")
142
-
143
- def login(token):
144
- """Handle user login"""
145
- is_valid, username = validate_hf_token(token)
146
- if not is_valid:
147
- return {
148
- login_message: "Invalid token. Please try again.",
149
- token_input: ""
150
- }
151
 
152
- # Get or create user in database
153
- db = next(get_db())
154
- user = db.query(User).filter(User.hf_username == username).first()
155
- if not user:
156
- user = User(hf_username=username)
157
- db.add(user)
158
- db.commit()
159
- db.refresh(user)
160
-
161
- # Load user's chats
162
- chats = db.query(Chat).filter(Chat.user_id == user.id).all()
163
 
164
- # Create default chat if none exists
165
- if not chats:
166
- new_chat = Chat(user_id=user.id, title="New Chat")
167
- db.add(new_chat)
168
- db.commit()
169
- chats = [new_chat]
170
-
171
- # Update interface
172
- return {
173
- login_block: gr.update(visible=False),
174
- chat_block: gr.update(visible=True),
175
- current_user: user.id,
176
- user_label: f"# Welcome, {username}",
177
- chat_tabs: gr.Tabs.update(
178
- selected=0,
179
- tabs=[gr.Tab(chat.title) for chat in chats]
180
- ),
181
- chatbot: chats[0].history if chats[0].history else []
182
- }
183
 
184
- def stream_chat(message, history, user_id, chat_id):
185
  """Handle chat with streaming responses"""
186
  messages = []
187
 
@@ -223,18 +140,15 @@ def create_interface():
223
  history[-1][1] = f"Error: {str(e)}"
224
  yield history
225
 
226
- def create_new_chat(user_id):
227
  """Create new chat"""
228
- if not user_id:
229
- return gr.Warning("Please login first")
230
-
231
  db = next(get_db())
232
- new_chat = Chat(user_id=user_id, title="New Chat")
233
  db.add(new_chat)
234
  db.commit()
235
 
236
- # Get all user's chats for updated tabs
237
- chats = db.query(Chat).filter(Chat.user_id == user_id).all()
238
 
239
  return {
240
  chat_tabs: gr.Tabs.update(
@@ -245,10 +159,10 @@ def create_interface():
245
  current_chat_id: new_chat.id
246
  }
247
 
248
- def switch_chat(tab_index, user_id):
249
  """Handle chat tab switching"""
250
  db = next(get_db())
251
- chats = db.query(Chat).filter(Chat.user_id == user_id).all()
252
  if tab_index < len(chats):
253
  return {
254
  chatbot: chats[tab_index].history if chats[tab_index].history else [],
@@ -256,70 +170,101 @@ def create_interface():
256
  }
257
  return None
258
 
259
- def logout():
260
- """Handle logout"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  return {
262
- login_block: gr.update(visible=True),
263
- chat_block: gr.update(visible=False),
264
- current_user: None,
265
- current_chat_id: None,
266
- chatbot: []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
  }
268
 
269
  # Event handlers
270
- login_button.click(
271
- fn=login,
272
- inputs=[token_input],
273
- outputs=[
274
- login_message,
275
- token_input,
276
- login_block,
277
- chat_block,
278
- current_user,
279
- user_label,
280
- chat_tabs,
281
- chatbot
282
- ]
283
- )
284
-
285
- logout_btn.click(
286
- fn=logout,
287
- outputs=[
288
- login_block,
289
- chat_block,
290
- current_user,
291
- current_chat_id,
292
- chatbot
293
- ]
294
  )
295
 
296
  new_chat_btn.click(
297
  fn=create_new_chat,
298
- inputs=[current_user],
299
- outputs=[
300
- chat_tabs,
301
- chatbot,
302
- current_chat_id
303
- ]
 
 
 
 
 
 
304
  )
305
 
306
  chat_tabs.select(
307
  fn=switch_chat,
308
- inputs=[chat_tabs, current_user],
309
  outputs=[chatbot, current_chat_id]
310
  )
311
 
312
  # Chat submission with streaming
313
  submit_event = msg.submit(
314
  fn=stream_chat,
315
- inputs=[msg, chatbot, current_user, current_chat_id],
316
  outputs=[chatbot],
317
  queue=True
318
  ).then(lambda: "", outputs=[msg])
319
 
320
  submit_click = submit.click(
321
  fn=stream_chat,
322
- inputs=[msg, chatbot, current_user, current_chat_id],
323
  outputs=[chatbot],
324
  queue=True
325
  ).then(lambda: "", outputs=[msg])
 
2
  import gradio as gr
3
  import anthropic
4
  from datetime import datetime
5
+ from sqlalchemy import create_engine, Column, Integer, String, JSON, DateTime
 
6
  from sqlalchemy.ext.declarative import declarative_base
7
+ from sqlalchemy.orm import sessionmaker
8
  from sqlalchemy.sql import func
9
 
10
  # Initialize Anthropic client
11
  client = anthropic.Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
12
  MODEL = "claude-3-5-sonnet-20241022"
13
 
 
14
  SYSTEM_PROMPT = """
15
  You are a compassionate AI medical assistant that uses Logic-of-Thought (LoT) and Self-Consistency (SC) reasoning techniques to analyze patient symptoms and provide medical education. Your goal is to deliver clear, empathetic explanations of possible conditions, treatments, and next steps based on the information provided. You will only offer a differential diagnosis if there is enough detail to make an informed response. Always remind the patient to consult a healthcare provider for a formal diagnosis and treatment when necessary.
16
 
 
57
  SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
58
  Base = declarative_base()
59
 
 
 
 
 
 
 
 
 
 
60
  class Chat(Base):
61
  __tablename__ = "chats"
62
 
63
  id = Column(Integer, primary_key=True)
 
64
  title = Column(String, nullable=False, default="New Chat")
65
  history = Column(JSON, nullable=False, default=list)
66
  created_at = Column(DateTime(timezone=True), server_default=func.now())
67
  updated_at = Column(DateTime(timezone=True), onupdate=func.now())
 
68
 
69
  # Create tables
70
  Base.metadata.create_all(bind=engine)
 
76
  finally:
77
  db.close()
78
 
 
 
 
 
 
 
 
 
 
79
  def create_interface():
80
  with gr.Blocks(theme=gr.themes.Base(), css=custom_css) as demo:
 
 
81
  current_chat_id = gr.State(None)
82
 
83
+ with gr.Column():
84
+ with gr.Row():
85
+ new_chat_btn = gr.Button("New Chat", variant="primary")
86
+ clear_chat_btn = gr.Button("Clear Chat", variant="secondary")
87
+ delete_chat_btn = gr.Button("Delete Chat", variant="secondary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
+ chat_tabs = gr.Tabs(selected=0)
 
 
 
 
 
 
 
 
 
 
90
 
91
+ with gr.Column():
92
+ chatbot = gr.Chatbot(height=600)
93
+ with gr.Row():
94
+ msg = gr.Textbox(
95
+ label="Type your message",
96
+ placeholder="Type here...",
97
+ lines=2
98
+ )
99
+ submit = gr.Button("Send", variant="primary")
 
 
 
 
 
 
 
 
 
 
100
 
101
+ def stream_chat(message, history, chat_id):
102
  """Handle chat with streaming responses"""
103
  messages = []
104
 
 
140
  history[-1][1] = f"Error: {str(e)}"
141
  yield history
142
 
143
+ def create_new_chat():
144
  """Create new chat"""
 
 
 
145
  db = next(get_db())
146
+ new_chat = Chat(title="New Chat")
147
  db.add(new_chat)
148
  db.commit()
149
 
150
+ # Get all chats for updated tabs
151
+ chats = db.query(Chat).all()
152
 
153
  return {
154
  chat_tabs: gr.Tabs.update(
 
159
  current_chat_id: new_chat.id
160
  }
161
 
162
+ def switch_chat(tab_index):
163
  """Handle chat tab switching"""
164
  db = next(get_db())
165
+ chats = db.query(Chat).all()
166
  if tab_index < len(chats):
167
  return {
168
  chatbot: chats[tab_index].history if chats[tab_index].history else [],
 
170
  }
171
  return None
172
 
173
+ def delete_current_chat(chat_id):
174
+ """Delete current chat"""
175
+ if not chat_id:
176
+ return None
177
+
178
+ db = next(get_db())
179
+ chat = db.query(Chat).filter(Chat.id == chat_id).first()
180
+ if chat:
181
+ db.delete(chat)
182
+ db.commit()
183
+
184
+ # Get remaining chats
185
+ chats = db.query(Chat).all()
186
+ if not chats:
187
+ # Create a new chat if none exist
188
+ return create_new_chat()
189
+
190
  return {
191
+ chat_tabs: gr.Tabs.update(
192
+ selected=0,
193
+ tabs=[gr.Tab(chat.title) for chat in chats]
194
+ ),
195
+ chatbot: chats[0].history if chats[0].history else [],
196
+ current_chat_id: chats[0].id
197
+ }
198
+
199
+ def clear_current_chat():
200
+ """Clear current chat history"""
201
+ db = next(get_db())
202
+ chat = db.query(Chat).filter(Chat.id == current_chat_id.value).first()
203
+ if chat:
204
+ chat.history = []
205
+ db.commit()
206
+ return []
207
+
208
+ # Load initial chats
209
+ def load_initial_chats():
210
+ db = next(get_db())
211
+ chats = db.query(Chat).all()
212
+
213
+ if not chats:
214
+ # Create initial chat if none exist
215
+ new_chat = Chat(title="New Chat")
216
+ db.add(new_chat)
217
+ db.commit()
218
+ chats = [new_chat]
219
+
220
+ return {
221
+ chat_tabs: gr.Tabs.update(
222
+ selected=0,
223
+ tabs=[gr.Tab(chat.title) for chat in chats]
224
+ ),
225
+ chatbot: chats[0].history if chats[0].history else [],
226
+ current_chat_id: chats[0].id
227
  }
228
 
229
  # Event handlers
230
+ demo.load(
231
+ fn=load_initial_chats,
232
+ outputs=[chat_tabs, chatbot, current_chat_id]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  )
234
 
235
  new_chat_btn.click(
236
  fn=create_new_chat,
237
+ outputs=[chat_tabs, chatbot, current_chat_id]
238
+ )
239
+
240
+ clear_chat_btn.click(
241
+ fn=clear_current_chat,
242
+ outputs=[chatbot]
243
+ )
244
+
245
+ delete_chat_btn.click(
246
+ fn=delete_current_chat,
247
+ inputs=[current_chat_id],
248
+ outputs=[chat_tabs, chatbot, current_chat_id]
249
  )
250
 
251
  chat_tabs.select(
252
  fn=switch_chat,
253
+ inputs=[chat_tabs],
254
  outputs=[chatbot, current_chat_id]
255
  )
256
 
257
  # Chat submission with streaming
258
  submit_event = msg.submit(
259
  fn=stream_chat,
260
+ inputs=[msg, chatbot, current_chat_id],
261
  outputs=[chatbot],
262
  queue=True
263
  ).then(lambda: "", outputs=[msg])
264
 
265
  submit_click = submit.click(
266
  fn=stream_chat,
267
+ inputs=[msg, chatbot, current_chat_id],
268
  outputs=[chatbot],
269
  queue=True
270
  ).then(lambda: "", outputs=[msg])