File size: 25,840 Bytes
4b48d1e
a2268ab
 
4b48d1e
a2268ab
 
 
 
 
 
 
 
 
4b48d1e
be5cddc
4b48d1e
 
3a04dc9
 
 
 
 
 
 
 
 
 
 
 
2aad837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b48d1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a04dc9
2aad837
 
 
 
 
 
 
 
 
 
 
 
 
 
4b48d1e
 
 
 
 
 
 
 
 
 
 
2aad837
 
 
 
 
 
 
 
 
 
 
 
4b48d1e
2aad837
 
 
 
 
 
 
 
 
 
4b48d1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2aad837
4b48d1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be5cddc
 
4b48d1e
 
 
2aad837
4b48d1e
 
 
 
 
 
 
 
 
 
be5cddc
4b48d1e
be5cddc
2aad837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b48d1e
 
 
 
2aad837
4b48d1e
 
 
be5cddc
2aad837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b48d1e
 
 
 
 
 
 
 
 
 
 
 
be5cddc
4b48d1e
 
2aad837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b48d1e
 
 
 
 
 
 
 
 
 
 
 
 
be5cddc
4b48d1e
 
 
 
 
 
 
 
be5cddc
4b48d1e
 
 
 
 
 
 
 
be5cddc
4b48d1e
 
 
 
2aad837
4b48d1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be5cddc
 
4b48d1e
 
 
2aad837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b48d1e
2aad837
4b48d1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2aad837
 
 
4b48d1e
 
 
 
2aad837
 
 
4b48d1e
 
 
 
2aad837
 
 
4b48d1e
 
2aad837
4b48d1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2aad837
 
 
 
 
 
 
 
 
 
 
 
 
4b48d1e
2aad837
 
 
4b48d1e
 
2aad837
 
4b48d1e
be5cddc
4b48d1e
 
 
2aad837
 
4b48d1e
be5cddc
 
 
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
import os
import sys
import subprocess
import html

# Tự động cài đặt transformers & accelerate nếu chưa có trên môi trường
try:
    import transformers
except ImportError:
    print("Installing missing dependencies: transformers, accelerate...")
    subprocess.check_call([sys.executable, "-m", "pip", "install", "transformers", "accelerate"])
    import transformers

import torch
import gradio as gr
from transformers import AutoTokenizer, AutoModelForTokenClassification, pipeline

# Hỗ trợ Hugging Face ZeroGPU (nếu Space đang cấu hình phần cứng GPU)
try:
    import spaces
except ImportError:
    class _MockSpaces:
        @staticmethod
        def GPU(fn=None, *args, **kwargs):
            if fn is not None:
                return fn
            return lambda f: f
    spaces = _MockSpaces()

# 1. Quản lý danh sách mô hình & Caching Pipeline
DEFAULT_MODEL = "NhanSoHocCode/xlmr-ner-4labels-v2"
MODEL_OPTIONS = [
    ("✨ XLM-RoBERTa NER 4Labels v2 (Mới nhất / Khuyên dùng)", "NhanSoHocCode/xlmr-ner-4labels-v2"),
    ("🏷️ XLM-RoBERTa NER 4Labels v1 (Bản gốc)", "NhanSoHocCode/xlmr-ner-4labels"),
    ("⚙️ Tùy chỉnh (Nhập checkpoint Hugging Face khác...)", "custom")
]

PIPELINE_CACHE = {}

def get_ner_pipeline(model_id: str):
    """
    Tải hoặc lấy từ cache pipeline trích xuất thực thể theo model_id.
    Hỗ trợ cả checkpoint có sẵn hoặc checkpoint tùy chỉnh có cùng kiến trúc.
    """
    model_id = model_id.strip() if model_id else DEFAULT_MODEL
    if model_id in PIPELINE_CACHE:
        return PIPELINE_CACHE[model_id], None

    try:
        print(f"Loading model checkpoint: {model_id} ...")
        device = 0 if torch.cuda.is_available() else -1
        tokenizer = AutoTokenizer.from_pretrained(model_id)
        model = AutoModelForTokenClassification.from_pretrained(model_id)
        pipe = pipeline(
            "token-classification",
            model=model,
            tokenizer=tokenizer,
            aggregation_strategy="simple",
            device=device
        )
        PIPELINE_CACHE[model_id] = pipe
        print(f"Model loaded successfully: {model_id}")
        return pipe, None
    except Exception as e:
        err_msg = f"Không thể tải mô hình '{model_id}'. Chi tiết lỗi: {str(e)}"
        print(err_msg)
        return None, err_msg

# Tải trước mô hình mặc định khi khởi động ứng dụng
print(f"Pre-loading default model: {DEFAULT_MODEL} ...")
get_ner_pipeline(DEFAULT_MODEL)

# 2. Cấu hình nhãn & biểu tượng & màu sắc
LABEL_CONFIG = {
    "HARD_SKILL": {
        "icon": "🛠️",
        "name": "HARD_SKILL",
        "color": "#ef4444",      # Đỏ san hô
        "bg": "#ef4444",
        "text_color": "#ffffff"
    },
    "SOFT_SKILL": {
        "icon": "🤝",
        "name": "SOFT_SKILL",
        "color": "#d97706",      # Hổ phách / Vàng cam
        "bg": "#d97706",
        "text_color": "#ffffff"
    },
    "EDUCATION": {
        "icon": "🎓",
        "name": "EDUCATION",
        "color": "#0284c7",      # Xanh lam / Cyan
        "bg": "#0284c7",
        "text_color": "#ffffff"
    },
    "MAJOR": {
        "icon": "📊",
        "name": "MAJOR",
        "color": "#16a34a",      # Xanh lá lục bảo
        "bg": "#16a34a",
        "text_color": "#ffffff"
    }
}

ORDERED_LABELS = ["HARD_SKILL", "SOFT_SKILL", "EDUCATION", "MAJOR"]

@spaces.GPU
def analyze_ner(title, text, threshold=0.0, model_choice="NhanSoHocCode/xlmr-ner-4labels-v2", custom_model_id=""):
    # Xác định checkpoint thực tế được chọn
    if model_choice == "custom":
        active_model = (custom_model_id or "").strip()
        if not active_model:
            err_html = """
            <div style="padding: 18px; text-align: center; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px;">
                ⚠️ <b>Chưa nhập thông tin mô hình:</b> Vui lòng điền Hugging Face Repo ID hoặc checkpoint tùy chỉnh để tiếp tục.
            </div>
            """
            return err_html, "Lỗi: Bạn đã chọn mô hình tùy chỉnh nhưng chưa nhập Hugging Face Repo ID.", []
    else:
        active_model = model_choice.strip() if model_choice else DEFAULT_MODEL

    if not text or not text.strip():
        empty_msg = """
        <div style="padding: 24px; text-align: center; color: #6b7280; font-family: monospace;">
            Vui lòng nhập văn bản mô tả công việc (Job Description) để bắt đầu phân tích.
        </div>
        """
        return empty_msg, "Vui lòng nhập văn bản JD.", []

    title = title.strip() if title and title.strip() else "Kết quả phân tích JD"
    raw_text = text.strip()

    # Lấy pipeline mô hình
    ner_pipe, load_err = get_ner_pipeline(active_model)
    if load_err or ner_pipe is None:
        err_html = f"""
        <div style="padding: 18px; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; font-family: sans-serif;">
            <b>❌ Lỗi tải mô hình ({html.escape(active_model)}):</b><br/>
            <span style="font-size: 13.5px;">{html.escape(load_err or 'Không thể khởi tạo mô hình.')}</span><br/><br/>
            <small style="color: #6b7280;">Vui lòng kiểm tra lại tên repo trên Hugging Face hoặc đảm bảo mô hình có cùng kiến trúc Token Classification.</small>
        </div>
        """
        return err_html, f"Lỗi tải mô hình '{active_model}': {load_err}", []

    # Thực hiện trích xuất
    try:
        raw_results = ner_pipe(raw_text)
    except Exception as e:
        err_msg = f"Lỗi trong quá trình trích xuất thực thể: {str(e)}"
        err_html = f"""
        <div style="padding: 18px; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px;">
            <b>❌ Lỗi thực thi mô hình:</b> {html.escape(err_msg)}
        </div>
        """
        return err_html, err_msg, []

    # Lọc theo ngưỡng tin cậy
    entities = [
        item for item in raw_results
        if float(item["score"]) >= threshold
    ]

    # Sắp xếp các thực thể theo thứ tự xuất hiện trong câu
    entities = sorted(entities, key=lambda x: x["start"])

    # Xử lý gối vị trí (nếu có chồng lấn start/end)
    filtered_entities = []
    last_end = -1
    for ent in entities:
        if ent["start"] >= last_end:
            filtered_entities.append(ent)
            last_end = ent["end"]

    # 1. Tạo câu có đánh dấu thực thể dạng HTML màu sắc & dạng văn bản thô
    rendered_parts = []
    raw_parts = []
    last_idx = 0

    for ent in filtered_entities:
        start = ent["start"]
        end = ent["end"]
        label = ent["entity_group"]
        cfg = LABEL_CONFIG.get(label, {
            "icon": "🏷️",
            "color": "#6366f1",
            "bg": "#6366f1",
            "text_color": "#ffffff"
        })

        # Đoạn chữ thường phía trước
        if start > last_idx:
            plain_segment = raw_text[last_idx:start]
            rendered_parts.append(html.escape(plain_segment))
            raw_parts.append(plain_segment)

        # Lấy từ thực tế trong chuỗi gốc
        ent_word = raw_text[start:end]
        
        # Thẻ màu HTML
        badge_html = (
            f'<span class="ner-badge" style="background-color: {cfg["bg"]}; color: {cfg["text_color"]};">'
            f'[{label}: {html.escape(ent_word)}]'
            f'</span>'
        )
        rendered_parts.append(badge_html)
        raw_parts.append(f"[{label}: {ent_word}]")

        last_idx = end

    # Đoạn văn bản còn lại sau thực thể cuối cùng
    if last_idx < len(raw_text):
        plain_segment = raw_text[last_idx:]
        rendered_parts.append(html.escape(plain_segment))
        raw_parts.append(plain_segment)

    tagged_html = "".join(rendered_parts)
    tagged_plain = "".join(raw_parts)

    # 2. Thống kê danh sách thực thể theo nhóm
    grouped = {lbl: [] for lbl in ORDERED_LABELS}
    for ent in filtered_entities:
        lbl = ent["entity_group"]
        if lbl in grouped:
            grouped[lbl].append(ent)
        else:
            grouped.setdefault(lbl, []).append(ent)

    stats_html_lines = []
    stats_plain_lines = []
    table_rows = []

    stt = 1
    for lbl in ORDERED_LABELS:
        items = grouped.get(lbl, [])
        if not items:
            continue
        cfg = LABEL_CONFIG.get(lbl, {"icon": "🏷️", "color": "#4b5563"})
        
        items_detail = []
        for it in items:
            word = it["word"]
            score_pct = float(it["score"]) * 100
            items_detail.append(f"{word} ({score_pct:.1f}%)")
            table_rows.append([stt, f"{cfg['icon']} {lbl}", word, f"{score_pct:.1f}%", f"{it['start']}:{it['end']}"])
            stt += 1

        items_str = ", ".join(items_detail)

        # Dòng thống kê HTML
        stat_html = (
            f'<div class="stat-row">'
            f'  <span class="stat-tag" style="color: {cfg["color"]}; font-weight: 700;">'
            f'    {cfg["icon"]} {lbl} ({len(items)}):'
            f'  </span> '
            f'  <span class="stat-content">{html.escape(items_str)}</span>'
            f'</div>'
        )
        stats_html_lines.append(stat_html)

        # Dòng thống kê thô
        stats_plain_lines.append(f"  {cfg['icon']} {lbl} ({len(items)}): {items_str}")

    stats_html_content = "\n".join(stats_html_lines)
    stats_plain_content = "\n".join(stats_plain_lines)

    # 3. Kết xuất giao diện thẻ theo đúng hình mẫu
    card_html = f"""
    <div class="jd-result-card">
        <div class="border-line-double">===============================================================================================</div>
        <div class="jd-title">📌 {html.escape(title)}</div>
        <div class="model-badge-info">🤖 Mô hình: <code>{html.escape(active_model)}</code></div>
        <div class="border-line-single">-----------------------------------------------------------------------------------------------</div>
        
        <div class="section-heading">Văn bản gốc:</div>
        <div class="section-body raw-body">{html.escape(raw_text)}</div>
        
        <div class="border-line-single">-----------------------------------------------------------------------------------------------</div>
        
        <div class="section-heading">Kết quả trích xuất trực tiếp trong câu:</div>
        <div class="section-body tagged-body">{tagged_html}</div>
        
        <div class="border-line-single">-----------------------------------------------------------------------------------------------</div>
        
        <div class="section-heading">Thống kê danh sách thực thể:</div>
        <div class="section-body stats-body">
            {stats_html_content if stats_html_content else '<div style="color: #888;">Không phát hiện thực thể nào vượt qua ngưỡng tin cậy.</div>'}
        </div>
        
        <div class="border-line-double">===============================================================================================</div>
    </div>
    """

    # 4. Văn bản Plain Text hoàn chỉnh (sao chép nhanh)
    plain_output = f"""===============================================================================================
📌 {title}
🤖 Mô hình: {active_model}
-----------------------------------------------------------------------------------------------
Văn bản gốc:
{raw_text}
-----------------------------------------------------------------------------------------------
Kết quả trích xuất trực tiếp trong câu:
{tagged_plain}
-----------------------------------------------------------------------------------------------
Thống kê danh sách thực thể:
{stats_plain_content if stats_plain_content else '  (Không phát hiện thực thể nào)'}
==============================================================================================="""

    return card_html, plain_output, table_rows

# Helper tạo link Hugging Face
def render_model_link(model_choice, custom_id):
    is_custom = (model_choice == "custom")
    target = (custom_id or "").strip() if is_custom else model_choice
    
    if target and not target.startswith("http"):
        hf_url = f"https://huggingface.co/{target}"
        return (
            f'<div class="hf-link-wrapper">'
            f'  <span class="hf-icon">🤗</span>'
            f'  <span>Checkpoint hiện tại: </span>'
            f'  <a href="{hf_url}" target="_blank" class="hf-link"><b>{html.escape(target)}</b> ↗</a>'
            f'</div>'
        )
    return (
        '<div class="hf-link-wrapper">'
        '  <span class="hf-icon">💡</span>'
        '  <span>Nhập Hugging Face Repo ID hoặc checkpoint cục bộ tương thích với 4 nhãn chuẩn.</span>'
        '</div>'
    )

def handle_model_change(choice, custom_id):
    show_custom = (choice == "custom")
    link_html = render_model_link(choice, custom_id)
    return gr.update(visible=show_custom), link_html

def handle_custom_id_change(custom_id):
    return render_model_link("custom", custom_id)

# Custom CSS cho giao diện
custom_css = """
/* Font và định dạng tổng quát */
.container {
    max-width: 1050px !important;
    margin: 0 auto !important;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* Khung chọn mô hình thay thế dòng chữ mô tả */
.model-selector-panel {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    padding: 14px 18px;
    margin: 10px 0 16px 0;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
}

.hf-link-wrapper {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: #475569;
    margin-top: 6px;
    padding-left: 2px;
}

.hf-link {
    color: #2563eb !important;
    text-decoration: none !important;
    transition: color 0.15s ease;
}

.hf-link:hover {
    color: #1d4ed8 !important;
    text-decoration: underline !important;
}

.model-badge-info {
    font-size: 13px;
    color: #4b5563;
    margin: 4px 0 6px 0;
}

.model-badge-info code {
    background-color: #f3f4f6;
    color: #1f2937;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12.5px;
}

/* Thẻ kết quả mô phỏng chính xác hình mẫu */
.jd-result-card {
    background-color: #ffffff;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 20px 24px;
    margin-top: 10px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
    font-family: "Consolas", "Courier New", monospace, sans-serif;
    color: #1f2937;
    line-height: 1.8;
}

/* Dark mode compatibility */
@media (prefers-color-scheme: dark) {
    .model-selector-panel {
        background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
        border-color: #334155;
    }
    .hf-link-wrapper {
        color: #94a3b8;
    }
    .hf-link {
        color: #60a5fa !important;
    }
    .model-badge-info {
        color: #94a3b8;
    }
    .model-badge-info code {
        background-color: #334155;
        color: #f1f5f9;
    }
    .jd-result-card {
        background-color: #1e293b;
        border-color: #334155;
        color: #f1f5f9;
    }
    .jd-result-card .section-heading {
        color: #e2e8f0 !important;
    }
    .jd-result-card .border-line-double,
    .jd-result-card .border-line-single {
        color: #64748b !important;
    }
}

.border-line-double {
    color: #9ca3af;
    font-size: 13px;
    letter-spacing: 1px;
    user-select: none;
    overflow: hidden;
    white-space: nowrap;
}

.border-line-single {
    color: #d1d5db;
    font-size: 13px;
    margin: 10px 0;
    user-select: none;
    overflow: hidden;
    white-space: nowrap;
}

.jd-title {
    font-size: 16px;
    font-weight: 700;
    color: #111827;
    margin: 6px 0 2px 0;
}
@media (prefers-color-scheme: dark) {
    .jd-title { color: #f8fafc; }
}

.section-heading {
    font-size: 14px;
    font-weight: 600;
    color: #374151;
    margin-bottom: 6px;
}

.section-body {
    font-size: 14.5px;
    line-height: 1.9;
    word-break: break-word;
}

.raw-body {
    color: #374151;
}
@media (prefers-color-scheme: dark) {
    .raw-body { color: #cbd5e1; }
}

/* Các nhãn thực thể highlight trong câu */
.ner-badge {
    display: inline-block;
    padding: 1px 7px;
    margin: 1px 2px;
    border-radius: 4px;
    font-size: 13.5px;
    font-weight: 600;
    letter-spacing: 0.2px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    white-space: nowrap;
}

/* Phần thống kê */
.stats-body {
    margin-top: 4px;
}

.stat-row {
    margin-bottom: 6px;
    line-height: 1.7;
}

.stat-tag {
    font-size: 14px;
}

.stat-content {
    font-size: 14px;
    color: #374151;
}
@media (prefers-color-scheme: dark) {
    .stat-content { color: #cbd5e1; }
}

/* Legend badges trên đầu trang */
.legend-pill {
    display: inline-flex;
    align-items: center;
    padding: 4px 10px;
    border-radius: 9999px;
    font-size: 12.5px;
    font-weight: 600;
    margin-right: 8px;
    margin-bottom: 6px;
    color: white;
}
"""

# Khởi tạo giao diện Gradio
with gr.Blocks(title="XLM-RoBERTa NER Job Description") as demo:
    gr.HTML(f"<style>{custom_css}</style>")
    
    # Tiêu đề chính
    gr.Markdown("# 🏷️ Trích xuất Kỹ năng & Thực thể từ Job Description")

    # VỊ TRÍ THAY THẾ DÒNG CHỮ CŨ: KHỐI CHỨC NĂNG CHỌN MÔ HÌNH
    with gr.Group(elem_classes=["model-selector-panel"]):
        with gr.Row():
            model_dropdown = gr.Dropdown(
                label="🎯 Chọn mô hình trích xuất (Model Checkpoint)",
                choices=MODEL_OPTIONS,
                value=DEFAULT_MODEL,
                interactive=True,
                scale=5,
                info="Chuyển đổi giữa 2 checkpoint v1 / v2 đã huấn luyện hoặc tùy chỉnh checkpoint mới."
            )
            custom_model_textbox = gr.Textbox(
                label="🔗 Hugging Face Repo ID hoặc Checkpoint tùy chỉnh",
                placeholder="Ví dụ: NhanSoHocCode/xlmr-ner-4labels hoặc username/model-name",
                value="",
                interactive=True,
                visible=False,
                scale=5,
                info="Mô hình cần có cùng kiến trúc Token Classification và 4 nhãn thực thể chuẩn."
            )

        model_link_html = gr.HTML(
            value=render_model_link(DEFAULT_MODEL, ""),
            elem_classes=["hf-link-container"]
        )

    # Dải hiển thị 4 nhóm nhãn thực thể chuẩn
    gr.HTML(
        """
        <div style="margin-top: 4px; margin-bottom: 16px;">
            <span class="legend-pill" style="background-color: #ef4444;">🛠️ HARD_SKILL: Kỹ năng chuyên môn / Công nghệ</span>
            <span class="legend-pill" style="background-color: #d97706;">🤝 SOFT_SKILL: Kỹ năng mềm / Giao tiếp</span>
            <span class="legend-pill" style="background-color: #0284c7;">🎓 EDUCATION: Học vị / Bằng cấp</span>
            <span class="legend-pill" style="background-color: #16a34a;">📊 MAJOR: Chuyên ngành đào tạo</span>
        </div>
        """
    )

    with gr.Row():
        with gr.Column(scale=5):
            title_input = gr.Textbox(
                label="Tiêu đề JD (Tùy chọn)",
                placeholder="Ví dụ: Mẫu JD Senior Golang / Distributed Systems",
                value="Mẫu JD Senior Golang / Distributed Systems",
                lines=1
            )
            text_input = gr.Textbox(
                label="Nội dung Job Description (Văn bản gốc)",
                placeholder="Nhập hoặc dán nội dung tuyển dụng vào đây...",
                value=(
                    "Tuyển dụng Senior Backend Engineer yêu cầu tốt nghiệp Cử nhân chuyên ngành Công nghệ thông tin. "
                    "Có từ 4 năm kinh nghiệm làm việc với Golang, gRPC, Microservices và Event-Driven Architecture. "
                    "Thành thạo cơ sở dữ liệu PostgreSQL, Redis Caching và Apache Kafka. "
                    "Kinh nghiệm triển khai trên Kubernetes, Docker, CI/CD. "
                    "Sử dụng thành thạo Cursor, GitHub Copilot để tăng tốc lập trình. "
                    "Yêu cầu kỹ năng làm việc nhóm, tư duy giải quyết vấn đề và tiếng Anh giao tiếp tốt."
                ),
                lines=6
            )

            with gr.Accordion("⚙️ Tùy chỉnh nâng cao", open=False):
                threshold_slider = gr.Slider(
                    minimum=0.0,
                    maximum=1.0,
                    value=0.5,
                    step=0.05,
                    label="Ngưỡng độ tin cậy tối thiểu (Confidence Threshold)",
                    info="Chỉ hiển thị các thực thể có độ tin cậy lớn hơn hoặc bằng giá trị này."
                )

            with gr.Row():
                submit_btn = gr.Button("🚀 Phân tích & Trích xuất", variant="primary", size="lg")
                clear_btn = gr.ClearButton([text_input, title_input], value="🧹 Xóa nội dung", size="lg")

            # Các ví dụ mẫu chuẩn bị sẵn
            gr.Examples(
                examples=[
                    [
                        "Mẫu JD Senior Golang / Distributed Systems",
                        "Tuyển dụng Senior Backend Engineer yêu cầu tốt nghiệp Cử nhân chuyên ngành Công nghệ thông tin. Có từ 4 năm kinh nghiệm làm việc với Golang, gRPC, Microservices và Event-Driven Architecture. Thành thạo cơ sở dữ liệu PostgreSQL, Redis Caching và Apache Kafka. Kinh nghiệm triển khai trên Kubernetes, Docker, CI/CD. Sử dụng thành thạo Cursor, GitHub Copilot để tăng tốc lập trình. Yêu cầu kỹ năng làm việc nhóm, tư duy giải quyết vấn đề và tiếng Anh giao tiếp tốt.",
                        0.5,
                        "NhanSoHocCode/xlmr-ner-4labels-v2",
                        ""
                    ],
                    [
                        "Mẫu JD AI / Data Science Engineer",
                        "Tìm kiếm Kỹ sư AI tốt nghiệp Thạc sĩ hoặc Cử nhân ngành Khoa học Máy tính. Có kinh nghiệm với Python, PyTorch, Transformers và mô hình ngôn ngữ lớn (LLM). Thành thạo kỹ thuật RAG, Fine-tuning, triển khai mô hình với FastAPI, Docker trên GCP. Yêu cầu tư duy phản biện, kỹ năng nghiên cứu độc lập và khả năng tiếng Anh chuyên ngành xuất sắc.",
                        0.5,
                        "NhanSoHocCode/xlmr-ner-4labels-v2",
                        ""
                    ],
                    [
                        "Mẫu JD Frontend Lead Developer",
                        "Yêu cầu bằng Kỹ sư hoặc Đại học chuyên ngành Công nghệ phần mềm. Tối thiểu 5 năm kinh nghiệm với JavaScript, TypeScript, ReactJS, Next.js và TailwindCSS. Có kinh nghiệm tối ưu hiệu năng web, quản trị state với Redux Toolkit hoặc Zustand. Cần có kỹ năng lãnh đạo đội ngũ, khả năng giao tiếp và truyền đạt thông tin mạch lạc.",
                        0.5,
                        "NhanSoHocCode/xlmr-ner-4labels",
                        ""
                    ]
                ],
                inputs=[title_input, text_input, threshold_slider, model_dropdown, custom_model_textbox],
                label="💡 Nhấp vào các mẫu JD để thử nghiệm nhanh:"
            )

        with gr.Column(scale=6):
            with gr.Tabs():
                with gr.TabItem("🎨 Giao diện trực quan (Visual Card)"):
                    card_output = gr.HTML(label="Kết quả trực quan")

                with gr.TabItem("📋 Văn bản thô (Plain Text)"):
                    raw_output = gr.Textbox(
                        lines=16,
                        max_lines=30,
                        label="Văn bản định dạng Console (Sao chép nhanh)"
                    )

                with gr.TabItem("📊 Bảng dữ liệu chi tiết (Table)"):
                    table_output = gr.Dataframe(
                        headers=["STT", "Nhóm nhãn", "Thực thể", "Độ tin cậy", "Vị trí (Start:End)"],
                        label="Danh sách thực thể chi tiết"
                    )

    # Sự kiện tương tác bộ chọn mô hình
    model_dropdown.change(
        fn=handle_model_change,
        inputs=[model_dropdown, custom_model_textbox],
        outputs=[custom_model_textbox, model_link_html]
    )

    custom_model_textbox.input(
        fn=handle_custom_id_change,
        inputs=[custom_model_textbox],
        outputs=[model_link_html]
    )

    # Xử lý sự kiện click nút
    common_inputs = [title_input, text_input, threshold_slider, model_dropdown, custom_model_textbox]
    common_outputs = [card_output, raw_output, table_output]

    submit_btn.click(
        fn=analyze_ner,
        inputs=common_inputs,
        outputs=common_outputs
    )

    # Chạy lần đầu khi load trang
    demo.load(
        fn=analyze_ner,
        inputs=common_inputs,
        outputs=common_outputs
    )

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