File size: 16,895 Bytes
bfe41f2
c57c848
b53833d
 
55cbf6a
e99c594
c967ac9
bfe41f2
 
e99c594
be9e2ba
c57c848
be9e2ba
 
 
dad3685
be9e2ba
 
 
 
 
dad3685
be9e2ba
 
dad3685
c57c848
be9e2ba
 
 
 
c57c848
 
 
a2b0083
c57c848
a2b0083
c57c848
 
 
 
 
 
 
e99c594
bfe41f2
e99c594
 
a57714d
be9e2ba
 
a57714d
e99c594
be9e2ba
 
 
 
e99c594
a57714d
c57c848
a57714d
e09232a
bfe41f2
04b9742
f97e9a9
e99c594
f97e9a9
ed23447
 
 
 
bfe41f2
ed23447
 
 
bfe41f2
ed23447
 
f97e9a9
 
 
 
72241b4
f97e9a9
 
 
 
 
 
470f102
f97e9a9
 
 
470f102
724a60b
f97e9a9
18e11fc
 
25dea08
db8f51d
25dea08
bfe41f2
 
0fd14a7
da1ebea
bfe41f2
2160e26
 
b55fefb
 
2160e26
 
 
 
a57714d
 
7ea8ec5
bfe41f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
911b4eb
bfe41f2
 
 
 
 
 
 
c57c848
911b4eb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367

import gradio as gr
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
import re
from tokenizers import normalizers
from tokenizers.normalizers import Sequence, Replace, Strip, NFKC
from tokenizers import Regex


device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

model1_path = "modernbert.bin"
model2_path = "https://huggingface.co/mihalykiss/modernbert_2/resolve/main/Model_groups_3class_seed12"
model3_path = "https://huggingface.co/mihalykiss/modernbert_2/resolve/main/Model_groups_3class_seed22"

tokenizer = AutoTokenizer.from_pretrained("answerdotai/ModernBERT-base")

model_1 = AutoModelForSequenceClassification.from_pretrained("answerdotai/ModernBERT-base", num_labels=41)
model_1.load_state_dict(torch.load(model1_path, map_location=device))
model_1.to(device).eval()

model_2 = AutoModelForSequenceClassification.from_pretrained("answerdotai/ModernBERT-base", num_labels=41)
model_2.load_state_dict(torch.hub.load_state_dict_from_url(model2_path, map_location=device))
model_2.to(device).eval()

model_3 = AutoModelForSequenceClassification.from_pretrained("answerdotai/ModernBERT-base", num_labels=41)
model_3.load_state_dict(torch.hub.load_state_dict_from_url(model3_path, map_location=device))
model_3.to(device).eval()

label_mapping = {
    0: '13B', 1: '30B', 2: '65B', 3: '7B', 4: 'GLM130B', 5: 'bloom_7b',
    6: 'bloomz', 7: 'cohere', 8: 'davinci', 9: 'dolly', 10: 'dolly-v2-12b',
    11: 'flan_t5_base', 12: 'flan_t5_large', 13: 'flan_t5_small',
    14: 'flan_t5_xl', 15: 'flan_t5_xxl', 16: 'gemma-7b-it', 17: 'gemma2-9b-it',
    18: 'gpt-3.5-turbo', 19: 'gpt-35', 20: 'gpt4', 21: 'gpt4o',
    22: 'gpt_j', 23: 'gpt_neox', 24: 'human', 25: 'llama3-70b', 26: 'llama3-8b',
    27: 'mixtral-8x7b', 28: 'opt_1.3b', 29: 'opt_125m', 30: 'opt_13b',
    31: 'opt_2.7b', 32: 'opt_30b', 33: 'opt_350m', 34: 'opt_6.7b',
    35: 'opt_iml_30b', 36: 'opt_iml_max_1.3b', 37: 't0_11b', 38: 't0_3b',
    39: 'text-davinci-002', 40: 'text-davinci-003'
}

def clean_text(text: str) -> str:
    text = re.sub(r'\s{2,}', ' ', text)
    text = re.sub(r'\s+([,.;:?!])', r'\1', text)
    return text

newline_to_space  = Replace(Regex(r'\s*\n\s*'), " ")
join_hyphen_break = Replace(Regex(r'(\w+)[--]\s*\n\s*(\w+)'), r"\1\2")

tokenizer.backend_tokenizer.normalizer = Sequence([
    tokenizer.backend_tokenizer.normalizer,
    join_hyphen_break,
    newline_to_space,
    Strip()
])

def classify_text(text):
    cleaned_text = clean_text(text)
    if not text.strip():
        result_message = (f"---- \n")
        return result_message

    inputs = tokenizer(cleaned_text, return_tensors="pt", truncation=True, padding=True).to(device)

    with torch.no_grad():
        logits_1 = model_1(**inputs).logits
        logits_2 = model_2(**inputs).logits
        logits_3 = model_3(**inputs).logits

        softmax_1 = torch.softmax(logits_1, dim=1)
        softmax_2 = torch.softmax(logits_2, dim=1)
        softmax_3 = torch.softmax(logits_3, dim=1)

        averaged_probabilities = (softmax_1 + softmax_2 + softmax_3) / 3
        probabilities = averaged_probabilities[0]

    ai_probs = probabilities.clone()
    ai_probs[24] = 0
    ai_total_prob = ai_probs.sum().item() * 100
    human_prob = 100 - ai_total_prob

    ai_argmax_index = torch.argmax(ai_probs).item()
    ai_argmax_model = label_mapping[ai_argmax_index]

    if human_prob > ai_total_prob:
        result_message = (
            f"**The text is** <span class='highlight-human'>**{human_prob:.2f}%** likely <b>Human written</b>.</span>"
        )
    else:
        result_message = (
            f"**The text is** <span class='highlight-ai'>**{ai_total_prob:.2f}%** likely <b>AI generated</b>.</span>\n\n"
            f"**Identified LLM: {ai_argmax_model}**"
        )
    return result_message

title = "AI Text Detector"

description = """
This tool uses the <b>ModernBERT</b> model to identify whether a given text was written by a human or generated by AI.
It uses a soft-voting ensemble of <b>three</b> models for improved accuracy.
"""

bottom_text = "Built by <b>SzegedAI</b> • ModernBERT Ensemble • Works best with longer texts"

AI_texts = [
"Camels are remarkable desert animals known for their unique adaptations to harsh, arid environments. Native to the Middle East, North Africa, and parts of Asia, camels have been essential to human life for centuries, serving as a mode of transportation, a source of food, and even a symbol of endurance and survival. There are two primary species of camels: the dromedary camel, which has a single hump and is commonly found in the Middle East and North Africa, and the Bactrian camel, which has two humps and is native to Central Asia. Their humps store fat, not water, as commonly believed, allowing them to survive long periods without food by metabolizing the stored fat for energy. Camels are highly adapted to desert life. They can go for weeks without water, and when they do drink, they can consume up to 40 gallons in one sitting. Their thick eyelashes, sealable nostrils, and wide, padded feet protect them from sand and help them walk easily on loose desert terrain.",
"Wines are a fascinating reflection of culture, history, and craftsmanship. They embody a rich diversity shaped by the land, climate, and traditions where they are produced. From the bold reds of Bordeaux to the crisp whites of New Zealand, each bottle tells a unique story. What makes wine so special is its ability to connect people. Whether shared at a family dinner, a celebratory event, or a quiet evening with friends, wine enhances experiences and brings people together. The variety of flavors and aromas, influenced by grape type, fermentation techniques, and aging processes, make wine tasting a complex yet rewarding journey for the senses.",
"I find artificial intelligence (AI) to be one of the most transformative and fascinating technologies of our time. Its potential spans a wide range of applications, from automating mundane tasks to revolutionizing industries like healthcare, education, and entertainment. AI has already made significant contributions in fields like language processing, image recognition, and decision-making systems, enabling innovations that were once purely science fiction. However, as powerful as AI can be, it also brings challenges and responsibilities. Ethical considerations, such as bias in data, transparency, and the potential for misuse, need to be carefully addressed to ensure fairness and accountability. The rise of generative AI has also sparked debates about creativity, originality, and intellectual property, making it essential to strike a balance between technological advancement and respecting human contributions."
]

Human_texts = [
"The present book is intended as a text in basic mathematics. As such, it can have multiple use: for a one-year course in the high schools during the third or fourth year (if possible the third, so that calculus can be taken during the fourth year); for a complementary reference in earlier high school grades (elementary algebra and geometry are covered); for a one-semester course at the college level, to review or to get a firm foundation in the basic mathematics necessary to go ahead in calculus, linear algebra, or other topics. Years ago, the colleges used to give courses in “ college algebra” and other subjects which should have been covered in high school. More recently, such courses have been thought unnecessary, but some experiences I have had show that they are just as necessary as ever. What is happening is that thecolleges are getting a wide variety of students from high schools, ranging from exceedingly well-prepared ones who have had a good first course in calculus, down to very poorly prepared ones.",
"Fats are rich in energy, build body cells, support brain development of infants, help body processes, and facilitate the absorption and use of fat-soluble vitamins A, D, E, and K. The major component of lipids is glycerol and fatty acids. According to chemical properties, fatty acids can be divided into saturated and unsaturated fatty acids. Generally lipids containing saturated fatty acids are solid at room temperature and include animal fats (butter, lard, tallow, ghee) and tropical oils (palm,coconut, palm kernel). Saturated fats increase the risk of heart disease.",
"To make BERT handle a variety of down-stream tasks, our input representation is able to unambiguously represent both a single sentence and a pair of sentences (e.g., h Question, Answeri) in one token sequence. Throughout this work, a “sentence” can be an arbitrary span of contiguous text, rather than an actual linguistic sentence. A “sequence” refers to the input token sequence to BERT, which may be a single sentence or two sentences packed together. We use WordPiece embeddings (Wu et al., 2016) with a 30,000 token vocabulary. The first token of every sequence is always a special classification token ([CLS]). The final hidden state corresponding to this token is used as the aggregate sequence representation for classification tasks. Sentence pairs are packed together into a single sequence."]



css_template = r"""
/* Typography */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
:root {
  --radius: 14px;
  --ring: 1px solid rgba(99,102,241,0.35); /* indigo glow */
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg: #0B0F17;
    --panel: #0F1524;
    --panel-2: #121A2B;
    --text: #E7EAF3;
    --muted: #AAB2C5;
    --brand: #6E56CF;  /* violet */
    --brand-2: #06B6D4; /* cyan accent */
    --ok: #22C55E;
    --warn: #F59E0B;
    --danger: #EF4444;
    --shadow: 0 10px 30px rgba(110,86,207,0.15);
    --card-border: 1px solid rgba(255,255,255,0.06);
    --gradient: linear-gradient(135deg, rgba(110,86,207,0.22), rgba(6,182,212,0.22));
    --chip-bg: rgba(110,86,207,0.16);
  }
}

@media (prefers-color-scheme: light) {
  :root {
    --bg: #FFFFFF;
    --panel: #F7F8FB;
    --panel-2: #FFFFFF;
    --text: #0B0F17;
    --muted: #4B5563;
    --brand: #6E56CF;
    --brand-2: #0891B2;
    --ok: #16A34A;
    --warn: #D97706;
    --danger: #DC2626;
    --shadow: 0 10px 26px rgba(110,86,207,0.12);
    --card-border: 1px solid rgba(14,20,34,0.08);
    --gradient: linear-gradient(135deg, rgba(110,86,207,0.15), rgba(6,182,212,0.15));
    --chip-bg: rgba(110,86,207,0.10);
  }
}

body, .gradio-container {
  background: radial-gradient(1200px 600px at 10% -10%, rgba(110,86,207,0.14), transparent 40%),
              radial-gradient(900px 500px at 90% -20%, rgba(6,182,212,0.12), transparent 40%),
              var(--bg) !important;
  color: var(--text);
  font-family: 'Inter', system-ui, -apple-system, Segoe UI, Roboto, 'Helvetica Neue', Arial, sans-serif !important;
}

.header-card {
  background: var(--panel-2);
  border: var(--card-border);
  border-radius: var(--radius);
  padding: 18px 20px;
  box-shadow: var(--shadow);
  display: flex;
  align-items: center;
  gap: 14px;
}
.logo-dot {
  width: 14px; height: 14px; border-radius: 50%;
  background: radial-gradient(circle at 30% 30%, var(--brand), var(--brand-2));
  box-shadow: 0 0 0 6px rgba(110,86,207,0.08), 0 0 24px rgba(6,182,212,0.25);
}
.header-title {
  font-weight: 700; letter-spacing: 0.2px; font-size: 18px;
}
.header-sub {
  margin-left: auto; font-size: 12px; color: var(--muted);
}

.card {
  background: var(--panel-2);
  border: var(--card-border);
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: 18px;
}

#text_input_box textarea {
  background: var(--panel);
  border: var(--card-border);
  border-radius: calc(var(--radius) - 2px);
  box-shadow: inset 0 0 0 999px transparent, var(--shadow);
  padding: 16px 14px;
  font-size: 15px;
  line-height: 1.5;
  color: var(--text);
}
#text_input_box textarea:focus {
  outline: none;
  border: 1px solid rgba(110,86,207,0.65);
  box-shadow: 0 0 0 4px rgba(110,86,207,0.20);
}

.controls-row {
  display: flex; align-items: center; justify-content: space-between;
  margin-top: 10px; gap: 10px;
}
.chips {
  display: flex; gap: 6px; flex-wrap: wrap;
}
.chip {
  background: var(--chip-bg);
  border: 1px solid rgba(110,86,207,0.25);
  padding: 6px 10px; border-radius: 999px;
  font-size: 12px; color: var(--text);
}

button.primary, .primary button, .btn-primary {
  background: linear-gradient(135deg, var(--brand), var(--brand-2));
  border: none !important;
  color: white !important;
  border-radius: 10px !important;
  padding: 10px 14px !important;
  box-shadow: 0 8px 24px rgba(110,86,207,0.25);
}
button.primary:hover, .primary button:hover, .btn-primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 10px 28px rgba(6,182,212,0.25);
}

/* Result */
#result_output_box {
  background: var(--panel);
  border: var(--card-border);
  border-radius: var(--radius);
  padding: 16px;
  font-size: 16px;
}
.highlight-human {
  color: var(--ok);
  background: rgba(34,197,94,0.12);
  padding: 2px 6px; border-radius: 8px;
}
.highlight-ai {
  color: var(--danger);
  background: rgba(239,68,68,0.12);
  padding: 2px 6px; border-radius: 8px;
}


.tabs-wrap {
  background: var(--panel-2);
  border: var(--card-border);
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: 10px;
}
.examples-note {
  font-size: 12px; color: var(--muted); margin-top: 8px;
}


.footer {
  margin-top: 8px; text-align: center; color: var(--muted); font-size: 12px;
}

.container-narrow {
  max-width: 980px; margin: 0 auto;
}
.section-gap { margin-top: 14px; }


.form.svelte-633qhp, .block.svelte-11xb1hd { background: transparent !important; box-shadow: none !important; border: none !important; }
"""


def text_stats(s: str):

    chars = len(s or "")
    words = len((s or "").split())
    return f"{chars} chars • {words} words"

with gr.Blocks(css=css_template, fill_height=True, theme=gr.themes.Base()) as iface:
    with gr.Column(elem_classes=["container-narrow"]):

        with gr.Row(elem_classes=["header-card"]):
            gr.HTML("<div class='logo-dot'></div>")
            gr.HTML(f"<div class='header-title'>{title}</div>")
            gr.HTML("<div class='header-sub'>ModernBERT • 3-model ensemble</div>")

        with gr.Column(elem_classes=["section-gap", "card"]):
            gr.Markdown(
                f"""
<span style="font-size:16px">{description}</span>
<div class="chips" style="margin-top:10px">
  <div class="chip">ModernBERT-base</div>
  <div class="chip">Ensemble (x3)</div>
  <div class="chip">Multiclass source ID</div>
  <div class="chip">Human vs AI decision</div>
</div>
                """,
                elem_id="desc_top"
            )

        with gr.Column(elem_classes=["section-gap"]):
            with gr.Row():
                with gr.Column(scale=6, elem_classes=["card"]):
                    text_input = gr.Textbox(
                        label="Paste text",
                        placeholder="Paste or type your content here…",
                        lines=10,
                        elem_id="text_input_box"
                    )

                    with gr.Row(elem_classes=["controls-row"]):
                        stats_md = gr.Markdown("0 chars • 0 words")
                        with gr.Row():
                            clear_btn = gr.Button("Clear", elem_classes=["btn-primary"], variant="secondary")
                            copy_btn = gr.Button("Copy Result", elem_classes=["btn-primary"], variant="secondary")

                with gr.Column(scale=4, elem_classes=["card"]):
                    gr.Markdown("### Result")
                    result_output = gr.Markdown("", elem_id="result_output_box")

        with gr.Column(elem_classes=["section-gap", "tabs-wrap"]):
            with gr.Tabs():
                with gr.Tab("AI text examples"):
                    gr.Examples(AI_texts, inputs=text_input, examples_per_page=3)
                with gr.Tab("Human text examples"):
                    gr.Examples(Human_texts, inputs=text_input, examples_per_page=3)
            gr.Markdown(
                "Use an example to prefill the textbox, then edit as needed.",
                elem_classes=["examples-note"]
            )

        gr.Markdown(
            f"<div class='footer'>{bottom_text} • <a href='https://aclanthology.org/2025.genaidetect-1.15/' target='_blank'>Paper</a></div>"
        )

    def _stats_update(s): return text_stats(s)
    text_input.change(classify_text, inputs=text_input, outputs=result_output)
    text_input.change(_stats_update, inputs=text_input, outputs=stats_md)
    clear_btn.click(fn=lambda: ("", "0 chars • 0 words", ""), outputs=[text_input, stats_md, result_output])


    def _noop(s): return s
    hidden_copy_src = gr.Textbox(visible=False)
    copy_btn.click(_noop, inputs=result_output, outputs=hidden_copy_src)

iface.launch(share=True)