moderation / main.py
Kiran5's picture
adding files
4e1d594
'''
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 dotenv import load_dotenv
from flask_swagger_ui import get_swaggerui_blueprint
from flask_cors import CORS
from waitress import serve
from router.router import app # Assuming router is correctly defined elsewhere
from config.logger import CustomLogger, request_id_var # Ensure logger is set up properly
# Load environment variables
load_dotenv()
# Initialize the request ID
request_id_var.set("StartUp")
# Set up Swagger UI and API URL
SWAGGER_URL = '/rai/v1/moderations/docs' # URL for exposing Swagger UI (without trailing '/')
API_URL = '/static/metadata.json' # Swagger API URL for the documentation
# Initialize the Flask app
app1 = Flask(__name__)
# Set up Swagger UI Blueprint
swaggerui_blueprint = get_swaggerui_blueprint(
SWAGGER_URL,
API_URL,
config={'app_name': "Infosys Responsible AI - Moderation"}
)
# Register Blueprints
app1.register_blueprint(app) # Assuming 'app' comes from the router
app1.register_blueprint(swaggerui_blueprint)
# Enable CORS (Cross-Origin Resource Sharing)
CORS(app1)
# 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 UnprocessableEntity 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 InternalServerError."""
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 application starts with waitress in production
if __name__ == "__main__":
# Ensure environment variables are set and log them
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.info(f"PORT: {os.getenv('PORT', 7860)}") # Default to 7860 if not set
logging.info(f"THREADS: {os.getenv('THREADS', 6)}")
logging.info(f"CONNECTION_LIMIT: {os.getenv('CONNECTION_LIMIT', 500)}")
logging.info(f"CHANNEL_TIMEOUT: {os.getenv('CHANNEL_TIMEOUT', 120)}")
try:
# Get port from environment or default to 7860
port = int(os.getenv("PORT", 7860))
logging.info(f"Starting the application with Waitress on port {port}...")
# Start the server using waitress (production WSGI server)
serve(app1, host='0.0.0.0', port=port,
threads=int(os.getenv('THREADS', 6)),
connection_limit=int(os.getenv('CONNECTION_LIMIT', 500)),
channel_timeout=int(os.getenv('CHANNEL_TIMEOUT', 120)))
except Exception as e:
logging.error(f"Error starting the application: {e}")