Spaces:
Sleeping
Sleeping
Create detector.py
Browse files- src/detector.py +100 -0
src/detector.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoTokenizer, AutoConfig, AutoModelForSequenceClassification
|
| 3 |
+
import numpy as np
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
MODEL_DIR = "abhi099k/ai-text-detector-v-n4.0" # Your fine-tuned model
|
| 7 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 8 |
+
|
| 9 |
+
# === Load tokenizer and config ===
|
| 10 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)
|
| 11 |
+
config = AutoConfig.from_pretrained(MODEL_DIR)
|
| 12 |
+
model = AutoModelForSequenceClassification.from_pretrained(MODEL_DIR, config=config).to(device)
|
| 13 |
+
model.eval()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# === Preprocessing: Normalize + Flatten ===
|
| 17 |
+
def preprocess_text_for_detection(text: str) -> str:
|
| 18 |
+
"""
|
| 19 |
+
Convert structured notes (bullets, lists) into clean sentences for AI detection.
|
| 20 |
+
"""
|
| 21 |
+
# Replace bullets / dashes with periods
|
| 22 |
+
text = re.sub(r"[\n•\-–]+", ". ", text)
|
| 23 |
+
|
| 24 |
+
# Remove multiple spaces
|
| 25 |
+
text = re.sub(r"\s+", " ", text)
|
| 26 |
+
|
| 27 |
+
# Ensure consistent punctuation spacing
|
| 28 |
+
text = re.sub(r"\s*([,.!?;:])\s*", r"\1 ", text)
|
| 29 |
+
|
| 30 |
+
return text.strip()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# === Core Scoring ===
|
| 34 |
+
def score_texts(texts, max_len=512):
|
| 35 |
+
"""Return AI probability scores (float between 0-1) for 2-class models."""
|
| 36 |
+
encoded = tokenizer(
|
| 37 |
+
texts,
|
| 38 |
+
padding=True,
|
| 39 |
+
truncation=True,
|
| 40 |
+
max_length=max_len,
|
| 41 |
+
return_tensors="pt"
|
| 42 |
+
).to(device)
|
| 43 |
+
|
| 44 |
+
# Some models may not need token_type_ids
|
| 45 |
+
encoded.pop("token_type_ids", None)
|
| 46 |
+
|
| 47 |
+
with torch.no_grad():
|
| 48 |
+
logits = model(**encoded).logits # shape: [batch, 2]
|
| 49 |
+
probs = torch.softmax(logits, dim=-1).cpu().numpy()
|
| 50 |
+
|
| 51 |
+
# Extract AI probability (label=1)
|
| 52 |
+
ai_probs = [float(p[1]) for p in probs]
|
| 53 |
+
return ai_probs
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# === Threshold Calibration ===
|
| 57 |
+
def calibrate_threshold(human_texts, calibration_proportion=0.05, max_len=512):
|
| 58 |
+
scores = score_texts(human_texts, max_len=max_len)
|
| 59 |
+
tau = np.percentile(scores, 100 * (1 - calibration_proportion))
|
| 60 |
+
return tau
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# === Predictions ===
|
| 64 |
+
def predict_chunks_with_tau(chunks, tau, max_len=768):
|
| 65 |
+
probs = score_texts(chunks, max_len=max_len)
|
| 66 |
+
results = []
|
| 67 |
+
for text, prob in zip(chunks, probs):
|
| 68 |
+
label = "AI" if prob >= tau else "Human"
|
| 69 |
+
results.append({"text": text, "type": label, "score": prob})
|
| 70 |
+
return results
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# === Smart Chunking ===
|
| 74 |
+
def smart_chunk_text(text, max_tokens=80, min_last_chunk=70):
|
| 75 |
+
text = preprocess_text_for_detection(text)
|
| 76 |
+
sentences = re.split(r'(?<=[.!?])\s+(?=[A-Z(“"])', text)
|
| 77 |
+
chunks, buffer = [], []
|
| 78 |
+
|
| 79 |
+
for sent in sentences:
|
| 80 |
+
buffer.append(sent)
|
| 81 |
+
if len(buffer) == 2 or len(" ".join(buffer)) > max_tokens:
|
| 82 |
+
chunks.append(" ".join(buffer).strip())
|
| 83 |
+
buffer = []
|
| 84 |
+
|
| 85 |
+
if buffer:
|
| 86 |
+
chunks.append(" ".join(buffer).strip())
|
| 87 |
+
|
| 88 |
+
if len(chunks) > 1 and len(chunks[-1]) < min_last_chunk:
|
| 89 |
+
chunks[-2] = chunks[-2] + " " + chunks[-1]
|
| 90 |
+
chunks.pop(-1)
|
| 91 |
+
|
| 92 |
+
return chunks
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# === Artifact Detection ===
|
| 96 |
+
def has_html_or_ai_artifacts(text: str) -> bool:
|
| 97 |
+
"""Detect HTML tags or attributes typical of copy-pasted AI output."""
|
| 98 |
+
html_pattern = re.compile(r'<[^>]+>')
|
| 99 |
+
data_attr_pattern = re.compile(r'data-(start|end)=["\']?\d+')
|
| 100 |
+
return bool(html_pattern.search(text) or data_attr_pattern.search(text))
|