File size: 10,076 Bytes
722a16a
891728f
722a16a
 
 
891728f
 
 
 
 
 
 
 
 
 
 
 
722a16a
 
 
 
891728f
 
 
 
 
 
722a16a
 
891728f
722a16a
 
 
 
 
 
891728f
722a16a
 
891728f
 
 
722a16a
891728f
 
722a16a
891728f
 
722a16a
891728f
722a16a
891728f
 
 
 
 
 
 
 
 
 
 
 
 
 
722a16a
891728f
 
 
 
 
 
 
 
722a16a
891728f
722a16a
 
 
 
 
 
891728f
722a16a
 
 
 
 
 
 
 
 
 
 
891728f
722a16a
891728f
722a16a
 
891728f
722a16a
891728f
 
722a16a
891728f
722a16a
 
 
 
891728f
 
 
 
 
722a16a
 
 
891728f
722a16a
 
 
 
891728f
722a16a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
891728f
 
 
 
722a16a
891728f
 
722a16a
 
891728f
722a16a
 
 
 
 
 
 
 
 
 
891728f
722a16a
 
 
 
 
 
 
 
 
 
 
 
 
891728f
722a16a
 
 
 
891728f
 
 
722a16a
891728f
 
 
 
 
 
 
 
 
 
 
722a16a
891728f
 
 
 
 
 
 
 
 
722a16a
 
891728f
722a16a
 
891728f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
722a16a
891728f
 
 
 
 
 
 
722a16a
891728f
722a16a
891728f
 
 
 
 
 
 
 
 
 
722a16a
891728f
 
 
 
 
 
 
722a16a
891728f
 
 
722a16a
891728f
 
 
722a16a
891728f
 
 
722a16a
891728f
 
 
 
 
 
 
 
 
 
 
 
 
722a16a
 
891728f
722a16a
 
891728f
722a16a
891728f
722a16a
891728f
 
 
 
 
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
# ============================================================================
# HUGGINGFACE SPACES DEPLOYMENT - FUNCTIONGEMMA CLASSIFIER
# ============================================================================

"""
FunctionGemma Domain Classifier deployed on HuggingFace Spaces.
Uses Spaces Secrets for authentication - no token pasting needed!

SETUP INSTRUCTIONS:
1. Go to your Space Settings β†’ Repository secrets
2. Click "New secret"
3. Name: HF_TOKEN
4. Value: your_huggingface_token_here
5. Save and the space will automatically restart with the token!

Get your token: https://huggingface.co/settings/tokens
Accept license: https://huggingface.co/google/functiongemma-270m-it
"""

import os
import sys
import gradio as gr
import torch
import json
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
from huggingface_hub import login

# ============================================================================
# CONFIGURATION
# ============================================================================

MODEL_REPO = "ovinduG/functiongemma-domain-classifier"
BASE_MODEL = "google/functiongemma-270m-it"

# ============================================================================
# AUTHENTICATION
# ============================================================================

print("="*80)
print("πŸ” HUGGINGFACE SPACES AUTHENTICATION")
print("="*80)

# HuggingFace Spaces automatically provides this
HF_TOKEN = os.environ.get('HF_TOKEN', '').strip()

if not HF_TOKEN:
    print("\n❌ ERROR: HF_TOKEN not found in Spaces secrets!")
    print("\n" + "="*80)
    print("πŸ“ SETUP INSTRUCTIONS FOR HUGGINGFACE SPACES")
    print("="*80)
    print("\n1. Go to your Space Settings")
    print("2. Click on 'Repository secrets' tab")
    print("3. Click 'New secret'")
    print("4. Add:")
    print("   Name:  HF_TOKEN")
    print("   Value: hf_your_token_here")
    print("5. Click 'Add secret'")
    print("6. Space will automatically restart with the token!")
    print("\nπŸ”‘ Get your token: https://huggingface.co/settings/tokens")
    print("πŸ“‹ Accept license: https://huggingface.co/google/functiongemma-270m-it")
    print("="*80)
    sys.exit(1)

print(f"βœ… Token found: {HF_TOKEN[:10]}...{HF_TOKEN[-4:]}")

# Login
print("\nπŸ”„ Logging in...")
try:
    login(token=HF_TOKEN, add_to_git_credential=False)
    print("βœ… Logged in successfully!")
except Exception as e:
    print(f"❌ Login failed: {e}")
    sys.exit(1)

print("="*80)

# ============================================================================
# LOAD MODEL
# ============================================================================

print("\n" + "="*80)
print("πŸš€ LOADING MODEL")
print("="*80)

print("\nπŸ“₯ Loading base model...")
try:
    base_model = AutoModelForCausalLM.from_pretrained(
        BASE_MODEL,
        torch_dtype=torch.bfloat16,
        device_map="auto",
        trust_remote_code=True,
        token=HF_TOKEN
    )
    print("βœ… Base model loaded")
except Exception as e:
    print(f"❌ Failed: {e}")
    sys.exit(1)

print("\nπŸ“₯ Loading adapter...")
try:
    model = PeftModel.from_pretrained(base_model, MODEL_REPO, token=HF_TOKEN)
    print("βœ… Adapter loaded")
except Exception as e:
    print(f"❌ Failed: {e}")
    sys.exit(1)

print("\nπŸ“₯ Loading tokenizer...")
try:
    tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, token=HF_TOKEN)
    print("βœ… Tokenizer loaded")
except:
    tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, token=HF_TOKEN)
    print("βœ… Base tokenizer loaded")

model.eval()

print(f"\nβœ… Model ready!")
print(f"   Device: {model.device}")
print("="*80)

# ============================================================================
# CLASSIFICATION FUNCTION
# ============================================================================

def create_function_schema():
    return {
        "type": "function",
        "function": {
            "name": "classify_query_domain",
            "description": "Classify query into domains",
            "parameters": {
                "type": "object",
                "properties": {
                    "primary_domain": {"type": "string"},
                    "primary_confidence": {"type": "number"},
                    "is_multi_domain": {"type": "boolean"},
                    "secondary_domains": {"type": "array"}
                }
            }
        }
    }

def classify_query(text):
    """Classify a query and return formatted results."""
    if not text or not text.strip():
        return "⚠️ Please enter a query!", ""
    
    # Prepare input
    function_def = create_function_schema()
    messages = [
        {"role": "developer", "content": "You are a model that can do function calling"},
        {"role": "user", "content": text.strip()}
    ]
    
    inputs = tokenizer.apply_chat_template(
        messages,
        tools=[function_def],
        add_generation_prompt=True,
        return_dict=True,
        return_tensors="pt"
    ).to(model.device)
    
    # Generate
    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_new_tokens=150,
            do_sample=False,
            pad_token_id=tokenizer.eos_token_id
        )
    
    response = tokenizer.decode(
        outputs[0][inputs["input_ids"].shape[-1]:],
        skip_special_tokens=True
    )
    
    # Parse result
    try:
        if "{" in response:
            start = response.find("{")
            end = response.rfind("}") + 1
            result = json.loads(response[start:end])
        else:
            result = {"primary_domain": "unknown", "primary_confidence": 0.0}
    except:
        result = {"primary_domain": "unknown", "primary_confidence": 0.0}
    
    # Format output
    primary = result.get('primary_domain', 'unknown')
    confidence = result.get('primary_confidence', 0) * 100
    is_multi = result.get('is_multi_domain', False)
    secondary = result.get('secondary_domains', [])
    
    # Primary domain output
    primary_output = f"🎯 **Primary Domain:** {primary.upper()}\n"
    primary_output += f"πŸ“Š **Confidence:** {confidence:.1f}%"
    
    # Secondary domain output
    secondary_output = ""
    if is_multi and secondary:
        secondary_output = "πŸ”€ **Multi-Domain Query Detected!**\n\n"
        secondary_output += "**Secondary Domains:**\n"
        for sec in secondary:
            secondary_output += f"β€’ {sec['domain']}: {sec['confidence']*100:.1f}%\n"
    
    return primary_output, secondary_output

# ============================================================================
# GRADIO INTERFACE
# ============================================================================

# Custom CSS for styling
custom_css = """
.primary-box {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px;
    border-radius: 10px;
    font-size: 18px;
}
.secondary-box {
    background: #f0f0f0;
    padding: 15px;
    border-radius: 10px;
    margin-top: 10px;
}
"""

# Example queries
examples = [
    ["Write a Python function to reverse a linked list"],
    ["Build ML model to predict customer churn and create REST API"],
    ["What are the symptoms and treatment for diabetes?"],
    ["Explain the theory of relativity in simple terms"],
    ["Create a business plan for a coffee shop"],
    ["Calculate the derivative of x^2 + 3x + 5"],
]

# Create Gradio interface
with gr.Blocks(css=custom_css, title="FunctionGemma Domain Classifier") as demo:
    gr.Markdown(
        """
        # 🎯 FunctionGemma Domain Classifier
        
        Classify queries into 15+ domains with multi-domain detection. 
        Powered by **FunctionGemma-270M** fine-tuned with LoRA.
        
        **Performance:** 95.51% accuracy | 270M parameters | Fast inference
        """
    )
    
    with gr.Row():
        with gr.Column():
            query_input = gr.Textbox(
                label="Enter Your Query",
                placeholder="e.g., Write a Python function to sort a list",
                lines=3
            )
            
            classify_btn = gr.Button("πŸ” Classify", variant="primary", size="lg")
            
            gr.Markdown("### πŸ“ Example Queries")
            gr.Examples(
                examples=examples,
                inputs=query_input,
                label=None
            )
    
    with gr.Row():
        with gr.Column():
            primary_output = gr.Markdown(label="Classification Result")
        
        with gr.Column():
            secondary_output = gr.Markdown(label="Additional Domains")
    
    gr.Markdown(
        """
        ---
        ### πŸ“Š Supported Domains
        
        `coding` β€’ `api_generation` β€’ `mathematics` β€’ `data_analysis` β€’ `science` β€’ `medicine` β€’ 
        `business` β€’ `law` β€’ `technology` β€’ `literature` β€’ `creative_content` β€’ `education` β€’ 
        `general_knowledge` β€’ `ambiguous` β€’ `sensitive`
        
        ### πŸ”— Links
        - [Model on HuggingFace](https://huggingface.co/ovinduG/functiongemma-domain-classifier)
        - [Base Model: FunctionGemma](https://huggingface.co/google/functiongemma-270m-it)
        
        Made with ❀️ by ovinduG
        """
    )
    
    # Set up the classification action
    classify_btn.click(
        fn=classify_query,
        inputs=query_input,
        outputs=[primary_output, secondary_output]
    )
    
    # Also trigger on Enter
    query_input.submit(
        fn=classify_query,
        inputs=query_input,
        outputs=[primary_output, secondary_output]
    )

# ============================================================================
# LAUNCH
# ============================================================================

if __name__ == "__main__":
    print("\n" + "="*80)
    print("🌐 LAUNCHING GRADIO INTERFACE")
    print("="*80)
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False  # Set to True for temporary public link
    )