Update app.py
Browse files
app.py
CHANGED
@@ -8,53 +8,68 @@ 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 |
-
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 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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()[
|
32 |
-
except
|
33 |
-
return f"[
|
34 |
else:
|
35 |
-
return f"[API
|
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
|
46 |
-
return f"[
|
47 |
-
|
48 |
|
49 |
-
with gr.Blocks(title="
|
50 |
gr.HTML(INTRO_TEXT)
|
51 |
-
chatbot = gr.Chatbot(height=400,
|
52 |
-
|
53 |
with gr.Row():
|
54 |
-
msg = gr.Textbox(label="
|
55 |
lang_select = gr.Dropdown(
|
56 |
-
label="
|
57 |
-
|
|
|
58 |
("English (US)", "en-US"),
|
59 |
("日本語", "ja-JP"),
|
60 |
("한국어", "ko-KR"),
|
@@ -62,35 +77,31 @@ with gr.Blocks(title="HydroChat – Molecular Hydrogen Supplement Assistant") as
|
|
62 |
("Tiếng Việt", "vi-VN"),
|
63 |
("Français", "fr-FR"),
|
64 |
("Deutsch", "de-DE"),
|
65 |
-
],
|
|
|
66 |
)
|
67 |
-
|
68 |
with gr.Row():
|
69 |
-
audio_input = gr.Audio(label="
|
70 |
-
voice_to_text = gr.Button("
|
71 |
|
72 |
with gr.Row():
|
73 |
-
ask = gr.Button("
|
74 |
-
clear = gr.Button("
|
75 |
-
|
76 |
-
|
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
|
86 |
-
|
87 |
-
|
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()
|
|
|
8 |
|
9 |
INTRO_TEXT = """
|
10 |
<div>
|
11 |
+
<h1>氫鬆聊 - 專屬於您的健康諮詢夥伴 HydroChat - Your Personalized Assistant about Molecular Hydrogen </h1>
|
12 |
+
<p>本聊天機器人專為探討「氫分子 營養補充」搭配 <b>主流醫學</b> 、<b>臨床場景</b> 與 <b>健康保養</b> 的應用而設計。</p>
|
13 |
+
<p>我們致力於透過氫分子 營養補充,完成正規的臨床試驗、醫療期刊發表、查驗登記,來輔助主流醫學、幫助病人。</p>
|
14 |
</div>
|
15 |
"""
|
16 |
|
17 |
+
def call_gemini(message):
|
|
|
|
|
|
|
|
|
18 |
headers = {"Content-Type": "application/json"}
|
19 |
+
prompt = f"""你是「氫分子營養補充膠囊」的諮詢機器人,氫分子膠囊或水塑膠囊產品成分為
|
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()['candidates'][0]['content']['parts'][0]['text']
|
49 |
+
except Exception as e:
|
50 |
+
return f"[錯誤解析回應]: {str(e)}"
|
51 |
else:
|
52 |
+
return f"[API 錯誤 {response.status_code}]: {response.text}"
|
53 |
|
54 |
+
def transcribe_audio(audio_file, lang_code):
|
|
|
|
|
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 e:
|
61 |
+
return f"[語音辨識失敗]:{str(e)}"
|
|
|
62 |
|
63 |
+
with gr.Blocks(title="氫鬆聊 - 專屬於您的健康諮詢夥伴") as demo:
|
64 |
gr.HTML(INTRO_TEXT)
|
65 |
+
chatbot = gr.Chatbot(height=400, type="messages")
|
66 |
+
|
67 |
with gr.Row():
|
68 |
+
msg = gr.Textbox(label="請輸入您的問題", placeholder="例如:我正在接受__治療,可以吃___?")
|
69 |
lang_select = gr.Dropdown(
|
70 |
+
label="語音語言",
|
71 |
+
choices=[
|
72 |
+
("中文(台灣)", "zh-TW"),
|
73 |
("English (US)", "en-US"),
|
74 |
("日本語", "ja-JP"),
|
75 |
("한국어", "ko-KR"),
|
|
|
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="🎙 請錄音", type="filepath")
|
86 |
+
voice_to_text = gr.Button("🎤 語音轉文字")
|
87 |
|
88 |
with gr.Row():
|
89 |
+
ask = gr.Button("提問")
|
90 |
+
clear = gr.Button("清除對話")
|
91 |
+
|
92 |
+
def respond(message, history):
|
|
|
|
|
|
|
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 |
+
text = transcribe_audio(audio_path, lang_code)
|
100 |
+
return text
|
|
|
|
|
|
|
|
|
|
|
|
|
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()
|