consy commited on
Commit
ac1c096
·
verified ·
1 Parent(s): 921bf7f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -81
app.py CHANGED
@@ -1,91 +1,35 @@
1
- import os
2
- from huggingface_hub import InferenceClient
3
  import gradio as gr
4
 
5
- # — your imports for embeddings, etc. —
6
- from sentence_transformers import SentenceTransformer
7
- import torch
8
- from sklearn.metrics.pairwise import cosine_similarity
 
 
 
 
9
 
10
- # (Assuming you have helper functions get_top_chunks, etc.)
 
 
 
11
 
12
- # Create InferenceClient (no model name here)
13
- client = InferenceClient()
14
 
15
- def respond(message, history):
16
- # Your logic to pick context, e.g.:
17
- info = get_top_chunks(message, chunk_embeddings, cleaned_chunks)
18
- system_prompt = f"You are a friendly public health chatbot. Use this info as context: {info}"
19
- messages = [{'role': 'system', 'content': system_prompt}]
20
- if history:
21
- messages.extend(history)
22
- messages.append({'role': 'user', 'content': message})
23
 
24
- try:
25
- # Use the new chat completions API
26
- response = client.chat.completions.create(
27
- model="microsoft/phi-4",
28
- messages=messages,
29
- max_tokens=500,
30
- top_p=0.8
31
- )
32
- # Extract the content
33
- text = response.choices[0].message.content.strip()
34
- return text
35
- except Exception as e:
36
- # Log error and return fallback message
37
- print("Error during chat completion:", e)
38
- return "Sorry — I ran into an internal error while generating a response."
39
 
40
- def title():
41
- return "Public Health Bot"
 
 
42
 
43
- def description():
44
- return (
45
- "Public Health Bot uses scientific sources to answer questions about public health. "
46
- "Ask me anything about epidemiology, prevention, health policy, etc."
47
- )
48
-
49
- def css():
50
- return """
51
- /* custom CSS if any */
52
- """
53
-
54
- def load_model():
55
- # If you have any model loading (e.g. embedding model), do it here
56
- global chunk_embeddings, cleaned_chunks
57
- # Example:
58
- model = SentenceTransformer("all-MiniLM-L6-v2")
59
- # Load your chunks, embeddings, etc.
60
- # chunk_embeddings = ...
61
- # cleaned_chunks = ...
62
- return
63
-
64
- def main():
65
- load_model()
66
- with gr.Blocks(css=css()) as demo:
67
- chatbot = gr.Chatbot()
68
- msg = gr.Textbox(
69
- placeholder="Ask me a question about public health...",
70
- show_label=False,
71
- lines=1
72
- )
73
- submit = gr.Button("Send")
74
- clear = gr.Button("Clear")
75
-
76
- # Note: Temporarily disable examples to avoid startup crashes
77
- demo_interface = gr.ChatInterface(
78
- fn=respond,
79
- title=title(),
80
- description=description(),
81
- type="messages",
82
- theme="default"
83
- # examples=[["What is epidemiology?"], ["How to prevent spread of disease?"]]
84
- )
85
-
86
- demo_interface.queue()
87
- return demo
88
 
 
89
  if __name__ == "__main__":
90
- demo = main()
91
- demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
 
 
 
1
  import gradio as gr
2
 
3
+ def chatbot_response(message, history):
4
+ # Example knowledge base — replace or expand with your own logic
5
+ responses = {
6
+ "covid": "COVID-19 is caused by the SARS-CoV-2 virus. Vaccination, mask use, and hand hygiene help prevent transmission.",
7
+ "flu": "Influenza (the flu) is caused by influenza viruses. Annual flu vaccines are recommended for everyone over 6 months old.",
8
+ "mental health": "Mental health is vital for overall well-being. Prioritizing self-care, social connection, and seeking professional help when needed can make a big difference.",
9
+ "nutrition": "A balanced diet with fruits, vegetables, whole grains, and lean proteins supports long-term health."
10
+ }
11
 
12
+ message_lower = message.lower()
13
+ for key, response in responses.items():
14
+ if key in message_lower:
15
+ return response
16
 
17
+ return "I'm not sure about that topic, but I can help you find reliable public health information."
 
18
 
19
+ # Build Gradio interface
20
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
21
+ gr.Markdown("# 🩺 Public Health Bot\n### Ask me anything about health, wellness, and disease prevention!")
 
 
 
 
 
22
 
23
+ chatbot = gr.Chatbot()
24
+ msg = gr.Textbox(placeholder="Type your question here...", label="Your message")
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ def respond(message, history):
27
+ response = chatbot_response(message, history)
28
+ history.append((message, response))
29
+ return "", history
30
 
31
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ # Run the app
34
  if __name__ == "__main__":
35
+ demo.launch()