Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,26 +6,22 @@ import pandas as pd
|
|
| 6 |
import gradio as gr
|
| 7 |
import os
|
| 8 |
|
|
|
|
|
|
|
|
|
|
| 9 |
# -----------------------------
|
| 10 |
# MODEL INITIALIZATION
|
| 11 |
# -----------------------------
|
| 12 |
MODEL_NAME = "desklib/ai-text-detector-v1.01"
|
| 13 |
tokenizer = None
|
| 14 |
model = None
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
if torch.cuda.is_available():
|
| 18 |
-
device = torch.device("cuda")
|
| 19 |
-
dtype = torch.float16 # Half precision for GPU speed/memory
|
| 20 |
-
else:
|
| 21 |
-
device = torch.device("cpu")
|
| 22 |
-
dtype = torch.float32 # Full precision for CPU stability
|
| 23 |
|
| 24 |
def get_model():
|
| 25 |
global tokenizer, model
|
| 26 |
if model is None:
|
| 27 |
-
print(f"Loading
|
| 28 |
-
# Added low_cpu_mem_usage to prevent Build Exit Code 1 (OOM)
|
| 29 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_fast=False)
|
| 30 |
model = AutoModelForSequenceClassification.from_pretrained(
|
| 31 |
MODEL_NAME,
|
|
@@ -73,48 +69,57 @@ def split_preserving_structure(text):
|
|
| 73 |
return final_blocks
|
| 74 |
|
| 75 |
# -----------------------------
|
| 76 |
-
# ANALYSIS
|
| 77 |
# -----------------------------
|
| 78 |
@torch.inference_mode()
|
| 79 |
-
def analyze(text):
|
| 80 |
text = text.strip()
|
| 81 |
if not text:
|
| 82 |
return "—", "—", "<em>Please enter text...</em>", None
|
| 83 |
|
| 84 |
word_count = len(text.split())
|
| 85 |
if word_count < 300:
|
| 86 |
-
warning_msg = f"⚠️ <b>Insufficient Text:</b>
|
| 87 |
-
return "Too Short", "N/A", f"<div style='color: #b80d0d;
|
| 88 |
|
| 89 |
try:
|
| 90 |
tok, mod = get_model()
|
| 91 |
except Exception as e:
|
| 92 |
-
return "ERROR", "0%", f"
|
| 93 |
|
| 94 |
blocks = split_preserving_structure(text)
|
| 95 |
pure_sents_indices = [i for i, b in enumerate(blocks) if b.strip() and not b.startswith("\n")]
|
| 96 |
pure_sents = [blocks[i] for i in pure_sents_indices]
|
| 97 |
|
| 98 |
if not pure_sents:
|
| 99 |
-
return "—", "—", "
|
| 100 |
|
|
|
|
| 101 |
windows = []
|
| 102 |
for i in range(len(pure_sents)):
|
| 103 |
start = max(0, i - 1)
|
| 104 |
end = min(len(pure_sents), i + 2)
|
| 105 |
windows.append(" ".join(pure_sents[start:end]))
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
lengths = [len(s.split()) for s in pure_sents]
|
| 112 |
total_words = sum(lengths)
|
| 113 |
weighted_avg = sum(p * l for p, l in zip(probs, lengths)) / total_words if total_words > 0 else 0
|
| 114 |
|
| 115 |
-
#
|
| 116 |
-
# HTML RECONSTRUCTION
|
| 117 |
-
# -----------------------------
|
| 118 |
highlighted_html = "<div style='font-family: sans-serif; line-height: 1.8;'>"
|
| 119 |
prob_map = {idx: probs[i] for i, idx in enumerate(pure_sents_indices)}
|
| 120 |
|
|
@@ -125,45 +130,37 @@ def analyze(text):
|
|
| 125 |
|
| 126 |
if i in prob_map:
|
| 127 |
score = prob_map[i]
|
| 128 |
-
if score >= THRESHOLD
|
| 129 |
-
color, bg = "#b80d0d", "rgba(184, 13, 13, 0.15)" # RED
|
| 130 |
-
else:
|
| 131 |
-
color, bg = "#11823b", "rgba(17, 130, 59, 0.15)" # GREEN
|
| 132 |
-
|
| 133 |
highlighted_html += (
|
| 134 |
-
f"<span style='background:{bg}; padding:2px 4px; border-radius:4px; border-bottom: 2px solid {color};'
|
| 135 |
-
f"title='Raw Model Score: {score:.4f}'>"
|
| 136 |
f"<b style='color:{color}; font-size: 0.8em;'>[{score:.1%}]</b> {block}</span>"
|
| 137 |
)
|
| 138 |
else:
|
| 139 |
highlighted_html += block
|
| 140 |
|
| 141 |
highlighted_html += "</div>"
|
| 142 |
-
label = f"{weighted_avg:.1%} AI Probability"
|
| 143 |
-
display_score = f"{weighted_avg:.2%}"
|
| 144 |
|
| 145 |
df = pd.DataFrame({"Sentence": pure_sents, "AI Confidence": [f"{p:.2%}" for p in probs]})
|
| 146 |
-
return
|
| 147 |
|
| 148 |
# -----------------------------
|
| 149 |
# GRADIO INTERFACE
|
| 150 |
# -----------------------------
|
| 151 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 152 |
-
gr.Markdown("## 🕵️ AI Detector Pro
|
| 153 |
-
gr.Markdown(f"Visual highlight triggers at **{THRESHOLD*100:.0f}%**.")
|
| 154 |
|
| 155 |
with gr.Row():
|
| 156 |
with gr.Column(scale=3):
|
| 157 |
text_input = gr.Textbox(label="Paste Text", lines=12, placeholder="Min 300 words...")
|
| 158 |
-
run_btn = gr.Button("
|
| 159 |
with gr.Column(scale=1):
|
| 160 |
-
verdict_out = gr.Label(label="
|
| 161 |
-
score_out = gr.Label(label="Exact
|
| 162 |
|
| 163 |
with gr.Tabs():
|
| 164 |
with gr.TabItem("Visual Heatmap"):
|
| 165 |
html_out = gr.HTML()
|
| 166 |
-
with gr.TabItem("
|
| 167 |
table_out = gr.Dataframe(headers=["Sentence", "AI Confidence"], wrap=True)
|
| 168 |
|
| 169 |
run_btn.click(analyze, inputs=text_input, outputs=[verdict_out, score_out, html_out, table_out])
|
|
|
|
| 6 |
import gradio as gr
|
| 7 |
import os
|
| 8 |
|
| 9 |
+
# 1. OPTIMIZE CPU PERFORMANCE
|
| 10 |
+
torch.set_num_threads(os.cpu_count() or 4) # Use all cores
|
| 11 |
+
|
| 12 |
# -----------------------------
|
| 13 |
# MODEL INITIALIZATION
|
| 14 |
# -----------------------------
|
| 15 |
MODEL_NAME = "desklib/ai-text-detector-v1.01"
|
| 16 |
tokenizer = None
|
| 17 |
model = None
|
| 18 |
+
device = torch.device("cpu") # Hardcoding CPU as requested
|
| 19 |
+
dtype = torch.float32
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def get_model():
|
| 22 |
global tokenizer, model
|
| 23 |
if model is None:
|
| 24 |
+
print(f"Loading Model: {MODEL_NAME} on CPU...")
|
|
|
|
| 25 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_fast=False)
|
| 26 |
model = AutoModelForSequenceClassification.from_pretrained(
|
| 27 |
MODEL_NAME,
|
|
|
|
| 69 |
return final_blocks
|
| 70 |
|
| 71 |
# -----------------------------
|
| 72 |
+
# ANALYSIS (With Batching & Progress)
|
| 73 |
# -----------------------------
|
| 74 |
@torch.inference_mode()
|
| 75 |
+
def analyze(text, progress=gr.Progress(track_tqdm=True)):
|
| 76 |
text = text.strip()
|
| 77 |
if not text:
|
| 78 |
return "—", "—", "<em>Please enter text...</em>", None
|
| 79 |
|
| 80 |
word_count = len(text.split())
|
| 81 |
if word_count < 300:
|
| 82 |
+
warning_msg = f"⚠️ <b>Insufficient Text:</b> {word_count} words. Min 300 required."
|
| 83 |
+
return "Too Short", "N/A", f"<div style='color: #b80d0d; border: 1px solid #b80d0d; padding: 10px;'>{warning_msg}</div>", None
|
| 84 |
|
| 85 |
try:
|
| 86 |
tok, mod = get_model()
|
| 87 |
except Exception as e:
|
| 88 |
+
return "ERROR", "0%", f"Load Error: {str(e)}", None
|
| 89 |
|
| 90 |
blocks = split_preserving_structure(text)
|
| 91 |
pure_sents_indices = [i for i, b in enumerate(blocks) if b.strip() and not b.startswith("\n")]
|
| 92 |
pure_sents = [blocks[i] for i in pure_sents_indices]
|
| 93 |
|
| 94 |
if not pure_sents:
|
| 95 |
+
return "—", "—", "No sentences found.", None
|
| 96 |
|
| 97 |
+
# Windows for context
|
| 98 |
windows = []
|
| 99 |
for i in range(len(pure_sents)):
|
| 100 |
start = max(0, i - 1)
|
| 101 |
end = min(len(pure_sents), i + 2)
|
| 102 |
windows.append(" ".join(pure_sents[start:end]))
|
| 103 |
|
| 104 |
+
# 2. BATCHED INFERENCE (Crucial for CPU)
|
| 105 |
+
probs = []
|
| 106 |
+
batch_size = 4 # Small batches so CPU doesn't hang
|
| 107 |
+
|
| 108 |
+
progress(0, desc="Starting Analysis...")
|
| 109 |
+
for i in range(0, len(windows), batch_size):
|
| 110 |
+
batch = windows[i : i + batch_size]
|
| 111 |
+
inputs = tok(batch, return_tensors="pt", padding=True, truncation=True, max_length=512).to(device)
|
| 112 |
+
output = mod(**inputs)
|
| 113 |
+
batch_probs = torch.sigmoid(output.logits).cpu().numpy().flatten().tolist()
|
| 114 |
+
probs.extend(batch_probs)
|
| 115 |
+
progress((i + batch_size) / len(windows), desc=f"Analyzing sentences {i+1}-{min(i+batch_size, len(windows))}...")
|
| 116 |
+
|
| 117 |
+
# Statistics
|
| 118 |
lengths = [len(s.split()) for s in pure_sents]
|
| 119 |
total_words = sum(lengths)
|
| 120 |
weighted_avg = sum(p * l for p, l in zip(probs, lengths)) / total_words if total_words > 0 else 0
|
| 121 |
|
| 122 |
+
# 3. HTML GENERATION
|
|
|
|
|
|
|
| 123 |
highlighted_html = "<div style='font-family: sans-serif; line-height: 1.8;'>"
|
| 124 |
prob_map = {idx: probs[i] for i, idx in enumerate(pure_sents_indices)}
|
| 125 |
|
|
|
|
| 130 |
|
| 131 |
if i in prob_map:
|
| 132 |
score = prob_map[i]
|
| 133 |
+
color, bg = ("#b80d0d", "rgba(184, 13, 13, 0.15)") if score >= THRESHOLD else ("#11823b", "rgba(17, 130, 59, 0.15)")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
highlighted_html += (
|
| 135 |
+
f"<span style='background:{bg}; padding:2px 4px; border-radius:4px; border-bottom: 2px solid {color};'>"
|
|
|
|
| 136 |
f"<b style='color:{color}; font-size: 0.8em;'>[{score:.1%}]</b> {block}</span>"
|
| 137 |
)
|
| 138 |
else:
|
| 139 |
highlighted_html += block
|
| 140 |
|
| 141 |
highlighted_html += "</div>"
|
|
|
|
|
|
|
| 142 |
|
| 143 |
df = pd.DataFrame({"Sentence": pure_sents, "AI Confidence": [f"{p:.2%}" for p in probs]})
|
| 144 |
+
return f"{weighted_avg:.1%} AI Probability", f"{weighted_avg:.2%}", highlighted_html, df
|
| 145 |
|
| 146 |
# -----------------------------
|
| 147 |
# GRADIO INTERFACE
|
| 148 |
# -----------------------------
|
| 149 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 150 |
+
gr.Markdown("## 🕵️ AI Detector Pro (CPU Optimized)")
|
|
|
|
| 151 |
|
| 152 |
with gr.Row():
|
| 153 |
with gr.Column(scale=3):
|
| 154 |
text_input = gr.Textbox(label="Paste Text", lines=12, placeholder="Min 300 words...")
|
| 155 |
+
run_btn = gr.Button("Run Analysis", variant="primary")
|
| 156 |
with gr.Column(scale=1):
|
| 157 |
+
verdict_out = gr.Label(label="Weighted Verdict")
|
| 158 |
+
score_out = gr.Label(label="Exact Score")
|
| 159 |
|
| 160 |
with gr.Tabs():
|
| 161 |
with gr.TabItem("Visual Heatmap"):
|
| 162 |
html_out = gr.HTML()
|
| 163 |
+
with gr.TabItem("Detailed Breakdown"):
|
| 164 |
table_out = gr.Dataframe(headers=["Sentence", "AI Confidence"], wrap=True)
|
| 165 |
|
| 166 |
run_btn.click(analyze, inputs=text_input, outputs=[verdict_out, score_out, html_out, table_out])
|