Files
encoach_backend/helper/gpt_zero.py
2024-07-25 16:55:42 +01:00

50 lines
1.7 KiB
Python

from logging import getLogger
from typing import Dict, Optional
import requests
class GPTZero:
_GPT_ZERO_ENDPOINT = 'https://api.gptzero.me/v2/predict/text'
def __init__(self, gpt_zero_key: str):
self._logger = getLogger(__name__)
if gpt_zero_key is None:
self._logger.warning('GPT Zero key was not included! Skipping ai detection when grading.')
self._gpt_zero_key = gpt_zero_key
self._header = {
'x-api-key': gpt_zero_key
}
def run_detection(self, text: str):
if self._gpt_zero_key is None:
return None
data = {
'document': text,
'version': '',
'multilingual': False
}
response = requests.post(self._GPT_ZERO_ENDPOINT, headers=self._header, json=data)
if response.status_code != 200:
return None
return self._parse_detection(response.json())
def _parse_detection(self, response: Dict) -> Optional[Dict]:
try:
text_scan = response["documents"][0]
filtered_sentences = [
{
"sentence": item["sentence"],
"highlight_sentence_for_ai": item["highlight_sentence_for_ai"]
}
for item in text_scan["sentences"]
]
return {
"class_probabilities": text_scan["class_probabilities"],
"confidence_category": text_scan["confidence_category"],
"predicted_class": text_scan["predicted_class"],
"sentences": filtered_sentences
}
except Exception as e:
self._logger.error(f'Failed to parse GPT\'s Zero response: {str(e)}')
return None