-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmain.py
More file actions
1359 lines (1122 loc) · 52.1 KB
/
main.py
File metadata and controls
1359 lines (1122 loc) · 52.1 KB
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import time
from typing import Dict, Tuple
from flask import Flask, request, jsonify
from flask_cors import CORS
import logging
import re
# Import our utility modules
from paraphraser import paraphrase_text, load_model, get_available_models, get_current_model, get_device_info
from rewriter import rewrite_text, get_synonym, refine_text
from detector import (
AITextDetector,
detect_with_all_models,
detect_with_selected_models,
detect_with_top_models,
get_available_models as get_detection_models,
get_ai_lines,
get_ai_sentences,
highlight_ai_text
)
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize Flask app
app = Flask(__name__)
CORS(app, origins="*")
def clean_final_text(text: str) -> str:
"""
Clean the final text by:
1. Replacing every "—" with ", "
2. Removing spaces that appear before "," or "."
"""
if not text:
return text
# Step 1: Replace em dashes with commas
cleaned_text = text.replace("—", ", ")
# Step 2: Remove spaces before commas and periods
# This regex finds spaces that are followed by comma or period
cleaned_text = re.sub(r' +([,.])', r'\1', cleaned_text)
return cleaned_text
class HumanizerService:
"""Main orchestrator service that combines paraphrasing and rewriting"""
def __init__(self):
logger.info("HumanizerService initialized")
def humanize_text(
self,
text: str,
use_paraphrasing: bool = True,
use_enhanced_rewriting: bool = False,
paraphrase_model: str = None
) -> Tuple[str, Dict]:
"""
Complete text humanization pipeline:
1. Paraphrase the text (optional)
2. Rewrite and refine the result
3. Clean the final text
"""
stats = {
"original_length": len(text),
"paraphrasing_used": False,
"enhanced_rewriting_used": use_enhanced_rewriting,
"model_used": None,
"processing_steps": []
}
try:
current_text = text
# Step 1: Paraphrasing (if enabled)
if use_paraphrasing:
logger.info("Starting paraphrasing step")
paraphrased, err = paraphrase_text(current_text, paraphrase_model)
if not err and paraphrased and paraphrased.strip():
current_text = paraphrased
stats["paraphrasing_used"] = True
stats["model_used"] = get_current_model()
stats["processing_steps"].append("paraphrasing")
logger.info("Paraphrasing successful")
# Clean up common formatting issues from paraphrasing
if current_text.startswith(": "):
current_text = current_text[2:]
else:
logger.warning(f"Paraphrasing failed or skipped: {err}")
stats["processing_steps"].append("paraphrasing_failed")
# Step 2: Rewriting and refinement
logger.info("Starting rewriting step")
final_text, err = rewrite_text(current_text, enhanced=use_enhanced_rewriting)
if err:
logger.warning(f"Rewriting failed: {err}")
final_text = current_text
stats["processing_steps"].append("rewriting_failed")
else:
stats["processing_steps"].append("rewriting")
# Step 3: Clean the final text
logger.info("Cleaning final text")
final_text = clean_final_text(final_text)
stats["processing_steps"].append("text_cleaning")
stats["final_length"] = len(final_text)
stats["length_change"] = stats["final_length"] - stats["original_length"]
return final_text, stats
except Exception as e:
logger.error(f"Error in humanization pipeline: {str(e)}")
return text, {
**stats,
"error": str(e),
"processing_steps": stats["processing_steps"] + ["error"]
}
# Initialize services
humanizer_service = HumanizerService()
ai_detector = AITextDetector()
@app.route('/', methods=['GET'])
def health_check():
"""Health check endpoint"""
current_model = get_current_model()
return jsonify({
"status": "healthy",
"message": "🚀 Humanize AI Server is running!",
"features": {
"paraphrasing": current_model is not None,
"current_model": current_model,
"available_models": get_available_models(),
"local_refinement": True,
"synonym_support": True,
"device": get_device_info()
}
})
@app.route('/health', methods=['GET'])
def detailed_health():
"""Detailed health check with system information - matches frontend expectations"""
current_model = get_current_model()
return jsonify({
"status": "healthy",
"timestamp": time.time(),
"features": {
"paraphrasing_available": current_model is not None,
"current_paraphrase_model": current_model,
"local_processing": True,
"device": get_device_info()
},
"version": "3.0.0"
})
@app.route('/models', methods=['GET'])
def get_models():
"""Get available paraphrasing models - matches frontend expectations"""
return jsonify({
"available_models": get_available_models(),
"current_model": get_current_model(),
"device": get_device_info()
})
@app.route('/load_model', methods=['POST'])
def load_model_endpoint():
"""Load a specific paraphrasing model - matches frontend expectations"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
model_name = data.get('model_name', '').strip()
if not model_name:
return jsonify({"error": "No model_name provided"}), 400
available_models = get_available_models()
if model_name not in available_models:
return jsonify({
"error": f"Model {model_name} not supported",
"available_models": available_models
}), 400
success, error = load_model(model_name)
if success:
return jsonify({
"message": f"Successfully loaded {model_name}",
"current_model": get_current_model(),
"success": True
})
else:
return jsonify({"error": error or f"Failed to load model {model_name}"}), 500
except Exception as e:
logger.error(f"Error in /load_model: {str(e)}")
return jsonify({"error": str(e)}), 500
@app.route('/humanize', methods=['POST'])
def humanize_handler():
"""Main endpoint for humanizing AI-generated text - matches frontend expectations"""
try:
logger.info("Humanize request received")
# Validate request
if not request.is_json:
logger.error("Invalid content type")
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
if not data or "text" not in data:
logger.error("Missing text field in request")
return jsonify({"error": "Text field is required"}), 400
text = data.get("text", "").strip()
if not text:
logger.error("Empty text received")
return jsonify({"error": "Text cannot be empty"}), 400
# Validate text length
if len(text) < 10:
return jsonify({"error": "Text must be at least 10 characters long"}), 400
if len(text) > 50000: # Changed from 5000 to 50000
return jsonify({"error": "Text must be less than 50000 characters"}), 400
# Extract options - match frontend parameter names
use_paraphrasing = data.get("paraphrasing", True)
use_enhanced = data.get("enhanced", True) # Changed from False to True
paraphrase_model = data.get("model", None)
# Process text through humanization pipeline
humanized_text, stats = humanizer_service.humanize_text(
text=text,
use_paraphrasing=use_paraphrasing,
use_enhanced_rewriting=use_enhanced, # This will now use the more aggressive mode
paraphrase_model=paraphrase_model
)
# Ensure we return something
if not humanized_text or not humanized_text.strip():
humanized_text = text
response = {
"humanized_text": humanized_text,
"success": True,
"statistics": stats
}
logger.info(f"Successfully processed text: {stats['original_length']} -> {stats['final_length']} chars")
return jsonify(response)
except Exception as e:
logger.error(f"Error processing request: {str(e)}", exc_info=True)
return jsonify({
"error": "Internal server error",
"success": False
}), 500
# Additional endpoints for direct access
@app.route('/paraphrase', methods=['POST'])
def paraphrase_handler():
"""Direct paraphrasing endpoint"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
model_name = data.get('model_name', None)
if not text:
return jsonify({"error": "No text provided"}), 400
paraphrased_text, error = paraphrase_text(text, model_name)
if error:
return jsonify({"error": error}), 500
return jsonify({
'paraphrased': paraphrased_text,
'success': True,
'model_used': get_current_model(),
'original_text': text
})
except Exception as e:
logger.error(f"Error in /paraphrase: {str(e)}")
return jsonify({"error": str(e)}), 500
@app.route('/synonym', methods=['POST'])
def synonym_handler():
"""Get synonym for a word"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
word = data.get('word', '').strip()
if not word:
return jsonify({"error": "No word provided"}), 400
synonym, error = get_synonym(word)
if error:
return jsonify({"error": error}), 400
return jsonify({
'synonym': synonym,
'original_word': word,
'success': True
})
except Exception as e:
logger.error(f"Error in /synonym: {str(e)}")
return jsonify({"error": str(e)}), 500
@app.route('/refine', methods=['POST'])
def refine_handler():
"""Refine text using NLP tools"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
if not text:
return jsonify({"error": "No text provided"}), 400
refined_text, error = refine_text(text)
if error:
return jsonify({"error": error}), 500
return jsonify({
'refined_text': refined_text,
'original_text': text,
'success': True
})
except Exception as e:
logger.error(f"Error in /refine: {str(e)}")
return jsonify({"error": str(e)}), 500
@app.route('/paraphrase_only', methods=['POST'])
def paraphrase_only_handler():
"""Paraphrase text without rewriting - for step-by-step processing"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
model_name = data.get('model', None)
if not text:
return jsonify({"error": "No text provided"}), 400
if len(text) < 10:
return jsonify({"error": "Text must be at least 10 characters long"}), 400
if len(text) > 50000: # Changed from 5000 to 50000
return jsonify({"error": "Text must be less than 50000 characters"}), 400
paraphrased_text, error = paraphrase_text(text, model_name)
if error:
return jsonify({"error": error}), 500
# Clean up common formatting issues
if paraphrased_text and paraphrased_text.startswith(": "):
paraphrased_text = paraphrased_text[2:]
return jsonify({
'paraphrased_text': paraphrased_text or text,
'success': True,
'model_used': get_current_model(),
'original_text': text,
'statistics': {
'original_length': len(text),
'paraphrased_length': len(paraphrased_text) if paraphrased_text else len(text),
'length_change': (len(paraphrased_text) if paraphrased_text else len(text)) - len(text),
'model_used': get_current_model(),
'paraphrasing_used': True
}
})
except Exception as e:
logger.error(f"Error in /paraphrase_only: {str(e)}")
return jsonify({"error": str(e)}), 500
@app.route('/rewrite_only', methods=['POST'])
def rewrite_only_handler():
"""Rewrite text without paraphrasing - for step-by-step processing"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
enhanced = data.get('enhanced', False)
if not text:
return jsonify({"error": "No text provided"}), 400
rewritten_text, error = rewrite_text(text, enhanced=enhanced)
if error:
return jsonify({"error": error}), 500
# Clean the final rewritten text
rewritten_text = clean_final_text(rewritten_text or text)
return jsonify({
'rewritten_text': rewritten_text,
'success': True,
'original_text': text,
'statistics': {
'original_length': len(text),
'rewritten_length': len(rewritten_text),
'length_change': len(rewritten_text) - len(text),
'enhanced_rewriting_used': enhanced,
'text_cleaning_applied': True
}
})
except Exception as e:
logger.error(f"Error in /rewrite_only: {str(e)}")
return jsonify({"error": str(e)}), 500
@app.route('/paraphrase_multi', methods=['POST'])
def paraphrase_multi_handler():
"""Paraphrase text through 2 best models in PIPELINE (each model processes previous output)"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
if not text:
return jsonify({"error": "No text provided"}), 400
if len(text) < 10:
return jsonify({"error": "Text must be at least 10 characters long"}), 400
if len(text) > 50000: # Changed from 5000 to 50000
return jsonify({"error": "Text must be less than 50000 characters"}), 400
# Define the 2 best models (prioritize specialized paraphrasing models)
best_models = [
"humarin/chatgpt_paraphraser_on_T5_base",
"Vamsi/T5_Paraphrase_Paws"
]
# Filter available models
available_models = get_available_models()
models_to_use = [model for model in best_models if model in available_models]
# Fallback to first 2 available models if best models aren't available
if len(models_to_use) < 2:
models_to_use = available_models[:2]
if not models_to_use:
return jsonify({"error": "No models available for paraphrasing"}), 500
results = []
errors = []
current_text = text # Start with original text
for i, model_name in enumerate(models_to_use):
try:
logger.info(f"Pipeline step {i+1}: Paraphrasing with model {model_name}")
paraphrased_text, error = paraphrase_text(current_text, model_name)
if error:
errors.append(f"Step {i+1} ({model_name}): {error}")
# On error, continue with current text (don't break the pipeline)
paraphrased_text = current_text
# Clean up common formatting issues
if paraphrased_text and paraphrased_text.startswith(": "):
paraphrased_text = paraphrased_text[2:]
# If paraphrasing failed, use current text
if not paraphrased_text or not paraphrased_text.strip():
paraphrased_text = current_text
results.append({
"step": i + 1,
"model": model_name,
"input_text": current_text,
"output_text": paraphrased_text,
"input_length": len(current_text),
"output_length": len(paraphrased_text),
"length_change": len(paraphrased_text) - len(current_text),
"success": not error
})
# Update current_text for next iteration (PIPELINE EFFECT)
current_text = paraphrased_text
except Exception as e:
logger.error(f"Error with model {model_name}: {str(e)}")
errors.append(f"Step {i+1} ({model_name}): {str(e)}")
# Continue with current text on error
results.append({
"step": i + 1,
"model": model_name,
"input_text": current_text,
"output_text": current_text, # No change on error
"input_length": len(current_text),
"output_length": len(current_text),
"length_change": 0,
"success": False,
"error": str(e)
})
return jsonify({
"pipeline_results": results,
"success": True,
"original_text": text,
"final_text": current_text, # Final output after all pipeline steps
"models_used": [r["model"] for r in results],
"errors": errors if errors else None,
"statistics": {
"pipeline_steps": len(results),
"successful_steps": len([r for r in results if r.get("success", False)]),
"failed_steps": len([r for r in results if not r.get("success", False)]),
"original_length": len(text),
"final_length": len(current_text),
"total_length_change": len(current_text) - len(text),
"pipeline_mode": "sequential"
}
})
except Exception as e:
logger.error(f"Error in /paraphrase_multi: {str(e)}")
return jsonify({"error": str(e)}), 500
@app.route('/paraphrase_all', methods=['POST'])
def paraphrase_all_handler():
"""Paraphrase text through ALL available models in PIPELINE (each model processes previous output)"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
if not text:
return jsonify({"error": "No text provided"}), 400
if len(text) < 10:
return jsonify({"error": "Text must be at least 10 characters long"}), 400
if len(text) > 50000: # Changed from 5000 to 50000
return jsonify({"error": "Text must be less than 50000 characters"}), 400
available_models = get_available_models()
if not available_models:
return jsonify({"error": "No models available for paraphrasing"}), 500
results = []
errors = []
current_text = text # Start with original text
processing_time_start = time.time()
for i, model_name in enumerate(available_models):
model_start_time = time.time()
try:
logger.info(f"Pipeline step {i+1}/{len(available_models)}: Paraphrasing with model {model_name}")
paraphrased_text, error = paraphrase_text(current_text, model_name)
model_time = time.time() - model_start_time
if error:
errors.append(f"Step {i+1} ({model_name}): {error}")
# On error, continue with current text (don't break the pipeline)
paraphrased_text = current_text
# Clean up common formatting issues
if paraphrased_text and paraphrased_text.startswith(": "):
paraphrased_text = paraphrased_text[2:]
# If paraphrasing failed, use current text
if not paraphrased_text or not paraphrased_text.strip():
paraphrased_text = current_text
results.append({
"step": i + 1,
"model": model_name,
"input_text": current_text,
"output_text": paraphrased_text,
"input_length": len(current_text),
"output_length": len(paraphrased_text),
"length_change": len(paraphrased_text) - len(current_text),
"processing_time": round(model_time, 2),
"success": not error
})
# Update current_text for next iteration (PIPELINE EFFECT)
current_text = paraphrased_text
except Exception as e:
model_time = time.time() - model_start_time
logger.error(f"Error with model {model_name}: {str(e)}")
errors.append(f"Step {i+1} ({model_name}): {str(e)}")
# Continue with current text on error
results.append({
"step": i + 1,
"model": model_name,
"input_text": current_text,
"output_text": current_text, # No change on error
"input_length": len(current_text),
"output_length": len(current_text),
"length_change": 0,
"processing_time": round(model_time, 2),
"success": False,
"error": str(e)
})
total_processing_time = time.time() - processing_time_start
successful_steps = [r for r in results if r.get("success", False)]
return jsonify({
"pipeline_results": results,
"successful_steps": successful_steps,
"success": len(successful_steps) > 0,
"original_text": text,
"final_text": current_text, # Final output after all pipeline steps
"models_attempted": available_models,
"errors": errors if errors else None,
"statistics": {
"pipeline_steps": len(results),
"successful_steps": len(successful_steps),
"failed_steps": len(results) - len(successful_steps),
"original_length": len(text),
"final_length": len(current_text),
"total_length_change": len(current_text) - len(text),
"total_processing_time": round(total_processing_time, 2),
"average_processing_time": round(total_processing_time / len(available_models), 2) if available_models else 0,
"pipeline_mode": "sequential"
}
})
except Exception as e:
logger.error(f"Error in /paraphrase_all: {str(e)}")
return jsonify({"error": str(e)}), 500
# AI detection endpoints
@app.route('/detect', methods=['POST'])
def detect_ai_handler():
"""Main AI detection endpoint using ensemble method with enhanced options"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
threshold = data.get('threshold', 0.7)
models = data.get('models', None) # Optional specific models
use_all_models = data.get('use_all_models', False) # New option
top_n = data.get('top_n', None) # New option for top N models
criteria = data.get('criteria', 'performance') # New option for model selection criteria
if not text:
return jsonify({"error": "No text provided"}), 400
if len(text) < 20:
return jsonify({"error": "Text must be at least 20 characters long"}), 400
if len(text) > 50000: # Changed from 10000 to 50000
return jsonify({"error": "Text must be less than 50,000 characters"}), 400
# Get detection results based on options
if use_all_models:
result = detect_with_all_models(text)
elif top_n and isinstance(top_n, int) and top_n > 0:
result = detect_with_top_models(text, n=top_n, criteria=criteria)
elif models and isinstance(models, list):
result = detect_with_selected_models(text, models)
else:
# Default ensemble method
detector = AITextDetector()
result = detector.detect_ensemble(text, models=models)
# Add simple classification
is_ai = result['ensemble_ai_probability'] > threshold
response = {
"text_preview": text[:100] + "..." if len(text) > 100 else text,
"is_ai_generated": is_ai,
"ai_probability": result['ensemble_ai_probability'],
"human_probability": result['ensemble_human_probability'],
"prediction": result['prediction'],
"confidence": result['confidence'],
"threshold_used": threshold,
"models_used": result['models_used'],
"individual_results": result['individual_results'],
"text_length": len(text),
"detection_method": "all_models" if use_all_models else f"top_{top_n}" if top_n else "selected" if models else "default",
"success": True
}
logger.info(f"AI detection completed: {result['prediction']} ({result['ensemble_ai_probability']:.3f})")
return jsonify(response)
except Exception as e:
logger.error(f"Error in AI detection: {str(e)}")
return jsonify({
"error": "Failed to analyze text",
"success": False
}), 500
@app.route('/detect_all_models', methods=['POST'])
def detect_all_models_handler():
"""Detect AI text using ALL available models"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
threshold = data.get('threshold', 0.7)
if not text:
return jsonify({"error": "No text provided"}), 400
if len(text) < 20:
return jsonify({"error": "Text must be at least 20 characters long"}), 400
if len(text) > 50000: # Changed from 10000 to 50000
return jsonify({"error": "Text must be less than 50,000 characters"}), 400
# Use all available models
result = detect_with_all_models(text)
is_ai = result['ensemble_ai_probability'] > threshold
response = {
"text_preview": text[:100] + "..." if len(text) > 100 else text,
"is_ai_generated": is_ai,
"ai_probability": result['ensemble_ai_probability'],
"human_probability": result['ensemble_human_probability'],
"prediction": result['prediction'],
"confidence": result['confidence'],
"threshold_used": threshold,
"models_used": result['models_used'],
"individual_results": result['individual_results'],
"total_models_used": len(result['models_used']),
"detection_method": "all_models",
"text_length": len(text),
"success": True
}
logger.info(f"All models detection: {result['prediction']} with {len(result['models_used'])} models")
return jsonify(response)
except Exception as e:
logger.error(f"Error in all models detection: {str(e)}")
return jsonify({
"error": "Failed to analyze text with all models",
"success": False
}), 500
@app.route('/detect_selected', methods=['POST'])
def detect_selected_models_handler():
"""Detect AI text using specific selected models"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
models = data.get('models', [])
threshold = data.get('threshold', 0.7)
if not text:
return jsonify({"error": "No text provided"}), 400
if not models or not isinstance(models, list):
return jsonify({"error": "Models list is required"}), 400
if len(text) < 20:
return jsonify({"error": "Text must be at least 20 characters long"}), 400
if len(text) > 50000: # Changed from 10000 to 50000
return jsonify({"error": "Text must be less than 50,000 characters"}), 400
# Use selected models
result = detect_with_selected_models(text, models)
is_ai = result['ensemble_ai_probability'] > threshold
response = {
"text_preview": text[:100] + "..." if len(text) > 100 else text,
"is_ai_generated": is_ai,
"ai_probability": result['ensemble_ai_probability'],
"human_probability": result['ensemble_human_probability'],
"prediction": result['prediction'],
"confidence": result['confidence'],
"threshold_used": threshold,
"models_requested": models,
"models_used": result['models_used'],
"individual_results": result['individual_results'],
"detection_method": "selected_models",
"text_length": len(text),
"success": True
}
logger.info(f"Selected models detection: {result['prediction']} with models {result['models_used']}")
return jsonify(response)
except Exception as e:
logger.error(f"Error in selected models detection: {str(e)}")
return jsonify({
"error": "Failed to analyze text with selected models",
"success": False
}), 500
@app.route('/detect_top_models', methods=['POST'])
def detect_top_models_handler():
"""Detect AI text using top N models based on criteria"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
n = data.get('n', 3)
criteria = data.get('criteria', 'performance')
threshold = data.get('threshold', 0.7)
if not text:
return jsonify({"error": "No text provided"}), 400
if not isinstance(n, int) or n < 1 or n > 8:
return jsonify({"error": "n must be an integer between 1 and 8"}), 400
if criteria not in ['performance', 'speed', 'accuracy']:
return jsonify({"error": "criteria must be 'performance', 'speed', or 'accuracy'"}), 400
if len(text) < 20:
return jsonify({"error": "Text must be at least 20 characters long"}), 400
if len(text) > 50000: # Changed from 10000 to 50000
return jsonify({"error": "Text must be less than 50,000 characters"}), 400
# Use top N models
result = detect_with_top_models(text, n=n, criteria=criteria)
is_ai = result['ensemble_ai_probability'] > threshold
response = {
"text_preview": text[:100] + "..." if len(text) > 100 else text,
"is_ai_generated": is_ai,
"ai_probability": result['ensemble_ai_probability'],
"human_probability": result['ensemble_human_probability'],
"prediction": result['prediction'],
"confidence": result['confidence'],
"threshold_used": threshold,
"models_used": result['models_used'],
"individual_results": result['individual_results'],
"selection_criteria": criteria,
"top_n": n,
"detection_method": f"top_{n}_{criteria}",
"text_length": len(text),
"success": True
}
logger.info(f"Top {n} {criteria} models detection: {result['prediction']}")
return jsonify(response)
except Exception as e:
logger.error(f"Error in top models detection: {str(e)}")
return jsonify({
"error": "Failed to analyze text with top models",
"success": False
}), 500
@app.route('/detect_lines', methods=['POST'])
def detect_lines_handler():
"""Detect which specific lines in text are AI-generated"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
threshold = data.get('threshold', 0.6)
min_line_length = data.get('min_line_length', 20)
if not text:
return jsonify({"error": "No text provided"}), 400
if len(text) < 50:
return jsonify({"error": "Text must be at least 50 characters long for line detection"}), 400
if len(text) > 15000:
return jsonify({"error": "Text must be less than 15,000 characters for line detection"}), 400
# Detect AI lines
detector = AITextDetector()
result = detector.detect_ai_lines(text, threshold, min_line_length)
response = {
"ai_detected_lines": result['ai_detected_lines'],
"human_lines": result['human_lines'],
"line_analysis": result['line_analysis'],
"statistics": result['statistics'],
"threshold_used": result['threshold_used'],
"min_line_length": min_line_length,
"text_length": len(text),
"success": True
}
logger.info(f"Line detection: {result['statistics']['ai_generated_lines']}/{result['statistics']['total_lines_analyzed']} lines detected as AI")
return jsonify(response)
except Exception as e:
logger.error(f"Error in line detection: {str(e)}")
return jsonify({
"error": "Failed to detect AI lines",
"success": False
}), 500
@app.route('/detect_sentences', methods=['POST'])
def detect_sentences_handler():
"""Detect which specific sentences in text are AI-generated"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
threshold = data.get('threshold', 0.6)
if not text:
return jsonify({"error": "No text provided"}), 400
if len(text) < 50:
return jsonify({"error": "Text must be at least 50 characters long for sentence detection"}), 400
if len(text) > 15000:
return jsonify({"error": "Text must be less than 15,000 characters for sentence detection"}), 400
# Detect AI sentences
detector = AITextDetector()
result = detector.detect_ai_sentences(text, threshold)
response = {
"ai_detected_sentences": result['ai_detected_sentences'],
"human_sentences": result['human_sentences'],
"sentence_analysis": result['sentence_analysis'],
"statistics": result['statistics'],
"threshold_used": result['threshold_used'],
"text_length": len(text),
"success": True
}
logger.info(f"Sentence detection: {result['statistics']['ai_generated_sentences']}/{result['statistics']['total_sentences_analyzed']} sentences detected as AI")
return jsonify(response)
except Exception as e:
logger.error(f"Error in sentence detection: {str(e)}")
return jsonify({
"error": "Failed to detect AI sentences",
"success": False
}), 500
@app.route('/highlight_ai', methods=['POST'])
def highlight_ai_handler():
"""Highlight AI-detected portions in text"""
try:
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
text = data.get('text', '').strip()
threshold = data.get('threshold', 0.6)
output_format = data.get('format', 'markdown')
if not text:
return jsonify({"error": "No text provided"}), 400
if output_format not in ['markdown', 'html', 'plain']:
return jsonify({"error": "format must be 'markdown', 'html', or 'plain'"}), 400