File size: 4,741 Bytes
71a1638
 
 
c78f550
71a1638
e34d178
 
c3d0665
71a1638
8cda827
0d8f866
 
 
71a1638
 
 
0d8f866
 
 
 
 
71a1638
0d8f866
 
 
 
9b02775
71a1638
 
 
0d8f866
 
 
71a1638
0d8f866
71a1638
0d8f866
 
 
c78f550
 
 
 
 
0d8f866
 
 
c78f550
0d8f866
71a1638
0d8f866
 
c78f550
0d8f866
c78f550
0d8f866
 
c78f550
 
 
 
 
 
 
0d8f866
c78f550
0d8f866
c78f550
0d8f866
 
e998977
71a1638
0d8f866
 
 
 
 
 
 
71a1638
e998977
 
71a1638
 
0d8f866
 
 
 
 
 
 
 
 
c78f550
71a1638
0d8f866
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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")

    # ----- Callbacks -------------------------------------------------------
    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()