Sjanmanchi commited on
Commit
20c8230
·
verified ·
1 Parent(s): b8f2159

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +115 -54
  2. requirements.txt +5 -1
app.py CHANGED
@@ -1,64 +1,125 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
27
 
28
- response = ""
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
+ from transformers import pipeline
3
+ from sentence_transformers import SentenceTransformer
4
+ import numpy as np
5
+ import gradio as gr
 
6
 
7
+ # Load models
8
+ intent_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
9
+ model = SentenceTransformer('all-MiniLM-L6-v2')
10
 
11
+ # Intents list
12
+ intents = [
13
+ "schedule appointment", "clinic hours", "insurance inquiry", "test results",
14
+ "appointment cancellation", "prescription refill", "covid protocols",
15
+ "update personal info", "services offered", "telehealth availability", "contact support"
16
+ ]
17
 
18
+ # FAQ data and intents
19
+ faq_data = {
20
+ "questions": [
21
+ "How do I schedule an appointment?", "Can I book an appointment online?", "What is the process to make a doctor's appointment?",
22
+ "What are your clinic hours?", "Are you open on weekends?", "When does the clinic open and close?",
23
+ "Do you accept my insurance?", "Which insurance plans do you accept?", "Can I use my insurance for treatment?",
24
+ "How can I get my test results?", "When will my lab results be ready?", "How do I access my blood test results?",
25
+ "How do I cancel or reschedule my appointment?", "Can I change my appointment time?", "What is the cancellation policy?",
26
+ "How do I refill my prescription?", "Can I get a refill for my medication online?", "What is the process to renew my prescription?",
27
+ "What COVID-19 protocols are in place?", "Do I need to wear a mask to my appointment?", "How is your clinic handling COVID-19 safety?",
28
+ "How do I update my personal information?", "Can I change my address or phone number online?", "Where do I update my contact details?",
29
+ "What services do you offer?", "Do you provide pediatric care?", "What types of medical services are available?",
30
+ "Are telehealth visits available?", "Can I book a virtual doctor visit?", "Do you offer video consultations?",
31
+ "How can I contact customer service?", "What is your support phone number?", "Who do I talk to for more help?"
32
+ ],
33
+ "answers": [
34
+ "You can schedule an appointment by calling our clinic or using our online booking system.",
35
+ "Yes, appointments can be booked online via our website or patient portal.",
36
+ "To make a doctor's appointment, call our front desk or use the online scheduler.",
37
+ "Our clinic is open Monday to Friday from 8 AM to 6 PM, and Saturdays from 9 AM to 1 PM.",
38
+ "Yes, we are open on Saturdays from 9 AM to 1 PM but closed on Sundays.",
39
+ "We open at 8 AM and close at 6 PM on weekdays.",
40
+ "We accept most major insurance providers. Please contact us to verify your coverage.",
41
+ "Our clinic accepts a variety of insurance plans including Aetna, Blue Cross, and United Healthcare.",
42
+ "Yes, your insurance can be used for most treatments at our clinic.",
43
+ "Test results are usually available within 3-5 business days and can be accessed through your patient portal.",
44
+ "Lab results are typically ready within 3-5 days after testing.",
45
+ "You can view your blood test results online through the patient portal.",
46
+ "To cancel or reschedule, please call us at least 24 hours before your appointment or use the patient portal.",
47
+ "You can change your appointment time by contacting our front desk.",
48
+ "Our cancellation policy requires 24-hour notice to avoid fees.",
49
+ "You can request prescription refills by contacting our pharmacy or through the patient portal.",
50
+ "Refills can be requested online via your patient account.",
51
+ "To renew your prescription, contact your doctor or use the online refill service.",
52
+ "We follow all recommended COVID-19 safety protocols, including mask mandates and social distancing.",
53
+ "Masks are required for all visitors during appointments.",
54
+ "Our clinic enforces strict COVID-19 guidelines to ensure patient safety.",
55
+ "You can update your personal information by logging into your patient account or contacting our front desk.",
56
+ "Changes to your address or phone number can be made online.",
57
+ "Please update your contact details through the patient portal or by calling us.",
58
+ "Our services include primary care, pediatrics, lab testing, immunizations, and wellness checkups.",
59
+ "Yes, we offer pediatric care as part of our services.",
60
+ "We provide a wide range of medical services including preventive care and diagnostics.",
61
+ "Telehealth visits are available for many of our services.",
62
+ "You can book a virtual doctor visit online through our patient portal.",
63
+ "Video consultations are offered for appropriate medical concerns.",
64
+ "You can contact customer service via phone at 1-800-123-4567 or email [email protected].",
65
+ "Our support phone number is 1-800-123-4567.",
66
+ "For more help, please contact our support team by phone or email."
67
+ ]
68
+ }
69
 
70
+ intent_tags = [
71
+ "schedule appointment", "schedule appointment", "schedule appointment",
72
+ "clinic hours", "clinic hours", "clinic hours",
73
+ "insurance inquiry", "insurance inquiry", "insurance inquiry",
74
+ "test results", "test results", "test results",
75
+ "appointment cancellation", "appointment cancellation", "appointment cancellation",
76
+ "prescription refill", "prescription refill", "prescription refill",
77
+ "covid protocols", "covid protocols", "covid protocols",
78
+ "update personal info", "update personal info", "update personal info",
79
+ "services offered", "services offered", "services offered",
80
+ "telehealth availability", "telehealth availability", "telehealth availability",
81
+ "contact support", "contact support", "contact support"
82
+ ]
83
 
84
+ def chatbot_response(user_question, threshold_intent=0.2, threshold_faq=0.4):
85
+ user_embedding = model.encode([user_question], convert_to_tensor=True)
86
+
87
+ # Intent prediction
88
+ intent_result = intent_classifier(user_question, candidate_labels=intents)
89
+ predicted_intent = intent_result['labels'][0]
90
+ intent_confidence = intent_result['scores'][0]
91
+
92
+ if intent_confidence < threshold_intent:
93
+ return {"answer": "Sorry, I couldn't understand your question. Could you please rephrase?"}
94
+
95
+ # Filter FAQ questions by predicted intent
96
+ filtered_faqs = [
97
+ (q, a) for q, a, intent_tag in zip(faq_data["questions"], faq_data["answers"], intent_tags)
98
+ if intent_tag == predicted_intent
99
+ ]
100
+ if not filtered_faqs:
101
+ return {"answer": "Sorry, I don't have an answer for that question yet."}
102
+
103
+ # Encode filtered FAQ questions
104
+ faq_embeddings = model.encode([q for q, _ in filtered_faqs], convert_to_tensor=True)
105
+
106
+ # Calculate cosine similarities
107
+ cosine_scores = (user_embedding @ faq_embeddings.T).cpu().numpy()[0]
108
+ max_idx = np.argmax(cosine_scores)
109
+ max_score = cosine_scores[max_idx]
110
+
111
+ if max_score < threshold_faq:
112
+ return {"answer": "Sorry, I couldn't find a good match for your question."}
113
+
114
+ return {"answer": filtered_faqs[max_idx][1]}
115
 
116
+ # Gradio Interface
117
+ def respond(user_question):
118
+ response = chatbot_response(user_question)
119
+ return response["answer"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
+ iface = gr.Interface(fn=respond, inputs="text", outputs="text", title="Healthcare Support Chatbot",
122
+ description="Ask your questions related to appointments, test results, COVID protocols, telehealth, and more!")
123
 
124
  if __name__ == "__main__":
125
+ iface.launch()
requirements.txt CHANGED
@@ -1 +1,5 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
1
+ transformers
2
+ sentence-transformers
3
+ gradio
4
+ torch
5
+ numpy