File size: 3,619 Bytes
67982b2
11c2b89
67982b2
e4ac69f
11c2b89
e4ac69f
67982b2
11c2b89
e4ac69f
 
 
2d37034
 
 
 
 
 
67982b2
d1ffeb9
67982b2
11c2b89
 
 
 
 
67982b2
11c2b89
 
 
 
 
 
 
67982b2
11c2b89
 
 
67982b2
11c2b89
 
67982b2
11c2b89
 
 
 
 
67982b2
11c2b89
 
 
 
 
 
 
67982b2
11c2b89
 
 
67982b2
11c2b89
e4ac69f
 
 
11c2b89
 
 
 
 
 
 
 
 
 
 
 
 
67982b2
 
11c2b89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67982b2
 
11c2b89
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
98
99
100
101
102
103
104
105
106
107
108
import gradio as gr
import os
from huggingface_hub import InferenceClient
import huggingface_hub
import logging
from typing import List, Tuple

logging.basicConfig(level=logging.INFO)

# Debugging info
hf_token = os.environ.get("ZEPHYR_BRIGHTSIDE_TOKEN")
print("Hugging Face Hub version:", huggingface_hub.__version__)

if not hf_token:
    print("❌ Hugging Face token not loaded. Check your Space secrets.")
else:
    print("βœ… Token loaded successfully.")

client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=hf_token)

MAX_HISTORY_LENGTH = 20
MEMORY_WINDOW = 5
MAX_TOKENS = 1024
TEMPERATURE = 0.7
TOP_P = 0.95

def get_conversation_prompt():
    return """You are Mr. Brightside, an endlessly positive, caring, and upbeat AI.
Your job is to help the user see the bright side of any situation, no matter how bad it seems.
Respond warmly and naturally. Use humor, kindness, or optimism to shift their perspective.
Never dismiss their feelings β€” acknowledge them first, then gently guide them toward something good.
Keep your replies short (2–4 sentences). Ask light questions or offer hopeful thoughts to keep the conversation going.
You are not a therapist β€” you are a supportive and sunny companion who always looks on the bright side."""

def respond(message: str, chat_history: List[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str]]]:
    if not message.strip():
        return "", chat_history

    try:
        api_messages = [{"role": "system", "content": get_conversation_prompt()}]

        for user_msg, bot_msg in chat_history[-MEMORY_WINDOW:]:
            api_messages.extend([
                {"role": "user", "content": user_msg},
                {"role": "assistant", "content": bot_msg}
            ])

        api_messages.append({"role": "user", "content": message})
        response = client.chat_completion(
            messages=api_messages,
            max_tokens=MAX_TOKENS,
            temperature=TEMPERATURE,
            top_p=TOP_P
        )

        bot_message = response.choices[0].message.content
        updated_history = chat_history + [(message, bot_message)]
        return "", updated_history

    except Exception as e:
        import traceback
        traceback.print_exc()
        error_msg = f"[ERROR] {type(e).__name__}: {str(e)}"
        return "", chat_history + [(message, error_msg)]

def get_avatar_url():
    return "https://api.dicebear.com/7.x/lorelei/svg?seed=sunshine"

custom_css = """
#voice-controls {
    margin-top: 1em;
    text-align: center;
    opacity: 0.5;
    font-size: 0.9rem;
    font-style: italic;
}
"""

with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
    gr.Markdown("""
    # β˜€οΈ Mr. Brightside – Your Optimism Coach  
    Talk to Mr. Brightside when things feel rough β€” he’s here to help you find the silver lining in any situation.
    """)

    avatar = get_avatar_url()
    chatbot = gr.Chatbot(
        height=400,
        bubble_full_width=True,
        show_copy_button=True,
        avatar_images=[None, avatar],
        scale=1,
        min_width=800
    )

    msg = gr.Textbox(placeholder="Tell Mr. Brightside what's going on...")

    with gr.Row():
        submit = gr.Button("Send", variant="primary")
        clear = gr.Button("New Chat")

    msg.submit(fn=respond, inputs=[msg, chatbot], outputs=[msg, chatbot])
    submit.click(fn=respond, inputs=[msg, chatbot], outputs=[msg, chatbot])
    clear.click(lambda: [], None, chatbot, queue=False)
    clear.click(lambda: "", None, msg, queue=False)

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)