File size: 27,934 Bytes
f4d5aab
 
 
 
 
 
 
65d40d5
 
7725101
 
 
270b4c0
 
 
f4d5aab
7725101
 
 
 
042e3b2
 
 
d7db16b
 
 
 
 
 
 
 
 
 
 
 
a486265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270b4c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a486265
6fc23f1
 
 
 
 
 
 
f4d5aab
6fc23f1
 
f4d5aab
6fc23f1
 
4ab50fb
 
6fc23f1
4ab50fb
 
6fc23f1
 
 
4ab50fb
 
3f899a4
6fc23f1
 
 
 
 
4ab50fb
3f899a4
6fc23f1
 
 
4ab50fb
6fc23f1
4ab50fb
 
6fc23f1
4ab50fb
 
 
 
 
 
 
 
 
 
 
 
 
 
6fc23f1
 
 
4ab50fb
 
3f899a4
6fc23f1
4ab50fb
 
3f899a4
6fc23f1
3f899a4
4ab50fb
3f899a4
6fc23f1
4ab50fb
3f899a4
6fc23f1
 
 
 
4ab50fb
 
 
6fc23f1
 
4ab50fb
 
 
 
 
 
 
6fc23f1
 
 
3f899a4
4ab50fb
6fc23f1
 
4ab50fb
 
 
 
6fc23f1
4ab50fb
 
3f899a4
6fc23f1
 
 
4ab50fb
3f899a4
6fc23f1
 
3f899a4
6fc23f1
4ab50fb
 
 
 
 
 
 
 
 
 
 
3f899a4
6fc23f1
3f899a4
4ab50fb
 
 
 
 
6fc23f1
4ab50fb
3f899a4
6fc23f1
 
4ab50fb
 
 
3f899a4
6fc23f1
 
4ab50fb
 
 
3f899a4
6fc23f1
 
4ab50fb
 
 
3f899a4
6fc23f1
 
 
 
4ab50fb
 
 
3f899a4
6fc23f1
 
 
4ab50fb
 
 
 
 
4d37b8b
6fc23f1
 
be06814
4ab50fb
 
 
 
 
 
 
6fc23f1
 
 
 
 
4ab50fb
6fc23f1
 
 
 
4ab50fb
 
6fc23f1
4ab50fb
 
 
6fc23f1
 
 
4ab50fb
6fc23f1
4ab50fb
be06814
270b4c0
 
 
 
4ab50fb
 
 
 
 
270b4c0
 
 
 
 
4ab50fb
 
 
 
270b4c0
 
 
 
 
4ab50fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270b4c0
4ab50fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270b4c0
f4d5aab
6fc23f1
f4d5aab
4ab50fb
6fc23f1
 
 
 
 
 
f0d09f3
4ab50fb
6fc23f1
4ab50fb
 
 
 
 
6fc23f1
4ab50fb
6fc23f1
 
 
 
8a052ba
 
 
 
6fc23f1
 
 
 
 
 
12ccc3e
 
a48f89a
 
8a052ba
 
6fc23f1
 
 
 
 
 
12ccc3e
 
a48f89a
 
8a052ba
 
6fc23f1
 
 
4ab50fb
6fc23f1
 
 
 
 
 
 
 
 
 
 
 
 
4ab50fb
6fc23f1
 
 
 
 
 
 
4ab50fb
6fc23f1
 
 
 
 
 
 
 
 
4d37b8b
6fc23f1
270b4c0
4d37b8b
d7db16b
 
 
 
7c117db
 
 
 
 
6fc23f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99fbeb9
 
 
6fc23f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fdfda4
6fc23f1
 
 
 
 
 
 
 
 
 
 
 
8a052ba
6fc23f1
 
 
 
 
270b4c0
 
 
 
6fc23f1
270b4c0
 
 
 
 
 
 
 
 
6fc23f1
270b4c0
6fc23f1
 
 
 
 
 
 
270b4c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fc23f1
270b4c0
6fc23f1
 
270b4c0
6fc23f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270b4c0
 
 
 
 
 
 
 
6fc23f1
 
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
import streamlit as st
import torch
from transformers import AutoTokenizer
from semviqa.ser.qatc_model import QATCForQuestionAnswering
from semviqa.tvc.model import ClaimModelForClassification
from semviqa.ser.ser_eval import extract_evidence_tfidf_qatc
from semviqa.tvc.tvc_eval import classify_claim
import time
import pandas as pd
import os
import psutil
import gc
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime

# Set environment variables to optimize CPU performance
os.environ["OMP_NUM_THREADS"] = str(psutil.cpu_count(logical=False))
os.environ["MKL_NUM_THREADS"] = str(psutil.cpu_count(logical=False))

# Set device globally
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

@st.cache_resource()
def load_model(model_name, model_class, is_bc=False, device=None):
    if device is None:
        device = "cuda" if torch.cuda.is_available() else "cpu"
    
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model = model_class.from_pretrained(model_name, num_labels=3 if not is_bc else 2)
    model.eval()
    
    model.to(device)
    return tokenizer, model

@st.cache_data
def preprocess_text(text):
    # Add any text cleaning or normalization here
    return text.strip()

# Optimized function for evidence extraction and classification with better CPU performance
def perform_verification(claim, context, model_qatc, tokenizer_qatc, model_tc, tokenizer_tc, 
                          model_bc, tokenizer_bc, tfidf_threshold, length_ratio_threshold):
    # Extract evidence
    evidence_start_time = time.time()
    evidence = extract_evidence_tfidf_qatc(
        claim, context, model_qatc, tokenizer_qatc,
        DEVICE,
        confidence_threshold=tfidf_threshold,
        length_ratio_threshold=length_ratio_threshold
    )
    evidence_time = time.time() - evidence_start_time
    
    # Explicit garbage collection after evidence extraction
    gc.collect()
    
    # Classify the claim
    verdict_start_time = time.time()
    with torch.no_grad():
        verdict = "NEI"
        prob3class, pred_tc = classify_claim(
            claim, evidence, model_tc, tokenizer_tc, DEVICE
        )
        
        # Only run binary classifier if needed
        prob2class, pred_bc = 0, 0
        if pred_tc != 0:
            prob2class, pred_bc = classify_claim(
                claim, evidence, model_bc, tokenizer_bc, DEVICE
            )
            verdict = "SUPPORTED" if pred_bc == 0 else "REFUTED" if prob2class > prob3class else ["NEI", "SUPPORTED", "REFUTED"][pred_tc]
            
    verdict_time = time.time() - verdict_start_time

    return {
        "evidence": evidence,
        "verdict": verdict,
        "evidence_time": evidence_time,
        "verdict_time": verdict_time,
        "prob3class": prob3class.item() if isinstance(prob3class, torch.Tensor) else prob3class,
        "pred_tc": pred_tc,
        "prob2class": prob2class.item() if isinstance(prob2class, torch.Tensor) else prob2class,
        "pred_bc": pred_bc
    }

# Add new functions for analysis
def analyze_verdict_distribution(history):
    if not history:
        return None
    
    df = pd.DataFrame(history)
    verdict_counts = df['verdict'].value_counts()
    
    fig = px.pie(
        values=verdict_counts.values,
        names=verdict_counts.index,
        title='Phân bố Kết quả Kiểm chứng',
        color_discrete_sequence=['#2ecc71', '#e74c3c', '#f1c40f']
    )
    return fig

def analyze_processing_time(history):
    if not history:
        return None
    
    df = pd.DataFrame(history)
    df['timestamp'] = pd.to_datetime(df['timestamp'])
    
    fig = px.line(
        df,
        x='timestamp',
        y=['evidence_time', 'verdict_time', 'total_time'],
        title='Thời gian Xử lý theo Thời gian',
        labels={'value': 'Thời gian (giây)', 'timestamp': 'Thời điểm'}
    )
    return fig

def generate_report(result):
    report = f"""
    BÁO CÁO KIỂM CHỨNG THÔNG TIN
    Thời gian: {datetime.now().strftime('%d/%m/%Y %H:%M:%S')}
    
    1. THÔNG TIN CƠ BẢN
    -------------------
    Câu khẳng định: {result['claim']}
    Kết luận: {result['verdict']}
    
    2. BẰNG CHỨNG
    -------------
    {result['evidence']}
    
    3. THỐNG KÊ THỜI GIAN
    ---------------------
    - Thời gian trích xuất bằng chứng: {result['evidence_time']:.2f} giây
    - Thời gian phân loại: {result['verdict_time']:.2f} giây
    - Tổng thời gian xử lý: {result['total_time']:.2f} giây
    
    4. CHI TIẾT KỸ THUẬT
    -------------------
    {result['details']}
    
    5. MÔ HÌNH SỬ DỤNG
    ------------------
    - QATC Model: {result['qatc_model']}
    - Binary Classification Model: {result['bc_model']}
    - 3-Class Classification Model: {result['tc_model']}
    """
    return report

# Set page configuration
st.set_page_config(
    page_title="SemViQA - Hệ thống Kiểm chứng Thông tin Tiếng Việt",
    page_icon="🔍",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Custom CSS
st.markdown("""
    <style>
    /* Main theme colors */
    :root {
        --primary-color: #2c3e50;
        --secondary-color: #3498db;
        --accent-color: #e74c3c;
        --success-color: #2ecc71;
        --warning-color: #f1c40f;
        --background-color: #f8f9fa;
        --text-color: #2c3e50;
        --border-color: #e0e0e0;
        --gradient-start: #2c3e50;
        --gradient-end: #3498db;
    }
    
    /* General styling */
    .stApp {
        background-color: var(--background-color);
        color: var(--text-color);
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    
    /* Header styling */
    .main-header {
        background: linear-gradient(135deg, var(--gradient-start), var(--gradient-end));
        color: white;
        padding: 3rem 2rem;
        border-radius: 15px;
        margin-bottom: 2rem;
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        position: relative;
        overflow: hidden;
    }
    
    .main-header::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('data:image/svg+xml,<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" fill="rgba(255,255,255,0.05)"/></svg>');
        opacity: 0.1;
    }
    
    .main-title {
        font-size: 3rem;
        font-weight: 800;
        text-align: center;
        margin-bottom: 1rem;
        text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
        letter-spacing: 1px;
    }
    
    .sub-title {
        font-size: 1.4rem;
        text-align: center;
        opacity: 0.9;
        font-weight: 300;
    }
    
    /* Input styling */
    .stTextArea textarea {
        border: 2px solid var(--border-color);
        border-radius: 12px;
        padding: 1.2rem;
        font-size: 1.1rem;
        min-height: 150px;
        background-color: white;
        transition: all 0.3s ease;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }
    
    .stTextArea textarea:focus {
        border-color: var(--secondary-color);
        box-shadow: 0 4px 8px rgba(52, 152, 219, 0.1);
    }
    
    /* Button styling */
    .stButton>button {
        background: linear-gradient(135deg, var(--secondary-color), var(--primary-color));
        color: white;
        border: none;
        border-radius: 12px;
        padding: 1rem 2.5rem;
        font-size: 1.2rem;
        font-weight: 600;
        transition: all 0.3s ease;
        text-transform: uppercase;
        letter-spacing: 1px;
    }
    
    .stButton>button:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 16px rgba(52, 152, 219, 0.2);
    }
    
    /* Result box styling */
    .result-box {
        background-color: white;
        border-radius: 15px;
        padding: 2.5rem;
        margin: 1.5rem 0;
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        border: 1px solid rgba(0, 0, 0, 0.05);
    }
    
    .result-box:hover {
        transform: translateY(-2px);
        box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
    }
    
    .verdict {
        font-size: 2rem;
        font-weight: 800;
        padding: 1.5rem;
        border-radius: 12px;
        margin: 1.5rem 0;
        text-align: center;
        transition: all 0.3s ease;
    }
    
    .verdict-supported {
        background: linear-gradient(135deg, #2ecc71, #27ae60);
        color: white;
        box-shadow: 0 4px 8px rgba(46, 204, 113, 0.2);
    }
    
    .verdict-refuted {
        background: linear-gradient(135deg, #e74c3c, #c0392b);
        color: white;
        box-shadow: 0 4px 8px rgba(231, 76, 60, 0.2);
    }
    
    .verdict-nei {
        background: linear-gradient(135deg, #f1c40f, #f39c12);
        color: white;
        box-shadow: 0 4px 8px rgba(241, 196, 15, 0.2);
    }
    
    /* Sidebar styling */
    .css-1d391kg {
        background-color: white;
        padding: 2.5rem;
        border-radius: 15px;
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    }
    
    /* Stats box styling */
    .stats-box {
        background: linear-gradient(135deg, #f8f9fa, #e9ecef);
        border-radius: 12px;
        padding: 1.5rem;
        margin: 1rem 0;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
    }
    
    /* Code block styling */
    .code-block {
        background-color: #2c3e50;
        border-radius: 12px;
        padding: 1.5rem;
        font-family: 'Fira Code', monospace;
        margin: 1.5rem 0;
        color: #ecf0f1;
        overflow-x: auto;
    }
    
    /* Tab styling */
    .stTabs [data-baseweb="tab-list"] {
        gap: 2rem;
        background-color: transparent;
    }
    
    .stTabs [data-baseweb="tab"] {
        background-color: white;
        border-radius: 12px;
        padding: 0.8rem 1.5rem;
        margin: 0 0.5rem;
        font-weight: 600;
        transition: all 0.3s ease;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }
    
    .stTabs [aria-selected="true"] {
        background: linear-gradient(135deg, var(--secondary-color), var(--primary-color));
        color: white;
        box-shadow: 0 4px 8px rgba(52, 152, 219, 0.2);
    }
    
    /* Analysis box styling */
    .analysis-box {
        background-color: white;
        border-radius: 15px;
        padding: 2rem;
        margin: 1.5rem 0;
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
        border-left: 4px solid var(--secondary-color);
    }
    
    /* Search box styling */
    .search-box {
        background-color: white;
        border-radius: 12px;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
    }
    
    /* Comparison box styling */
    .comparison-box {
        background-color: white;
        border-radius: 15px;
        padding: 2rem;
        margin: 1.5rem 0;
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
        border-left: 4px solid var(--secondary-color);
    }
    
    /* Selectbox styling */
    .stSelectbox select {
        border-radius: 8px;
        padding: 0.8rem;
        font-size: 1rem;
        border: 2px solid var(--border-color);
        background-color: white;
        transition: all 0.3s ease;
    }
    
    .stSelectbox select:focus {
        border-color: var(--secondary-color);
        box-shadow: 0 4px 8px rgba(52, 152, 219, 0.1);
    }
    
    /* Slider styling */
    .stSlider > div > div {
        background-color: var(--secondary-color);
    }
    
    /* Checkbox styling */
    .stCheckbox > label {
        font-weight: 500;
    }
    
    /* Info box styling */
    .info-box {
        background: linear-gradient(135deg, #f8f9fa, #e9ecef);
        border-radius: 15px;
        padding: 2rem;
        margin: 1.5rem 0;
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    }
    
    /* Chart container styling */
    .js-plotly-plot {
        border-radius: 12px !important;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05) !important;
    }
    
    /* Dataframe styling */
    .dataframe {
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
    }
    
    .dataframe thead th {
        background-color: var(--primary-color);
        color: white;
    }
    
    /* Download button styling */
    .stDownloadButton > button {
        background: linear-gradient(135deg, var(--success-color), #27ae60);
        color: white;
        border: none;
        border-radius: 12px;
        padding: 0.8rem 2rem;
        font-size: 1.1rem;
        font-weight: 600;
        transition: all 0.3s ease;
    }
    
    .stDownloadButton > button:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(46, 204, 113, 0.2);
    }
    </style>
""", unsafe_allow_html=True)

# Main header with updated design
st.markdown("""
    <div class="main-header">
        <div class="main-title">SemViQA</div>
        <div class="sub-title">Hệ thống Kiểm chứng Thông tin Tiếng Việt</div>
    </div>
""", unsafe_allow_html=True)

# Sidebar with updated design
with st.sidebar:
    st.markdown("""
        <div class="info-box">
            <h3>⚙️ Cài đặt Hệ thống</h3>
        </div>
    """, unsafe_allow_html=True)
    
    # Model selection with updated styling
    st.markdown("#### 🧠 Chọn Mô hình")
    qatc_model_name = st.selectbox(
        "Mô hình QATC",
        [
            "SemViQA/qatc-infoxlm-viwikifc",
            "SemViQA/qatc-infoxlm-isedsc01",
            "SemViQA/qatc-vimrc-viwikifc",
            "SemViQA/qatc-vimrc-isedsc01"
        ]
    )
    
    bc_model_name = st.selectbox(
        "Mô hình Phân loại Nhị phân",
        [
            "SemViQA/bc-xlmr-viwikifc",
            "SemViQA/bc-xlmr-isedsc01",
            "SemViQA/bc-infoxlm-viwikifc",
            "SemViQA/bc-infoxlm-isedsc01",
            "SemViQA/bc-erniem-viwikifc",
            "SemViQA/bc-erniem-isedsc01"
        ]
    )
    
    tc_model_name = st.selectbox(
        "Mô hình Phân loại Ba lớp",
        [
            "SemViQA/tc-xlmr-viwikifc",
            "SemViQA/tc-xlmr-isedsc01",
            "SemViQA/tc-infoxlm-viwikifc",
            "SemViQA/tc-infoxlm-isedsc01",
            "SemViQA/tc-erniem-viwikifc",
            "SemViQA/tc-erniem-isedsc01"
        ]
    )
    
    # Threshold settings with updated styling
    st.markdown("#### ⚖️ Ngưỡng Phân tích")
    tfidf_threshold = st.slider(
        "Ngưỡng TF-IDF",
        0.0, 1.0, 0.5,
        help="Điều chỉnh độ nhạy trong việc tìm kiếm bằng chứng"
    )
    
    length_ratio_threshold = st.slider(
        "Ngưỡng Tỷ lệ Độ dài",
        0.1, 1.0, 0.5,
        help="Điều chỉnh độ dài tối đa của bằng chứng"
    )
    
    # Display settings with updated styling
    st.markdown("#### 👁️ Hiển thị")
    show_details = st.checkbox(
        "Hiển thị Chi tiết Xác suất",
        value=False,
        help="Hiển thị thông tin chi tiết về xác suất dự đoán"
    )
    
    # Performance settings with updated styling
    st.markdown("#### ⚡ Hiệu suất")
    num_threads = st.slider(
        "Số luồng CPU",
        1, psutil.cpu_count(),
        psutil.cpu_count(logical=False),
        help="Điều chỉnh hiệu suất xử lý"
    )
    os.environ["OMP_NUM_THREADS"] = str(num_threads)
    os.environ["MKL_NUM_THREADS"] = str(num_threads)

# Main content
tabs = st.tabs(["🔍 Kiểm chứng", "📊 Lịch sử", "📈 Phân tích", "ℹ️ Thông tin"])

tokenizer_qatc, model_qatc = load_model(qatc_model_name, QATCForQuestionAnswering, device=DEVICE)
tokenizer_bc, model_bc = load_model(bc_model_name, ClaimModelForClassification, is_bc=True, device=DEVICE)
tokenizer_tc, model_tc = load_model(tc_model_name, ClaimModelForClassification, device=DEVICE)

verdict_icons = {
    "SUPPORTED": "✅",
    "REFUTED": "❌",
    "NEI": "⚠️"
}
# --- Tab Verify ---
with tabs[0]:
    col1, col2 = st.columns([2, 1])
    
    with col1:
        st.markdown("### 📝 Nhập Thông tin")
        claim = st.text_area(
            "Câu khẳng định cần kiểm chứng",
            "Chiến tranh với Campuchia đã kết thúc trước khi Việt Nam thống nhất.",
            help="Nhập câu khẳng định cần được kiểm chứng"
        )
        
        context = st.text_area(
            "Ngữ cảnh",
            "Sau khi thống nhất, Việt Nam tiếp tục gặp khó khăn do sự sụp đổ và tan rã của đồng minh Liên Xô cùng Khối phía Đông, các lệnh cấm vận của Hoa Kỳ, chiến tranh với Campuchia, biên giới giáp Trung Quốc và hậu quả của chính sách bao cấp sau nhiều năm áp dụng. Năm 1986, Đảng Cộng sản ban hành cải cách đổi mới, tạo điều kiện hình thành kinh tế thị trường và hội nhập sâu rộng. Cải cách đổi mới kết hợp cùng quy mô dân số lớn đưa Việt Nam trở thành một trong những nước đang phát triển có tốc độ tăng trưởng thuộc nhóm nhanh nhất thế giới, được coi là Hổ mới châu Á dù cho vẫn gặp phải những thách thức như tham nhũng, tội phạm gia tăng, ô nhiễm môi trường và phúc lợi xã hội chưa đầy đủ. Ngoài ra, giới bất đồng chính kiến, chính phủ một số nước phương Tây và các tổ chức theo dõi nhân quyền có quan điểm chỉ trích hồ sơ nhân quyền của Việt Nam liên quan đến các vấn đề tôn giáo, kiểm duyệt truyền thông, hạn chế hoạt động ủng hộ nhân quyền cùng các quyền tự do dân sự.",
            help="Nhập ngữ cảnh hoặc văn bản tham khảo"
        )
        
        verify_button = st.button("🔍 Kiểm chứng", use_container_width=True)
    
    with col2:
        st.markdown("### 📊 Kết quả")
        if verify_button:
            with st.spinner("Đang kiểm chứng..."):
                # Preprocess texts
                preprocessed_claim = preprocess_text(claim)
                preprocessed_context = preprocess_text(context)
                
                # Clear memory and perform verification
                gc.collect()
                start_time = time.time()
                
                result = perform_verification(
                    preprocessed_claim, preprocessed_context,
                    model_qatc, tokenizer_qatc,
                    model_tc, tokenizer_tc,
                    model_bc, tokenizer_bc,
                    tfidf_threshold, length_ratio_threshold
                )
                
                total_time = time.time() - start_time
                
                # Format details
                details = ""
                if show_details:
                    details = f"""
                        3-Class Probability: {result['prob3class']:.2f}
                        3-Class Predicted Label: {['NEI', 'SUPPORTED', 'REFUTED'][result['pred_tc']]}
                        2-Class Probability: {result['prob2class']:.2f}
                        2-Class Predicted Label: {['SUPPORTED', 'REFUTED'][result['pred_bc']] if isinstance(result['pred_bc'], int) and result['pred_tc'] != 0 else 'Not used'}
                    """
                
                # Store result
                st.session_state.latest_result = {
                    "claim": claim,
                    "evidence": result['evidence'],
                    "verdict": result['verdict'],
                    "evidence_time": result['evidence_time'],
                    "verdict_time": result['verdict_time'],
                    "total_time": total_time,
                    "details": details,
                    "qatc_model": qatc_model_name,
                    "bc_model": bc_model_name,
                    "tc_model": tc_model_name
                }
                
                # Add to history
                if 'history' not in st.session_state:
                    st.session_state.history = []
                st.session_state.history.append(st.session_state.latest_result)
                
                # Display result
                res = st.session_state.latest_result
                verdict_class = {
                    "SUPPORTED": "verdict-supported",
                    "REFUTED": "verdict-refuted",
                    "NEI": "verdict-nei"
                }.get(res['verdict'], "")
                
                st.markdown(f"""
                    <div class="result-box">
                        <h3>Kết quả Kiểm chứng</h3>
                        <p><strong>Câu khẳng định:</strong> {res['claim']}</p>
                        <p><strong>Bằng chứng:</strong> {res['evidence']}</p>
                        <p class="verdict {verdict_class}">
                            {verdict_icons.get(res['verdict'], '')} {res['verdict']}
                        </p>
                        <div class="stats-box">
                            <p><strong>Thời gian trích xuất bằng chứng:</strong> {res['evidence_time']:.2f} giây</p>
                            <p><strong>Thời gian phân loại:</strong> {res['verdict_time']:.2f} giây</p>
                            <p><strong>Tổng thời gian:</strong> {res['total_time']:.2f} giây</p>
                        </div>
                        {f"<div class='code-block'><pre>{res['details']}</pre></div>" if show_details else ""}
                    </div>
                """, unsafe_allow_html=True)
                
                # Download button
                result_text = f"Câu khẳng định: {res['claim']}\nBằng chứng: {res['evidence']}\nKết luận: {res['verdict']}\nChi tiết: {res['details']}"
                st.download_button(
                    "📥 Tải kết quả",
                    data=result_text,
                    file_name="ket_qua_kiem_chung.txt",
                    mime="text/plain"
                )
        else:
            st.info("Vui lòng nhập thông tin và nhấn nút Kiểm chứng để bắt đầu.")

# --- Tab History ---
with tabs[1]:
    st.markdown("### 📊 Lịch sử Kiểm chứng")
    
    # Add search functionality
    search_query = st.text_input("🔍 Tìm kiếm trong lịch sử", "")
    
    if 'history' in st.session_state and st.session_state.history:
        # Filter history based on search query
        filtered_history = st.session_state.history
        if search_query:
            filtered_history = [
                record for record in st.session_state.history
                if search_query.lower() in record['claim'].lower() or
                   search_query.lower() in record['evidence'].lower()
            ]
        
        # Download full history
        history_df = pd.DataFrame(filtered_history)
        st.download_button(
            "📥 Tải toàn bộ lịch sử",
            data=history_df.to_csv(index=False).encode('utf-8'),
            file_name="lich_su_kiem_chung.csv",
            mime="text/csv"
        )
        
        # Display history with comparison option
        for idx, record in enumerate(reversed(filtered_history), 1):
            col1, col2 = st.columns([3, 1])
            
            with col1:
                st.markdown(f"""
                    <div class="result-box">
                        <h4>Kiểm chứng #{idx}</h4>
                        <p><strong>Câu khẳng định:</strong> {record['claim']}</p>
                        <p><strong>Kết luận:</strong> {verdict_icons.get(record['verdict'], '')} {record['verdict']}</p>
                        <p><strong>Thời gian:</strong> {record['total_time']:.2f} giây</p>
                    </div>
                """, unsafe_allow_html=True)
            
            with col2:
                if st.button("🔄 So sánh", key=f"compare_{idx}"):
                    st.session_state.selected_for_comparison = record

# --- Tab Analysis ---
with tabs[2]:
    st.markdown("### 📈 Phân tích Chi tiết")
    
    if 'history' in st.session_state and st.session_state.history:
        # Add timestamp to history records
        for record in st.session_state.history:
            if 'timestamp' not in record:
                record['timestamp'] = datetime.now()
        
        # Distribution analysis
        st.markdown("#### 📊 Phân bố Kết quả")
        verdict_fig = analyze_verdict_distribution(st.session_state.history)
        if verdict_fig:
            st.plotly_chart(verdict_fig, use_container_width=True)
        
        # Processing time analysis
        st.markdown("#### ⏱️ Phân tích Thời gian Xử lý")
        time_fig = analyze_processing_time(st.session_state.history)
        if time_fig:
            st.plotly_chart(time_fig, use_container_width=True)
        
        # Model performance analysis
        st.markdown("#### 🧠 Phân tích Hiệu suất Mô hình")
        model_stats = pd.DataFrame(st.session_state.history)
        if not model_stats.empty:
            st.markdown("##### Thống kê theo Mô hình")
            model_performance = model_stats.groupby(['qatc_model', 'bc_model', 'tc_model']).agg({
                'total_time': ['mean', 'count'],
                'verdict': lambda x: (x == 'SUPPORTED').mean()
            }).round(2)
            st.dataframe(model_performance)
    else:
        st.info("Chưa có dữ liệu để phân tích.")

# --- Tab Info ---
with tabs[3]:
    st.markdown("""
        <div class="result-box">
            <h3>ℹ️ Thông tin về SemViQA</h3>
            <p>SemViQA là hệ thống kiểm chứng thông tin tự động cho tiếng Việt, được phát triển bởi nhóm nghiên cứu tại Đại học Công nghệ Thông tin - Đại học Quốc gia TP.HCM.</p>
            
            <h4>🔍 Cách sử dụng</h4>
            <ol>
                <li>Nhập câu khẳng định cần kiểm chứng</li>
                <li>Nhập ngữ cảnh hoặc văn bản tham khảo</li>
                <li>Điều chỉnh các tham số trong phần Cài đặt nếu cần</li>
                <li>Nhấn nút Kiểm chứng</li>
            </ol>
            
            <h4>⚙️ Các tham số</h4>
            <ul>
                <li><strong>Ngưỡng TF-IDF:</strong> Điều chỉnh độ nhạy trong việc tìm kiếm bằng chứng</li>
                <li><strong>Ngưỡng Tỷ lệ Độ dài:</strong> Điều chỉnh độ dài tối đa của bằng chứng</li>
                <li><strong>Số luồng CPU:</strong> Điều chỉnh hiệu suất xử lý</li>
            </ul>
            
            <h4>📊 Kết quả</h4>
            <ul>
                <li><strong>SUPPORTED:</strong> Câu khẳng định được hỗ trợ bởi bằng chứng</li>
                <li><strong>REFUTED:</strong> Câu khẳng định bị bác bỏ bởi bằng chứng</li>
                <li><strong>NEI:</strong> Không đủ bằng chứng để kết luận</li>
            </ul>
            
            <h4>🆕 Tính năng Mới</h4>
            <ul>
                <li><strong>Phân tích Chi tiết:</strong> Xem thống kê và biểu đồ về kết quả kiểm chứng</li>
                <li><strong>Tìm kiếm Lịch sử:</strong> Dễ dàng tìm kiếm trong lịch sử kiểm chứng</li>
                <li><strong>So sánh Kết quả:</strong> So sánh các kết quả kiểm chứng với nhau</li>
                <li><strong>Báo cáo Chi tiết:</strong> Xuất báo cáo chi tiết về kết quả kiểm chứng</li>
            </ul>
        </div>
    """, unsafe_allow_html=True)