# import torch
# from transformers import pipeline

# # Load the model for AI text detection
# text_classifier = pipeline("text-classification", model="roberta-large-openai-detector")

# def is_generated_by_ai(paragraph):
#     inputs = text_classifier.tokenizer(paragraph, padding=True, truncation=True, max_length=512, return_tensors="pt")
#     result = text_classifier.model(**inputs)
#     logits = result.logits
#     confidence = torch.softmax(logits, dim=-1).max().item()

#     confidence_percentage = confidence * 100

#     # Adjust the threshold as needed
#     confidence_threshold = 70  # Raise the threshold to 70% for AI detection
#     return {
#         "is_ai_generated": confidence_percentage >= confidence_threshold,
#         "confidence_percentage": confidence_percentage
#     }

import torch
from transformers import pipeline
 
# Load AI text classification model
device = "cuda" if torch.cuda.is_available() else "cpu"
text_classifier = pipeline("text-classification", model="roberta-large-openai-detector", device=0 if torch.cuda.is_available() else -1)
 
def is_generated_by_ai(paragraph):
    if not paragraph.strip():
        return {"error": "Input text is empty", "is_ai_generated": None, "confidence_percentage": None}
 
    # Ensure tokenized input is on the correct device
    inputs = text_classifier.tokenizer(paragraph, padding=True, truncation=True, max_length=512, return_tensors="pt").to(device)
 
    # Get model output
    with torch.no_grad():  # Disable gradient tracking for efficiency
        result = text_classifier.model(**inputs)
 
    logits = result.logits
    probabilities = torch.softmax(logits, dim=-1)
    # Extract AI-generated vs. human-written scores
    ai_confidence = probabilities[0][1].item() * 100  # Assuming AI-generated class is index 1
    human_confidence = probabilities[0][0].item() * 100  # Assuming Human-written class is index 0
    confidence_threshold = 70  # Adjust threshold if needed
 
    return {
        "is_ai_generated": ai_confidence >= confidence_threshold,
        "ai_confidence_percentage": ai_confidence,
        "human_confidence_percentage": human_confidence
    }