|
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 = """ |
|
<div> |
|
<h1>HydroChat – Your Personalized Assistant on Molecular Hydrogen Supplements</h1> |
|
<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> |
|
<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> |
|
</div> |
|
""" |
|
|
|
|
|
def call_gemini(message: str) -> str: |
|
"""Send the user message as a structured prompt to the Gemini endpoint and |
|
return the assistant's reply text. Errors are surfaced in‑line for easier debugging. |
|
""" |
|
headers = {"Content-Type": "application/json"} |
|
|
|
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""" |
|
|
|
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 (KeyError, IndexError) as err: |
|
return f"[Parsing Error]: {err}" |
|
else: |
|
return f"[API Error {response.status_code}]: {response.text}" |
|
|
|
|
|
def transcribe_audio(audio_file: str, lang_code: str) -> str: |
|
"""Transcribe an uploaded audio file using Google Speech Recognition.""" |
|
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 err: |
|
return f"[Speech‑to‑Text Error]: {err}" |
|
|
|
|
|
with gr.Blocks(title="HydroChat – Molecular Hydrogen Supplement Assistant") as demo: |
|
gr.HTML(INTRO_TEXT) |
|
chatbot = gr.Chatbot(height=400, label="HydroChat Conversation", show_copy_button=True) |
|
|
|
with gr.Row(): |
|
msg = gr.Textbox(label="Enter your question", placeholder="e.g. I am currently on __ therapy; can I take __?", scale=6) |
|
lang_select = gr.Dropdown( |
|
label="Speech recognition language", 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="en-US", scale=2 |
|
) |
|
|
|
with gr.Row(): |
|
audio_input = gr.Audio(label="🎙️ Record voice", type="filepath") |
|
voice_to_text = gr.Button("Transcribe 🎤") |
|
|
|
with gr.Row(): |
|
ask = gr.Button("Submit") |
|
clear = gr.Button("Clear Chat") |
|
|
|
|
|
def respond(message: str, history: list): |
|
if not message.strip(): |
|
return "", history |
|
reply = call_gemini(message) |
|
history.append({"role": "user", "content": message}) |
|
history.append({"role": "assistant", "content": reply}) |
|
return "", history |
|
|
|
def handle_audio(audio_path: str, lang_code: str): |
|
if not audio_path: |
|
return "" |
|
return transcribe_audio(audio_path, lang_code) |
|
|
|
msg.submit(respond, inputs=[msg, chatbot], outputs=[msg, chatbot]) |
|
ask.click(respond, inputs=[msg, chatbot], outputs=[msg, chatbot]) |
|
clear.click(lambda: [], outputs=chatbot) |
|
voice_to_text.click(handle_audio, inputs=[audio_input, lang_select], outputs=msg) |
|
|
|
|
|
demo.launch() |
|
|