Update app.py
Browse files
app.py
CHANGED
@@ -8,68 +8,53 @@ API_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-f
|
|
8 |
|
9 |
INTRO_TEXT = """
|
10 |
<div>
|
11 |
-
<h1
|
12 |
-
<p
|
13 |
-
<p
|
14 |
</div>
|
15 |
"""
|
16 |
|
17 |
-
|
|
|
|
|
|
|
|
|
18 |
headers = {"Content-Type": "application/json"}
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
你的主要任務是提供實證醫學導向的健康衛教與建議。請根據以下原則回答:
|
24 |
-
1. 鼓勵使用者思考如何將此氫分子膠囊與其他保健品或處方藥搭配使用以產生**協同作用**,並提醒用藥相關事項仍需醫療人員確認。
|
25 |
-
2. 在衛教與產品效果回應中,請**聚焦於「氫分子(Molecular Hydrogen)」的已知效益與研究證據**(如抗氧化、抗發炎、細胞保護等),並提及「珊瑚鈣為穩定載體」的角色。
|
26 |
-
3. 所有回應應**簡明、實證、不可編造**,避免誇大療效。
|
27 |
-
4. You are a multilingual assistant for dietary supplements. Please respond in the same language as the question.
|
28 |
-
You are a clinical assistant chatbot for a nutritional capsule product that contains:
|
29 |
-
- Coral calcium as a carrier for molecular hydrogen
|
30 |
-
- Additional vitamins and nutrients
|
31 |
-
- Delivered in oral capsule form
|
32 |
-
Your task is to provide scientifically sound health education. Please follow these principles:
|
33 |
-
1. Encourage users to explore **synergistic use** of this hydrogen capsule with existing supplements or medications, while reminding them to consult a healthcare provider.
|
34 |
-
2. Focus education and efficacy discussion on **Molecular Hydrogen**, highlighting its documented roles in antioxidation, anti-inflammation, and cell protection, and mention that coral calcium serves as a stable hydrogen carrier.
|
35 |
-
3. All responses must be **concise, evidence-based, and not exaggerated or speculative
|
36 |
-
4. You are a multilingual assistant for dietary supplements. Please respond in the same language as the question.
|
37 |
-
情境:{message}"""
|
38 |
-
|
39 |
-
data = {
|
40 |
-
"contents": [
|
41 |
-
{"parts": [{"text": prompt}]}
|
42 |
-
]
|
43 |
-
}
|
44 |
|
45 |
response = requests.post(API_URL, headers=headers, data=json.dumps(data))
|
46 |
if response.status_code == 200:
|
47 |
try:
|
48 |
-
return response.json()[
|
49 |
-
except
|
50 |
-
return f"[
|
51 |
else:
|
52 |
-
return f"[API
|
53 |
|
54 |
-
|
|
|
|
|
55 |
recognizer = sr.Recognizer()
|
56 |
with sr.AudioFile(audio_file) as source:
|
57 |
audio = recognizer.record(source)
|
58 |
try:
|
59 |
return recognizer.recognize_google(audio, language=lang_code)
|
60 |
-
except Exception as
|
61 |
-
return f"[
|
|
|
62 |
|
63 |
-
with gr.Blocks(title="
|
64 |
gr.HTML(INTRO_TEXT)
|
65 |
-
chatbot = gr.Chatbot(height=400,
|
66 |
-
|
67 |
with gr.Row():
|
68 |
-
msg = gr.Textbox(label="
|
69 |
lang_select = gr.Dropdown(
|
70 |
-
label="
|
71 |
-
|
72 |
-
("中文(台灣)", "zh-TW"),
|
73 |
("English (US)", "en-US"),
|
74 |
("日本語", "ja-JP"),
|
75 |
("한국어", "ko-KR"),
|
@@ -77,31 +62,35 @@ with gr.Blocks(title="氫鬆聊 - 專屬於您的健康諮詢夥伴") as demo:
|
|
77 |
("Tiếng Việt", "vi-VN"),
|
78 |
("Français", "fr-FR"),
|
79 |
("Deutsch", "de-DE"),
|
80 |
-
],
|
81 |
-
value="zh-TW"
|
82 |
)
|
83 |
-
|
84 |
with gr.Row():
|
85 |
-
audio_input = gr.Audio(label="
|
86 |
-
voice_to_text = gr.Button("🎤
|
87 |
|
88 |
with gr.Row():
|
89 |
-
ask = gr.Button("
|
90 |
-
clear = gr.Button("
|
91 |
-
|
92 |
-
|
|
|
|
|
|
|
93 |
reply = call_gemini(message)
|
94 |
history.append({"role": "user", "content": message})
|
95 |
history.append({"role": "assistant", "content": reply})
|
96 |
return "", history
|
97 |
|
98 |
-
def handle_audio(audio_path, lang_code):
|
99 |
-
|
100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
|
102 |
-
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
103 |
-
ask.click(respond, [msg, chatbot], [msg, chatbot])
|
104 |
-
clear.click(lambda: [], None, chatbot)
|
105 |
-
voice_to_text.click(handle_audio, [audio_input, lang_select], msg)
|
106 |
|
107 |
-
demo.launch()
|
|
|
8 |
|
9 |
INTRO_TEXT = """
|
10 |
<div>
|
11 |
+
<h1>HydroChat – Your Personalized Assistant on Molecular Hydrogen Supplements</h1>
|
12 |
+
<p>This chatbot delivers evidence‑based guidance on using molecular hydrogen (H<sub>2</sub>) supplements in conjunction with conventional medicine and everyday health practices.</p>
|
13 |
+
<p>Our mission is to translate peer‑reviewed clinical research into practical advice so that users can make informed decisions about hydrogen‑rich coral‑calcium capsules.</p>
|
14 |
</div>
|
15 |
"""
|
16 |
|
17 |
+
|
18 |
+
def call_gemini(message: str) -> str:
|
19 |
+
"""Send the user message as a structured prompt to the Gemini endpoint and
|
20 |
+
return the assistant's reply text. Errors are surfaced in‑line for easier debugging.
|
21 |
+
"""
|
22 |
headers = {"Content-Type": "application/json"}
|
23 |
+
|
24 |
+
prompt = f"""You are HydroChat, an evidence‑based clinical assistant for an oral capsule product that contains\n- Coral calcium as a stable carrier of molecular hydrogen (H₂)\n- Additional vitamins and nutrients\n\nYour task is to provide scientifically sound health education and supplement‑drug interaction advice. Follow these principles:\n1. Encourage users to explore **synergistic use** of this hydrogen capsule with existing supplements or prescription medications, while reminding them to consult a qualified healthcare professional.\n2. Keep the discussion anchored on **molecular hydrogen**: its documented antioxidative, anti‑inflammatory, and cytoprotective mechanisms, and coral calcium's role as a solid‑state hydrogen carrier.\n3. All answers must be **concise, evidence‑based, and free of exaggerated or speculative claims**.\n4. Respond in the **same language** the user used.\n\nUser message: {message}\n"""
|
25 |
+
|
26 |
+
data = {"contents": [{"parts": [{"text": prompt}]}]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
response = requests.post(API_URL, headers=headers, data=json.dumps(data))
|
29 |
if response.status_code == 200:
|
30 |
try:
|
31 |
+
return response.json()["candidates"][0]["content"]["parts"][0]["text"]
|
32 |
+
except (KeyError, IndexError) as err:
|
33 |
+
return f"[Parsing Error]: {err}"
|
34 |
else:
|
35 |
+
return f"[API Error {response.status_code}]: {response.text}"
|
36 |
|
37 |
+
|
38 |
+
def transcribe_audio(audio_file: str, lang_code: str) -> str:
|
39 |
+
"""Transcribe an uploaded audio file using Google Speech Recognition."""
|
40 |
recognizer = sr.Recognizer()
|
41 |
with sr.AudioFile(audio_file) as source:
|
42 |
audio = recognizer.record(source)
|
43 |
try:
|
44 |
return recognizer.recognize_google(audio, language=lang_code)
|
45 |
+
except Exception as err:
|
46 |
+
return f"[Speech‑to‑Text Error]: {err}"
|
47 |
+
|
48 |
|
49 |
+
with gr.Blocks(title="HydroChat – Molecular Hydrogen Supplement Assistant") as demo:
|
50 |
gr.HTML(INTRO_TEXT)
|
51 |
+
chatbot = gr.Chatbot(height=400, label="HydroChat Conversation", show_copy_button=True)
|
52 |
+
|
53 |
with gr.Row():
|
54 |
+
msg = gr.Textbox(label="Enter your question", placeholder="e.g. I am currently on __ therapy; can I take __?", scale=6)
|
55 |
lang_select = gr.Dropdown(
|
56 |
+
label="Speech recognition language", choices=[
|
57 |
+
("中文 (台灣)", "zh-TW"),
|
|
|
58 |
("English (US)", "en-US"),
|
59 |
("日本語", "ja-JP"),
|
60 |
("한국어", "ko-KR"),
|
|
|
62 |
("Tiếng Việt", "vi-VN"),
|
63 |
("Français", "fr-FR"),
|
64 |
("Deutsch", "de-DE"),
|
65 |
+
], value="en-US", scale=2
|
|
|
66 |
)
|
67 |
+
|
68 |
with gr.Row():
|
69 |
+
audio_input = gr.Audio(label="🎙️ Record voice", type="filepath")
|
70 |
+
voice_to_text = gr.Button("Transcribe 🎤")
|
71 |
|
72 |
with gr.Row():
|
73 |
+
ask = gr.Button("Submit")
|
74 |
+
clear = gr.Button("Clear Chat")
|
75 |
+
|
76 |
+
# ----- Callbacks -------------------------------------------------------
|
77 |
+
def respond(message: str, history: list):
|
78 |
+
if not message.strip():
|
79 |
+
return "", history
|
80 |
reply = call_gemini(message)
|
81 |
history.append({"role": "user", "content": message})
|
82 |
history.append({"role": "assistant", "content": reply})
|
83 |
return "", history
|
84 |
|
85 |
+
def handle_audio(audio_path: str, lang_code: str):
|
86 |
+
if not audio_path:
|
87 |
+
return ""
|
88 |
+
return transcribe_audio(audio_path, lang_code)
|
89 |
+
|
90 |
+
msg.submit(respond, inputs=[msg, chatbot], outputs=[msg, chatbot])
|
91 |
+
ask.click(respond, inputs=[msg, chatbot], outputs=[msg, chatbot])
|
92 |
+
clear.click(lambda: [], outputs=chatbot)
|
93 |
+
voice_to_text.click(handle_audio, inputs=[audio_input, lang_select], outputs=msg)
|
94 |
|
|
|
|
|
|
|
|
|
95 |
|
96 |
+
demo.launch()
|