AIDetector / app.py
VictorM-Coder's picture
Update app.py
9f95d83 verified
raw
history blame
1.93 kB
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
import re
# Stable AI detection model
MODEL = "Hello-SimpleAI/HC3-DeBERTa"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForSequenceClassification.from_pretrained(MODEL)
def get_color(ai_score):
red = int(ai_score * 255)
green = int((1 - ai_score) * 255)
return f"rgb({red},{green},0)"
def detect_ai(text):
sentences = re.split(r'(?<=[.!?]) +', text)
results = []
for sent in sentences:
if not sent.strip():
continue
inputs = tokenizer(sent, return_tensors="pt", truncation=True, max_length=512)
with torch.no_grad():
outputs = model(**inputs)
probs = torch.softmax(outputs.logits, dim=1)
# HC3 model: [0] = human, [1] = ChatGPT
ai_score = float(probs[0][1])
results.append({"sentence": sent, "ai_score": ai_score})
# Highlight
highlighted = ""
for r in results:
color = get_color(r['ai_score'])
highlighted += f"<span style='background-color:{color}; padding:2px'>{r['sentence']} </span>"
# Total AI probability
if results:
avg_ai = sum(r['ai_score'] for r in results) / len(results)
total_percent = round(avg_ai * 100, 2)
highlighted += f"<p><b>Total AI Probability: {total_percent}%</b></p>"
else:
total_percent = 0.0
return highlighted, {"sentences": results, "total_ai_percent": total_percent}
with gr.Blocks() as demo:
gr.Markdown("## 🤖 AI Detector (HC3 DeBERTa)")
gr.Markdown("Paste text: green = human-like, red = AI-like")
input_text = gr.Textbox(lines=8, placeholder="Enter text here…")
output_html = gr.HTML()
output_json = gr.JSON()
run_btn = gr.Button("Detect AI")
run_btn.click(detect_ai, inputs=input_text, outputs=[output_html, output_json])
demo.launch()