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(""" """, unsafe_allow_html=True) # Main header with updated design st.markdown("""
SemViQA
Hệ thống Kiểm chứng Thông tin Tiếng Việt
""", unsafe_allow_html=True) # Sidebar with updated design with st.sidebar: st.markdown("""

⚙️ Cài đặt Hệ thống

""", 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"""

Kết quả Kiểm chứng

Câu khẳng định: {res['claim']}

Bằng chứng: {res['evidence']}

{verdict_icons.get(res['verdict'], '')} {res['verdict']}

Thời gian trích xuất bằng chứng: {res['evidence_time']:.2f} giây

Thời gian phân loại: {res['verdict_time']:.2f} giây

Tổng thời gian: {res['total_time']:.2f} giây

{f"
{res['details']}
" if show_details else ""}
""", 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"""

Kiểm chứng #{idx}

Câu khẳng định: {record['claim']}

Kết luận: {verdict_icons.get(record['verdict'], '')} {record['verdict']}

Thời gian: {record['total_time']:.2f} giây

""", 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("""

ℹ️ Thông tin về SemViQA

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.

🔍 Cách sử dụng

  1. Nhập câu khẳng định cần kiểm chứng
  2. Nhập ngữ cảnh hoặc văn bản tham khảo
  3. Điều chỉnh các tham số trong phần Cài đặt nếu cần
  4. Nhấn nút Kiểm chứng

⚙️ Các tham số

📊 Kết quả

🆕 Tính năng Mới

""", unsafe_allow_html=True)