File size: 3,000 Bytes
ef83142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
import os
from flask import Flask, request, jsonify
from flask_cors import CORS
from explain_model import SentenceBasedTextDetector
from ensemble_image_detector import EnsembleImageDetector
import traceback

app = Flask(__name__)
CORS(app)

# Load models
TEXT_MODEL = "Hello-SimpleAI/chatgpt-detector-roberta"
IMAGE_MODEL = "Organika/sdxl-detector"

print("Starting server and loading models...")
text_detector = SentenceBasedTextDetector(TEXT_MODEL)
image_detector = EnsembleImageDetector()
print("Server ready!")

@app.route('/', methods=['GET'])
def home():
    """Home endpoint"""
    return jsonify({
        'status': 'ok',
        'message': 'DetectAI API is running',
        'endpoints': {
            'health': '/health',
            'text': '/analyze',
            'image': '/analyze-image'
        }
    })

@app.route('/health', methods=['GET'])
def health():
    """Check if server is running"""
    return jsonify({
        'status': 'ok', 
        'message': 'Server is running',
        'text_model': TEXT_MODEL,
        'image_model': IMAGE_MODEL
    })

@app.route('/analyze', methods=['POST'])
def analyze_text():
    """Analyze text and return prediction"""
    try:
        data = request.get_json()

        if not data or 'text' not in data:
            return jsonify({'error': 'No text provided'}), 400

        text = data['text'].strip()

        if len(text) == 0:
            return jsonify({'error': 'Text is empty'}), 400

        if len(text) < 10:
            return jsonify({'error': 'Text is too short (minimum 10 characters)'}), 400

        print(f"Analyzing text ({len(text)} characters)...")
        result = text_detector.explain(text)
        print(f"Result: {result['prediction']} ({result['ai_probability']}%)")

        return jsonify(result)

    except Exception as e:
        print(f"Error: {str(e)}")
        traceback.print_exc()
        return jsonify({'error': 'Analysis failed'}), 500

@app.route('/analyze-image', methods=['POST'])
def analyze_image():
    """Analyze image and return prediction"""
    try:
        data = request.get_json()

        if not data or 'image' not in data:
            return jsonify({'error': 'No image provided'}), 400

        image_base64 = data['image']
        
        print("Analyzing image...")
        result = image_detector.detect_from_base64(image_base64)
        print(f"Result: {result['prediction']} ({result['ai_probability']}%)")

        return jsonify(result)

    except Exception as e:
        print(f"Error: {str(e)}")
        traceback.print_exc()
        return jsonify({'error': 'Analysis failed'}), 500

if __name__ == '__main__':
    PORT = int(os.environ.get('PORT', 5000))
    print("\n" + "=" * 70)
    print("DetectAI API Server")
    print("=" * 70)
    print(f"Text Model: {TEXT_MODEL}")
    print(f"Image Model: {IMAGE_MODEL}")
    print(f"Server running on port: {PORT}")
    print("=" * 70 + "\n")
    
    app.run(host='0.0.0.0', port=PORT, debug=False)