import gradio as gr from googleapiclient.discovery import build import google.generativeai as genai import torch from transformers import AutoTokenizer, AutoModelForSequenceClassification import re import os import numpy as np import json import sqlite3 from datetime import datetime import hashlib import io import os from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload, MediaIoBaseUpload GOOGLE_API_KEY = "AIzaSyASwqVh3ELFVKH-W3WuHtmjg3XgtwjJQKg" SEARCH_ENGINE_ID = "f34f8a4816771488b" GEMINI_API_KEY = "AIzaSyAHPzJ_VjTX3gZLBV28d3sq97SdER2qfkc" MODEL_PATH = "./vietnamese_fake_news_model" genai.configure(api_key=GEMINI_API_KEY) # Knowledge Base Configuration KNOWLEDGE_BASE_DB = "knowledge_base.db" CONFIDENCE_THRESHOLD = 0.95 # 95% Gemini confidence threshold for RAG knowledge base ENABLE_KNOWLEDGE_BASE_SEARCH = True # Enable knowledge base search with training data # Cloud Storage Configuration USE_CLOUD_STORAGE = True # Set to True to use cloud storage instead of local DB CLOUD_STORAGE_TYPE = "google_drive" # Options: "google_drive", "google_cloud", "local" GOOGLE_DRIVE_FILE_ID = None # Will be set when file is created # Load Google Drive file ID if it exists try: if os.path.exists('google_drive_file_id.txt'): with open('google_drive_file_id.txt', 'r') as f: GOOGLE_DRIVE_FILE_ID = f.read().strip() print(f"📁 Loaded Google Drive file ID: {GOOGLE_DRIVE_FILE_ID}") except Exception as e: print(f"Could not load Google Drive file ID: {e}") GOOGLE_CLOUD_BUCKET = "your-bucket-name" # For Google Cloud Storage print("Loading the DistilBERT model we trained...") try: if os.path.exists(MODEL_PATH): tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH) model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH) print("DistilBERT model loaded successfully!") else: print(f"Model directory '{MODEL_PATH}' not found!") print("Our custom model isn't available, trying a backup model...") try: tokenizer = AutoTokenizer.from_pretrained("distilbert-base-multilingual-cased") model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-multilingual-cased", num_labels=2) print("Fallback DistilBERT model loaded successfully!") except Exception as fallback_error: print(f"Fallback model also failed: {fallback_error}") tokenizer = None model = None except Exception as e: print(f"Error loading DistilBERT model: {e}") print("Something went wrong, trying the backup model...") try: tokenizer = AutoTokenizer.from_pretrained("distilbert-base-multilingual-cased") model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-multilingual-cased", num_labels=2) print("Fallback DistilBERT model loaded successfully!") except Exception as fallback_error: print(f"Fallback model also failed: {fallback_error}") tokenizer = None model = None # --- CLOUD STORAGE FUNCTIONS --- def get_google_drive_service(): """Get authenticated Google Drive service for Hugging Face Spaces""" try: SCOPES = ['https://www.googleapis.com/auth/drive.file'] creds = None # Check if running on Hugging Face Spaces import os is_hf_space = os.getenv('SPACE_ID') is not None if is_hf_space: # For Hugging Face Spaces, use environment variables client_id = os.getenv('GOOGLE_CLIENT_ID') client_secret = os.getenv('GOOGLE_CLIENT_SECRET') refresh_token = os.getenv('GOOGLE_REFRESH_TOKEN') if client_id and client_secret and refresh_token: creds = Credentials.from_authorized_user_info({ 'client_id': client_id, 'client_secret': client_secret, 'refresh_token': refresh_token, 'token_uri': 'https://oauth2.googleapis.com/token' }, SCOPES) else: print("⚠️ Google Drive credentials not found in Hugging Face secrets") return None else: # For local development, use files if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If no valid credentials, request authorization if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: if os.path.exists('credentials.json'): flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) else: print("⚠️ credentials.json not found for local development") return None # Save credentials for next run with open('token.json', 'w') as token: token.write(creds.to_json()) return build('drive', 'v3', credentials=creds) except Exception as e: print(f"Error setting up Google Drive: {e}") return None def upload_to_google_drive(data, filename="knowledge_base.json"): """Upload knowledge base data to Google Drive""" try: service = get_google_drive_service() if not service: return None # Convert data to JSON json_data = json.dumps(data, ensure_ascii=False, indent=2) file_metadata = { 'name': filename, 'parents': [] # Root folder } media = MediaIoBaseUpload( io.BytesIO(json_data.encode('utf-8')), mimetype='application/json' ) file = service.files().create( body=file_metadata, media_body=media, fields='id' ).execute() print(f"✅ Uploaded {filename} to Google Drive (ID: {file.get('id')})") return file.get('id') except Exception as e: print(f"Error uploading to Google Drive: {e}") return None def download_from_google_drive(file_id): """Download knowledge base data from Google Drive""" try: service = get_google_drive_service() if not service: return [] request = service.files().get_media(fileId=file_id) file_content = io.BytesIO() downloader = MediaIoBaseDownload(file_content, request) done = False while done is False: status, done = downloader.next_chunk() file_content.seek(0) data = json.loads(file_content.read().decode('utf-8')) print(f"✅ Downloaded knowledge base from Google Drive") return data except Exception as e: print(f"Error downloading from Google Drive: {e}") return [] def save_knowledge_base_cloud(data): """Save knowledge base to cloud storage""" if CLOUD_STORAGE_TYPE == "google_drive": file_id = upload_to_google_drive(data) if file_id: global GOOGLE_DRIVE_FILE_ID GOOGLE_DRIVE_FILE_ID = file_id return file_id is not None elif CLOUD_STORAGE_TYPE == "google_cloud": # TODO: Implement Google Cloud Storage print("Google Cloud Storage not implemented yet") return False return False def load_knowledge_base_cloud(): """Load knowledge base from cloud storage""" if CLOUD_STORAGE_TYPE == "google_drive" and GOOGLE_DRIVE_FILE_ID: return download_from_google_drive(GOOGLE_DRIVE_FILE_ID) elif CLOUD_STORAGE_TYPE == "google_cloud": # TODO: Implement Google Cloud Storage print("Google Cloud Storage not implemented yet") return [] return [] # --- KNOWLEDGE BASE MANAGEMENT --- def init_knowledge_base(): """Initialize the SQLite knowledge base""" conn = sqlite3.connect(KNOWLEDGE_BASE_DB) cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS knowledge_entries ( id INTEGER PRIMARY KEY AUTOINCREMENT, content_hash TEXT UNIQUE, news_text TEXT, prediction TEXT, confidence REAL, search_results TEXT, gemini_analysis TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, last_accessed TIMESTAMP DEFAULT CURRENT_TIMESTAMP, access_count INTEGER DEFAULT 1 ) ''') conn.commit() conn.close() print("Knowledge base initialized successfully!") def add_to_knowledge_base(news_text, prediction, confidence, search_results, gemini_analysis): """Add high-confidence result to knowledge base""" try: # Create content hash for deduplication content_hash = hashlib.md5(news_text.encode('utf-8')).hexdigest() if USE_CLOUD_STORAGE: # Add to cloud storage data = load_knowledge_base_cloud() # Check if entry already exists for entry in data: if entry.get('content_hash') == content_hash: print(f"Entry already exists in cloud knowledge base (hash: {content_hash[:8]}...)") return False # Create new entry new_entry = { 'content_hash': content_hash, 'news_text': news_text, 'prediction': prediction, 'confidence': confidence, 'search_results': search_results, 'gemini_analysis': gemini_analysis, 'created_at': datetime.now().isoformat(), 'last_accessed': datetime.now().isoformat(), 'access_count': 1 } # Add to data and save to cloud data.append(new_entry) success = save_knowledge_base_cloud(data) if success: print(f"✅ Added high-confidence result to cloud knowledge base (confidence: {confidence:.1%})") print(f" Hash: {content_hash[:8]}...") print(f" Prediction: {prediction}") return True else: return False else: # Add to local SQLite database conn = sqlite3.connect(KNOWLEDGE_BASE_DB) cursor = conn.cursor() # Check if entry already exists cursor.execute('SELECT id FROM knowledge_entries WHERE content_hash = ?', (content_hash,)) if cursor.fetchone(): print(f"Entry already exists in knowledge base (hash: {content_hash[:8]}...)") conn.close() return False # Insert new entry cursor.execute(''' INSERT INTO knowledge_entries (content_hash, news_text, prediction, confidence, search_results, gemini_analysis) VALUES (?, ?, ?, ?, ?, ?) ''', ( content_hash, news_text, prediction, confidence, json.dumps(search_results, ensure_ascii=False), gemini_analysis )) conn.commit() conn.close() print(f"✅ Added high-confidence result to knowledge base (confidence: {confidence:.1%})") print(f" Hash: {content_hash[:8]}...") print(f" Prediction: {prediction}") return True except Exception as e: print(f"Error adding to knowledge base: {e}") return False def search_knowledge_base(query_text, limit=5): """Search the knowledge base for similar entries""" try: if USE_CLOUD_STORAGE: # Search in cloud storage data = load_knowledge_base_cloud() if not data: return [] # Simple text similarity search in JSON data results = [] query_lower = query_text[:50].lower() for entry in data: if (query_lower in entry.get('news_text', '').lower() or query_lower in entry.get('gemini_analysis', '').lower()): results.append(( entry['news_text'], entry['prediction'], entry['confidence'], entry.get('search_results', []), entry.get('gemini_analysis', ''), entry.get('created_at', ''), entry.get('access_count', 1) )) # Sort by confidence and access count results.sort(key=lambda x: (x[2], x[6]), reverse=True) results = results[:limit] if results: print(f"📚 Found {len(results)} similar entries in cloud knowledge base") return results else: return [] else: # Search in local SQLite database conn = sqlite3.connect(KNOWLEDGE_BASE_DB) cursor = conn.cursor() # Simple text similarity search (you can enhance this with embeddings later) cursor.execute(''' SELECT news_text, prediction, confidence, search_results, gemini_analysis, created_at, access_count FROM knowledge_entries WHERE news_text LIKE ? OR gemini_analysis LIKE ? ORDER BY confidence DESC, access_count DESC LIMIT ? ''', (f'%{query_text[:50]}%', f'%{query_text[:50]}%', limit)) results = cursor.fetchall() # Update access count and last_accessed for result in results: cursor.execute(''' UPDATE knowledge_entries SET access_count = access_count + 1, last_accessed = CURRENT_TIMESTAMP WHERE news_text = ? ''', (result[0],)) conn.commit() conn.close() if results: print(f"📚 Found {len(results)} similar entries in knowledge base") return results else: return [] except Exception as e: print(f"Error searching knowledge base: {e}") return [] def format_knowledge_for_rag(knowledge_results): """Format knowledge base results for RAG augmentation""" if not knowledge_results: return "" knowledge_summary = "\n=== KIẾN THỨC TƯƠNG TỰ TỪ CƠ SỞ DỮ LIỆU ===\n" for i, (news_text, prediction, confidence, search_results, gemini_analysis, created_at, access_count) in enumerate(knowledge_results, 1): knowledge_summary += f"\n{i}. Tin tức tương tự (Độ tin cậy: {confidence:.1%}, Lần truy cập: {access_count}):\n" knowledge_summary += f" Nội dung: {news_text[:200]}...\n" knowledge_summary += f" Kết luận: {prediction}\n" knowledge_summary += f" Thời gian: {created_at}\n" knowledge_summary += "\n==========================================\n" return knowledge_summary def get_knowledge_base_stats(): """Get statistics about the knowledge base""" try: conn = sqlite3.connect(KNOWLEDGE_BASE_DB) cursor = conn.cursor() # Get total entries cursor.execute('SELECT COUNT(*) FROM knowledge_entries') total_entries = cursor.fetchone()[0] # Get entries by prediction cursor.execute('SELECT prediction, COUNT(*) FROM knowledge_entries GROUP BY prediction') prediction_counts = dict(cursor.fetchall()) # Get average confidence cursor.execute('SELECT AVG(confidence) FROM knowledge_entries') avg_confidence = cursor.fetchone()[0] or 0 # Get most accessed entries cursor.execute('SELECT news_text, access_count FROM knowledge_entries ORDER BY access_count DESC LIMIT 3') top_accessed = cursor.fetchall() conn.close() return { 'total_entries': total_entries, 'prediction_counts': prediction_counts, 'avg_confidence': avg_confidence, 'top_accessed': top_accessed } except Exception as e: print(f"Error getting knowledge base stats: {e}") return None # Initialize knowledge base on startup init_knowledge_base() def populate_knowledge_base_from_training_data(): """Populate knowledge base with existing training data""" try: import pandas as pd # Load training data df = pd.read_csv('train_final.csv') print(f"📚 Loading {len(df)} training samples into knowledge base...") conn = sqlite3.connect(KNOWLEDGE_BASE_DB) cursor = conn.cursor() added_count = 0 skipped_count = 0 for index, row in df.iterrows(): news_text = str(row['content']) label = int(row['label']) prediction = "REAL" if label == 0 else "FAKE" # Create content hash for deduplication content_hash = hashlib.md5(news_text.encode('utf-8')).hexdigest() # Check if entry already exists cursor.execute('SELECT id FROM knowledge_entries WHERE content_hash = ?', (content_hash,)) if cursor.fetchone(): skipped_count += 1 continue # Create synthetic analysis for training data synthetic_analysis = f"""1. KẾT LUẬN: {prediction} 2. ĐỘ TIN CẬY: THẬT: {95 if prediction == 'REAL' else 5}% / GIẢ: {5 if prediction == 'REAL' else 95}% 3. PHÂN TÍCH CHI TIẾT: - Nội dung: {'Tin tức được xác minh từ nguồn đào tạo' if prediction == 'REAL' else 'Tin tức giả được xác định từ nguồn đào tạo'} - Nguồn tin: Dữ liệu huấn luyện đã được xác minh - Ngữ cảnh: Mẫu từ bộ dữ liệu huấn luyện DistilBERT - Ngôn ngữ: {'Ngôn ngữ khách quan, tin cậy' if prediction == 'REAL' else 'Ngôn ngữ có dấu hiệu tin giả'} - Thời gian: Dữ liệu huấn luyện đã được kiểm chứng 4. CÁC DẤU HIỆU CẢNH BÁO: {'Không có dấu hiệu cảnh báo' if prediction == 'REAL' else 'Tin tức được xác định là giả từ nguồn đào tạo'} 5. KHUYẾN NGHỊ CHO NGƯỜI ĐỌC: - Nguồn: Dữ liệu huấn luyện đã được xác minh - Độ tin cậy: Cao (từ bộ dữ liệu đào tạo) - Lưu ý: Mẫu từ tập huấn luyện DistilBERT""" # Insert training sample cursor.execute(''' INSERT INTO knowledge_entries (content_hash, news_text, prediction, confidence, search_results, gemini_analysis) VALUES (?, ?, ?, ?, ?, ?) ''', ( content_hash, news_text, prediction, 0.95, # High confidence for training data json.dumps([], ensure_ascii=False), # Empty search results for training data synthetic_analysis )) added_count += 1 # Show progress every 1000 entries if added_count % 1000 == 0: print(f" Added {added_count} entries...") conn.commit() conn.close() print(f"✅ Knowledge base populated successfully!") print(f" 📊 Added: {added_count} entries") print(f" ⏭️ Skipped: {skipped_count} duplicates") print(f" 🎯 Total entries: {added_count}") return True except Exception as e: print(f"❌ Error populating knowledge base: {e}") return False # Populate knowledge base with training data on startup print("🚀 Populating knowledge base with training data...") populate_knowledge_base_from_training_data() CREDIBLE_SOURCES = { 'vnexpress.net': 0.95, 'tuoitre.vn': 0.95, 'thanhnien.vn': 0.90, 'dantri.com.vn': 0.90, 'vietnamnet.vn': 0.85, 'zing.vn': 0.85, 'kenh14.vn': 0.80, 'soha.vn': 0.80, 'baotintuc.vn': 0.85, 'nhandan.vn': 0.90, 'laodong.vn': 0.85, 'congan.com.vn': 0.90, 'quochoi.vn': 0.95, 'chinhphu.vn': 0.95, 'moh.gov.vn': 0.90, 'mofa.gov.vn': 0.90, 'mard.gov.vn': 0.85, 'moc.gov.vn': 0.85, 'mof.gov.vn': 0.85, 'mst.gov.vn': 0.85, 'wikipedia.org': 0.95, 'bbc.com': 0.95, 'bbc.co.uk': 0.95, 'cnn.com': 0.90, 'reuters.com': 0.95, 'ap.org': 0.95, 'espn.com': 0.85, 'fifa.com': 0.95, 'nytimes.com': 0.90, 'washingtonpost.com': 0.90, 'theguardian.com': 0.90 } def clean_text(text): """Clean up the text before feeding it to our model""" if not isinstance(text, str): text = str(text) text = re.sub(r'\s+', ' ', text.strip()) if len(text) < 10: text = "Tin tức ngắn: " + text return text def predict_with_distilbert(text): """Run the text through our trained DistilBERT model to get a prediction""" if model is None or tokenizer is None: return None, None, None, None try: clean_text_input = clean_text(text) inputs = tokenizer( clean_text_input, return_tensors="pt", truncation=True, padding=True, max_length=512 ) with torch.no_grad(): outputs = model(**inputs) predictions = torch.nn.functional.softmax(outputs.logits, dim=-1) real_score = predictions[0][0].item() fake_score = predictions[0][1].item() if real_score > fake_score: prediction = "REAL" confidence = real_score else: prediction = "FAKE" confidence = fake_score return prediction, confidence, real_score, fake_score except Exception as e: print(f"DistilBERT prediction error: {e}") return None, None, None, None def process_search_results(items): search_results = [] for item in items: search_results.append({ 'title': item.get('title', ''), 'snippet': item.get('snippet', ''), 'link': item.get('link', '') }) return search_results def google_search_fallback(news_text): print("Google Search is unavailable - using enhanced content analysis") # Enhanced content analysis without external search fake_indicators = ['giả', 'sai', 'không đúng', 'bịa đặt', 'lừa đảo', 'fake news', 'tin đồn', 'nghi vấn'] real_indicators = ['chính thức', 'xác nhận', 'chính xác', 'đúng', 'verified', 'chính phủ', 'bộ y tế', 'cơ quan'] text_lower = news_text.lower() fake_count = sum(1 for word in fake_indicators if word in text_lower) real_count = sum(1 for word in real_indicators if word in text_lower) # Create more detailed analysis analysis_details = [] if fake_count > real_count: analysis_details.append("Nhiều từ khóa nghi ngờ được sử dụng") elif real_count > fake_count: analysis_details.append("Có từ khóa xác thực từ nguồn chính thức") # Check for other patterns if len(news_text) < 100: analysis_details.append("Tin tức quá ngắn, thiếu thông tin chi tiết") if '!' in news_text or '!!!' in news_text: analysis_details.append("Sử dụng dấu chấm than thái quá") snippet = f"Phân tích nội dung: {fake_count} từ nghi ngờ, {real_count} từ xác thực. " snippet += "; ".join(analysis_details) if analysis_details else "Không phát hiện dấu hiệu đặc biệt" return [{ 'title': 'Phân tích nội dung chi tiết (không có tìm kiếm Google)', 'snippet': snippet, 'link': 'content-analysis-only' }] def google_search(news_text): """Search Google for information about the news, with backup options if it fails""" try: service = build("customsearch", "v1", developerKey=GOOGLE_API_KEY) search_queries = [] if "Argentina" in news_text and "World Cup" in news_text: search_queries = [ "Argentina World Cup 2022 champion winner", "Argentina vô địch World Cup 2022", "World Cup 2022 Argentina final" ] elif "COVID" in news_text or "covid" in news_text: search_queries = [ "COVID-19 Vietnam news", "COVID Vietnam 2022 2023", "dịch COVID Việt Nam" ] else: vietnamese_words = re.findall(r'[À-ỹ]+', news_text) english_words = re.findall(r'[A-Za-z]+', news_text) numbers = re.findall(r'\d{4}', news_text) # Years if english_words: search_queries.append(' '.join(english_words[:5])) if vietnamese_words: search_queries.append(' '.join(vietnamese_words[:5])) if numbers: search_queries.append(' '.join(english_words[:3] + numbers)) keywords = re.findall(r'[A-Za-zÀ-ỹ]+|\b(?:19|20)\d{2}\b|\b\d{1,2}\b', news_text) search_queries.append(' '.join(keywords[:10])) for i, search_query in enumerate(search_queries): if not search_query.strip(): continue print(f"Strategy {i+1}: Searching for '{search_query}'") result = service.cse().list( q=search_query, cx=SEARCH_ENGINE_ID, num=10 # Restored to 10 for more comprehensive results ).execute() print(f"API Response keys: {list(result.keys())}") if 'searchInformation' in result: print(f"Total results: {result['searchInformation'].get('totalResults', 'Unknown')}") if 'items' in result and result['items']: print(f"Found {len(result['items'])} results with strategy {i+1}") return process_search_results(result['items']) else: print(f"No results with strategy {i+1}") print("All strategies failed, trying simple phrase search...") simple_query = news_text[:30] # First 30 characters result = service.cse().list( q=simple_query, cx=SEARCH_ENGINE_ID, num=10 ).execute() if 'items' in result and result['items']: print(f"Found {len(result['items'])} results with simple search") return process_search_results(result['items']) print("All search strategies failed, using fallback...") return google_search_fallback(news_text) except Exception as e: print(f"Google Search error: {e}") print(f"Error type: {type(e).__name__}") error_str = str(e).lower() if any(keyword in error_str for keyword in ["403", "blocked", "quota", "limit", "exceeded"]): print("Google Search API blocked/quota exceeded, using fallback...") elif "invalid" in error_str or "unauthorized" in error_str: print("API key issue, using fallback...") return google_search_fallback(news_text) def analyze_sources(search_results): """Check how trustworthy the news sources are""" if not search_results: return 0.50, 0.20, "No sources found", [] credible_count = 0 total_sources = len(search_results) found_sources = [] credible_sources_found = [] for result in search_results: domain = result['link'].split('/')[2] if '//' in result['link'] else '' found_sources.append(domain) # Check if this domain matches any credible source for source, credibility in CREDIBLE_SOURCES.items(): if source in domain: credible_count += 1 credible_sources_found.append(f"{source} ({credibility:.0%})") break source_credibility = credible_count / total_sources if total_sources > 0 else 0.50 popularity_score = min(1.0, total_sources / 5.0) # Normalize to 0-1 # Create a summary of what we found if source_credibility > 0.7: credibility_text = f"High credibility: {credible_count}/{total_sources} sources from reputable outlets" elif source_credibility > 0.4: credibility_text = f"Medium credibility: {credible_count}/{total_sources} sources from reputable outlets" else: credibility_text = f"Low credibility: {credible_count}/{total_sources} sources from reputable outlets" return source_credibility, popularity_score, credibility_text, found_sources, credible_sources_found def analyze_source_support(news_text, search_results): """Check if the search results agree or disagree with the news""" if not search_results: return 0.5, "No sources to analyze" support_count = 0 contradict_count = 0 total_sources = len(search_results) # Look for years mentioned in the news import re news_years = re.findall(r'\b(20\d{2})\b', news_text) news_year = news_years[0] if news_years else None for result in search_results: title_snippet = (result.get('title', '') + ' ' + result.get('snippet', '')).lower() # See if the years match up if news_year: source_years = re.findall(r'\b(20\d{2})\b', title_snippet) if source_years and news_year not in source_years: contradict_count += 1 continue # Look for words that suggest agreement or disagreement support_keywords = ['confirm', 'verify', 'true', 'accurate', 'correct', 'xác nhận', 'chính xác', 'đúng'] contradict_keywords = ['false', 'fake', 'incorrect', 'wrong', 'sai', 'giả', 'không đúng'] support_score = sum(1 for keyword in support_keywords if keyword in title_snippet) contradict_score = sum(1 for keyword in contradict_keywords if keyword in title_snippet) if contradict_score > support_score: contradict_count += 1 elif support_score > contradict_score: support_count += 1 else: # If unclear, assume slight support support_count += 0.5 support_ratio = support_count / total_sources if total_sources > 0 else 0.5 if support_ratio > 0.7: support_text = f"Sources strongly support the news: {support_count:.1f}/{total_sources} sources confirm" elif support_ratio > 0.4: support_text = f"Sources mixed: {support_count:.1f}/{total_sources} sources support, {contradict_count} contradict" else: support_text = f"Sources contradict the news: {contradict_count}/{total_sources} sources contradict" return support_ratio, support_text def analyze_with_gemini(news_text, search_results, distilbert_prediction, distilbert_confidence): """Use Gemini AI to analyze the news and compare with our model results""" try: # Knowledge base search with training data if ENABLE_KNOWLEDGE_BASE_SEARCH: print("🔍 Searching knowledge base for similar entries...") knowledge_results = search_knowledge_base(news_text, limit=2) # Reduced to 2 for speed knowledge_context = format_knowledge_for_rag(knowledge_results) else: knowledge_context = "" # Try to use the latest Gemini model available try: model = genai.GenerativeModel('gemini-2.0-flash-exp') except: try: model = genai.GenerativeModel('gemini-2.5-flash') except: try: model = genai.GenerativeModel('gemini-1.5-pro') except: model = genai.GenerativeModel('gemini-1.5-flash') # Format the search results for Gemini (limit to top 3 for speed) search_summary = "" if search_results: search_summary = "Kết quả tìm kiếm Google:\n" for i, result in enumerate(search_results[:3], 1): # Reduced from 5 to 3 search_summary += f"{i}. {result['title']}\n {result['snippet']}\n Nguồn: {result['link']}\n\n" else: search_summary = "Không tìm thấy kết quả tìm kiếm Google cho tin tức này. Điều này có thể do API bị giới hạn hoặc tin tức quá mới/chưa được đăng tải." # Note: We're not including DistilBERT results to keep Gemini analysis independent prompt = f""" Bạn là một chuyên gia phân tích tin tức chuyên nghiệp. Hãy phân tích chi tiết tin tức sau và đánh giá độ tin cậy của nó: "{news_text}" {search_summary} {knowledge_context} Hãy thực hiện phân tích toàn diện theo các tiêu chí sau: 1. Phân tích nội dung: Kiểm tra tính logic, mâu thuẫn, ngôn ngữ cảm xúc thái quá 2. Phân tích nguồn tin: Đánh giá uy tín và độ tin cậy của nguồn 3. Phân tích ngữ cảnh: So sánh với thông tin có sẵn và kiến thức thực tế 4. Phân tích ngôn ngữ: Tìm dấu hiệu của tin giả như từ ngữ gây sốc, cảm xúc 5. Phân tích thời gian: Kiểm tra tính hợp lý về mặt thời gian Trả lời theo định dạng sau (chỉ bằng tiếng Việt, viết chi tiết và chuyên nghiệp): 1. KẾT LUẬN: [THẬT/GIẢ/KHÔNG XÁC ĐỊNH] 2. ĐỘ TIN CẬY: [THẬT: X% / GIẢ: Y%] (Trong đó X% là độ tin cậy tin THẬT, Y% là độ tin cậy tin GIẢ, X+Y=100%) 3. PHÂN TÍCH CHI TIẾT: - Nội dung: [Phân tích chi tiết về nội dung tin tức] - Nguồn tin: [Đánh giá về nguồn và độ tin cậy] - Ngữ cảnh: [So sánh với thông tin có sẵn] - Ngôn ngữ: [Phân tích cách sử dụng từ ngữ] - Thời gian: [Kiểm tra tính hợp lý về mặt thời gian] 4. CÁC DẤU HIỆU CẢNH BÁO: [Liệt kê các dấu hiệu đáng ngờ nếu có] 5. KHUYẾN NGHỊ CHO NGƯỜI ĐỌC: - [Hướng dẫn cụ thể để kiểm chứng thông tin] - [Các nguồn tin đáng tin cậy để tham khảo] - [Cách phân biệt tin thật và tin giả] QUAN TRỌNG: Trong phần "ĐỘ TIN CẬY", hãy cung cấp tỷ lệ phần trăm chính xác dựa trên phân tích của bạn. Ví dụ: "THẬT: 95% / GIẢ: 5%" nghĩa là 95% tin tức này là THẬT, 5% là GIẢ. Viết chi tiết, chuyên nghiệp và hữu ích cho người đọc. """ print("Calling Gemini API...") print(f"DEBUG - News text being analyzed: {news_text}") print(f"DEBUG - Search results count: {len(search_results)}") if search_results: print(f"DEBUG - First search result title: {search_results[0].get('title', 'No title')}") # Use settings optimized for faster processing generation_config = genai.types.GenerationConfig( temperature=0.3, # Lower for more consistent results top_p=0.8, # Reduced for faster processing top_k=20, # Reduced for faster processing max_output_tokens=1000 # Reduced for faster responses ) response = model.generate_content(prompt, generation_config=generation_config) print("Gemini API response received successfully") return response.text except Exception as e: print(f"Gemini analysis error: {e}") print(f"Error type: {type(e).__name__}") # If we hit the API limit, provide a basic analysis if "429" in str(e) or "quota" in str(e).lower(): print("Gemini API quota exceeded, providing enhanced fallback analysis...") # Enhanced analysis based on content patterns fake_patterns = ['giả', 'sai', 'không đúng', 'bịa đặt', 'lừa đảo', 'fake news', 'tin đồn'] real_patterns = ['chính thức', 'xác nhận', 'chính xác', 'đúng', 'verified', 'chính phủ', 'bộ y tế'] news_lower = news_text.lower() fake_score = sum(1 for pattern in fake_patterns if pattern in news_lower) real_score = sum(1 for pattern in real_patterns if pattern in news_lower) # Adjust prediction based on patterns if fake_score > real_score and distilbert_prediction == 'FAKE': confidence_boost = "Cao (có từ khóa nghi ngờ)" elif real_score > fake_score and distilbert_prediction == 'REAL': confidence_boost = "Cao (có từ khóa xác thực)" else: confidence_boost = "Trung bình" # Create detailed fallback analysis conclusion = 'THẬT' if distilbert_prediction == 'REAL' else 'GIẢ' if distilbert_prediction == 'FAKE' else 'KHÔNG XÁC ĐỊNH' # Enhanced analysis based on content patterns suspicious_patterns = [] if fake_score > 0: suspicious_patterns.append(f"Tìm thấy {fake_score} từ khóa nghi ngờ") if real_score > 0: suspicious_patterns.append(f"Tìm thấy {real_score} từ khóa xác thực") warning_signs = [] if 'cảnh báo' in news_lower or 'nguy hiểm' in news_lower: warning_signs.append("Sử dụng từ ngữ gây sợ hãi") if 'ngay lập tức' in news_lower or 'khẩn cấp' in news_lower: warning_signs.append("Tạo cảm giác cấp bách không cần thiết") if len(news_text) < 100: warning_signs.append("Tin tức quá ngắn, thiếu thông tin chi tiết") fallback_analysis = f"""1. KẾT LUẬN: {conclusion} 2. ĐỘ TIN CẬY: {'THẬT: 5% / GIẢ: 95%' if conclusion == 'GIẢ' else 'THẬT: 95% / GIẢ: 5%' if conclusion == 'THẬT' else 'THẬT: 50% / GIẢ: 50%'} 3. PHÂN TÍCH CHI TIẾT: - Nội dung: {'Tin tức có vẻ hợp lý' if distilbert_prediction == 'REAL' else 'Tin tức có nhiều dấu hiệu đáng ngờ' if distilbert_prediction == 'FAKE' else 'Nội dung không rõ ràng'} - Nguồn tin: Google Search không khả dụng (hết quota) - không thể kiểm tra nguồn - Ngữ cảnh: Phân tích từ khóa: {confidence_boost} - Ngôn ngữ: {'Ngôn ngữ trung tính' if fake_score == real_score else 'Có dấu hiệu cảm xúc thái quá' if fake_score > real_score else 'Ngôn ngữ khách quan'} - Thời gian: Không thể xác minh do thiếu thông tin bổ sung 4. CÁC DẤU HIỆU CẢNH BÁO: {chr(10).join([f"- {sign}" for sign in warning_signs]) if warning_signs else "- Không phát hiện dấu hiệu cảnh báo rõ ràng"} 5. KHUYẾN NGHỊ CHO NGƯỜI ĐỌC: - Kiểm tra nguồn: Tìm kiếm thông tin tương tự trên các trang báo uy tín như VnExpress, Tuổi Trẻ, Thanh Niên - Xác minh thời gian: Kiểm tra xem tin tức có được đăng tải đồng thời trên nhiều nguồn không - Đánh giá ngôn ngữ: Tránh chia sẻ tin tức có ngôn ngữ cảm xúc thái quá hoặc tạo cảm giác cấp bách - Lưu ý: Do hệ thống API tạm thời không khả dụng, kết quả phân tích có thể không hoàn toàn chính xác""" return fallback_analysis # For other errors, see what models are available try: models = genai.list_models() print("Available models:") for model in models: if 'gemini' in model.name.lower(): print(f" - {model.name}") except Exception as list_error: print(f"Could not list models: {list_error}") return f"Lỗi phân tích Gemini: {e}" def extract_gemini_percentage(gemini_analysis): """Extract percentage confidence from Gemini analysis""" try: gemini_lower = gemini_analysis.lower() # Look for the confidence percentage pattern import re # Pattern to match "THẬT: X% / GIẢ: Y%" format percentage_pattern = r'độ tin cậy.*?thật.*?(\d+)%.*?giả.*?(\d+)%' match = re.search(percentage_pattern, gemini_lower) if match: real_percent = int(match.group(1)) fake_percent = int(match.group(2)) # Normalize to ensure they add up to 100 total = real_percent + fake_percent if total > 0: real_percent = real_percent / total fake_percent = fake_percent / total else: real_percent = 0.5 fake_percent = 0.5 print(f"Extracted Gemini percentages: {real_percent:.1%} real, {fake_percent:.1%} fake") return real_percent, fake_percent # Fallback: try to find individual percentages real_match = re.search(r'(\d+)%.*?thật', gemini_lower) fake_match = re.search(r'(\d+)%.*?giả', gemini_lower) if real_match and fake_match: real_percent = int(real_match.group(1)) / 100 fake_percent = int(fake_match.group(1)) / 100 print(f"Extracted Gemini percentages (fallback): {real_percent:.1%} real, {fake_percent:.1%} fake") return real_percent, fake_percent print("Could not extract Gemini percentages, using conclusion analysis") return None, None except Exception as e: print(f"Error extracting Gemini percentages: {e}") return None, None # If we hit the API limit, provide a basic analysis if "429" in str(e) or "quota" in str(e).lower(): print("Gemini API quota exceeded, providing enhanced fallback analysis...") # Enhanced analysis based on content patterns fake_patterns = ['giả', 'sai', 'không đúng', 'bịa đặt', 'lừa đảo', 'fake news', 'tin đồn'] real_patterns = ['chính thức', 'xác nhận', 'chính xác', 'đúng', 'verified', 'chính phủ', 'bộ y tế'] news_lower = news_text.lower() fake_score = sum(1 for pattern in fake_patterns if pattern in news_lower) real_score = sum(1 for pattern in real_patterns if pattern in news_lower) # Adjust prediction based on patterns if fake_score > real_score and distilbert_prediction == 'FAKE': confidence_boost = "Cao (có từ khóa nghi ngờ)" elif real_score > fake_score and distilbert_prediction == 'REAL': confidence_boost = "Cao (có từ khóa xác thực)" else: confidence_boost = "Trung bình" # Create detailed fallback analysis conclusion = 'THẬT' if distilbert_prediction == 'REAL' else 'GIẢ' if distilbert_prediction == 'FAKE' else 'KHÔNG XÁC ĐỊNH' # Enhanced analysis based on content patterns suspicious_patterns = [] if fake_score > 0: suspicious_patterns.append(f"Tìm thấy {fake_score} từ khóa nghi ngờ") if real_score > 0: suspicious_patterns.append(f"Tìm thấy {real_score} từ khóa xác thực") warning_signs = [] if 'cảnh báo' in news_lower or 'nguy hiểm' in news_lower: warning_signs.append("Sử dụng từ ngữ gây sợ hãi") if 'ngay lập tức' in news_lower or 'khẩn cấp' in news_lower: warning_signs.append("Tạo cảm giác cấp bách không cần thiết") if len(news_text) < 100: warning_signs.append("Tin tức quá ngắn, thiếu thông tin chi tiết") fallback_analysis = f"""**1. KẾT LUẬN:** {conclusion} **2. PHÂN TÍCH CHI TIẾT:** - **Nội dung:** {'Tin tức có vẻ hợp lý' if distilbert_prediction == 'REAL' else 'Tin tức có nhiều dấu hiệu đáng ngờ' if distilbert_prediction == 'FAKE' else 'Nội dung không rõ ràng'} - **Nguồn tin:** Google Search không khả dụng (hết quota) - không thể kiểm tra nguồn - **Ngữ cảnh:** Phân tích từ khóa: {confidence_boost} - **Ngôn ngữ:** {'Ngôn ngữ trung tính' if fake_score == real_score else 'Có dấu hiệu cảm xúc thái quá' if fake_score > real_score else 'Ngôn ngữ khách quan'} - **Thời gian:** Không thể xác minh do thiếu thông tin bổ sung **3. CÁC DẤU HIỆU CẢNH BÁO:** {chr(10).join([f"- {sign}" for sign in warning_signs]) if warning_signs else "- Không phát hiện dấu hiệu cảnh báo rõ ràng"} **4. KHUYẾN NGHỊ CHO NGƯỜI ĐỌC:** - **Kiểm tra nguồn:** Tìm kiếm thông tin tương tự trên các trang báo uy tín như VnExpress, Tuổi Trẻ, Thanh Niên - **Xác minh thời gian:** Kiểm tra xem tin tức có được đăng tải đồng thời trên nhiều nguồn không - **Đánh giá ngôn ngữ:** Tránh chia sẻ tin tức có ngôn ngữ cảm xúc thái quá hoặc tạo cảm giác cấp bách - **Lưu ý:** Do hệ thống API tạm thời không khả dụng, kết quả phân tích có thể không hoàn toàn chính xác""" return fallback_analysis # For other errors, see what models are available try: models = genai.list_models() print("Available models:") for model in models: if 'gemini' in model.name.lower(): print(f" - {model.name}") except Exception as list_error: print(f"Could not list models: {list_error}") return f"Lỗi phân tích Gemini: {e}" def calculate_combined_confidence(distilbert_prediction, distilbert_confidence, source_credibility, popularity_score, gemini_analysis, source_support=0.5): """Calculate combined confidence using weighted approach: - DistilBERT: 30% weight - Gemini AI: 30% weight - Google Search (source credibility + support): 20% weight - Other factors: 20% weight """ # 1. DISTILBERT SCORE (30% weight) if distilbert_prediction == "REAL": distilbert_score = distilbert_confidence else: distilbert_score = 1 - distilbert_confidence print(f"DistilBERT Score: {distilbert_score:.3f} (30% weight)") # 2. GEMINI AI SCORE (30% weight) gemini_lower = gemini_analysis.lower() # Try to extract percentage from Gemini analysis first gemini_real_percent, gemini_fake_percent = extract_gemini_percentage(gemini_analysis) if gemini_real_percent is not None and gemini_fake_percent is not None: # Use the extracted percentage directly gemini_score = gemini_real_percent print(f"Gemini Score (from percentage): {gemini_score:.3f} (30% weight) - {gemini_real_percent:.1%} real, {gemini_fake_percent:.1%} fake") else: # Fallback to conclusion analysis conclusion_score = 0.5 # Default neutral if "kết luận: giả" in gemini_lower or "kết luận: fake" in gemini_lower: conclusion_score = 0.1 # Very low for FAKE print("Gemini Conclusion: FAKE") elif "kết luận: thật" in gemini_lower or "kết luận: real" in gemini_lower: conclusion_score = 0.9 # Very high for REAL print("Gemini Conclusion: REAL") elif "giả" in gemini_lower and "kết luận" in gemini_lower: # Check if "giả" appears near "kết luận" conclusion_start = gemini_lower.find("kết luận") if conclusion_start != -1: conclusion_section = gemini_lower[conclusion_start:conclusion_start + 50] if "giả" in conclusion_section: conclusion_score = 0.1 print("Gemini Conclusion: FAKE (detected in conclusion section)") elif "thật" in conclusion_section: conclusion_score = 0.9 print("Gemini Conclusion: REAL (detected in conclusion section)") # Additional analysis indicators fake_indicators = ["giả", "fake", "vô lý", "phi thực tế", "absurd", "preposterous", "impossible", "không thể xảy ra", "không có căn cứ", "tin giả"] real_indicators = ["thật", "real", "chính xác", "đúng", "xác nhận", "verified", "đáng tin cậy"] fake_count = sum(1 for indicator in fake_indicators if indicator in gemini_lower) real_count = sum(1 for indicator in real_indicators if indicator in gemini_lower) # Adjust based on analysis indicators (but conclusion takes priority) if fake_count > real_count: analysis_adjustment = -0.2 print(f"Gemini Analysis: {fake_count} fake indicators vs {real_count} real indicators") elif real_count > fake_count: analysis_adjustment = 0.2 print(f"Gemini Analysis: {real_count} real indicators vs {fake_count} fake indicators") else: analysis_adjustment = 0.0 gemini_score = max(0.1, min(0.9, conclusion_score + analysis_adjustment)) print(f"Gemini Score (from conclusion): {gemini_score:.3f} (30% weight)") # 3. GOOGLE SEARCH SCORE (20% weight - source credibility + support) # Source credibility component (10%) credibility_component = source_credibility * 0.5 # Convert to 0-0.5 scale # Source support component (10%) support_component = source_support * 0.5 # Convert to 0-0.5 scale google_search_score = credibility_component + support_component + 0.5 # Add base 0.5 for neutral # If Gemini strongly says FAKE, reduce Google Search score if gemini_score < 0.3: # Gemini says FAKE (low score) google_search_score = min(google_search_score, 0.4) # Cap at 0.4 when Gemini says fake print(f"Google Search Score: {google_search_score:.3f} (20% weight) - Credibility: {source_credibility:.2f}, Support: {source_support:.2f} - CAPPED due to Gemini FAKE") else: print(f"Google Search Score: {google_search_score:.3f} (20% weight) - Credibility: {source_credibility:.2f}, Support: {source_support:.2f}") # 4. OTHER FACTORS (20% weight - popularity, etc.) other_factors_score = popularity_score * 0.4 + 0.6 # Convert popularity to 0.6-1.0 scale # If Gemini strongly says FAKE, reduce Other Factors score if gemini_score < 0.3: # Gemini says FAKE (low score) other_factors_score = min(other_factors_score, 0.5) # Cap at 0.5 when Gemini says fake print(f"Other Factors Score: {other_factors_score:.3f} (20% weight) - Popularity: {popularity_score:.2f} - CAPPED due to Gemini FAKE") else: print(f"Other Factors Score: {other_factors_score:.3f} (20% weight) - Popularity: {popularity_score:.2f}") # 5. COMBINE WITH WEIGHTS final_confidence = ( distilbert_score * 0.30 + # DistilBERT: 30% gemini_score * 0.30 + # Gemini AI: 30% google_search_score * 0.20 + # Google Search: 20% other_factors_score * 0.20 # Other factors: 20% ) final_confidence = max(0.05, min(0.95, final_confidence)) print(f"Final Weighted Confidence: {final_confidence:.3f}") print(f" - DistilBERT (30%): {distilbert_score:.3f} × 0.30 = {distilbert_score * 0.30:.3f}") print(f" - Gemini (30%): {gemini_score:.3f} × 0.30 = {gemini_score * 0.30:.3f}") print(f" - Google Search (20%): {google_search_score:.3f} × 0.20 = {google_search_score * 0.20:.3f}") print(f" - Other Factors (20%): {other_factors_score:.3f} × 0.20 = {other_factors_score * 0.20:.3f}") return final_confidence def analyze_news(news_text): """Main analysis function combining all three tools""" try: if not news_text.strip(): empty_message = """
Để bắt đầu phân tích
Hướng dẫn:
{confidence_emoji} Độ tin cậy: {confidence_level} ({combined_confidence:.0%})
Kết quả: {prediction_emoji} {'Tin tức này có vẻ THẬT' if final_prediction == 'REAL' else 'Tin tức này có vẻ GIẢ' if final_prediction == 'FAKE' else 'Không thể xác định'}
Độ chắc chắn: {f"{distilbert_confidence:.0%}" if distilbert_confidence else 'Không có'} - {'Rất cao' if distilbert_confidence and distilbert_confidence > 0.8 else 'Cao' if distilbert_confidence and distilbert_confidence > 0.6 else 'Trung bình' if distilbert_confidence and distilbert_confidence > 0.4 else 'Thấp'}
Tìm thấy: {source_count_text}
Chất lượng nguồn: {source_quality} ({source_credibility:.0%})
Đánh giá: {credibility_summary}
Hỗ trợ: {support_summary}
{sources_display and f'Nguồn tìm thấy:
{sources_display}
Tin tức này có khả năng {'THẬT' if final_prediction == 'REAL' else 'GIẢ' if final_prediction == 'FAKE' else 'KHÔNG XÁC ĐỊNH'} với độ tin cậy {max(real_confidence, fake_confidence):.0%}
Dựa trên phân tích AI, kiểm tra nguồn tin và đánh giá thông minh
Vui lòng thử lại sau
Chi tiết lỗi: {str(e)}
Gợi ý: Kiểm tra kết nối internet và thử lại
Powered by Google Search + Gemini AI + DistilBERT
💡 Lưu ý: Kết quả có thể thay đổi nhẹ giữa các lần phân tích do tính chất AI của Gemini, nhưng độ chính xác tổng thể vẫn được đảm bảo.
Khi độ tin cậy > 95%, hệ thống sẽ tự động lưu kết quả vào cơ sở tri thức để sử dụng cho các phân tích tương lai.