iyadalagha commited on
Commit
8134ad6
·
1 Parent(s): 778b6ac

handle both ar and eng

Browse files
Files changed (2) hide show
  1. Dockerfile +21 -10
  2. app.py +209 -54
Dockerfile CHANGED
@@ -1,17 +1,28 @@
1
- FROM python:3.11-slim
 
2
 
 
3
  WORKDIR /app
4
 
5
- COPY requirements.txt .
 
 
 
 
 
 
 
 
 
 
 
6
  RUN pip install --no-cache-dir -r requirements.txt
7
 
8
- # Create Hugging Face cache directory with permissions
9
- ENV HF_HOME=/app/.cache
10
- ENV TRANSFORMERS_CACHE=/app/.cache
11
- ENV HF_HUB_CACHE=/app/.cache
12
- RUN mkdir -p /app/.cache && chmod -R 777 /app/.cache
13
 
14
- COPY . .
 
15
 
16
- EXPOSE 7860
17
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
1
+ # Use Python 3.9 as the base image
2
+ FROM python:3.9
3
 
4
+ # Set working directory in the container
5
  WORKDIR /app
6
 
7
+ # Create a non-root user and set permissions
8
+ RUN useradd -m myuser && chown -R myuser:myuser /app
9
+ USER myuser
10
+
11
+ # Set Hugging Face cache directory
12
+ ENV HF_HOME=/app/.cache/huggingface
13
+
14
+ # Update PATH for uvicorn
15
+ ENV PATH="/home/myuser/.local/bin:${PATH}"
16
+
17
+ # Copy requirements.txt and install dependencies
18
+ COPY --chown=myuser:myuser requirements.txt .
19
  RUN pip install --no-cache-dir -r requirements.txt
20
 
21
+ # Clear cache and pre-download models
22
+ RUN rm -rf /app/.cache/huggingface/* && python -c "from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM; pipeline('text-classification', model='Hello-SimpleAI/chatgpt-detector-roberta'); pipeline('text-classification', model='openai-community/roberta-large-openai-detector'); pipeline('text-classification', model='sabaridsnfuji/arabic-ai-text-detector'); AutoTokenizer.from_pretrained('gpt2'); AutoModelForCausalLM.from_pretrained('gpt2'); AutoTokenizer.from_pretrained('aubmindlab/araGPT2'); AutoModelForCausalLM.from_pretrained('aubmindlab/araGPT2')"
 
 
 
23
 
24
+ # Copy the application code
25
+ COPY --chown=myuser:myuser . .
26
 
27
+ # Run the FastAPI app with Uvicorn
28
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py CHANGED
@@ -1,35 +1,82 @@
1
- from fastapi import FastAPI
2
- from pydantic import BaseModel
3
- from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForCausalLM
4
  import torch
5
- import math
 
 
 
6
 
7
- app = FastAPI(title="Improved AI Text Detector")
8
-
9
- # 1. Classifier model (better than akshayvkt)
10
- clf_model_name = "Hello-SimpleAI/chatgpt-detector-roberta"
11
- clf_tokenizer = AutoTokenizer.from_pretrained(clf_model_name)
12
- clf_model = AutoModelForSequenceClassification.from_pretrained(clf_model_name)
13
-
14
- # 2. Perplexity model (GPT-2)
15
- ppl_model_name = "gpt2"
16
- ppl_tokenizer = AutoTokenizer.from_pretrained(ppl_model_name)
17
- ppl_model = AutoModelForCausalLM.from_pretrained(ppl_model_name)
18
 
19
- class InputText(BaseModel):
20
- text: str
21
 
22
- def get_classifier_score(text: str) -> float:
23
- inputs = clf_tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
24
- with torch.no_grad():
25
- outputs = clf_model(**inputs)
26
- probs = torch.softmax(outputs.logits, dim=-1)
27
- ai_prob = probs[0][1].item() # label 1 = AI
28
- return ai_prob
29
-
30
- def get_perplexity(text: str) -> float:
31
- encodings = ppl_tokenizer(text, return_tensors="pt")
32
- max_length = ppl_model.config.n_positions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  stride = 512
34
  seq_len = encodings.input_ids.size(1)
35
 
@@ -38,12 +85,12 @@ def get_perplexity(text: str) -> float:
38
  for begin_loc in range(0, seq_len, stride):
39
  end_loc = min(begin_loc + stride, seq_len)
40
  trg_len = end_loc - prev_end_loc
41
- input_ids = encodings.input_ids[:, begin_loc:end_loc]
42
  target_ids = input_ids.clone()
43
  target_ids[:, :-trg_len] = -100
44
 
45
  with torch.no_grad():
46
- outputs = ppl_model(input_ids, labels=target_ids)
47
  neg_log_likelihood = outputs.loss * trg_len
48
 
49
  nlls.append(neg_log_likelihood)
@@ -52,30 +99,138 @@ def get_perplexity(text: str) -> float:
52
  if end_loc == seq_len:
53
  break
54
 
55
- ppl = torch.exp(torch.stack(nlls).sum() / end_loc)
56
- return ppl.item()
57
-
58
- @app.post("/detect")
59
- def detect(input_text: InputText):
60
- text = input_text.text.strip()
61
-
62
- # Run classifier
63
- clf_score = get_classifier_score(text)
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- # Run perplexity
66
- ppl = get_perplexity(text)
 
 
 
 
 
 
 
67
 
68
- # Decision rule: combine both
69
- # Lower perplexity (<50) + high classifier_score (>0.7) = AI
70
- if clf_score > 0.6 and ppl < 70:
71
- final = "AI"
72
- elif clf_score < 0.4 and ppl > 60:
73
- final = "Human"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  else:
75
- final = "Uncertain"
76
-
77
- return {
78
- "classifier_score": round(clf_score, 4),
79
- "perplexity": round(ppl, 2),
80
- "final_label": final
81
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel, validator
3
+ import re
4
  import torch
5
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForCausalLM, pipeline
6
+ from collections import Counter
7
+ import logging
8
+ import numpy as np
9
 
10
+ # Configure logging with more detail
11
+ logging.basicConfig(filename="predictions.log", level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
 
 
 
 
 
 
 
 
 
12
 
13
+ app = FastAPI(title="Improved AI Text Detector")
 
14
 
15
+ # Enable GPU if available, else use CPU
16
+ device = 0 if torch.cuda.is_available() else -1
17
+ torch.manual_seed(42)
18
+
19
+ # Load classifier models
20
+ english_detectors = [
21
+ pipeline("text-classification", model="Hello-SimpleAI/chatgpt-detector-roberta", device=device, truncation=True, max_length=512),
22
+ pipeline("text-classification", model="openai-community/roberta-large-openai-detector", device=device, truncation=True, max_length=512)
23
+ ]
24
+ arabic_detector = pipeline("text-classification", model="sabaridsnfuji/arabic-ai-text-detector", device=device, truncation=True, max_length=512)
25
+
26
+ # Load perplexity models
27
+ ppl_english = {
28
+ "tokenizer": AutoTokenizer.from_pretrained("gpt2"),
29
+ "model": AutoModelForCausalLM.from_pretrained("gpt2").to(device)
30
+ }
31
+ ppl_arabic = {
32
+ "tokenizer": AutoTokenizer.from_pretrained("aubmindlab/araGPT2"),
33
+ "model": AutoModelForCausalLM.from_pretrained("aubmindlab/araGPT2").to(device)
34
+ }
35
+
36
+ def detect_language(text: str) -> str:
37
+ """Detect if text is Arabic or English based on Unicode character ranges."""
38
+ arabic_chars = len(re.findall(r'[\u0600-\u06FF]', text))
39
+ latin_chars = len(re.findall(r'[A-Za-z]', text))
40
+ total_chars = arabic_chars + latin_chars
41
+ if total_chars == 0:
42
+ return 'en'
43
+ arabic_ratio = arabic_chars / total_chars
44
+ return 'ar' if arabic_ratio > 0.5 else 'en'
45
+
46
+ def calculate_burstiness(text: str) -> float:
47
+ """Calculate burstiness (std/mean of sentence lengths) to bias toward human text."""
48
+ sentences = re.split(r'[.!?]', text)
49
+ lengths = [len(s.split()) for s in sentences if s]
50
+ return np.std(lengths) / (np.mean(lengths) + 1e-6) if lengths else 0
51
+
52
+ def calculate_ttr(text: str) -> float:
53
+ """Calculate type-token ratio (lexical diversity) to bias toward human text."""
54
+ words = text.split()
55
+ if not words:
56
+ return 0
57
+ unique_words = len(set(words))
58
+ total_words = len(words)
59
+ return unique_words / total_words
60
+
61
+ def clean_text(text: str, language: str) -> str:
62
+ """Clean text by removing special characters and normalizing spaces. Skip lowercase for Arabic."""
63
+ text = re.sub(r'\s+', ' ', text)
64
+ text = re.sub(r'[^\w\s.,!?]', '', text)
65
+ text = text.strip()
66
+ if language == 'en':
67
+ text = text.lower()
68
+ return text
69
+
70
+ def get_classifier_score(text: str, detector) -> float:
71
+ """Get classifier probability for AI label."""
72
+ result = detector(text, truncation=True, max_length=512)[0]
73
+ score = result['score']
74
+ return score if result['label'] in ['AI', 'Fake'] else 1 - score
75
+
76
+ def get_perplexity(text: str, tokenizer, model) -> float:
77
+ """Calculate perplexity using a language model."""
78
+ encodings = tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(device)
79
+ max_length = model.config.n_positions
80
  stride = 512
81
  seq_len = encodings.input_ids.size(1)
82
 
 
85
  for begin_loc in range(0, seq_len, stride):
86
  end_loc = min(begin_loc + stride, seq_len)
87
  trg_len = end_loc - prev_end_loc
88
+ input_ids = encodings.input_ids[:, begin_loc:end_loc].to(device)
89
  target_ids = input_ids.clone()
90
  target_ids[:, :-trg_len] = -100
91
 
92
  with torch.no_grad():
93
+ outputs = model(input_ids, labels=target_ids)
94
  neg_log_likelihood = outputs.loss * trg_len
95
 
96
  nlls.append(neg_log_likelihood)
 
99
  if end_loc == seq_len:
100
  break
101
 
102
+ ppl = torch.exp(torch.stack(nlls).sum() / end_loc if nlls else torch.tensor(0)).item()
103
+ return ppl
104
+
105
+ def split_text(text: str, max_chars: int = 5000) -> list:
106
+ """Split text into chunks of max_chars, preserving sentence boundaries."""
107
+ sentences = re.split(r'(?<=[.!?])\s+', text)
108
+ chunks = []
109
+ current_chunk = ""
110
+ for sentence in sentences:
111
+ if len(current_chunk) + len(sentence) <= max_chars:
112
+ current_chunk += sentence + " "
113
+ else:
114
+ if current_chunk:
115
+ chunks.append(current_chunk.strip())
116
+ current_chunk = sentence + " "
117
+ if current_chunk:
118
+ chunks.append(current_chunk.strip())
119
+ return chunks
120
+
121
+ class TextInput(BaseModel):
122
+ text: str
123
 
124
+ @validator("text")
125
+ def validate_text(cls, value):
126
+ """Validate input text for minimum length and content."""
127
+ word_count = len(value.split())
128
+ if word_count < 50:
129
+ raise ValueError(f"Text too short ({word_count} words). Minimum 50 words required.")
130
+ if not re.search(r'[\w]', value):
131
+ raise ValueError("Text must contain alphabetic characters.")
132
+ return value
133
 
134
+ @app.post("/detect")
135
+ def detect(input_text: TextInput):
136
+ detected_lang = detect_language(input_text.text)
137
+ note_lang = f"Detected language: {'Arabic' if detected_lang == 'ar' else 'English'}"
138
+ cleaned_text = clean_text(input_text.text, detected_lang)
139
+ burstiness = calculate_burstiness(cleaned_text)
140
+ ttr = calculate_ttr(cleaned_text)
141
+ note_features = f"Burstiness: {burstiness:.2f} (high suggests human), TTR: {ttr:.2f} (low suggests human)"
142
+
143
+ # Select appropriate models
144
+ detectors = english_detectors if detected_lang == 'en' else [arabic_detector]
145
+ ppl_model = ppl_english if detected_lang == 'en' else ppl_arabic
146
+ is_ensemble = detected_lang == 'en'
147
+
148
+ if len(cleaned_text) > 10000:
149
+ chunks = split_text(cleaned_text, max_chars=5000)
150
+ labels = []
151
+ clf_scores = []
152
+ ppls = []
153
+
154
+ for chunk_idx, chunk in enumerate(chunks):
155
+ chunk_labels = []
156
+ chunk_clf_scores = []
157
+ for det_idx, detector in enumerate(detectors):
158
+ clf_score = get_classifier_score(chunk, detector)
159
+ label = "AI" if clf_score >= 0.99 else "Human" if clf_score < 0.60 else "Uncertain"
160
+ chunk_labels.append(label)
161
+ chunk_clf_scores.append(clf_score)
162
+ logging.debug(f"Chunk {chunk_idx}, Model {det_idx}: Label={label}, Classifier Score={clf_score:.4f}")
163
+ ppl = get_perplexity(chunk, ppl_model["tokenizer"], ppl_model["model"])
164
+ chunk_final_label = Counter(chunk_labels).most_common(1)[0][0]
165
+ avg_clf_score = np.mean(chunk_clf_scores)
166
+
167
+ # Combine classifier, perplexity, burstiness, and TTR
168
+ if chunk_final_label == "Uncertain" or len(set(chunk_labels)) == len(detectors) or any(l == "Human" for l in chunk_labels):
169
+ if ppl > 60 or burstiness > 1.2 or ttr < 0.12:
170
+ chunk_final_label = "Human"
171
+ elif chunk_final_label == "AI" and (ppl > 60 or burstiness > 1.2 or ttr < 0.12):
172
+ chunk_final_label = "Human"
173
+ labels.append(chunk_final_label)
174
+ clf_scores.append(avg_clf_score)
175
+ ppls.append(ppl)
176
+ logging.debug(f"Chunk {chunk_idx} Final: Label={chunk_final_label}, Avg Classifier Score={avg_clf_score:.4f}, Perplexity={ppl:.2f}, Burstiness={burstiness:.2f}, TTR={ttr:.2f}")
177
+
178
+ label_counts = Counter(labels)
179
+ final_label = label_counts.most_common(1)[0][0]
180
+ if final_label == "Uncertain" or len(set(labels)) == len(detectors) or any(l == "Human" for l in labels):
181
+ if any(ppl > 60 for ppl in ppls) or burstiness > 1.2 or ttr < 0.12:
182
+ final_label = "Human"
183
+ avg_clf_score = sum(clf_scores) / len(clf_scores) if clf_scores else 0.0
184
+ avg_ppl = sum(ppls) / len(ppls) if ppls else 0.0
185
+ logging.info(f"Language: {detected_lang} | Text Length: {len(cleaned_text)} | Chunks: {len(chunks)} | Prediction: {final_label} | Avg Classifier Score: {avg_clf_score:.4f} | Avg Perplexity: {avg_ppl:.2f} | {note_features}")
186
+ return {
187
+ "prediction": final_label,
188
+ "classifier_score": round(avg_clf_score, 4),
189
+ "perplexity": round(avg_ppl, 2),
190
+ "note": f"{note_lang}. Text was split into {len(chunks)} chunks due to length > 10,000 characters. {note_features}.",
191
+ "chunk_results": [
192
+ {"chunk": chunk[:50] + "...", "label": labels[i], "classifier_score": clf_scores[i], "perplexity": ppls[i], "burstiness": burstiness, "ttr": ttr}
193
+ for i, chunk in enumerate(chunks)
194
+ ]
195
+ }
196
  else:
197
+ if is_ensemble:
198
+ clf_scores = []
199
+ labels = []
200
+ for det_idx, detector in enumerate(detectors):
201
+ clf_score = get_classifier_score(cleaned_text, detector)
202
+ label = "AI" if clf_score >= 0.99 else "Human" if clf_score < 0.60 else "Uncertain"
203
+ labels.append(label)
204
+ clf_scores.append(clf_score)
205
+ logging.debug(f"Model {det_idx}: Label={label}, Classifier Score={clf_score:.4f}")
206
+ ppl = get_perplexity(cleaned_text, ppl_model["tokenizer"], ppl_model["model"])
207
+ label_counts = Counter(labels)
208
+ final_label = label_counts.most_common(1)[0][0]
209
+ if final_label == "Uncertain" or len(set(labels)) == len(detectors) or any(l == "Human" for l in labels):
210
+ if ppl > 60 or burstiness > 1.2 or ttr < 0.12:
211
+ final_label = "Human"
212
+ elif final_label == "AI" and (ppl > 60 or burstiness > 1.2 or ttr < 0.12):
213
+ final_label = "Human"
214
+ avg_clf_score = sum(clf_scores) / len(clf_scores) if clf_scores else 0.0
215
+ note = f"{note_lang}. Ensemble used: {len(detectors)} models. {note_features}. Perplexity: {ppl:.2f}."
216
+ if 0.60 <= avg_clf_score < 0.99:
217
+ note += " Warning: Close to threshold, result may be uncertain."
218
+ logging.info(f"Language: {detected_lang} | Text Length: {len(cleaned_text)} | Prediction: {final_label} | Avg Classifier Score: {avg_clf_score:.4f} | Perplexity: {ppl:.2f} | Model Scores: {clf_scores} | {note_features}")
219
+ else:
220
+ clf_score = get_classifier_score(cleaned_text, arabic_detector)
221
+ ppl = get_perplexity(cleaned_text, ppl_model["tokenizer"], ppl_model["model"])
222
+ final_label = "AI" if clf_score >= 0.97 else "Human" if clf_score < 0.60 else "Uncertain"
223
+ if final_label == "Uncertain" or final_label == "Human":
224
+ if ppl > 60 or burstiness > 0.8 or ttr < 0.12:
225
+ final_label = "Human"
226
+ avg_clf_score = clf_score
227
+ note = f"{note_lang}. {note_features}. Perplexity: {ppl:.2f}."
228
+ if 0.60 <= clf_score < 0.97:
229
+ note += " Warning: Close to threshold, result may be uncertain."
230
+ logging.info(f"Language: {detected_lang} | Text Length: {len(cleaned_text)} | Prediction: {final_label} | Classifier Score: {avg_clf_score:.4f} | Perplexity: {ppl:.2f} | {note_features}")
231
+ return {
232
+ "prediction": final_label,
233
+ "classifier_score": round(avg_clf_score, 4),
234
+ "perplexity": round(ppl, 2),
235
+ "note": note
236
+ }