Hey o1, I want to design a fake news detection application in Python.
The program should ask the user for an URL or headline or text, which the program will decide automatically what it is - if it is a URL it will go to the URL and read the news, else it would read the text directly.
The program will use a set of several transformers like BERT to judge whether the news is fake or not. We want to use as many transformers as possible to ensure correct result. Try to include as many different transformers as possible.
It would then extract the output with the degree of confidence it has.
The program is called Veritas so I would love it if you can include the following text in the output:
code
# ASCII art banner for VERITAS AI
print("""
\033[94m
╦ ╦╔═╗╦═╗╦╔╦╗╔═╗╔═╗ ╔═╗╦
╚╗╔╝║╣ ╠╦╝║ ║ ╠═╣╚═╗ ╠═╣║
╚╝ ╚═╝╩╚═╩ ╩ ╩ ╩╚═╝ ╩ ╩╩
Truth Through AI
\033[0m""")
Assistant
Hello! Designing a fake news detection application using multiple transformer models is an excellent approach to ensure higher accuracy and reliability. Below is a Python script for the Veritas application that fulfills your requirements.
Overview of the Approach:
Input Handling:
The program prompts the user to input a URL, headline, or text.
It determines whether the input is a URL. If it is, the program fetches the content from the URL; otherwise, it uses the text directly.
Data Extraction:
For URLs, the program retrieves the main content of the news article using BeautifulSoup.
Fake News Detection:
Utilizes multiple transformer-based models from Hugging Face's transformers library to predict whether the news is fake.
Each model provides a prediction along with its confidence score.
The final result is an aggregated confidence score based on all models' outputs.
Output:
Displays an ASCII art banner for VERITAS AI.
Shows the aggregated prediction along with the degree of confidence.
Prerequisites:
Before running the script, ensure you have the necessary libraries installed. You can install them using pip:
import re
import requests
from bs4 import BeautifulSoup
from transformers import pipeline
import torch
# ASCII art banner for VERITAS AI
def print_banner():
banner = """
\033[94m
╦ ╦╔═╗╦═╗╦╔╦╗╔═╗╔═╗ ╔═╗╦
╚╗╔╝║╣ ╠╦╝║ ║ ╠═╣╚═╗ ╠═╣║
╚╝ ╚═╝╩╚═╩ ╩ ╩ ╩╚═╝ ╩ ╩╩
Truth Through AI
\033[0m"""
print(banner)
# Function to check if the input is a URL
def is_url(input_text):
# Simple regex to check for URL pattern
url_pattern = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:\S+)' # Domain...
, re.IGNORECASE)
return re.match(url_pattern, input_text) is not None
# Function to extract text from URL
def extract_text_from_url(url):
try:
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"Failed to retrieve the URL. Status code: {response.status_code}")
return None
soup = BeautifulSoup(response.content, 'html.parser')
# Attempt to extract text from common HTML tags
paragraphs = soup.find_all(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'])
text = ' '.join([para.get_text() for para in paragraphs])
return text.strip()
except Exception as e:
print(f"An error occurred while extracting text from the URL: {e}")
return None
# Function to load multiple classifiers
def load_classifiers():
classifiers = []
model_names = [
"mrm8488/bert-mini-finetuned-fake-news-detection",
"distilbert-base-uncased-finetuned-sst-2-english",
"roberta-base-openai-detector",
"ynie/roberta-large-snli_mnli_fever_anli_R1_R2_R3-nli",
"facebook/bart-large-mnli"
# Add more model names as needed
]
for model_name in model_names:
try:
classifier = pipeline("text-classification", model=model_name, tokenizer=model_name, device=0 if torch.cuda.is_available() else -1)
classifiers.append((model_name, classifier))
print(f"Loaded model: {model_name}")
except Exception as e:
print(f"Failed to load model {model_name}: {e}")
return classifiers
# Function to predict using all classifiers
def predict_fake_news(text, classifiers):
predictions = []
for model_name, classifier in classifiers:
try:
result = classifier(text)[0]
label = result['label']
score = result['score']
predictions.append((label, score))
print(f"Model {model_name} prediction: {label} with confidence {score:.4f}")
except Exception as e:
print(f"Error in model {model_name}: {e}")
return predictions
# Function to aggregate predictions
def aggregate_predictions(predictions):
if not predictions:
return "Unable to make a prediction.", 0.0
# Simple aggregation: average confidence for 'LABEL_1' and 'LABEL_0' or respective labels
label_confidences = {}
for label, score in predictions:
if label not in label_confidences:
label_confidences[label] = []
label_confidences[label].append(score)
# Calculate average confidence for each label
avg_confidences = {label: sum(scores)/len(scores) for label, scores in label_confidences.items()}
# Determine the label with highest average confidence
final_label = max(avg_confidences, key=avg_confidences.get)
final_confidence = avg_confidences[final_label]
# Interpret labels based on model's convention
# You may need to adjust this based on specific model outputs
fake_labels = ['LABEL_1', 'FAKE', 'NEGATIVE'] # Example labels indicating fake news
real_labels = ['LABEL_0', 'REAL', 'POSITIVE'] # Example labels indicating real news
if final_label in fake_labels:
verdict = "FAKE"
elif final_label in real_labels:
verdict = "REAL"
else:
verdict = final_label # Fallback to the label name
return verdict, final_confidence
def main():
print_banner()
user_input = input("Enter a URL, headline, or text: ").strip()
if is_url(user_input):
print("Detected input as URL. Extracting content...")
text = extract_text_from_url(user_input)
if not text:
print("Unable to extract text from the provided URL.")
return
else:
text = user_input
print("Detected input as text.")
print("\nLoading classifiers...")
classifiers = load_classifiers()
if not classifiers:
print("No classifiers loaded. Exiting.")
return
print("\nPredicting fake news...")
predictions = predict_fake_news(text, classifiers)
verdict, confidence = aggregate_predictions(predictions)
print("\n=== VERITAS AI RESULT ===")
print(f"Verdict: {verdict}")
print(f"Confidence: {confidence*100:.2f}%")
if __name__ == "__main__":
main()
Explanation of the Script:
Banner Display:
The print_banner function displays the ASCII art banner in blue color using ANSI escape codes.
Input Validation:
The is_url function uses a regular expression to determine if the input string is a URL.
Content Extraction:
The extract_text_from_url function fetches the content of the URL and extracts text from common HTML tags like <p>, <h1>-<h6> using BeautifulSoup.
Loading Classifiers:
The load_classifiers function initializes multiple transformer-based classifiers. You can add or remove models from the model_names list based on availability and suitability.
Note: Some models might not be specifically trained for fake news detection. Ensure the models you choose are appropriate for your task or fine-tune them accordingly.
Prediction:
The predict_fake_news function runs the input text through each classifier and collects their predictions and confidence scores.
Aggregation of Predictions:
The aggregate_predictions function averages the confidence scores for each label and determines the final verdict based on the highest average confidence.
Customization: Depending on the labels used by different models, you might need to adjust the fake_labels and real_labels lists to correctly interpret the outputs.
Main Function:
Orchestrates the flow: displaying the banner, handling user input, loading classifiers, making predictions, and displaying the final result.
Considerations and Recommendations:
Model Selection: Ensure that the models you load are suitable for fake news detection. Some models listed above might not be explicitly trained for this task and may require fine-tuning.
Performance: Loading multiple large transformer models can be resource-intensive and may lead to longer prediction times, especially without GPU acceleration.
Extensibility: You can enhance the program by adding more sophisticated aggregation techniques, such as weighted voting based on model performance or using ensemble learning methods.
Error Handling: The script includes basic error handling, but you might want to make it more robust based on specific requirements and edge cases.
User Feedback: Consider adding more informative messages or progress indicators, especially if loading models takes significant time.
Feel free to customize and expand upon this script to better fit your specific needs and improve its performance and accuracy. Happy coding!