Hello!
Certainly! I can help you create a Python script that detects whether an entered text has been generated by AI or written by a human. We'll use a pre-trained transformer-based model and ensure that the code runs locally on your GPU using CUDA. Here's how you can do it:
Overview
We'll use the Hugging Face Transformers library along with PyTorch to load a pre-trained model designed to detect AI-generated text. The model we'll use is the roberta-base-openai-detector, which is trained to distinguish between human-written text and text generated by GPT-2.
Prerequisites
- Python 3.6 or higher: Ensure you have a compatible Python version installed.
- CUDA-compatible GPU: Make sure your system has a CUDA-compatible GPU.
- PyTorch with CUDA support: Install PyTorch configured for CUDA to leverage GPU acceleration.
- Transformers library: We'll use the
transformers library by Hugging Face.
Step-by-Step Guide
1. Install Required Libraries
Open your terminal or command prompt and run the following commands:
# Install PyTorch with CUDA support
# Visit https://pytorch.org/get-started/locally/ for the latest command specific to your system.
# Here's an example for Windows/Linux with CUDA 11.7:
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu117
# Install Transformers library
pip install transformers
2. Write the Python Script
Create a new Python file called ai_text_detector.py and add the following code:
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
def main():
# Check if CUDA is available and set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if device.type == 'cuda':
print(f"Using GPU: {torch.cuda.get_device_name(0)}")
else:
print("CUDA is not available. Using CPU instead.")
# Load the pre-trained model and tokenizer
model_name = "roberta-base-openai-detector"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)
model.to(device) # Move the model to the GPU if available
# Get text input from the user
print("\nEnter the text you want to check (press Enter twice to submit):")
text_lines = []
while True:
line = input()
if line == "":
break
text_lines.append(line)
text = "\n".join(text_lines)
# Tokenize the input text
inputs = tokenizer(
text,
return_tensors="pt",
truncation=True,
padding=True,
max_length=512 # Adjust as needed
)
inputs = {k: v.to(device) for k, v in inputs.items()} # Move inputs to GPU
# Perform inference
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
probabilities = torch.softmax(logits, dim=1).squeeze()
# Retrieve probabilities
prob_human = probabilities[0].item()
prob_ai = probabilities[1].item()
# Display the results
print("\n--- Detection Results ---")
print(f"Probability that the text is human-written: {prob_human * 100:.2f}%")
print(f"Probability that the text is AI-generated: {prob_ai * 100:.2f}%")
print("--------------------------")
if __name__ == "__main__":
main()
3. Understanding the Code
-
Imports: We import torch for PyTorch functionalities and AutoTokenizer, AutoModelForSequenceClassification from transformers to load the tokenizer and model.
-
Device Configuration:
- We check if CUDA is available using
torch.cuda.is_available().
- Set the device accordingly and print which device is being used.
-
Load Model and Tokenizer:
- We use
roberta-base-openai-detector, a model trained by OpenAI to detect if text is generated by GPT-2.
- Load the model and tokenizer using
from_pretrained() methods.
- Move the model to the GPU using
model.to(device) if CUDA is available.
-
Input Handling:
- The script prompts the user to input the text they'd like to check.
- Multi-line input is supported; the user can press Enter twice to finish.
-
Tokenization:
- The input text is tokenized using the loaded tokenizer.
- The tokenized inputs are moved to the GPU if available.
-
Inference:
- We use the model to predict the probabilities without calculating gradients (
torch.no_grad()).
- Apply softmax to the logits to get probabilities.
-
Results:
- The probabilities are printed to the console, indicating the likelihood of the text being human-written or AI-generated.
4. Run the Script
Ensure that your GPU is properly configured and that CUDA drivers are installed. Then run the script using:
python ai_text_detector.py
5. Example
Using GPU: NVIDIA GeForce RTX 3080
Enter the text you want to check (press Enter twice to submit):
The quick brown fox jumps over the lazy dog.
--- Detection Results ---
Probability that the text is human-written: 95.12%
Probability that the text is AI-generated: 4.88%
--------------------------
Additional Information
Model Description
- The
roberta-base-openai-detector model is a RoBERTa-based classifier fine-tuned to distinguish between human-written text and text generated by GPT-2.
- It outputs two probabilities: one for "Real" (human-written) and one for "Fake" (AI-generated).
Limitations
- Detection Accuracy: The model is trained on GPT-2 generated text and may not be as accurate for detecting text generated by more advanced models like GPT-3 or GPT-4.
- Text Length: Transformers models have a maximum input length (usually 512 tokens). Text longer than this limit will be truncated.
Potential Improvements
- Fine-Tuning: For better results, consider fine-tuning a model on a dataset that includes examples of AI-generated text from the models you're interested in detecting.
- Data Collection: Collect samples of AI-generated text and human-written text relevant to your use case.
Checking CUDA Availability
Before running the script, you can verify if PyTorch detects CUDA:
import torch
print(torch.cuda.is_available()) # Should output: True
If this outputs False, ensure that:
- Your GPU drivers are up to date.
- CUDA is properly installed.
- PyTorch is installed with CUDA support.
References
Summary
You've now set up a Python script that uses a pre-trained model to detect if a text is AI-generated or human-written. The script leverages GPU acceleration using CUDA for efficient computation.
Feel free to ask if you have any questions or need further assistance!