File size: 10,782 Bytes
4f42f3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import gradio as gr
from huggingface_hub import InferenceClient
import json
from datetime import datetime, timedelta
import os

# List of 20 well-known large language models
MODELS = [
    "meta-llama/Llama-3.3-70B-Instruct",
    "meta-llama/Llama-3.1-405B-Instruct",
    "mistralai/Mixtral-8x7B-Instruct-v0.1",
    "mistralai/Mistral-7B-Instruct-v0.3",
    "google/gemma-2-27b-it",
    "google/gemma-2-9b-it",
    "Qwen/Qwen2.5-72B-Instruct",
    "Qwen/Qwen2.5-Coder-32B-Instruct",
    "microsoft/Phi-3.5-mini-instruct",
    "tiiuae/falcon-180B-chat",
    "HuggingFaceH4/zephyr-7b-beta",
    "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO",
    "01-ai/Yi-34B-Chat",
    "databricks/dbrx-instruct",
    "openchat/openchat-3.5-0106",
    "teknium/OpenHermes-2.5-Mistral-7B",
    "cognitivecomputations/dolphin-2.6-mixtral-8x7b",
    "Nexusflow/Starling-LM-7B-beta",
    "EleutherAI/llemma_34b",
    "upstage/SOLAR-10.7B-Instruct-v1.0"
]

def get_usage_data(request: gr.Request):
    """Get usage data from browser storage"""
    try:
        # This will be handled by JavaScript
        return {"chats_used": 0, "reset_time": None}
    except:
        return {"chats_used": 0, "reset_time": None}

def check_usage_limit(chats_used, reset_time):
    """Check if user has exceeded usage limit"""
    if reset_time:
        reset_dt = datetime.fromisoformat(reset_time)
        if datetime.now() > reset_dt:
            return 0, None  # Reset the counter
    
    return chats_used, reset_time

def chat_with_model(message, history, model_name, hf_token, chats_used, reset_time):
    """Chat with the selected model"""
    
    # Check usage limit
    current_chats, current_reset = check_usage_limit(chats_used, reset_time)
    
    if current_chats >= 2:
        if current_reset:
            reset_dt = datetime.fromisoformat(current_reset)
            return history, current_chats, current_reset, f"⚠️ You've used your 2 free chats this month. Next reset: {reset_dt.strftime('%Y-%m-%d %H:%M')}"
        return history, current_chats, current_reset, "⚠️ You've used your 2 free chats this month."
    
    if not hf_token:
        return history, current_chats, current_reset, "⚠️ Please log in with your Hugging Face token first."
    
    if not message.strip():
        return history, current_chats, current_reset, ""
    
    try:
        # Initialize client with user's token
        client = InferenceClient(token=hf_token)
        
        # Prepare messages for API
        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})
        messages.append({"role": "user", "content": message})
        
        # Stream response
        response_text = ""
        history.append([message, ""])
        
        for chunk in client.chat_completion(
            model=model_name,
            messages=messages,
            max_tokens=2000,
            stream=True,
        ):
            if chunk.choices[0].delta.content:
                response_text += chunk.choices[0].delta.content
                history[-1][1] = response_text
                yield history, current_chats, current_reset, ""
        
        # Increment usage counter
        new_chats_used = current_chats + 1
        new_reset_time = current_reset
        
        if new_reset_time is None:
            # Set reset time to 1 month from now
            new_reset_time = (datetime.now() + timedelta(days=30)).isoformat()
        
        status_msg = f"βœ… Chat successful! Chats used: {new_chats_used}/2"
        if new_chats_used >= 2:
            reset_dt = datetime.fromisoformat(new_reset_time)
            status_msg += f" | Next reset: {reset_dt.strftime('%Y-%m-%d %H:%M')}"
        
        yield history, new_chats_used, new_reset_time, status_msg
        
    except Exception as e:
        error_msg = f"❌ Error: {str(e)}"
        if "429" in str(e):
            error_msg = "❌ Rate limit exceeded. Please try again later."
        elif "401" in str(e) or "403" in str(e):
            error_msg = "❌ Invalid Hugging Face token. Please check your token."
        
        yield history, current_chats, current_reset, error_msg

# Custom CSS
css = """
#header {
    text-align: center;
    padding: 20px;
    background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 10px;
    margin-bottom: 20px;
}
#header a {
    color: #FFD700;
    text-decoration: none;
    font-weight: bold;
    font-size: 0.9em;
}
#header a:hover {
    text-decoration: underline;
}
#chatbot {
    height: 500px;
}
.usage-info {
    padding: 10px;
    border-radius: 5px;
    margin: 10px 0;
}
"""

# JavaScript for localStorage management
js_code = """
function() {
    // Load usage data from localStorage
    const usageData = localStorage.getItem('hf_chat_usage');
    let chatsUsed = 0;
    let resetTime = null;
    
    if (usageData) {
        const data = JSON.parse(usageData);
        chatsUsed = data.chats_used || 0;
        resetTime = data.reset_time || null;
        
        // Check if reset time has passed
        if (resetTime && new Date() > new Date(resetTime)) {
            chatsUsed = 0;
            resetTime = null;
            localStorage.setItem('hf_chat_usage', JSON.stringify({chats_used: 0, reset_time: null}));
        }
    }
    
    return [chatsUsed, resetTime];
}
"""

# Build the Gradio interface
with gr.Blocks(css=css, theme=gr.themes.Soft(), title="HF Model Chat - 2 Free Chats/Month") as demo:
    
    # Header with attribution
    gr.HTML("""
        <div id="header">
            <h1>πŸ€— Hugging Face Model Chatbot</h1>
            <p>Chat with 20+ Large Language Models | 2 Free Chats per Month</p>
            <p><a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank">Built with anycoder</a></p>
        </div>
    """)
    
    # State variables
    chats_used_state = gr.State(0)
    reset_time_state = gr.State(None)
    
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### πŸ” Login & Settings")
            
            hf_token = gr.Textbox(
                label="Hugging Face Token",
                placeholder="hf_...",
                type="password",
                info="Enter your HF token to use the models"
            )
            
            gr.Markdown("""
                <small>Get your token from 
                <a href="https://huggingface.co/settings/tokens" target="_blank">
                Hugging Face Settings</a></small>
            """)
            
            model_dropdown = gr.Dropdown(
                choices=MODELS,
                value=MODELS[0],
                label="Select Model",
                info="Choose from 20 large language models"
            )
            
            usage_display = gr.Markdown("### πŸ“Š Usage: 0/2 chats used")
            status_box = gr.Textbox(
                label="Status",
                interactive=False,
                visible=True
            )
        
        with gr.Column(scale=2):
            gr.Markdown("### πŸ’¬ Chat")
            
            chatbot = gr.Chatbot(
                elem_id="chatbot",
                type="messages",
                height=500,
                show_copy_button=True
            )
            
            with gr.Row():
                msg_input = gr.Textbox(
                    placeholder="Type your message here...",
                    show_label=False,
                    scale=4
                )
                send_btn = gr.Button("Send", variant="primary", scale=1)
            
            clear_btn = gr.Button("Clear Chat")
    
    # Usage info display
    def update_usage_display(chats_used, reset_time):
        msg = f"### πŸ“Š Usage: {chats_used}/2 chats used"
        if chats_used >= 2 and reset_time:
            reset_dt = datetime.fromisoformat(reset_time)
            msg += f"\n**Next reset:** {reset_dt.strftime('%Y-%m-%d %H:%M')}"
        return msg
    
    # Event handlers
    def user_submit(message, history, model, token, chats_used, reset_time):
        return "", history, chats_used, reset_time, ""
    
    submit_event = msg_input.submit(
        user_submit,
        [msg_input, chatbot, model_dropdown, hf_token, chats_used_state, reset_time_state],
        [msg_input, chatbot, chats_used_state, reset_time_state, status_box],
        queue=False
    ).then(
        chat_with_model,
        [msg_input, chatbot, model_dropdown, hf_token, chats_used_state, reset_time_state],
        [chatbot, chats_used_state, reset_time_state, status_box]
    )
    
    send_btn.click(
        user_submit,
        [msg_input, chatbot, model_dropdown, hf_token, chats_used_state, reset_time_state],
        [msg_input, chatbot, chats_used_state, reset_time_state, status_box],
        queue=False
    ).then(
        chat_with_model,
        [msg_input, chatbot, model_dropdown, hf_token, chats_used_state, reset_time_state],
        [chatbot, chats_used_state, reset_time_state, status_box]
    )
    
    clear_btn.click(
        lambda: ([], ""),
        None,
        [chatbot, status_box],
        queue=False
    )
    
    # Update usage display when state changes
    chats_used_state.change(
        update_usage_display,
        [chats_used_state, reset_time_state],
        usage_display
    )
    
    # Save to localStorage on state change
    demo.load(
        None,
        None,
        [chats_used_state, reset_time_state],
        js="""
        function() {
            const usageData = localStorage.getItem('hf_chat_usage');
            let chatsUsed = 0;
            let resetTime = null;
            
            if (usageData) {
                const data = JSON.parse(usageData);
                chatsUsed = data.chats_used || 0;
                resetTime = data.reset_time || null;
                
                if (resetTime && new Date() > new Date(resetTime)) {
                    chatsUsed = 0;
                    resetTime = null;
                    localStorage.setItem('hf_chat_usage', JSON.stringify({chats_used: 0, reset_time: null}));
                }
            }
            
            return [chatsUsed, resetTime];
        }
        """
    )
    
    # Save changes to localStorage
    chats_used_state.change(
        None,
        [chats_used_state, reset_time_state],
        None,
        js="""
        function(chats, reset) {
            localStorage.setItem('hf_chat_usage', JSON.stringify({
                chats_used: chats,
                reset_time: reset
            }));
        }
        """
    )

if __name__ == "__main__":
    demo.launch()