Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

idk, i like dispatching, this should be tested, rusty on flask #106

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 12 additions & 49 deletions src/api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from services.minio.minio_service import create_minio_client
from api.posthog import send_telemetry
from datetime import datetime
from validators import RequestValidator

auth = Auth()
pipeline = Pipeline()
Expand All @@ -39,24 +40,12 @@
logging.basicConfig(filename='./api-log.txt', level=logging.INFO)
logging.basicConfig(filename='./api-errors.txt', level=logging.ERROR)


@app.route("/embed", methods=['POST'])
def embed():
# TODO: add validator service
vectorflow_request = VectorflowRequest._from_flask_request(request)
if not vectorflow_request.vectorflow_key or not auth.validate_credentials(vectorflow_request.vectorflow_key):
return jsonify({'error': 'Invalid credentials'}), 401

if not vectorflow_request.embeddings_metadata or not vectorflow_request.vector_db_metadata or (not vectorflow_request.vector_db_key and not os.getenv('LOCAL_VECTOR_DB')):
return jsonify({'error': 'Missing required fields'}), 400

if vectorflow_request.embeddings_metadata.embeddings_type == EmbeddingsType.HUGGING_FACE and not vectorflow_request.embeddings_metadata.hugging_face_model_name:
return jsonify({'error': 'Hugging face embeddings models require a "hugging_face_model_name" in the "embeddings_metadata"'}), 400

if vectorflow_request.webhook_url and not vectorflow_request.webhook_key:
return jsonify({'error': 'Webhook URL provided but no webhook key'}), 400

if 'SourceData' not in request.files:
return jsonify({'error': 'No file part in the request'}), 400
if invalid := RequestValidator(request, auth).validate(["CRED", "METADATA", "EMBEDDING_TYPE", "WEBHOOK", "SOURCE_DATA"]):
return RequestValidator.dispatch_on_invalid(invalid, jsonify)

file = request.files['SourceData']

Expand Down Expand Up @@ -87,23 +76,10 @@ def embed():

@app.route('/jobs', methods=['POST'])
def create_jobs():
# TODO: add validator service
vectorflow_request = VectorflowRequest._from_flask_request(request)
if not vectorflow_request.vectorflow_key or not auth.validate_credentials(vectorflow_request.vectorflow_key):
return jsonify({'error': 'Invalid credentials'}), 401

if not vectorflow_request.embeddings_metadata or not vectorflow_request.vector_db_metadata or (not vectorflow_request.vector_db_key and not os.getenv('LOCAL_VECTOR_DB')):
return jsonify({'error': 'Missing required fields'}), 400

if vectorflow_request.embeddings_metadata.embeddings_type == EmbeddingsType.HUGGING_FACE and not vectorflow_request.embeddings_metadata.hugging_face_model_name:
return jsonify({'error': 'Hugging face embeddings models require a "hugging_face_model_name" in the "embeddings_metadata"'}), 400

if vectorflow_request.webhook_url and not vectorflow_request.webhook_key:
return jsonify({'error': 'Webhook URL provided but no webhook key'}), 400

if not hasattr(request, "files") or not request.files:
return jsonify({'error': 'No file part in the request'}), 400

if invalid := RequestValidator(request, auth).validate(["CRED", "METADATA", "EMBEDDING_TYPE", "WEBHOOK", "HAS_FILES"]):
return RequestValidator.dispatch_on_invalid(invalid, jsonify)

files = request.files.getlist('file')
successfully_uploaded_files = dict()
failed_uploads = []
Expand Down Expand Up @@ -199,17 +175,11 @@ def get_job_statuses():

@app.route("/s3", methods=['POST'])
def s3_presigned_url():
# TODO: add validator service
vectorflow_request = VectorflowRequest._from_flask_request(request)
if not vectorflow_request.vectorflow_key or not auth.validate_credentials(vectorflow_request.vectorflow_key):
return jsonify({'error': 'Invalid credentials'}), 401

if vectorflow_request.webhook_url and not vectorflow_request.webhook_key:
return jsonify({'error': 'Webhook URL provided but no webhook key'}), 400

if invalid := RequestValidator.validate(["CRED", "WEBHOOK", "EMBEDDINGS", "PRE_SIGNED"]):
return RequestValidator.dispatch_on_invalid(invalid, jsonify)

pre_signed_url = request.form.get('PreSignedURL')
if not vectorflow_request.embeddings_metadata or not vectorflow_request.vector_db_metadata or (not vectorflow_request.vector_db_key and not os.getenv('LOCAL_VECTOR_DB')) or not pre_signed_url:
return jsonify({'error': 'Missing required fields'}), 400

response = requests.get(pre_signed_url)
file_name = get_s3_file_name(pre_signed_url)
Expand Down Expand Up @@ -307,17 +277,10 @@ def split_file(file_content, lines_per_chunk=1000):

@app.route("/images", methods=['POST'])
def upload_image():
# TODO: add validator service
vectorflow_request = VectorflowRequest._from_flask_request(request)
if not vectorflow_request.vectorflow_key or not auth.validate_credentials(vectorflow_request.vectorflow_key):
return jsonify({'error': 'Invalid credentials'}), 401

if not vectorflow_request.vector_db_metadata or (not vectorflow_request.vector_db_key and not os.getenv('LOCAL_VECTOR_DB')):
return jsonify({'error': 'Missing required fields'}), 400
if invalid := RequestValidator(request, auth).validate(["CRED", "METADATA2", "WEBHOOK", "SOURCE_DATA"]):
return RequestValidator.dispatch_on_invalid(invalid, jsonify)

if 'SourceData' not in request.files:
return jsonify({'error': 'No file part in the request'}), 400

file = request.files['SourceData']

# TODO: Remove this once the application is reworked to support large files
Expand Down
52 changes: 52 additions & 0 deletions src/api/validators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import os
from enum import Enum

from shared.vectorflow_request import VectorflowRequest
from shared.embeddings_type import EmbeddingsType


class Validations(Enum):
CRED = 'CRED'
METADATA = 'METADATA'
METADATA2 = 'METADATA2'
EMBEDDING_TYPE = 'EMBEDDING_TYPE'
WEBHOOK = 'WEBHOOK'
SOURCE_DATA = 'SOURCE_DATA'
HAS_FILES = 'HAS_FILES'
PRE_SIGNED = 'PRE_SIGNED'


class RequestValidator:
def __init__(self, request, auth):
self.request = request
self.auth = auth
self.vfr = VectorflowRequest._from_flask_request(request)

DISPATCH_ERROR_MAP = {
Validations.CRED: ('Invalid credentials', 401),
Validations.METADATA: ('Missing required fields', 400),
Validations.METADATA2: ('Missing required fields', 400),
Validations.EMBEDDING_TYPE: ('Hugging face embeddings models require a "hugging_face_model_name" in the "embeddings_metadata"', 400),
Validations.WEBHOOK: ('Webhook URL provided but no webhook key', 400),
Validations.SOURCE_DATA: ('No file part in the request', 400),
Validations.HAS_FILES: ('No file part in the request', 400),
Validations.PRE_SIGNED: ('Missing required fields', 400),
}

def validate(self, validatees: list[str] | tuple[str]):
VRF_VALIDATION_MAP = {
Validations.CRED: self.vfr.vectorflow_key and self.auth.validate_credentials(self.vfr.vectorflow_key),
Validations.METADATA: self.vfr.embeddings_metadata and self.vfr.vector_db_metadata and (self.vfr.vector_db_key or os.getenv('LOCAL_VECTOR_DB')),
Validations.METADATA2: self.vfr.vector_db_metadata and (self.vfr.vector_db_key or os.getenv('LOCAL_VECTOR_DB')),
Validations.EMBEDDING_TYPE: self.vfr.embeddings_metadata.embeddings_type == EmbeddingsType.HUGGING_FACE and self.vfr.embeddings_metadata.hugging_face_model_name,
Validations.WEBHOOK: not self.vfr.webhook_url or self.vfr.webhook_key,
Validations.SOURCE_DATA: 'SourceData' in self.request.files,
Validations.HAS_FILES: hasattr(self.request, "files") and self.request.files,
Validations.PRE_SIGNED: self.request.form.get('PreSignedURL'),
}
return next((v for v in validatees if not VRF_VALIDATION_MAP[v]), None)

@staticmethod
def dispatch_on_invalid(validation, serialize):
error_message, status_code = RequestValidator.DISPATCH_ERROR_MAP[validation]
return serialize({'error': error_message}), status_code
Loading