Spaces:
Sleeping

File size: 2,076 Bytes
f5ce59d
 
 
 
e96a586
 
 
f5ce59d
e96a586
7a69b76
e96a586
f5ce59d
 
4140e4e
adb8d48
33caf43
adb8d48
7a69b76
929a7dd
 
adb8d48
929a7dd
 
 
7a69b76
e96a586
4140e4e
33caf43
adb8d48
 
 
929a7dd
91f51bf
 
929a7dd
91f51bf
1569fb8
861e548
f5ce59d
4beb52c
929a7dd
 
f5ce59d
 
 
adb8d48
929a7dd
 
33caf43
929a7dd
91f51bf
f5ce59d
929a7dd
 
 
 
4beb52c
 
929a7dd
e96a586
33caf43
 
 
 
3d52ac8
929a7dd
4140e4e
33caf43
 
adb8d48
929a7dd
e96a586
 
929a7dd
33caf43
929a7dd
 
33caf43
 
adb8d48
3d52ac8
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
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import gradio as gr

MODEL_NAME = "mathanmithun/dhigrowth_qwen2p5_0_5b_merged_model"

tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME,
    torch_dtype=torch.float32,
    device_map="cpu"
)

SYSTEM_MESSAGE = {
    "role": "system",
    "content": "You are Dhigrowth Assistant. Answer only based on Dhigrowth knowledge."
}

def build_prompt(messages):
    all_msgs = [SYSTEM_MESSAGE] + messages
    return tokenizer.apply_chat_template(
        all_msgs,
        tokenize=False,
        add_generation_prompt=True
    )


def respond(message, history):
    if history is None:
        history = []

    # Add user message to internal storage
    history.append({"role": "user", "content": message})

    # Prepare prompt
    prompt = build_prompt(history)
    inputs = tokenizer(prompt, return_tensors="pt")

    output = model.generate(
        **inputs,
        max_new_tokens=200,
        temperature=0.7
    )

    reply = tokenizer.decode(output[0], skip_special_tokens=True)

    # Fix repeated prefix
    reply = reply.split("Assistant:")[-1].strip()

    # Store full internal assistant response
    history.append({"role": "assistant", "content": reply})

    # 🔥 UI RETURN FORMAT – clean (no system message)
    ui_history = [
        {"role": msg["role"], "content": msg["content"]}
        for msg in history if msg["role"] != "system"
    ]

    return ui_history, history


def clear_chat():
    return [], []


# ---------------- UI ---------------- #

with gr.Blocks() as demo:
    gr.Markdown("<h2 style='text-align:center;'>🤖 DhiGrowth AI Assistant</h2>")

    chatbot = gr.Chatbot()  # expects dict messages format
    state = gr.State([])

    text_input = gr.Textbox(placeholder="Ask something...")

    text_input.submit(respond, [text_input, state], [chatbot, state])
    text_input.submit(lambda: "", None, text_input)

    gr.Button("Clear Chat").click(clear_chat, None, [chatbot, state])

demo.launch()