Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,38 @@
|
|
| 1 |
import torch
|
|
|
|
| 2 |
import torch.nn.functional as F
|
| 3 |
-
from transformers import AutoTokenizer,
|
| 4 |
import re
|
| 5 |
import pandas as pd
|
| 6 |
import gradio as gr
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
# -----------------------------
|
| 9 |
# MODEL INITIALIZATION
|
| 10 |
# -----------------------------
|
| 11 |
-
# desklib/ai-text-detector-v1.01 is highly robust for academic/essay detection.
|
| 12 |
MODEL_NAME = "desklib/ai-text-detector-v1.01"
|
| 13 |
tokenizer = None
|
| 14 |
model = None
|
|
@@ -17,26 +41,20 @@ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
| 17 |
def get_model():
|
| 18 |
global tokenizer, model
|
| 19 |
if model is None:
|
| 20 |
-
print(f"Loading
|
| 21 |
-
|
| 22 |
-
# DeBERTa-v3 requires use_fast=False for stable SentencePiece tokenization.
|
| 23 |
-
# Ensure 'sentencepiece' is installed (pip install sentencepiece).
|
| 24 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_fast=False)
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
model = AutoModelForSequenceClassification.from_pretrained(
|
| 31 |
-
MODEL_NAME, torch_dtype=dtype
|
| 32 |
).to(device).eval()
|
| 33 |
return tokenizer, model
|
| 34 |
|
| 35 |
-
# Only 81% and above is flagged as AI
|
| 36 |
THRESHOLD = 0.81
|
| 37 |
|
| 38 |
# -----------------------------
|
| 39 |
-
#
|
| 40 |
# -----------------------------
|
| 41 |
ABBR = ["e.g", "i.e", "mr", "mrs", "ms", "dr", "prof", "vs", "etc", "fig", "al", "jr", "sr", "st", "inc", "ltd", "u.s", "u.k"]
|
| 42 |
ABBR_REGEX = re.compile(r"\b(" + "|".join(map(re.escape, ABBR)) + r")\.", re.IGNORECASE)
|
|
@@ -95,7 +113,6 @@ def analyze(text):
|
|
| 95 |
if not pure_sents:
|
| 96 |
return "—", "—", "<em>No sentences detected.</em>", None
|
| 97 |
|
| 98 |
-
# Sliding window inference (Contextual for better accuracy)
|
| 99 |
windows = []
|
| 100 |
for i in range(len(pure_sents)):
|
| 101 |
start = max(0, i - 1)
|
|
@@ -103,17 +120,16 @@ def analyze(text):
|
|
| 103 |
windows.append(" ".join(pure_sents[start:end]))
|
| 104 |
|
| 105 |
inputs = tok(windows, return_tensors="pt", padding=True, truncation=True, max_length=512).to(device)
|
| 106 |
-
logits = mod(
|
| 107 |
-
|
| 108 |
-
|
|
|
|
| 109 |
|
| 110 |
lengths = [len(s.split()) for s in pure_sents]
|
| 111 |
total_words = sum(lengths)
|
| 112 |
weighted_avg = sum(p * l for p, l in zip(probs, lengths)) / total_words if total_words > 0 else 0
|
| 113 |
|
| 114 |
-
#
|
| 115 |
-
# HTML RECONSTRUCTION (Strict Binary)
|
| 116 |
-
# -----------------------------
|
| 117 |
highlighted_html = "<div style='font-family: sans-serif; line-height: 1.8;'>"
|
| 118 |
prob_map = {idx: probs[i] for i, idx in enumerate(pure_sents_indices)}
|
| 119 |
|
|
@@ -124,12 +140,10 @@ def analyze(text):
|
|
| 124 |
|
| 125 |
if i in prob_map:
|
| 126 |
score = prob_map[i]
|
| 127 |
-
|
| 128 |
-
# Binary logic: Threshold applied to color
|
| 129 |
if score >= THRESHOLD:
|
| 130 |
-
color, bg = "#b80d0d", "rgba(184, 13, 13, 0.15)" # RED
|
| 131 |
else:
|
| 132 |
-
color, bg = "#11823b", "rgba(17, 130, 59, 0.15)" # GREEN
|
| 133 |
|
| 134 |
highlighted_html += (
|
| 135 |
f"<span style='background:{bg}; padding:2px 4px; border-radius:4px; border-bottom: 2px solid {color};' "
|
|
@@ -140,7 +154,6 @@ def analyze(text):
|
|
| 140 |
highlighted_html += block
|
| 141 |
highlighted_html += "</div>"
|
| 142 |
|
| 143 |
-
# --- FINAL VERDICT (Masking below 81%) ---
|
| 144 |
if weighted_avg >= THRESHOLD:
|
| 145 |
label = f"{weighted_avg:.0%} AI Content Detected"
|
| 146 |
display_score = f"{weighted_avg:.1%}"
|
|
@@ -156,7 +169,7 @@ def analyze(text):
|
|
| 156 |
# -----------------------------
|
| 157 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 158 |
gr.Markdown("## 🕵️ AI Detector Pro (Academic Edition)")
|
| 159 |
-
gr.Markdown(f"Using **{MODEL_NAME}**. Threshold: **{THRESHOLD*100:.0f}%**.
|
| 160 |
|
| 161 |
with gr.Row():
|
| 162 |
with gr.Column(scale=3):
|
|
|
|
| 1 |
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
import torch.nn.functional as F
|
| 4 |
+
from transformers import AutoTokenizer, AutoConfig, AutoModel, PreTrainedModel
|
| 5 |
import re
|
| 6 |
import pandas as pd
|
| 7 |
import gradio as gr
|
| 8 |
|
| 9 |
+
# -----------------------------
|
| 10 |
+
# CUSTOM MODEL DEFINITION
|
| 11 |
+
# -----------------------------
|
| 12 |
+
# The Desklib model uses a custom architecture: Mean Pooling + Linear Classifier.
|
| 13 |
+
class DesklibAIDetectionModel(PreTrainedModel):
|
| 14 |
+
config_class = AutoConfig
|
| 15 |
+
def __init__(self, config):
|
| 16 |
+
super().__init__(config)
|
| 17 |
+
self.model = AutoModel.from_config(config)
|
| 18 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 19 |
+
self.init_weights()
|
| 20 |
+
|
| 21 |
+
def forward(self, input_ids, attention_mask=None):
|
| 22 |
+
outputs = self.model(input_ids, attention_mask=attention_mask)
|
| 23 |
+
last_hidden_state = outputs[0]
|
| 24 |
+
# Mean Pooling logic
|
| 25 |
+
input_mask_expanded = attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()
|
| 26 |
+
sum_embeddings = torch.sum(last_hidden_state * input_mask_expanded, 1)
|
| 27 |
+
sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9)
|
| 28 |
+
mean_pooled = sum_embeddings / sum_mask
|
| 29 |
+
|
| 30 |
+
logits = self.classifier(mean_pooled)
|
| 31 |
+
return logits
|
| 32 |
+
|
| 33 |
# -----------------------------
|
| 34 |
# MODEL INITIALIZATION
|
| 35 |
# -----------------------------
|
|
|
|
| 36 |
MODEL_NAME = "desklib/ai-text-detector-v1.01"
|
| 37 |
tokenizer = None
|
| 38 |
model = None
|
|
|
|
| 41 |
def get_model():
|
| 42 |
global tokenizer, model
|
| 43 |
if model is None:
|
| 44 |
+
print(f"Loading Specialized Model: {MODEL_NAME} on {device}")
|
|
|
|
|
|
|
|
|
|
| 45 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_fast=False)
|
| 46 |
|
| 47 |
+
# Load the weights into our custom class
|
| 48 |
+
model = DesklibAIDetectionModel.from_pretrained(
|
| 49 |
+
MODEL_NAME,
|
| 50 |
+
torch_dtype=torch.float32 # Use float16/bfloat16 if your GPU supports it
|
|
|
|
|
|
|
| 51 |
).to(device).eval()
|
| 52 |
return tokenizer, model
|
| 53 |
|
|
|
|
| 54 |
THRESHOLD = 0.81
|
| 55 |
|
| 56 |
# -----------------------------
|
| 57 |
+
# UTILITIES (Sentence Splitting & Structure)
|
| 58 |
# -----------------------------
|
| 59 |
ABBR = ["e.g", "i.e", "mr", "mrs", "ms", "dr", "prof", "vs", "etc", "fig", "al", "jr", "sr", "st", "inc", "ltd", "u.s", "u.k"]
|
| 60 |
ABBR_REGEX = re.compile(r"\b(" + "|".join(map(re.escape, ABBR)) + r")\.", re.IGNORECASE)
|
|
|
|
| 113 |
if not pure_sents:
|
| 114 |
return "—", "—", "<em>No sentences detected.</em>", None
|
| 115 |
|
|
|
|
| 116 |
windows = []
|
| 117 |
for i in range(len(pure_sents)):
|
| 118 |
start = max(0, i - 1)
|
|
|
|
| 120 |
windows.append(" ".join(pure_sents[start:end]))
|
| 121 |
|
| 122 |
inputs = tok(windows, return_tensors="pt", padding=True, truncation=True, max_length=512).to(device)
|
| 123 |
+
logits = mod(inputs['input_ids'], inputs['attention_mask'])
|
| 124 |
+
|
| 125 |
+
# Sigmoid for single-logit probability
|
| 126 |
+
probs = torch.sigmoid(logits).cpu().numpy().flatten().tolist()
|
| 127 |
|
| 128 |
lengths = [len(s.split()) for s in pure_sents]
|
| 129 |
total_words = sum(lengths)
|
| 130 |
weighted_avg = sum(p * l for p, l in zip(probs, lengths)) / total_words if total_words > 0 else 0
|
| 131 |
|
| 132 |
+
# HTML Heatmap
|
|
|
|
|
|
|
| 133 |
highlighted_html = "<div style='font-family: sans-serif; line-height: 1.8;'>"
|
| 134 |
prob_map = {idx: probs[i] for i, idx in enumerate(pure_sents_indices)}
|
| 135 |
|
|
|
|
| 140 |
|
| 141 |
if i in prob_map:
|
| 142 |
score = prob_map[i]
|
|
|
|
|
|
|
| 143 |
if score >= THRESHOLD:
|
| 144 |
+
color, bg = "#b80d0d", "rgba(184, 13, 13, 0.15)" # RED
|
| 145 |
else:
|
| 146 |
+
color, bg = "#11823b", "rgba(17, 130, 59, 0.15)" # GREEN
|
| 147 |
|
| 148 |
highlighted_html += (
|
| 149 |
f"<span style='background:{bg}; padding:2px 4px; border-radius:4px; border-bottom: 2px solid {color};' "
|
|
|
|
| 154 |
highlighted_html += block
|
| 155 |
highlighted_html += "</div>"
|
| 156 |
|
|
|
|
| 157 |
if weighted_avg >= THRESHOLD:
|
| 158 |
label = f"{weighted_avg:.0%} AI Content Detected"
|
| 159 |
display_score = f"{weighted_avg:.1%}"
|
|
|
|
| 169 |
# -----------------------------
|
| 170 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 171 |
gr.Markdown("## 🕵️ AI Detector Pro (Academic Edition)")
|
| 172 |
+
gr.Markdown(f"Using **{MODEL_NAME}** (DeBERTa-v3-Large). Threshold: **{THRESHOLD*100:.0f}%**.")
|
| 173 |
|
| 174 |
with gr.Row():
|
| 175 |
with gr.Column(scale=3):
|