Kiran5 commited on
Commit
0b16b51
·
1 Parent(s): 4a14e46

Add application file

Browse files
Files changed (1) hide show
  1. main.py +54 -8
main.py CHANGED
@@ -70,14 +70,18 @@ if __name__ == "__main__":
70
  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.
71
  '''
72
  import json
 
 
73
  from werkzeug.exceptions import HTTPException, UnprocessableEntity, InternalServerError
74
  from flask import Flask
75
  from flask_swagger_ui import get_swaggerui_blueprint
76
  from flask_cors import CORS
77
  from waitress import serve
78
- import os
79
  from dotenv import load_dotenv
80
- from router.router import app # Importing the original blueprint
 
 
 
81
  load_dotenv()
82
 
83
  # Flask app setup
@@ -89,14 +93,32 @@ API_URL = '/static/metadata.json'
89
  swaggerui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL, config={'app_name': "Infosys Responsible AI - Moderation"})
90
  app1.register_blueprint(swaggerui_blueprint)
91
 
92
- # Register the app blueprint for the '/rai/v1/moderations' route
93
- app1.register_blueprint(app) # Registering the blueprint that contains the route
94
-
95
- # CORS and error handling setup
96
  CORS(app1)
97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  @app1.errorhandler(HTTPException)
99
  def handle_exception(e):
 
100
  response = e.get_response()
101
  response.data = json.dumps({
102
  "code": e.code,
@@ -107,6 +129,7 @@ def handle_exception(e):
107
 
108
  @app1.errorhandler(UnprocessableEntity)
109
  def validation_error_handler(exc):
 
110
  response = exc.get_response()
111
  exc_code_desc = exc.description.split("-")
112
  exc_code = int(exc_code_desc[0])
@@ -120,6 +143,7 @@ def validation_error_handler(exc):
120
 
121
  @app1.errorhandler(InternalServerError)
122
  def internal_server_error_handler(exc):
 
123
  response = exc.get_response()
124
  response.data = json.dumps({
125
  "code": 500,
@@ -128,9 +152,31 @@ def internal_server_error_handler(exc):
128
  response.content_type = "application/json"
129
  return response
130
 
131
- # Use Waitress for production server
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  if __name__ == "__main__":
133
- serve(app1, host="0.0.0.0", port=int(os.getenv("PORT", 7860))) # Ensure correct port is used
 
 
 
 
 
 
 
 
134
 
135
 
136
 
 
70
  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.
71
  '''
72
  import json
73
+ import os
74
+ import logging
75
  from werkzeug.exceptions import HTTPException, UnprocessableEntity, InternalServerError
76
  from flask import Flask
77
  from flask_swagger_ui import get_swaggerui_blueprint
78
  from flask_cors import CORS
79
  from waitress import serve
 
80
  from dotenv import load_dotenv
81
+ import spacy
82
+ from spacy.cli import download
83
+
84
+ # Load environment variables
85
  load_dotenv()
86
 
87
  # Flask app setup
 
93
  swaggerui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL, config={'app_name': "Infosys Responsible AI - Moderation"})
94
  app1.register_blueprint(swaggerui_blueprint)
95
 
96
+ # CORS setup
 
 
 
97
  CORS(app1)
98
 
99
+ # Ensure Spacy model is installed and loaded
100
+ def load_spacy_model():
101
+ try:
102
+ # Attempt to load the model
103
+ nlp = spacy.load('en_core_web_lg')
104
+ except OSError:
105
+ # If model is not found, download it
106
+ download('en_core_web_lg')
107
+ nlp = spacy.load('en_core_web_lg')
108
+ return nlp
109
+
110
+ # Attempt to load Spacy model
111
+ try:
112
+ nlp = load_spacy_model()
113
+ logging.info("Spacy model loaded successfully.")
114
+ except Exception as e:
115
+ logging.error(f"Failed to load Spacy model: {e}")
116
+ raise
117
+
118
+ # Error Handlers
119
  @app1.errorhandler(HTTPException)
120
  def handle_exception(e):
121
+ """Return JSON instead of HTML for HTTP errors."""
122
  response = e.get_response()
123
  response.data = json.dumps({
124
  "code": e.code,
 
129
 
130
  @app1.errorhandler(UnprocessableEntity)
131
  def validation_error_handler(exc):
132
+ """Return JSON instead of HTML for HTTP errors."""
133
  response = exc.get_response()
134
  exc_code_desc = exc.description.split("-")
135
  exc_code = int(exc_code_desc[0])
 
143
 
144
  @app1.errorhandler(InternalServerError)
145
  def internal_server_error_handler(exc):
146
+ """Return JSON instead of HTML for HTTP errors."""
147
  response = exc.get_response()
148
  response.data = json.dumps({
149
  "code": 500,
 
152
  response.content_type = "application/json"
153
  return response
154
 
155
+ # Ensure that log directories exist and are writable
156
+ log_dir = '/path/to/logs' # Update this path as needed
157
+ if not os.path.exists(log_dir):
158
+ os.makedirs(log_dir, exist_ok=True)
159
+
160
+ # Configure basic logging
161
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
162
+
163
+ # Debugging: log environment variables
164
+ logging.info(f"PORT: {os.getenv('PORT')}")
165
+ logging.info(f"THREADS: {os.getenv('THREADS')}")
166
+ logging.info(f"CONNECTION_LIMIT: {os.getenv('CONNECTION_LIMIT')}")
167
+ logging.info(f"CHANNEL_TIMEOUT: {os.getenv('CHANNEL_TIMEOUT')}")
168
+
169
+ # Use Waitress for production server, or Flask for development
170
  if __name__ == "__main__":
171
+ try:
172
+ # Start the Flask application
173
+ logging.info("Starting the application...")
174
+ serve(app1, host="0.0.0.0", port=int(os.getenv("PORT", 7860)), threads=int(os.getenv('THREADS', 6)),
175
+ connection_limit=int(os.getenv('CONNECTION_LIMIT', 500)), channel_timeout=int(os.getenv('CHANNEL_TIMEOUT', 120)))
176
+ except Exception as e:
177
+ logging.error(f"Error starting the application: {e}")
178
+ raise
179
+
180
 
181
 
182