import streamlit as st import torch from transformers import AutoTokenizer, AutoModelForSequenceClassification import nltk from nltk.tokenize import sent_tokenize from markupsafe import escape # Set page config at the very beginning st.set_page_config(page_title="LLM Detector", layout="centered") # Download the punkt tokenizer for sentence splitting (with caching) @st.cache_resource def download_nltk_punkt(): nltk.download("punkt", quiet=True) download_nltk_punkt() # Load the model and tokenizer (with caching) @st.cache_resource def load_model_and_tokenizer(): model_name = "CoolSpring/creative-writing-llm-detector-deberta-v3-xsmall" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSequenceClassification.from_pretrained(model_name) return tokenizer, model tokenizer, model = load_model_and_tokenizer() def classify_text(text): inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512) with torch.no_grad(): logits = model(**inputs).logits probabilities = torch.softmax(logits, dim=1) return probabilities[0][1].item() # Probability of being AI-generated def highlight_suspicious_sentences(text): sentences = sent_tokenize(text) inputs = tokenizer( sentences, return_tensors="pt", truncation=True, max_length=512, padding=True ) with torch.no_grad(): logits = model(**inputs).logits probabilities = torch.softmax(logits, dim=1) scores = probabilities[ :, 1 ].tolist() # Probability of being AI-generated for each sentence return sentences, scores def get_color(score): if score < 0.33: return "rgba(144, 238, 144, 0.3)" # Light green elif score < 0.66: return "rgba(255, 255, 0, 0.3)" # Light yellow else: return "rgba(255, 99, 71, 0.3)" # Light red st.title("🤖 LLM Detector") st.write("Enter text to detect if it's written by an AI language model.") # Use session state to store the input text if "text_input" not in st.session_state: st.session_state.text_input = "" text_input = st.text_area( "Enter your text here:", value=st.session_state.text_input, height=200 ) # Update session state when input changes if text_input != st.session_state.text_input: st.session_state.text_input = text_input if st.button("Analyze and Highlight"): if text_input: with st.spinner("Analyzing text..."): overall_probability = classify_text(text_input) st.html( f"