Spaces:
Sleeping
Sleeping
''' | |
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 | |
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 | |
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 | |
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 | |