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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MASH Inference & Evaluation
|
| 3 |
+
|
| 4 |
+
- Load trained model (SFT or DPO)
|
| 5 |
+
- Humanize AI-generated text
|
| 6 |
+
- Optionally apply Stage 4 refinement
|
| 7 |
+
- Evaluate with GPTZero
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
import json
|
| 13 |
+
import argparse
|
| 14 |
+
import time
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 18 |
+
from model import StyleBART
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def humanize_text(model, text: str, essay_type: str = 'ps',
|
| 22 |
+
device: str = 'cuda', max_length: int = 512,
|
| 23 |
+
num_beams: int = 4) -> str:
|
| 24 |
+
"""
|
| 25 |
+
Humanize a single AI-generated text.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
model: trained StyleBART model
|
| 29 |
+
text: AI-generated text to humanize
|
| 30 |
+
essay_type: 'ps' or 'supp'
|
| 31 |
+
device: device string
|
| 32 |
+
max_length: max generation length
|
| 33 |
+
num_beams: beam search width
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
Humanized text string
|
| 37 |
+
"""
|
| 38 |
+
model.eval()
|
| 39 |
+
style_key = f'human_{essay_type}'
|
| 40 |
+
|
| 41 |
+
inputs = model.tokenizer(
|
| 42 |
+
text,
|
| 43 |
+
max_length=512,
|
| 44 |
+
truncation=True,
|
| 45 |
+
return_tensors='pt',
|
| 46 |
+
).to(device)
|
| 47 |
+
|
| 48 |
+
with torch.no_grad():
|
| 49 |
+
generated = model.generate_text(
|
| 50 |
+
inputs['input_ids'],
|
| 51 |
+
inputs['attention_mask'],
|
| 52 |
+
style_keys=[style_key],
|
| 53 |
+
max_length=max_length,
|
| 54 |
+
num_beams=num_beams,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
output = model.tokenizer.decode(generated[0], skip_special_tokens=True)
|
| 58 |
+
return output
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def humanize_batch(model, texts: list, essay_types: list,
|
| 62 |
+
device: str = 'cuda', batch_size: int = 8,
|
| 63 |
+
max_length: int = 512, num_beams: int = 4) -> list:
|
| 64 |
+
"""Humanize a batch of texts."""
|
| 65 |
+
model.eval()
|
| 66 |
+
results = []
|
| 67 |
+
|
| 68 |
+
for i in range(0, len(texts), batch_size):
|
| 69 |
+
batch_texts = texts[i:i+batch_size]
|
| 70 |
+
batch_types = essay_types[i:i+batch_size]
|
| 71 |
+
style_keys = [f'human_{t}' for t in batch_types]
|
| 72 |
+
|
| 73 |
+
inputs = model.tokenizer(
|
| 74 |
+
batch_texts,
|
| 75 |
+
max_length=512,
|
| 76 |
+
truncation=True,
|
| 77 |
+
padding=True,
|
| 78 |
+
return_tensors='pt',
|
| 79 |
+
).to(device)
|
| 80 |
+
|
| 81 |
+
with torch.no_grad():
|
| 82 |
+
generated = model.generate_text(
|
| 83 |
+
inputs['input_ids'],
|
| 84 |
+
inputs['attention_mask'],
|
| 85 |
+
style_keys=style_keys,
|
| 86 |
+
max_length=max_length,
|
| 87 |
+
num_beams=num_beams,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
for j in range(len(batch_texts)):
|
| 91 |
+
output = model.tokenizer.decode(generated[j], skip_special_tokens=True)
|
| 92 |
+
results.append(output)
|
| 93 |
+
|
| 94 |
+
return results
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def evaluate_with_gptzero(texts: list, api_key: str = None) -> list:
|
| 98 |
+
"""Evaluate texts with GPTZero API."""
|
| 99 |
+
import requests
|
| 100 |
+
|
| 101 |
+
if api_key is None:
|
| 102 |
+
api_key = os.environ.get('GPTZERO_API_KEY', '')
|
| 103 |
+
|
| 104 |
+
results = []
|
| 105 |
+
for i, text in enumerate(texts):
|
| 106 |
+
try:
|
| 107 |
+
resp = requests.post(
|
| 108 |
+
'https://api.gptzero.me/v2/predict/text',
|
| 109 |
+
json={'document': text, 'version': '2024-04-04'},
|
| 110 |
+
headers={'x-api-key': api_key, 'Content-Type': 'application/json'},
|
| 111 |
+
timeout=30,
|
| 112 |
+
)
|
| 113 |
+
resp.raise_for_status()
|
| 114 |
+
doc = resp.json().get('documents', [{}])[0]
|
| 115 |
+
results.append({
|
| 116 |
+
'ai_prob': doc.get('completely_generated_prob', 0),
|
| 117 |
+
'human_prob': 1 - doc.get('completely_generated_prob', 0),
|
| 118 |
+
'class': doc.get('predicted_class', 'unknown'),
|
| 119 |
+
})
|
| 120 |
+
except Exception as e:
|
| 121 |
+
print(f" GPTZero error for text {i}: {e}")
|
| 122 |
+
results.append({'ai_prob': -1, 'human_prob': -1, 'class': 'error'})
|
| 123 |
+
|
| 124 |
+
time.sleep(0.5) # Rate limiting
|
| 125 |
+
|
| 126 |
+
return results
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def main():
|
| 130 |
+
parser = argparse.ArgumentParser()
|
| 131 |
+
parser.add_argument('--model_path', required=True, help='Path to trained model')
|
| 132 |
+
parser.add_argument('--input', required=True, help='Input JSONL file or single text')
|
| 133 |
+
parser.add_argument('--output', default='results.jsonl', help='Output JSONL file')
|
| 134 |
+
parser.add_argument('--essay_type', default='ps', choices=['ps', 'supp'])
|
| 135 |
+
parser.add_argument('--eval_gptzero', action='store_true', help='Evaluate with GPTZero')
|
| 136 |
+
parser.add_argument('--batch_size', type=int, default=8)
|
| 137 |
+
parser.add_argument('--num_beams', type=int, default=4)
|
| 138 |
+
parser.add_argument('--max_length', type=int, default=512)
|
| 139 |
+
args = parser.parse_args()
|
| 140 |
+
|
| 141 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 142 |
+
print(f"Device: {device}")
|
| 143 |
+
|
| 144 |
+
# Load model
|
| 145 |
+
print(f"Loading model from {args.model_path}...")
|
| 146 |
+
model = StyleBART.load_pretrained(args.model_path, device=str(device))
|
| 147 |
+
model = model.to(device)
|
| 148 |
+
model.eval()
|
| 149 |
+
|
| 150 |
+
# Load input
|
| 151 |
+
if os.path.isfile(args.input) and args.input.endswith('.jsonl'):
|
| 152 |
+
data = []
|
| 153 |
+
with open(args.input) as f:
|
| 154 |
+
for line in f:
|
| 155 |
+
data.append(json.loads(line))
|
| 156 |
+
texts = [d.get('input_text', d.get('ai_text', '')) for d in data]
|
| 157 |
+
essay_types = [d.get('essay_type', d.get('type', args.essay_type)) for d in data]
|
| 158 |
+
else:
|
| 159 |
+
texts = [args.input]
|
| 160 |
+
essay_types = [args.essay_type]
|
| 161 |
+
|
| 162 |
+
print(f"Processing {len(texts)} texts...")
|
| 163 |
+
|
| 164 |
+
# Humanize
|
| 165 |
+
t0 = time.time()
|
| 166 |
+
humanized = humanize_batch(
|
| 167 |
+
model, texts, essay_types,
|
| 168 |
+
device=str(device),
|
| 169 |
+
batch_size=args.batch_size,
|
| 170 |
+
max_length=args.max_length,
|
| 171 |
+
num_beams=args.num_beams,
|
| 172 |
+
)
|
| 173 |
+
elapsed = time.time() - t0
|
| 174 |
+
print(f"Humanization complete in {elapsed:.1f}s ({elapsed/len(texts):.2f}s/text)")
|
| 175 |
+
|
| 176 |
+
# Evaluate with GPTZero
|
| 177 |
+
gptzero_results = None
|
| 178 |
+
if args.eval_gptzero:
|
| 179 |
+
print("Evaluating with GPTZero...")
|
| 180 |
+
gptzero_results = evaluate_with_gptzero(humanized)
|
| 181 |
+
|
| 182 |
+
# Summary
|
| 183 |
+
ai_probs = [r['ai_prob'] for r in gptzero_results if r['ai_prob'] >= 0]
|
| 184 |
+
if ai_probs:
|
| 185 |
+
avg_ai = sum(ai_probs) / len(ai_probs)
|
| 186 |
+
n_pass = sum(1 for p in ai_probs if p < 0.5)
|
| 187 |
+
print(f" Average AI prob: {avg_ai:.2%}")
|
| 188 |
+
print(f" Pass rate (<50% AI): {n_pass}/{len(ai_probs)} ({n_pass/len(ai_probs):.0%})")
|
| 189 |
+
|
| 190 |
+
# Save results
|
| 191 |
+
with open(args.output, 'w') as f:
|
| 192 |
+
for i in range(len(texts)):
|
| 193 |
+
result = {
|
| 194 |
+
'input_text': texts[i][:500],
|
| 195 |
+
'humanized_text': humanized[i],
|
| 196 |
+
'essay_type': essay_types[i],
|
| 197 |
+
'input_words': len(texts[i].split()),
|
| 198 |
+
'output_words': len(humanized[i].split()),
|
| 199 |
+
}
|
| 200 |
+
if gptzero_results:
|
| 201 |
+
result['gptzero'] = gptzero_results[i]
|
| 202 |
+
f.write(json.dumps(result, ensure_ascii=False) + '\n')
|
| 203 |
+
|
| 204 |
+
print(f"Results saved to {args.output}")
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
if __name__ == '__main__':
|
| 208 |
+
main()
|