import gradio as gr
import numpy as np
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer, pipeline

# Load fine-tuned model and tokenizer from Hugging Face Hub
model_name = "AICodexLab/answerdotai-ModernBERT-base-ai-detector"

# Load model and tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)

# Use pipeline for text classification
classifier = pipeline("text-classification", model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)

# Define function for real-time AI text detection
def predict_ai_text(input_text):
    result = classifier(input_text)
    label = "AI-Generated" if result[0]["label"] == "LABEL_1" else "Human-Written"
    confidence = np.round(result[0]["score"], 3)
    return f"{label} (Confidence: {confidence})"

# Create Gradio interface
app = gr.Interface(
    fn=predict_ai_text,
    inputs=gr.Textbox(lines=5, placeholder="Enter your text here..."),
    outputs=gr.Textbox(),
    title="AI Text Detector",
    description="Detect whether a given text is AI-generated or human-written.",
    allow_flagging="never"
)

# Launch app
if __name__ == "__main__":
    app.launch()