import gradio as gr import requests import json import speech_recognition as sr GEMINI_API_KEY = "AIzaSyAZ3WSpx_o53zpmhIJRzR0JMsiBOTnttbg" API_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={GEMINI_API_KEY}" INTRO_TEXT = """

氫鬆聊 - 專屬於您的健康諮詢夥伴 HydroChat - Your Personalized Assistant about Molecular Hydrogen

本聊天機器人專為探討「氫分子 營養補充」搭配 主流醫學臨床場景健康保養 的應用而設計。

我們致力於透過氫分子 營養補充,完成正規的臨床試驗、醫療期刊發表、查驗登記,來輔助主流醫學、幫助病人。

""" def call_gemini(message): headers = {"Content-Type": "application/json"} prompt = f"""你是「氫分子營養補充膠囊」的諮詢機器人,氫分子膠囊或水塑膠囊產品成分為 含有吸附氫分子的珊瑚鈣基底 搭配維生素與其他營養素 以膠囊形式服用 你的主要任務是提供實證醫學導向的健康衛教與建議。請根據以下原則回答: 1. 鼓勵使用者思考如何將此氫分子膠囊與其他保健品或處方藥搭配使用以產生**協同作用**,並提醒用藥相關事項仍需醫療人員確認。 2. 在衛教與產品效果回應中,請**聚焦於「氫分子(Molecular Hydrogen)」的已知效益與研究證據**(如抗氧化、抗發炎、細胞保護等),並提及「珊瑚鈣為穩定載體」的角色。 3. 所有回應應**簡明、實證、不可編造**,避免誇大療效。 4. You are a multilingual assistant for dietary supplements. Please respond in the same language as the question. You are a clinical assistant chatbot for a nutritional capsule product that contains: - Coral calcium as a carrier for molecular hydrogen - Additional vitamins and nutrients - Delivered in oral capsule form Your task is to provide scientifically sound health education. Please follow these principles: 1. Encourage users to explore **synergistic use** of this hydrogen capsule with existing supplements or medications, while reminding them to consult a healthcare provider. 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. 3. All responses must be **concise, evidence-based, and not exaggerated or speculative 4. You are a multilingual assistant for dietary supplements. Please respond in the same language as the question. 情境:{message}""" data = { "contents": [ {"parts": [{"text": prompt}]} ] } response = requests.post(API_URL, headers=headers, data=json.dumps(data)) if response.status_code == 200: try: return response.json()['candidates'][0]['content']['parts'][0]['text'] except Exception as e: return f"[錯誤解析回應]: {str(e)}" else: return f"[API 錯誤 {response.status_code}]: {response.text}" def transcribe_audio(audio_file, lang_code): recognizer = sr.Recognizer() with sr.AudioFile(audio_file) as source: audio = recognizer.record(source) try: return recognizer.recognize_google(audio, language=lang_code) except Exception as e: return f"[語音辨識失敗]:{str(e)}" with gr.Blocks(title="氫鬆聊 - 專屬於您的健康諮詢夥伴") as demo: gr.HTML(INTRO_TEXT) chatbot = gr.Chatbot(height=400, type="messages") with gr.Row(): msg = gr.Textbox(label="請輸入您的問題", placeholder="例如:我正在接受__治療,可以吃___?") lang_select = gr.Dropdown( label="語音語言", choices=[ ("中文(台灣)", "zh-TW"), ("English (US)", "en-US"), ("日本語", "ja-JP"), ("한국어", "ko-KR"), ("Bahasa Indonesia", "id-ID"), ("Tiếng Việt", "vi-VN"), ("Français", "fr-FR"), ("Deutsch", "de-DE"), ], value="zh-TW" ) with gr.Row(): audio_input = gr.Audio(label="🎙 請錄音", type="filepath") voice_to_text = gr.Button("🎤 語音轉文字") with gr.Row(): ask = gr.Button("提問") clear = gr.Button("清除對話") def respond(message, history): reply = call_gemini(message) history.append({"role": "user", "content": message}) history.append({"role": "assistant", "content": reply}) return "", history def handle_audio(audio_path, lang_code): text = transcribe_audio(audio_path, lang_code) return text msg.submit(respond, [msg, chatbot], [msg, chatbot]) ask.click(respond, [msg, chatbot], [msg, chatbot]) clear.click(lambda: [], None, chatbot) voice_to_text.click(handle_audio, [audio_input, lang_select], msg) demo.launch()