File size: 7,755 Bytes
e6dc671
 
 
 
 
 
a1c55c3
d104a8c
 
d460687
e6dc671
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d104a8c
 
 
e6dc671
d104a8c
e6dc671
d104a8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6dc671
d104a8c
 
e6dc671
 
 
 
 
d460687
8996e2d
e6dc671
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d104a8c
 
e6dc671
d104a8c
 
 
 
 
 
 
e6dc671
 
 
 
 
 
 
 
 
 
d104a8c
e6dc671
 
d104a8c
 
e6dc671
 
 
d104a8c
 
 
 
 
e6dc671
 
 
 
 
 
 
 
d104a8c
e6dc671
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a22b65f
 
 
 
e6dc671
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a22b65f
e6dc671
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import gradio as gr
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer
import threading
import queue
import time
import spaces
import sys
from io import StringIO

# Model configuration
model_name = "HelpingAI/Dhanishtha-2.0-preview"

# Global variables for model and tokenizer
model = None
tokenizer = None

def load_model():
    """Load the model and tokenizer"""
    global model, tokenizer
    
    print("Loading tokenizer...")
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    
    print("Loading model...")
    model = AutoModelForCausalLM.from_pretrained(
        model_name,
        torch_dtype="auto",
        device_map="auto",
        trust_remote_code=True
    )
    
    print("Model loaded successfully!")

class StreamCapture:
    """Capture streaming output from TextStreamer"""
    def __init__(self):
        self.text_queue = queue.Queue()
        self.captured_text = ""
        
    def write(self, text):
        """Capture written text"""
        if text and text.strip():
            self.captured_text += text
            self.text_queue.put(text)
        return len(text)
    
    def flush(self):
        """Flush method for compatibility"""
        pass
    
    def get_text(self):
        """Get all captured text"""
        return self.captured_text
    
    def reset(self):
        """Reset the capture"""
        self.captured_text = ""
        while not self.text_queue.empty():
            try:
                self.text_queue.get_nowait()
            except queue.Empty:
                break

@spaces.GPU()
def generate_response(message, history, max_tokens, temperature, top_p):
    """Generate streaming response"""
    global model, tokenizer
    
    if model is None or tokenizer is None:
        yield "Model is still loading. Please wait..."
        return
    
    # Prepare conversation history
    messages = []
    for user_msg, assistant_msg in history:
        messages.append({"role": "user", "content": user_msg})
        if assistant_msg:
            messages.append({"role": "assistant", "content": assistant_msg})
    
    # Add current message
    messages.append({"role": "user", "content": message})
    
    # Apply chat template
    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )
    
    # Tokenize input
    model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
    
    # Create stream capture
    stream_capture = StreamCapture()
    
    # Create TextStreamer with our capture
    streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
    
    # Temporarily redirect the streamer's output
    original_stdout = sys.stdout
    
    # Generation parameters
    generation_kwargs = {
        **model_inputs,
        "max_new_tokens": max_tokens,
        "temperature": temperature,
        "top_p": top_p,
        "do_sample": True,
        "pad_token_id": tokenizer.eos_token_id,
        "streamer": streamer,
    }
    
    # Start generation in a separate thread
    def generate():
        try:
            # Redirect stdout to capture streamer output
            sys.stdout = stream_capture
            with torch.no_grad():
                model.generate(**generation_kwargs)
        except Exception as e:
            stream_capture.text_queue.put(f"Error: {str(e)}")
        finally:
            # Restore stdout
            sys.stdout = original_stdout
            stream_capture.text_queue.put(None)  # Signal end
    
    thread = threading.Thread(target=generate)
    thread.start()
    
    # Stream the results
    generated_text = ""
    while True:
        try:
            new_text = stream_capture.text_queue.get(timeout=30)
            if new_text is None:
                break
            generated_text += new_text
            yield generated_text
        except queue.Empty:
            break
    
    thread.join(timeout=1)
    
    # Final yield with complete text
    if generated_text:
        yield generated_text
    else:
        yield "No response generated."

def chat_interface(message, history, max_tokens, temperature, top_p):
    """Main chat interface"""
    if not message.strip():
        return history, ""
    
    # Add user message to history
    history.append([message, ""])
    
    # Generate response
    for partial_response in generate_response(message, history[:-1], max_tokens, temperature, top_p):
        history[-1][1] = partial_response
        yield history, ""
    
    return history, ""

# Load model on startup
print("Initializing model...")
load_model()

# Create Gradio interface
with gr.Blocks(title="Dhanishtha-2.0-preview Chat", theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        """
        # 🤖 Dhanishtha-2.0-preview Chat
        
        Chat with the **HelpingAI/Dhanishtha-2.0-preview** model!
        
        Dhanishtha 2.0 is the world's first LLM designed to think between the responses. Unlike other Reasoning LLMs, which think just once.

        Dhanishtha can think, rethink, self-evaluate, and refine in between responses using multiple <think> blocks.
        """
    )
    
    with gr.Row():
        with gr.Column(scale=4):
            chatbot = gr.Chatbot(
                [],
                elem_id="chatbot",
                bubble_full_width=False,
                height=500,
                show_copy_button=True
            )
            
            with gr.Row():
                msg = gr.Textbox(
                    container=False,
                    placeholder="Type your message here...",
                    label="Message",
                    autofocus=True,
                    scale=7
                )
                send_btn = gr.Button("Send", variant="primary", scale=1)
                
        with gr.Column(scale=1):
            gr.Markdown("### ⚙️ Parameters")
            
            max_tokens = gr.Slider(
                minimum=1,
                maximum=40960,
                value=2048,
                step=1,
                label="Max Tokens",
                info="Maximum number of tokens to generate"
            )
            
            temperature = gr.Slider(
                minimum=0.1,
                maximum=2.0,
                value=0.7,
                step=0.1,
                label="Temperature",
                info="Controls randomness in generation"
            )
            
            top_p = gr.Slider(
                minimum=0.1,
                maximum=1.0,
                value=0.9,
                step=0.05,
                label="Top-p",
                info="Controls diversity of generation"
            )
            
            clear_btn = gr.Button("🗑️ Clear Chat", variant="secondary")
    
    # Event handlers
    msg.submit(
        chat_interface,
        inputs=[msg, chatbot, max_tokens, temperature, top_p],
        outputs=[chatbot, msg],
        concurrency_limit=1
    )
    
    send_btn.click(
        chat_interface,
        inputs=[msg, chatbot, max_tokens, temperature, top_p],
        outputs=[chatbot, msg],
        concurrency_limit=1
    )
    
    clear_btn.click(
        lambda: ([], ""),
        outputs=[chatbot, msg]
    )
    
    # Example prompts
    gr.Examples(
        examples=[
            ["Hello! Who are you?"],
            ["Explain quantum computing in simple terms"],
            ["Write a short story about a robot learning to paint"],
            ["What are the benefits of renewable energy?"],
            ["Help me write a Python function to sort a list"]
        ],
        inputs=msg,
        label="💡 Example Prompts"
    )

if __name__ == "__main__":
    demo.queue(max_size=20).launch()