Spaces:
Running
Running
| import gradio as gr | |
| from transformers import AutoTokenizer, AutoModelForSequenceClassification | |
| import torch | |
| import re | |
| # Load more accurate detection model | |
| MODEL = "desklib/ai-text-detector-v1.01" | |
| 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) | |
| ai_score = float(probs[0][1]) | |
| results.append({"sentence": sent, "ai_score": ai_score}) | |
| highlighted = "" | |
| for r in results: | |
| color = get_color(r['ai_score']) | |
| highlighted += f"<span style='background-color:{color}; padding:2px'>{r['sentence']} </span>" | |
| 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 (upgraded to DeBERTa-v3 large)") | |
| gr.Markdown("Paste text: green = human-like, yellow = mixed, 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() | |