File size: 6,647 Bytes
60f01af
 
 
 
 
 
4a14e46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60f01af
 
 
 
0b16b51
 
498708d
60f01af
 
 
001c169
 
0b16b51
 
 
 
60f01af
c8cceb1
001c169
60f01af
 
001c169
 
 
 
c8cceb1
60f01af
0b16b51
60f01af
 
0b16b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60f01af
 
0b16b51
60f01af
 
 
 
 
 
 
 
 
 
0b16b51
c8cceb1
 
 
 
 
 
 
 
 
 
60f01af
 
c8cceb1
0b16b51
c8cceb1
 
 
 
 
 
 
 
0b16b51
2a46da5
0b16b51
 
68ecef9
 
 
0b16b51
 
 
 
 
68ecef9
 
 
 
0b16b51
68ecef9
60f01af
0b16b51
68ecef9
 
 
 
 
0b16b51
68ecef9
0b16b51
 
4a14e46
001c169
3d2dce1
498708d
60f01af
 
2a46da5
68ecef9
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
'''
Copyright 2024 Infosys Ltd.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
import json
from werkzeug.exceptions import HTTPException, UnprocessableEntity, InternalServerError
from flask import Flask
from flask_swagger_ui import get_swaggerui_blueprint
from flask_cors import CORS
from waitress import serve
import os
from dotenv import load_dotenv
from router.router import app  # Importing the original blueprint
load_dotenv()

# Flask app setup
app1 = Flask(__name__)

# Swagger UI setup
SWAGGER_URL = '/rai/v1/moderations/docs'  
API_URL = '/static/metadata.json'
swaggerui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL, config={'app_name': "Infosys Responsible AI - Moderation"})
app1.register_blueprint(swaggerui_blueprint)

# Register the app blueprint for the '/rai/v1/moderations' route
app1.register_blueprint(app)  # Registering the blueprint that contains the route

# CORS and error handling setup
CORS(app1)

@app1.errorhandler(HTTPException)
def handle_exception(e):
    response = e.get_response()
    response.data = json.dumps({
        "code": e.code,
        "details": e.description,
    })
    response.content_type = "application/json"
    return response

@app1.errorhandler(UnprocessableEntity)
def validation_error_handler(exc):
    response = exc.get_response()
    exc_code_desc = exc.description.split("-")
    exc_code = int(exc_code_desc[0])
    exc_desc = exc_code_desc[1]
    response.data = json.dumps({
        "code": exc_code,
        "details": exc_desc,
    })
    response.content_type = "application/json"
    return response

@app1.errorhandler(InternalServerError)
def internal_server_error_handler(exc):
    response = exc.get_response()
    response.data = json.dumps({
        "code": 500,
        "details": "Some Error Occurred, Please try later",
    })
    response.content_type = "application/json"
    return response

# Use Waitress for production server
if __name__ == "__main__":
    serve(app1, host="0.0.0.0", port=int(os.getenv("PORT", 7860)))  # Ensure correct port is used

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import json
import os
import logging
from werkzeug.exceptions import HTTPException, UnprocessableEntity, InternalServerError
from flask import Flask
from flask_swagger_ui import get_swaggerui_blueprint
from flask_cors import CORS
from waitress import serve
from dotenv import load_dotenv
import spacy
from spacy.cli import download

# Load environment variables
load_dotenv()

# Flask app setup
app1 = Flask(__name__)

# Swagger UI setup
SWAGGER_URL = '/rai/v1/moderations/docs'  
API_URL = '/static/metadata.json'
swaggerui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL, config={'app_name': "Infosys Responsible AI - Moderation"})
app1.register_blueprint(swaggerui_blueprint)

# CORS setup
CORS(app1)

# Ensure Spacy model is installed and loaded
def load_spacy_model():
    try:
        # Attempt to load the model
        nlp = spacy.load('en_core_web_lg')
    except OSError:
        # If model is not found, download it
        download('en_core_web_lg')
        nlp = spacy.load('en_core_web_lg')
    return nlp

# Attempt to load Spacy model
try:
    nlp = load_spacy_model()
    logging.info("Spacy model loaded successfully.")
except Exception as e:
    logging.error(f"Failed to load Spacy model: {e}")
    raise

# Error Handlers
@app1.errorhandler(HTTPException)
def handle_exception(e):
    """Return JSON instead of HTML for HTTP errors."""
    response = e.get_response()
    response.data = json.dumps({
        "code": e.code,
        "details": e.description,
    })
    response.content_type = "application/json"
    return response

@app1.errorhandler(UnprocessableEntity)
def validation_error_handler(exc):
    """Return JSON instead of HTML for HTTP errors."""
    response = exc.get_response()
    exc_code_desc = exc.description.split("-")
    exc_code = int(exc_code_desc[0])
    exc_desc = exc_code_desc[1]
    response.data = json.dumps({
        "code": exc_code,
        "details": exc_desc,
    })
    response.content_type = "application/json"
    return response

@app1.errorhandler(InternalServerError)
def internal_server_error_handler(exc):
    """Return JSON instead of HTML for HTTP errors."""
    response = exc.get_response()
    response.data = json.dumps({
        "code": 500,
        "details": "Some Error Occurred, Please try later",
    })
    response.content_type = "application/json"
    return response

# Ensure that log directories exist and are writable
log_dir = '/home/user/logs'  # Update to a directory inside user's home directory
if not os.path.exists(log_dir):
    os.makedirs(log_dir, exist_ok=True)
    logging.info(f"Created log directory at: {log_dir}")
else:
    logging.info(f"Log directory already exists: {log_dir}")

# Configure basic logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Debugging: log environment variables
logging.info(f"PORT: {os.getenv('PORT', 'Not Set')}")
logging.info(f"THREADS: {os.getenv('THREADS', 'Not Set')}")
logging.info(f"CONNECTION_LIMIT: {os.getenv('CONNECTION_LIMIT', 'Not Set')}")
logging.info(f"CHANNEL_TIMEOUT: {os.getenv('CHANNEL_TIMEOUT', 'Not Set')}")

# Use Flask development server for Hugging Face Spaces compatibility (instead of Waitress)
if __name__ == "__main__":
    try:
        # Log the server startup info
        logging.info("Starting Flask application...")

        # Start the Flask application with the development server for testing
        app1.run(host="0.0.0.0", port=int(os.getenv("PORT", 7860)), threaded=True)
    except Exception as e:
        logging.error(f"Error starting Flask application: {e}")
        raise