blackshadow1 commited on
Commit
72744fc
·
verified ·
1 Parent(s): a151a14

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +198 -80
app.py CHANGED
@@ -2,99 +2,217 @@ import gradio as gr
2
  import requests
3
  from urllib.parse import parse_qs, urlparse
4
  from transformers import pipeline
 
 
5
 
6
  # Backend API endpoints
7
- BACKEND_BASE_URL = "http://127.0.0.1:5000" # Replace with your Flask backend URL
8
  COMPLETE_APPOINTMENT_ENDPOINT = f"{BACKEND_BASE_URL}/complete_appointment"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- # Function to extract `appointment_id` from query parameters
11
  def get_appointment_id():
12
  query_params = parse_qs(urlparse(gr.Request().url).query)
13
  return query_params.get("appointment_id", ["Unknown"])[0]
14
 
15
- # Load Hugging Face pipelines
16
- ner_pipeline = pipeline("ner", model="dslim/bert-base-NER") # Named Entity Recognition
17
- sentiment_pipeline = pipeline("sentiment-analysis") # Sentiment Analysis
18
- summarization_pipeline = pipeline("summarization", model="facebook/bart-large-cnn") # Summarization
19
- conversation_pipeline = pipeline("text-generation", model="microsoft/DialoGPT-medium") # Conversational AI
 
 
 
 
 
20
 
21
- # Function to process user input
22
- def ai_doctor_interaction(user_input, chat_history=[]):
23
  try:
24
- # Perform NER
25
- ner_results = ner_pipeline(user_input)
26
- entities = [f"{entity['entity_group']}: {entity['word']}" for entity in ner_results]
27
-
28
- # Perform Sentiment Analysis
29
- sentiment_results = sentiment_pipeline(user_input)
30
- sentiment = f"{sentiment_results[0]['label']} (Confidence: {sentiment_results[0]['score']:.2f})"
31
-
32
- # Perform Summarization
33
- summary = summarization_pipeline(user_input, max_length=50, min_length=10, do_sample=False)[0]['summary_text']
34
-
35
- # Generate AI Doctor response
36
- ai_response = conversation_pipeline(user_input, max_length=100, num_return_sequences=1)[0]["generated_text"]
37
-
38
- # Combine results
39
- response = f"""
40
- **Entities Identified**: {', '.join(entities)}
41
- **Sentiment**: {sentiment}
42
- **Summary**: {summary}
43
- **AI Doctor Response**: {ai_response}
44
- """
45
- chat_history.append(("You", user_input))
46
- chat_history.append(("AI Doctor", response))
47
- return chat_history, chat_history
48
- except Exception as e:
49
- return chat_history + [("System", f"Error: {str(e)}")], chat_history
50
-
51
- # Function to handle "End Call" button
52
- def end_call():
53
- appointment_id = get_appointment_id()
54
- if appointment_id == "Unknown":
55
- return "Error: Appointment ID not found. Please try again."
56
-
57
- # Send a request to the backend to mark the appointment as completed
58
  try:
59
- response = requests.post(COMPLETE_APPOINTMENT_ENDPOINT, json={"appointment_id": appointment_id})
 
 
 
 
60
  if response.status_code == 200:
61
- return "Appointment marked as completed. Redirecting to the doctors' page..."
62
- else:
63
- return f"Error: {response.json().get('message', 'Failed to complete the appointment')}"
64
- except Exception as e:
65
- return f"Error: Unable to connect to the backend. Details: {str(e)}"
66
-
67
- # Gradio interface
68
- with gr.Blocks() as demo:
69
- gr.Markdown("<h1 style='text-align: center; color: #4CAF50;'>AI Doctor Avatar</h1>")
70
- gr.Markdown("<p style='text-align: center;'>Interact with the AI Doctor to resolve your health-related queries.</p>")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
- with gr.Row():
73
- with gr.Column(scale=1):
74
- gr.Markdown("<h3 style='text-align: center;'>AI Doctor Avatar</h3>")
75
- gr.HTML("""
76
- <div style="position: relative; overflow: hidden; aspect-ratio: 16/9;">
77
- <video autoplay muted loop preload="none" style="width: 100%; height: auto; border-radius: 10px;">
78
- <source src="http://127.0.0.1:5000/serve_video/ai_doctor_avatar.mp4" type="video/mp4">
79
- Your browser does not support the video tag.
80
- </video>
81
- </div>
82
- """)
83
- with gr.Column(scale=2):
84
- chatbot = gr.Chatbot(label="AI Doctor Chat Interface", height=400)
85
- user_input = gr.Textbox(label="Your Message", placeholder="Type your question here...", lines=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  with gr.Row():
87
- submit_button = gr.Button("Send", variant="primary")
88
- clear_button = gr.Button("Clear Chat", variant="secondary")
 
89
 
90
- # Define interactions
91
- submit_button.click(ai_doctor_interaction, inputs=[user_input, chatbot], outputs=[chatbot, chatbot])
92
- clear_button.click(lambda: [], inputs=[], outputs=[chatbot])
93
-
94
- # Add "End Call" button
95
- end_call_button = gr.Button("End Call", variant="stop")
96
- end_call_message = gr.Textbox(label="End Call Status", interactive=False)
97
- end_call_button.click(end_call, outputs=[end_call_message])
 
 
 
 
 
 
 
 
 
98
 
99
- # Launch the Gradio app
100
- demo.launch()
 
 
 
 
 
 
 
2
  import requests
3
  from urllib.parse import parse_qs, urlparse
4
  from transformers import pipeline
5
+ import os
6
+ import time
7
 
8
  # Backend API endpoints
9
+ BACKEND_BASE_URL = "http://127.0.0.1:5000"
10
  COMPLETE_APPOINTMENT_ENDPOINT = f"{BACKEND_BASE_URL}/complete_appointment"
11
+ VALIDATE_APPOINTMENT_ENDPOINT = f"{BACKEND_BASE_URL}/validate_appointment"
12
+
13
+ # Path to your pre-generated avatar video
14
+ AVATAR_VIDEO_PATH = "http://127.0.0.1:5000/serve_video/ai_doctor_avatar.mp4" # Replace with your actual video URL
15
+ # <source src="http://127.0.0.1:5000/serve_video/ai_doctor_avatar.mp4" type="video/mp4">
16
+
17
+ # Load lightweight models for faster performance
18
+ conversation_pipeline = pipeline(
19
+ "text-generation",
20
+ model="microsoft/DialoGPT-medium",
21
+ device="cpu" # Change to "cuda" if GPU available
22
+ )
23
+
24
+ medical_qa_pipeline = pipeline(
25
+ "question-answering",
26
+ model="medicalai/ClinicalBERT_QA",
27
+ device="cpu"
28
+ )
29
 
 
30
  def get_appointment_id():
31
  query_params = parse_qs(urlparse(gr.Request().url).query)
32
  return query_params.get("appointment_id", ["Unknown"])[0]
33
 
34
+ def validate_appointment(appointment_id):
35
+ try:
36
+ response = requests.post(
37
+ VALIDATE_APPOINTMENT_ENDPOINT,
38
+ json={"appointment_id": appointment_id},
39
+ timeout=3
40
+ )
41
+ return response.json().get("status") == "success"
42
+ except Exception:
43
+ return False
44
 
45
+ def generate_response(user_input):
46
+ """Lightning-fast response generation"""
47
  try:
48
+ # Try medical QA first
49
+ qa_result = medical_qa_pipeline({
50
+ "question": user_input,
51
+ "context": "Medical consultation between doctor and patient"
52
+ })
53
+ if qa_result['score'] > 0.25:
54
+ return qa_result['answer']
55
+
56
+ # Fallback to conversational AI
57
+ return conversation_pipeline(
58
+ f"Patient: {user_input}\nDoctor:",
59
+ max_length=150,
60
+ num_return_sequences=1,
61
+ do_sample=True,
62
+ top_p=0.9,
63
+ temperature=0.7
64
+ )[0]["generated_text"].split("Doctor:")[-1].strip()
65
+
66
+ except Exception:
67
+ return "I'm experiencing high demand. Could you please repeat your question?"
68
+
69
+ def end_call(appointment_id):
 
 
 
 
 
 
 
 
 
 
 
 
70
  try:
71
+ response = requests.post(
72
+ COMPLETE_APPOINTMENT_ENDPOINT,
73
+ json={"appointment_id": appointment_id},
74
+ timeout=3
75
+ )
76
  if response.status_code == 200:
77
+ return "Consultation completed successfully. Thank you!"
78
+ return "Couldn't complete appointment. Please contact support."
79
+ except Exception:
80
+ return "Network error. Please check your connection."
81
+
82
+ # Custom CSS for blazing fast UI
83
+ custom_css = """
84
+ :root {
85
+ --primary: #2d8cf0;
86
+ --secondary: #f8f9fa;
87
+ --accent: #ff6b6b;
88
+ }
89
+
90
+ .gradio-container {
91
+ font-family: 'Inter', sans-serif;
92
+ max-width: 1200px !important;
93
+ }
94
+
95
+ .avatar-container {
96
+ aspect-ratio: 9/16;
97
+ background: black;
98
+ border-radius: 12px;
99
+ overflow: hidden;
100
+ }
101
+
102
+ .video-container video {
103
+ object-fit: cover;
104
+ width: 100%;
105
+ height: 100%;
106
+ }
107
+
108
+ .chat-container {
109
+ height: 100%;
110
+ display: flex;
111
+ flex-direction: column;
112
+ }
113
+
114
+ .chatbot {
115
+ min-height: 500px;
116
+ flex-grow: 1;
117
+ border-radius: 12px;
118
+ background: var(--secondary);
119
+ }
120
+
121
+ .input-row {
122
+ margin-top: 0.5rem !important;
123
+ }
124
+
125
+ .primary-btn {
126
+ background: var(--primary) !important;
127
+ }
128
+
129
+ .end-btn {
130
+ background: var(--accent) !important;
131
+ }
132
+
133
+ /* Animation for smooth loading */
134
+ @keyframes fadeIn {
135
+ from { opacity: 0; }
136
+ to { opacity: 1; }
137
+ }
138
+
139
+ .gradio-app {
140
+ animation: fadeIn 0.3s ease-in;
141
+ }
142
+ """
143
+
144
+ with gr.Blocks(css=custom_css, title="AI Doctor Consultation") as demo:
145
+ appointment_id = gr.State(value=get_appointment_id())
146
+
147
+ # Header
148
+ gr.Markdown("""
149
+ <div style="text-align: center; margin-bottom: 1rem;">
150
+ <h1 style="margin: 0; color: #2d8cf0;">AI Doctor Consultation</h1>
151
+ <p style="margin: 0; color: #666;">Your health matters to us</p>
152
+ </div>
153
+ """)
154
 
155
+ with gr.Row(equal_height=True):
156
+ # Left column - Avatar video
157
+ with gr.Column(scale=1, elem_classes=["avatar-container"]):
158
+ gr.Markdown("### Dr. AI Avatar")
159
+ video = gr.Video(
160
+ value=AVATAR_VIDEO_PATH,
161
+ autoplay=True,
162
+ interactive=False,
163
+ elem_classes=["video-container"]
164
+ )
165
+
166
+ # Right column - Chat interface
167
+ with gr.Column(scale=2, elem_classes=["chat-container"]):
168
+ chatbot = gr.Chatbot(
169
+ label="Consultation Chat",
170
+ bubble_full_width=False,
171
+ show_copy_button=True,
172
+ avatar_images=(
173
+ "https://i.imgur.com/8Km9tLL.png", # User
174
+ "https://i.imgur.com/3Q3ZQ2u.png" # Doctor
175
+ )
176
+ )
177
+
178
+ with gr.Row(elem_classes=["input-row"]):
179
+ user_input = gr.Textbox(
180
+ placeholder="Describe your symptoms...",
181
+ label="",
182
+ container=False,
183
+ autofocus=True,
184
+ max_lines=3
185
+ )
186
+ submit_btn = gr.Button("Send", variant="primary", elem_classes=["primary-btn"])
187
+
188
  with gr.Row():
189
+ clear_btn = gr.Button("Clear Chat", variant="secondary")
190
+ end_btn = gr.Button("End Consultation", variant="stop", elem_classes=["end-btn"])
191
+ status = gr.Textbox(visible=False)
192
 
193
+ # Event handlers
194
+ submit_btn.click(
195
+ fn=lambda msg, hist: (msg, hist + [(msg, generate_response(msg))]),
196
+ inputs=[user_input, chatbot],
197
+ outputs=[user_input, chatbot],
198
+ queue=True
199
+ ).then(
200
+ lambda: gr.update(autoplay=True), # Ensure video keeps playing
201
+ outputs=video
202
+ )
203
+
204
+ clear_btn.click(lambda: [], None, chatbot)
205
+ end_btn.click(
206
+ fn=end_call,
207
+ inputs=appointment_id,
208
+ outputs=status
209
+ )
210
 
211
+ # Optimized launch settings
212
+ demo.launch(
213
+ server_name="0.0.0.0",
214
+ server_port=7860,
215
+ share=False,
216
+ favicon_path="https://i.imgur.com/3Q3ZQ2u.png",
217
+ prevent_thread_lock=True
218
+ )