Spaces:
Running
Running
eheguy commited on
Commit ·
8194c3e
1
Parent(s): 4516e1c
Swap to ChatGPT-specific detector model
Browse files- detector.py +34 -22
detector.py
CHANGED
|
@@ -1,28 +1,40 @@
|
|
|
|
|
| 1 |
from transformers import pipeline
|
| 2 |
|
| 3 |
-
# Cache the
|
| 4 |
-
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
"text-classification",
|
| 12 |
-
model="
|
|
|
|
| 13 |
)
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
else:
|
| 28 |
-
return 1
|
|
|
|
| 1 |
+
import torch
|
| 2 |
from transformers import pipeline
|
| 3 |
|
| 4 |
+
# Cache the pipeline at module level — load once, reuse forever
|
| 5 |
+
_pipeline = None
|
| 6 |
|
| 7 |
+
|
| 8 |
+
def _get_pipeline():
|
| 9 |
+
global _pipeline
|
| 10 |
+
if _pipeline is None:
|
| 11 |
+
_pipeline = pipeline(
|
| 12 |
"text-classification",
|
| 13 |
+
model="Hello-SimpleAI/chatgpt-detector-roberta",
|
| 14 |
+
device=0 if torch.cuda.is_available() else -1,
|
| 15 |
)
|
| 16 |
+
return _pipeline
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_ai_score(text: str) -> float:
|
| 20 |
+
"""
|
| 21 |
+
Returns a float between 0.0 and 1.0 representing the probability
|
| 22 |
+
that the text was AI-generated.
|
| 23 |
+
1.0 = definitely AI
|
| 24 |
+
0.0 = definitely human
|
| 25 |
+
"""
|
| 26 |
+
# Model has 512 token limit — truncate to be safe
|
| 27 |
+
truncated = text[:512]
|
| 28 |
+
|
| 29 |
+
result = _get_pipeline()(truncated)[0]
|
| 30 |
+
|
| 31 |
+
label = result["label"].upper()
|
| 32 |
+
score = result["score"]
|
| 33 |
+
|
| 34 |
+
# This model returns:
|
| 35 |
+
# "ChatGPT" label = AI-generated
|
| 36 |
+
# "Human" label = human-written
|
| 37 |
+
if label == "CHATGPT":
|
| 38 |
+
return round(score, 4)
|
| 39 |
else:
|
| 40 |
+
return round(1 - score, 4)
|