File size: 30,028 Bytes
f4d5aab
 
 
 
 
 
 
65d40d5
 
f4d5aab
 
 
ee53ecb
f4d5aab
ee53ecb
35de67c
f4d5aab
 
8a052ba
f4d5aab
 
3f899a4
4d37b8b
 
f4d5aab
3f899a4
 
 
 
 
 
 
fb62d04
3f899a4
 
 
6a1dd5e
3f899a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d37b8b
3f899a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d37b8b
f4d5aab
4d37b8b
 
 
f4d5aab
4d37b8b
4ebd212
65d40d5
5682e8a
 
 
620ddec
 
5682e8a
 
 
 
 
620ddec
5682e8a
 
620ddec
f0d09f3
 
4ebd212
 
 
 
8a052ba
 
 
 
 
4ebd212
8a052ba
 
 
 
 
 
 
f0d09f3
8a052ba
 
 
 
 
 
 
4d37b8b
f4d5aab
f0d09f3
8a052ba
 
 
 
f4d5aab
4d37b8b
8a052ba
 
 
f4d5aab
f0d09f3
8a052ba
 
 
 
 
f0d09f3
4d37b8b
f0d09f3
 
4d37b8b
f0d09f3
4d37b8b
 
8a052ba
4d37b8b
8a052ba
43449cb
 
4d37b8b
 
4ebd212
4d37b8b
 
 
5682e8a
 
4d37b8b
4fdfda4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a052ba
 
4fdfda4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d37b8b
4fdfda4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d37b8b
4fdfda4
 
4d37b8b
4fdfda4
 
 
 
 
 
3f899a4
4fdfda4
 
 
 
 
 
 
 
8a052ba
4d37b8b
8a052ba
4d37b8b
f0d09f3
4ebd212
8a052ba
65d40d5
 
 
 
 
 
 
 
8a052ba
4ebd212
8a052ba
4ebd212
f4d5aab
4d37b8b
f0d09f3
4ebd212
5682e8a
 
e816ea2
5682e8a
 
 
e816ea2
5682e8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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

# Load models with caching
@st.cache_resource()
def load_model(model_name, model_class, is_bc=False):
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model = model_class.from_pretrained(model_name, num_labels=3 if not is_bc else 2)
    model.eval()
    return tokenizer, model

# Set up page configuration
st.set_page_config(page_title="SemViQA Demo", layout="wide")

# Custom CSS: fixed header and tabs, dynamic height, result box formatting
st.markdown(
    """
    <style>
    html, body {
        height: 100%;
        margin: 0;
        overflow: hidden;
    }
    .main-container {
        height: calc(100vh - 55px); /* Browser height - 55px */
        overflow-y: auto;
        padding: 20px;
    }
    .big-title {
        font-size: 36px !important;
        font-weight: bold;
        color: #4A90E2;
        text-align: center;
        margin-top: 20px;
        position: sticky; /* Pin the header */
        top: 0;
        background-color: white; /* Ensure the header covers content when scrolling */
        z-index: 100; /* Ensure it's above other content */
    }
    .sub-title {
        font-size: 20px;
        color: #666;
        text-align: center;
        margin-bottom: 20px;
    }
    .stButton>button {
        background-color: #4CAF50;
        color: white;
        font-size: 16px;
        width: 100%;
        border-radius: 8px;
        padding: 10px;
    }
    .stTextArea textarea {
        font-size: 16px;
        min-height: 120px;
    }
    .result-box {
        background-color: #f9f9f9;
        padding: 20px;
        border-radius: 10px;
        box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
        margin-top: 20px;
    }
    .verdict {
        font-size: 24px;
        font-weight: bold;
        margin: 0;
        display: flex;
        align-items: center;
    }
    .verdict-icon {
        margin-right: 10px;
    }
    /* Fix the tabs at the top */
    div[data-baseweb="tab-list"] {
        position: sticky;
        top: 55px; /* Height of the header */
        background-color: white;
        z-index: 99;
    }
    /* Fix the sidebar content */
    .stSidebar .sidebar-content {
        background-color: #f0f2f6;
        padding: 20px;
        border-radius: 10px;
        position: sticky;
        top: 55px; /* Height of the header */
        height: calc(100vh - 75px); /* Adjust height to fit within the viewport */
        overflow-y: auto; /* Enable scrolling within the sidebar if content is too long */
    }
    .stSidebar .st-expander {
        background-color: #ffffff;
        border-radius: 10px;
        padding: 10px;
        margin-bottom: 10px;
    }
    .stSidebar .stSlider {
        margin-bottom: 20px;
    }
    .stSidebar .stSelectbox {
        margin-bottom: 20px;
    }
    .stSidebar .stCheckbox {
        margin-bottom: 20px;
    }
    </style>
    """,
    unsafe_allow_html=True,
)

# Container for the whole content with dynamic height
with st.container():
    st.markdown("<p class='big-title'>SemViQA: A Semantic Question Answering System for Vietnamese Information Fact-Checking</p>", unsafe_allow_html=True)
    st.markdown("""
        <div style="text-align: center; margin-bottom: 20px;">
            <p>
                <a href="https://github.com/DAVID-NGUYEN-S16">Nam V. Nguyen</a>*, 
                <a href="https://github.com/xndien2004">Dien X. Tran</a>*, 
                Thanh T. Tran, 
                Anh T. Hoang, 
                Tai V. Duong, 
                Di T. Le, 
                Phuc-Lu Le
            </p> 
        </div>
    """, unsafe_allow_html=True)
    # st.markdown("<p class='sub-title'>Enter the claim and context to verify its accuracy</p>", unsafe_allow_html=True)

    # Sidebar: Global Settings
    with st.sidebar.expander("⚙️ Settings", expanded=True):
        tfidf_threshold = st.slider("TF-IDF Threshold", 0.0, 1.0, 0.5, 0.01)
        length_ratio_threshold = st.slider("Length Ratio Threshold", 0.1, 1.0, 0.5, 0.01)
        qatc_model_name = st.selectbox("QATC Model", [
            "SemViQA/qatc-infoxlm-viwikifc",
            "SemViQA/qatc-infoxlm-isedsc01",
            "SemViQA/qatc-vimrc-viwikifc",
            "SemViQA/qatc-vimrc-isedsc01"
        ])
        bc_model_name = st.selectbox("Binary Classification Model", [
            "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("3-Class Classification Model", [
            "SemViQA/tc-xlmr-viwikifc",
            "SemViQA/tc-xlmr-isedsc01",
            "SemViQA/tc-infoxlm-viwikifc",
            "SemViQA/tc-infoxlm-isedsc01",
            "SemViQA/tc-erniem-viwikifc",
            "SemViQA/tc-erniem-isedsc01"
        ])
        show_details = st.checkbox("Show Probability Details", value=False)

    # Store verification history
    if 'history' not in st.session_state:
        st.session_state.history = []
    if 'latest_result' not in st.session_state:
        st.session_state.latest_result = None

    # Load the selected models
    tokenizer_qatc, model_qatc = load_model(qatc_model_name, QATCForQuestionAnswering)
    tokenizer_bc, model_bc = load_model(bc_model_name, ClaimModelForClassification, is_bc=True)
    tokenizer_tc, model_tc = load_model(tc_model_name, ClaimModelForClassification)

    # Icons for results
    verdict_icons = {
        "SUPPORTED": "✅",
        "REFUTED": "❌",
        "NEI": "⚠️"
    }

    # Tabs: Verify, History, About
    tabs = st.tabs(["Verify", "History", "About"])

    # --- Tab Verify ---
    with tabs[0]:
        st.subheader("Verify a Claim")
        # 2-column layout: input on the left, results on the right
        col_input, col_result = st.columns([2, 1])

        with col_input:
            claim = st.text_area("Enter Claim", "Chiến tranh với Campuchia đã kết thúc trước khi Việt Nam thống nhất.")
            context = st.text_area("Enter Context", "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ự.")
            verify_button = st.button("Verify", key="verify_button")

        with col_result:
            st.markdown("<h3>Verification Result</h3>", unsafe_allow_html=True)
            if verify_button:
                # Placeholder for displaying result/loading
                with st.spinner("Verifying..."): 
                    start_time = time.time() 

                    with torch.no_grad():
                        # Extract evidence
                        evidence_start_time = time.time()
                        evidence = extract_evidence_tfidf_qatc(
                            claim, context, model_qatc, tokenizer_qatc,
                            "cuda" if torch.cuda.is_available() else "cpu",
                            confidence_threshold=tfidf_threshold,
                            length_ratio_threshold=length_ratio_threshold
                        )
                        evidence_time = time.time() - evidence_start_time

                        # Classify the claim
                        verdict_start_time = time.time()
                        verdict = "NEI"
                        details = ""
                        prob3class, pred_tc = classify_claim(
                            claim, evidence, model_tc, tokenizer_tc,
                            "cuda" if torch.cuda.is_available() else "cpu"
                        )
                        if pred_tc != 0:
                            prob2class, pred_bc = classify_claim(
                                claim, evidence, model_bc, tokenizer_bc,
                                "cuda" if torch.cuda.is_available() else "cpu"
                            )
                            if pred_bc == 0:
                                verdict = "SUPPORTED"
                            elif prob2class > prob3class:
                                verdict = "REFUTED"
                            else:
                                verdict = ["NEI", "SUPPORTED", "REFUTED"][pred_tc]
                            if show_details:
                                details = f"""
                                    <p><strong>3-Class Probability:</strong> {prob3class.item():.2f}</p>
                                    <p><strong>3-Class Predicted Label:</strong> {['NEI', 'SUPPORTED', 'REFUTED'][pred_tc]}</p>
                                    <p><strong>2-Class Probability:</strong> {prob2class.item():.2f}</p>
                                    <p><strong>2-Class Predicted Label:</strong> {['SUPPORTED', 'REFUTED'][pred_bc]}</p>
                                """
                        verdict_time = time.time() - verdict_start_time

                        # Store verification history and the latest result
                        st.session_state.history.append({
                            "claim": claim,
                            "evidence": evidence,
                            "verdict": verdict,
                            "evidence_time": evidence_time,
                            "verdict_time": verdict_time,
                            "details": details
                        })
                        st.session_state.latest_result = {
                            "claim": claim,
                            "evidence": evidence,
                            "verdict": verdict,
                            "evidence_time": evidence_time,
                            "verdict_time": verdict_time,
                            "details": details
                        }

                        if torch.cuda.is_available():
                            torch.cuda.empty_cache()

                    # Display the result after verification
                    res = st.session_state.latest_result
                    st.markdown(f"""
                        <div class='result-box'>
                            <p><strong>Claim:</strong> {res['claim']}</p>
                            <p><strong>Evidence:</strong> {res['evidence']}</p>
                            <p class='verdict'><span class='verdict-icon'>{verdict_icons.get(res['verdict'], '')}</span>{res['verdict']}</p>
                            <p><strong>Evidence Inference Time:</strong> {res['evidence_time']:.2f} seconds</p>
                            <p><strong>Verdict Inference Time:</strong> {res['verdict_time']:.2f} seconds</p>
                            {res['details']}
                        </div>
                    """, unsafe_allow_html=True)
                    # Download Verification Result Feature
                    result_text = f"Claim: {res['claim']}\nEvidence: {res['evidence']}\nVerdict: {res['verdict']}\nDetails: {res['details']}"
                    st.download_button("Download Result", data=result_text, file_name="verification_result.txt", mime="text/plain")
            else:
                st.info("No verification result yet.")

    # --- Tab History ---
    with tabs[1]:
        st.subheader("Verification History")
        if st.session_state.history:
            # Convert history to DataFrame for easy download
            history_df = pd.DataFrame(st.session_state.history)
            st.download_button(
                label="Download Full History",
                data=history_df.to_csv(index=False).encode('utf-8'),
                file_name="verification_history.csv",
                mime="text/csv",
            )
            for idx, record in enumerate(reversed(st.session_state.history), 1):
                st.markdown(f"**{idx}. Claim:** {record['claim']}  \n**Result:** {verdict_icons.get(record['verdict'], '')} {record['verdict']}")
        else:
            st.write("No verification history yet.")

    # --- Tab About ---
    with tabs[2]:
        st.subheader("About")
        about_content = '''
<p align="center">
  <img alt="SemViQA Logo" src="https://raw.githubusercontent.com/DAVID-NGUYEN-S16/SemViQA/main/image/logo.png" height="200" /> 
    <br>
  </p>
</p>
  
<p align="center">
  <a href="https://arxiv.org/abs/2503.00955">
    <img src="https://img.shields.io/badge/arXiv-2411.00918-red?style=flat&label=arXiv">
  </a>
  <a href="https://huggingface.co/SemViQA">
    <img src="https://img.shields.io/badge/Hugging%20Face-Model-yellow?style=flat">
  </a>
  <a href="https://pypi.org/project/SemViQA">
    <img src="https://img.shields.io/pypi/v/SemViQA?color=blue&label=PyPI">
  </a>
  <a href="https://github.com/DAVID-NGUYEN-S16/SemViQA">
    <img src="https://img.shields.io/github/stars/DAVID-NGUYEN-S16/SemViQA?style=social">
  </a>
</p>


<p align="center">
    <a href="#-about">📌 About</a> •
    <a href="#-checkpoints">🔍 Checkpoints</a> •
    <a href="#-quick-start">🚀 Quick Start</a> •
    <a href="#-training">🏋️‍♂️ Training</a> •
    <a href="#-evaluation">📊 Evaluation</a> •
    <a href="#-citation">📖 Citation</a>
</p>  

---

## 📌 **About**  

Misinformation is a growing problem, exacerbated by the increasing use of **Large Language Models (LLMs)** like GPT and Gemini. This issue is even more critical for **low-resource languages like Vietnamese**, where existing fact-checking methods struggle with **semantic ambiguity, homonyms, and complex linguistic structures**.  

To address these challenges, we introduce **SemViQA**, a novel **Vietnamese fact-checking framework** integrating:  

- **Semantic-based Evidence Retrieval (SER)**: Combines **TF-IDF** with a **Question Answering Token Classifier (QATC)** to enhance retrieval precision while reducing inference time.  
- **Two-step Verdict Classification (TVC)**: Uses hierarchical classification optimized with **Cross-Entropy and Focal Loss**, improving claim verification across three categories:  
  - **Supported** ✅  
  - **Refuted** ❌  
  - **Not Enough Information (NEI)** 🤷‍♂️  

### **🏆 Achievements**
- **1st place** in the **UIT Data Science Challenge** 🏅  
- **State-of-the-art** performance on:  
  - **ISE-DSC01** → **78.97% strict accuracy**  
  - **ViWikiFC** → **80.82% strict accuracy**  
- **SemViQA Faster**: **7x speed improvement** over the standard model 🚀  

These results establish **SemViQA** as a **benchmark for Vietnamese fact verification**, advancing efforts to combat misinformation and ensure **information integrity**.  

---
## 🔍 Checkpoints
We are making our **SemViQA** experiment checkpoints publicly available to support the **Vietnamese fact-checking research community**. By sharing these models, we aim to:  

- **Facilitate reproducibility**: Allow researchers and developers to validate and build upon our results.  
- **Save computational resources**: Enable fine-tuning or transfer learning on top of **pre-trained and fine-tuned models** instead of training from scratch.  
- **Encourage further improvements**: Provide a strong baseline for future advancements in **Vietnamese misinformation detection**.  
 

<table>
  <tr>
    <th>Method</th>
    <th>Model</th>
    <th>ViWikiFC</th>
    <th>ISE-DSC01</th>
  </tr>
  <tr>
    <td rowspan="3"><strong>TC</strong></td>
    <td>InfoXLM<sub>large</sub></td>
    <td><a href="https://huggingface.co/SemViQA/tc-infoxlm-viwikifc">Link</a></td>
    <td><a href="https://huggingface.co/SemViQA/tc-infoxlm-isedsc01">Link</a></td>
  </tr>
  <tr>
    <td>XLM-R<sub>large</sub></td>
    <td><a href="https://huggingface.co/SemViQA/tc-xlmr-viwikifc">Link</a></td>
    <td><a href="https://huggingface.co/SemViQA/tc-xlmr-isedsc01">Link</a></td>
  </tr>
  <tr>
    <td>Ernie-M<sub>large</sub></td>
    <td><a href="https://huggingface.co/SemViQA/tc-erniem-viwikifc">Link</a></td>
    <td><a href="https://huggingface.co/SemViQA/tc-erniem-isedsc01">Link</a></td> 
  </tr>
  <tr>
    <td rowspan="3"><strong>BC</strong></td>
    <td>InfoXLM<sub>large</sub></td>
    <td><a href="https://huggingface.co/SemViQA/bc-infoxlm-viwikifc">Link</a></td>
    <td><a href="https://huggingface.co/SemViQA/bc-infoxlm-isedsc01">Link</a></td>
  </tr>
  <tr>
    <td>XLM-R<sub>large</sub></td>
    <td><a href="https://huggingface.co/SemViQA/bc-xlmr-viwikifc">Link</a></td>
    <td><a href="https://huggingface.co/SemViQA/bc-xlmr-isedsc01">Link</a></td>
  </tr>
  <tr>
    <td>Ernie-M<sub>large</sub></td>
    <td><a href="https://huggingface.co/SemViQA/bc-erniem-viwikifc">Link</a></td>
    <td><a href="https://huggingface.co/SemViQA/bc-erniem-isedsc01">Link</a></td>
  </tr>
  <tr>
    <td rowspan="2"><strong>QATC</strong></td>
    <td>InfoXLM<sub>large</sub></td>
    <td><a href="https://huggingface.co/SemViQA/qatc-infoxlm-viwikifc">Link</a></td>
    <td><a href="https://huggingface.co/SemViQA/qatc-infoxlm-isedsc01">Link</a></td>
  </tr>
  <tr>
    <td>ViMRC<sub>large</sub></td>
    <td><a href="https://huggingface.co/SemViQA/qatc-vimrc-viwikifc">Link</a></td>
    <td><a href="https://huggingface.co/SemViQA/qatc-vimrc-isedsc01">Link</a></td>
  </tr>
  <tr>
    <td rowspan="2"><strong>QA origin</strong></td>
    <td>InfoXLM<sub>large</sub></td>
    <td><a href="https://huggingface.co/SemViQA/infoxlm-large-viwikifc">Link</a></td>
    <td><a href="https://huggingface.co/SemViQA/infoxlm-large-isedsc01">Link</a></td>
  </tr>
  <tr>
    <td>ViMRC<sub>large</sub></td>
    <td><a href="https://huggingface.co/SemViQA/vi-mrc-large-viwikifc">Link</a></td>
    <td><a href="https://huggingface.co/SemViQA/vi-mrc-large-isedsc01">Link</a></td>
  </tr>
</table>

 

---

## 🚀 **Quick Start**  

### 📥 **Installation**  

#### **1️⃣ Clone this repository**  
```bash
git clone https://github.com/DAVID-NGUYEN-S16/SemViQA.git
cd SemViQA
```

#### **2️⃣ Set up Python environment**  
We recommend using **Python 3.11** in a virtual environment (`venv`) or **Anaconda**.  

**Using `venv`:**  
```bash
python -m venv semviqa_env
source semviqa_env/bin/activate  # On MacOS/Linux
semviqa_env\Scripts\activate      # On Windows
```

**Using `Anaconda`:**  
```bash
conda create -n semviqa_env python=3.11 -y
conda activate semviqa_env
```

#### **3️⃣ Install dependencies**  
```bash
pip install --upgrade pip
pip install transformers==4.42.3
pip install torch==2.3.0 torchvision==0.18.0 torchaudio==2.3.0 --index-url https://download.pytorch.org/whl/cu118
pip install -r requirements.txt
```
---

## 🏋️‍♂️ **Training**  

Train different components of **SemViQA** using the provided scripts:  

### **1️⃣ Three-Class Classification Training**  
Train a three-class claim classification model using the following command:
```bash
bash scripts/tc.sh
```
If you want to fine-tune the model using pre-trained weights, you can initialize it as follows:
```python
# Install semviqa
!pip install semviqa

# Initalize a pipeline
from transformers import AutoTokenizer
from semviqa.tvc.model import ClaimModelForClassification

tokenizer = AutoTokenizer.from_pretrained("SemViQA/tc-infoxlm-viwikifc")
model = ClaimModelForClassification.from_pretrained("SemViQA/tc-infoxlm-viwikifc", num_labels=3)
```

### **2️⃣ Binary Classification Training**  
Train a binary classification model using the command below:
```bash
bash scripts/bc.sh
```
To fine-tune the model with existing weights, use the following setup:
```python
# Install semviqa
!pip install semviqa

# Initalize a pipeline
from transformers import AutoTokenizer
from semviqa.tvc.model import ClaimModelForClassification

tokenizer = AutoTokenizer.from_pretrained("SemViQA/bc-infoxlm-viwikifc")
model = ClaimModelForClassification.from_pretrained("SemViQA/bc-infoxlm-viwikifc", num_labels=2)
```

### **3️⃣ QATC Model Training**  
Train the Question Answering Token Classifier (QATC) model using the following command:
```bash
bash scripts/qatc.sh
```

To continue training from pre-trained weights, use this setup:
```python
# Install semviqa
!pip install semviqa

# Initalize a pipeline
from transformers import AutoTokenizer
from semviqa.ser.qatc_model import QATCForQuestionAnswering

tokenizer = AutoTokenizer.from_pretrained("SemViQA/qatc-infoxlm-viwikifc")
model = QATCForQuestionAnswering.from_pretrained("SemViQA/qatc-infoxlm-viwikifc")
```

---

## 📊 **Evaluation**

### **1️⃣ Semantic-based Evidence Retrieval**
This module extracts the most relevant evidence from a given context based on a claim. It leverages TF-IDF combined with the QATC model to ensure accurate retrieval.
```python
# Install semviqa package
!pip install semviqa

# Import the ser module
import torch
from transformers import AutoTokenizer
from semviqa.ser.qatc_model import QATCForQuestionAnswering
from semviqa.ser.ser_eval import extract_evidence_tfidf_qatc

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

tokenizer = AutoTokenizer.from_pretrained("SemViQA/qatc-infoxlm-viwikifc")
model = QATCForQuestionAnswering.from_pretrained("SemViQA/qatc-infoxlm-viwikifc")

claim = "Chiến tranh với Campuchia đã kết thúc trước khi Việt Nam thống nhất."
context = "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ự."

evidence = extract_evidence_tfidf_qatc(
    claim, context, model, tokenizer, device, confidence_threshold=0.5, length_ratio_threshold=0.6
)

print(evidence)
# evidence: 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
```


### **2️⃣ Two-step Verdict Classification**
This module performs claim classification using a **two-step approach**:
1. **Three-class classification**: Determines if a claim is **Supported, Refuted, or Not Enough Information (NEI)**.
2. **Binary classification** (if necessary): Further verifies if the claim is **Supported** or **Refuted**.
```python
# Install semviqa package
!pip install semviqa

# Import the tvc module
import torch
from semviqa.tvc.tvc_eval import classify_claim
from semviqa.tvc.model import ClaimModelForClassification

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

tokenizer = AutoTokenizer.from_pretrained("SemViQA/tc-infoxlm-viwikifc")
model_tc = ClaimModelForClassification.from_pretrained("SemViQA/tc-infoxlm-viwikifc", num_labels=3).to(device)
model_bc = ClaimModelForClassification.from_pretrained("SemViQA/bc-infoxlm-viwikifc", num_labels=2).to(device)

claim = "Chiến tranh với Campuchia đã kết thúc trước khi Việt Nam thống nhất."
evidence = "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."

verdict = "NEI"
prob_tc, pred_tc = classify_claim(claim, evidence, model_tc, tokenizer, device)

if pred_tc != 0:
  prob_bc, pred_bc = classify_claim(claim, evidence, model_bc, tokenizer, device)
  verdict = "SUPPORTED" if pred_bc == 0 else "REFUTED" if prob_bc > prob_tc else ["NEI", "SUPPORTED", "REFUTED"][pred_tc]

print(verdict)
# Output: REFUTED
```

### **3️⃣ Full Pipeline Evaluation**
Use the trained models to **predict test data**:  
```bash
bash scripts/pipeline.sh
```

Alternatively, you can use **SemViQA** programmatically:

```python
# Install semviqa package
!pip install semviqa

# Import the pipeline
from semviqa.pipeline import SemViQAPipeline
claim = "Chiến tranh với Campuchia đã kết thúc trước khi Việt Nam thống nhất."
context = "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ự."
 
semviqa = SemViQAPipeline(
  model_evidence_QA="SemViQA/qatc-infoxlm-viwikifc", 
  model_bc="SemViQA/bc-infoxlm-viwikifc", 
  model_tc="SemViQA/tc-infoxlm-viwikifc", 
  thres_evidence=0.5,
  length_ratio_threshold=0.5,
  is_qatc_faster=False
  )
 
result = semviqa.predict(claim, context)
print(result)
# Output: {'verdict': 'REFUTED', 'evidence': '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'}

# Extract only evidence
evidence_only = semviqa.predict(claim, context, return_evidence_only=True)
print(evidence_only)
# Output: {'evidence': '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'}
```

## **Acknowledgment**  
Our development is based on our previous works:  
- [Check-Fact-Question-Answering-System](https://github.com/DAVID-NGUYEN-S16/Check-Fact-Question-Answering-System)  
- [Extract-Evidence-Question-Answering](https://github.com/DAVID-NGUYEN-S16/Extract-evidence-question-answering)  

**SemViQA** is the final version we have developed for verifying fact-checking in Vietnamese, achieving state-of-the-art (SOTA) performance compared to any other system for Vietnamese.

## 📖 **Citation**  

If you use **SemViQA** in your research, please cite our work:  

```bibtex
@misc{nguyen2025semviqasemanticquestionanswering,
      title={SemViQA: A Semantic Question Answering System for Vietnamese Information Fact-Checking}, 
      author={Nam V. Nguyen and Dien X. Tran and Thanh T. Tran and Anh T. Hoang and Tai V. Duong and Di T. Le and Phuc-Lu Le},
      year={2025},
      eprint={2503.00955},
      archivePrefix={arXiv},
      primaryClass={cs.CL},
      url={https://arxiv.org/abs/2503.00955}, 
}
```  

'''
    
        st.markdown(about_content, unsafe_allow_html=True)