File size: 2,371 Bytes
91ebfb1
75378b2
 
25e9608
ccb564c
75378b2
 
25e9608
 
 
 
 
 
 
75378b2
25e9608
ccb564c
 
25e9608
ccb564c
 
 
75378b2
ccb564c
25e9608
 
 
ccb564c
 
 
75378b2
ccb564c
 
75378b2
25e9608
 
 
 
 
 
ccb564c
25e9608
 
75378b2
25e9608
ccb564c
25e9608
ccb564c
25e9608
75378b2
25e9608
 
 
 
75378b2
 
25e9608
 
ccb564c
 
25e9608
 
ccb564c
25e9608
 
ccb564c
 
91ebfb1
 
75378b2
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
import gradio as gr
from transformers import pipeline, set_seed

# --- Model setup ---
generator = pipeline("text-generation", model="gpt2", device=-1)
set_seed(42)

SYSTEM_PROMPT = (
    "You are a friendly, concise fitness coach. "
    "Give short, clear, encouraging answers focused on fitness, exercise, nutrition, and motivation. "
    "Keep replies in simple language and avoid long paragraphs.\n\n"
)

MAX_EXCHANGES_IN_PROMPT = 4

def build_prompt_from_history(history):
    # history is in role/content format: [{"role": "user", "content": ...}, {"role": "assistant", ...}]
    recent_messages = history[-MAX_EXCHANGES_IN_PROMPT*2:]  # last N exchanges
    prompt = SYSTEM_PROMPT
    for msg in recent_messages:
        if msg["role"] == "user":
            prompt += f"User: {msg['content']}\n"
        else:
            prompt += f"Coach: {msg['content']}\n"
    prompt += "Coach:"
    return prompt

def fitness_coach_chat(history, user_message):
    if history is None:
        history = []

    history.append({"role": "user", "content": user_message})
    prompt = build_prompt_from_history(history)

    gen = generator(
        prompt,
        max_new_tokens=120,
        do_sample=True,
        temperature=0.8,
        top_p=0.9,
        return_full_text=False,
        num_return_sequences=1,
    )

    ai_text = gen[0]["generated_text"].strip()
    history.append({"role": "assistant", "content": ai_text})

    return history, ""

custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap');
body { background: linear-gradient(135deg, #ffe6f0 0%, #fff0f6 100%); font-family: 'Poppins', sans-serif; }
.gradio-container { font-family: 'Poppins', sans-serif; }
h1 { color: #9b2c6b; text-align:center; }
"""

with gr.Blocks(css=custom_css, title="AI Fitness Coach") as demo:
    gr.Markdown("<h1>💖 AI Fitness Coach</h1>")
    chatbot = gr.Chatbot(label="Coach", type="messages", height=480)
    state = gr.State([])

    with gr.Row():
        txt = gr.Textbox(show_label=False, placeholder="Type your question...")
        send = gr.Button("Send")

    send.click(fitness_coach_chat, inputs=[state, txt], outputs=[chatbot, txt])
    txt.submit(fitness_coach_chat, inputs=[state, txt], outputs=[chatbot, txt])

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