Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

feat: Added utils for flask services (#1208)

Chandrasekharan M4d3a18a39c68
diff --git a/unstract/core/pdm.lock b/unstract/core/pdm.lock
index 59b410181..e78d97849 100644
--- a/unstract/core/pdm.lock
+++ b/unstract/core/pdm.lock
@@ -2,10 +2,10 @@
# It is not intended for manual editing.
[metadata]
-groups = ["default"]
+groups = ["default", "flask"]
strategy = ["cross_platform", "inherit_metadata"]
lock_version = "4.4.2"
-content_hash = "sha256:2f44e0b5046665450445202b1fac11d41edb7e9c02440c32a863f2168fdaf510"
+content_hash = "sha256:e80a4c09d25b2b6e60298904c5d16ca6e2a210c96d2adb45ab7e70b8040df4d3"
[[package]]
name = "amqp"
@@ -33,6 +33,17 @@ files = [
{file = "async_timeout-5.0.1.tar.gz", hash = "sha256:d9321a7a3d5a6a5e187e824d2fa0793ce379a202935782d555d6e9d2735677d3"},
]
+[[package]]
+name = "blinker"
+version = "1.9.0"
+requires_python = ">=3.9"
+summary = "Fast, simple object-to-object and broadcast signaling"
+groups = ["flask"]
+files = [
+ {file = "blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc"},
+ {file = "blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf"},
+]
+
[[package]]
name = "certifi"
version = "2025.1.31"
@@ -94,6 +105,51 @@ files = [
{file = "charset_normalizer-3.4.1.tar.gz", hash = "sha256:44251f18cd68a75b56585dd00dae26183e102cd5e0f9f1466e6df5da2ed64ea3"},
]
+[[package]]
+name = "click"
+version = "8.1.8"
+requires_python = ">=3.7"
+summary = "Composable command line interface toolkit"
+groups = ["flask"]
+dependencies = [
+ "colorama; platform_system == \"Windows\"",
+]
+files = [
+ {file = "click-8.1.8-py3-none-any.whl", hash = "sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2"},
+ {file = "click-8.1.8.tar.gz", hash = "sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a"},
+]
+
+[[package]]
+name = "colorama"
+version = "0.4.6"
+requires_python = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
+summary = "Cross-platform colored terminal text."
+groups = ["flask"]
+marker = "platform_system == \"Windows\""
+files = [
+ {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
+ {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
+]
+
+[[package]]
+name = "flask"
+version = "3.1.0"
+requires_python = ">=3.9"
+summary = "A simple framework for building complex web applications."
+groups = ["flask"]
+dependencies = [
+ "Jinja2>=3.1.2",
+ "Werkzeug>=3.1",
+ "blinker>=1.9",
+ "click>=8.1.3",
+ "importlib-metadata>=3.6; python_version < \"3.10\"",
+ "itsdangerous>=2.2",
+]
+files = [
+ {file = "flask-3.1.0-py3-none-any.whl", hash = "sha256:d667207822eb83f1c4b50949b1623c8fc8d51f2341d65f72e1a1815397551136"},
+ {file = "flask-3.1.0.tar.gz", hash = "sha256:5f873c5184c897c8d9d1b05df1e3d01b14910ce69607a117bd3277098a5836ac"},
+]
+
[[package]]
name = "idna"
version = "3.10"
@@ -105,6 +161,46 @@ files = [
{file = "idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9"},
]
+[[package]]
+name = "importlib-metadata"
+version = "8.6.1"
+requires_python = ">=3.9"
+summary = "Read metadata from Python packages"
+groups = ["flask"]
+marker = "python_version < \"3.10\""
+dependencies = [
+ "zipp>=3.20",
+]
+files = [
+ {file = "importlib_metadata-8.6.1-py3-none-any.whl", hash = "sha256:02a89390c1e15fdfdc0d7c6b25cb3e62650d0494005c97d6f148bf5b9787525e"},
+ {file = "importlib_metadata-8.6.1.tar.gz", hash = "sha256:310b41d755445d74569f993ccfc22838295d9fe005425094fad953d7f15c8580"},
+]
+
+[[package]]
+name = "itsdangerous"
+version = "2.2.0"
+requires_python = ">=3.8"
+summary = "Safely pass data to untrusted environments and back."
+groups = ["flask"]
+files = [
+ {file = "itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef"},
+ {file = "itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173"},
+]
+
+[[package]]
+name = "jinja2"
+version = "3.1.6"
+requires_python = ">=3.7"
+summary = "A very fast and expressive template engine."
+groups = ["flask"]
+dependencies = [
+ "MarkupSafe>=2.0",
+]
+files = [
+ {file = "jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67"},
+ {file = "jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d"},
+]
+
[[package]]
name = "kombu"
version = "5.3.7"
@@ -121,6 +217,46 @@ files = [
{file = "kombu-5.3.7.tar.gz", hash = "sha256:011c4cd9a355c14a1de8d35d257314a1d2456d52b7140388561acac3cf1a97bf"},
]
+[[package]]
+name = "markupsafe"
+version = "3.0.2"
+requires_python = ">=3.9"
+summary = "Safely add untrusted strings to HTML/XML markup."
+groups = ["flask"]
+files = [
+ {file = "MarkupSafe-3.0.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7e94c425039cde14257288fd61dcfb01963e658efbc0ff54f5306b06054700f8"},
+ {file = "MarkupSafe-3.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9e2d922824181480953426608b81967de705c3cef4d1af983af849d7bd619158"},
+ {file = "MarkupSafe-3.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:38a9ef736c01fccdd6600705b09dc574584b89bea478200c5fbf112a6b0d5579"},
+ {file = "MarkupSafe-3.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bbcb445fa71794da8f178f0f6d66789a28d7319071af7a496d4d507ed566270d"},
+ {file = "MarkupSafe-3.0.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:57cb5a3cf367aeb1d316576250f65edec5bb3be939e9247ae594b4bcbc317dfb"},
+ {file = "MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3809ede931876f5b2ec92eef964286840ed3540dadf803dd570c3b7e13141a3b"},
+ {file = "MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:e07c3764494e3776c602c1e78e298937c3315ccc9043ead7e685b7f2b8d47b3c"},
+ {file = "MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b424c77b206d63d500bcb69fa55ed8d0e6a3774056bdc4839fc9298a7edca171"},
+ {file = "MarkupSafe-3.0.2-cp310-cp310-win32.whl", hash = "sha256:fcabf5ff6eea076f859677f5f0b6b5c1a51e70a376b0579e0eadef8db48c6b50"},
+ {file = "MarkupSafe-3.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:6af100e168aa82a50e186c82875a5893c5597a0c1ccdb0d8b40240b1f28b969a"},
+ {file = "MarkupSafe-3.0.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9025b4018f3a1314059769c7bf15441064b2207cb3f065e6ea1e7359cb46db9d"},
+ {file = "MarkupSafe-3.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:93335ca3812df2f366e80509ae119189886b0f3c2b81325d39efdb84a1e2ae93"},
+ {file = "MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cb8438c3cbb25e220c2ab33bb226559e7afb3baec11c4f218ffa7308603c832"},
+ {file = "MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a123e330ef0853c6e822384873bef7507557d8e4a082961e1defa947aa59ba84"},
+ {file = "MarkupSafe-3.0.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1e084f686b92e5b83186b07e8a17fc09e38fff551f3602b249881fec658d3eca"},
+ {file = "MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d8213e09c917a951de9d09ecee036d5c7d36cb6cb7dbaece4c71a60d79fb9798"},
+ {file = "MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5b02fb34468b6aaa40dfc198d813a641e3a63b98c2b05a16b9f80b7ec314185e"},
+ {file = "MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0bff5e0ae4ef2e1ae4fdf2dfd5b76c75e5c2fa4132d05fc1b0dabcd20c7e28c4"},
+ {file = "MarkupSafe-3.0.2-cp311-cp311-win32.whl", hash = "sha256:6c89876f41da747c8d3677a2b540fb32ef5715f97b66eeb0c6b66f5e3ef6f59d"},
+ {file = "MarkupSafe-3.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:70a87b411535ccad5ef2f1df5136506a10775d267e197e4cf531ced10537bd6b"},
+ {file = "MarkupSafe-3.0.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:eaa0a10b7f72326f1372a713e73c3f739b524b3af41feb43e4921cb529f5929a"},
+ {file = "MarkupSafe-3.0.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:48032821bbdf20f5799ff537c7ac3d1fba0ba032cfc06194faffa8cda8b560ff"},
+ {file = "MarkupSafe-3.0.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1a9d3f5f0901fdec14d8d2f66ef7d035f2157240a433441719ac9a3fba440b13"},
+ {file = "MarkupSafe-3.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:88b49a3b9ff31e19998750c38e030fc7bb937398b1f78cfa599aaef92d693144"},
+ {file = "MarkupSafe-3.0.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cfad01eed2c2e0c01fd0ecd2ef42c492f7f93902e39a42fc9ee1692961443a29"},
+ {file = "MarkupSafe-3.0.2-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:1225beacc926f536dc82e45f8a4d68502949dc67eea90eab715dea3a21c1b5f0"},
+ {file = "MarkupSafe-3.0.2-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:3169b1eefae027567d1ce6ee7cae382c57fe26e82775f460f0b2778beaad66c0"},
+ {file = "MarkupSafe-3.0.2-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:eb7972a85c54febfb25b5c4b4f3af4dcc731994c7da0d8a0b4a6eb0640e1d178"},
+ {file = "MarkupSafe-3.0.2-cp39-cp39-win32.whl", hash = "sha256:8c4e8c3ce11e1f92f6536ff07154f9d49677ebaaafc32db9db4620bc11ed480f"},
+ {file = "MarkupSafe-3.0.2-cp39-cp39-win_amd64.whl", hash = "sha256:6e296a513ca3d94054c2c881cc913116e90fd030ad1c656b3869762b754f5f8a"},
+ {file = "markupsafe-3.0.2.tar.gz", hash = "sha256:ee55d3edf80167e48ea11a923c7386f4669df67d7994554387f84e7d8b0a2bf0"},
+]
+
[[package]]
name = "redis"
version = "5.2.1"
@@ -185,3 +321,29 @@ files = [
{file = "vine-5.1.0-py3-none-any.whl", hash = "sha256:40fdf3c48b2cfe1c38a49e9ae2da6fda88e4794c810050a728bd7413811fb1dc"},
{file = "vine-5.1.0.tar.gz", hash = "sha256:8b62e981d35c41049211cf62a0a1242d8c1ee9bd15bb196ce38aefd6799e61e0"},
]
+
+[[package]]
+name = "werkzeug"
+version = "3.1.3"
+requires_python = ">=3.9"
+summary = "The comprehensive WSGI web application library."
+groups = ["flask"]
+dependencies = [
+ "MarkupSafe>=2.1.1",
+]
+files = [
+ {file = "werkzeug-3.1.3-py3-none-any.whl", hash = "sha256:54b78bf3716d19a65be4fceccc0d1d7b89e608834989dfae50ea87564639213e"},
+ {file = "werkzeug-3.1.3.tar.gz", hash = "sha256:60723ce945c19328679790e3282cc758aa4a6040e4bb330f53d30fa546d44746"},
+]
+
+[[package]]
+name = "zipp"
+version = "3.21.0"
+requires_python = ">=3.9"
+summary = "Backport of pathlib-compatible object wrapper for zip files"
+groups = ["flask"]
+marker = "python_version < \"3.10\""
+files = [
+ {file = "zipp-3.21.0-py3-none-any.whl", hash = "sha256:ac1bbe05fd2991f160ebce24ffbac5f6d11d83dc90891255885223d42b3cd931"},
+ {file = "zipp-3.21.0.tar.gz", hash = "sha256:2c9958f6430a2040341a52eb608ed6dd93ef4392e02ffe219417c1b28b5dd1f4"},
+]
diff --git a/unstract/core/pyproject.toml b/unstract/core/pyproject.toml
index 1734da830..22a6a354a 100644
--- a/unstract/core/pyproject.toml
+++ b/unstract/core/pyproject.toml
@@ -22,6 +22,10 @@ classifiers = [
]
# license = {text = "MIT"}
+[project.optional-dependencies]
+flask = [
+ "flask~=3.1.0",
+]
[tool.pdm.build]
includes = ["src"]
package-dir = "src"
diff --git a/unstract/core/src/unstract/core/flask/__init__.py b/unstract/core/src/unstract/core/flask/__init__.py
new file mode 100644
index 000000000..94eae362e
--- /dev/null
+++ b/unstract/core/src/unstract/core/flask/__init__.py
@@ -0,0 +1,2 @@
+from .exceptions import register_error_handlers # noqa: F401
+from .middleware import register_request_id_middleware # noqa: F401
diff --git a/unstract/core/src/unstract/core/flask/exceptions.py b/unstract/core/src/unstract/core/flask/exceptions.py
new file mode 100644
index 000000000..9e8c0e194
--- /dev/null
+++ b/unstract/core/src/unstract/core/flask/exceptions.py
@@ -0,0 +1,118 @@
+"""Flask exception handling utilities."""
+
+import traceback
+from dataclasses import asdict, dataclass
+from typing import Any, Optional
+
+from flask import Flask, jsonify, request
+from werkzeug.exceptions import HTTPException
+
+DEFAULT_ERR_MESSAGE = "An unexpected error occurred"
+
+
+@dataclass
+class ErrorResponse:
+ """Represents error response from Flask services."""
+
+ error: str = DEFAULT_ERR_MESSAGE
+ name: str = "ServiceError"
+ code: int = 500
+ payload: Optional[Any] = None
+
+
+class APIError(HTTPException):
+ """Base API error class for Flask services."""
+
+ code = 500
+ message = DEFAULT_ERR_MESSAGE
+
+ def __init__(
+ self,
+ message: Optional[str] = None,
+ code: Optional[int] = None,
+ payload: Any = None,
+ ):
+ if message:
+ self.message = message
+ if code:
+ self.code = code
+ self.payload = payload
+ super().__init__(description=message)
+
+ def to_dict(self):
+ """Convert error to dictionary format."""
+ err = ErrorResponse(
+ error=self.message,
+ code=self.code,
+ payload=self.payload,
+ name=self.__class__.__name__,
+ )
+ return asdict(err)
+
+ def __str__(self):
+ return str(self.message)
+
+
+def log_exceptions(e: HTTPException, logger):
+ """Helper method to log exceptions.
+
+ Args:
+ e (HTTPException): Exception to log
+ logger: Flask application logger instance
+ """
+ code = 500
+ if hasattr(e, "code"):
+ code = e.code or code
+
+ if code >= 500:
+ message = "{method} {url} {status}\n\n{error}\n\n````{tb}````".format(
+ method=request.method,
+ url=request.url,
+ status=code,
+ error=str(e),
+ tb=traceback.format_exc(),
+ )
+ else:
+ message = "{method} {url} {status} {error}".format(
+ method=request.method,
+ url=request.url,
+ status=code,
+ error=str(e),
+ )
+ logger.error(message)
+
+
+def register_error_handlers(app: Flask):
+ """Set up Flask error handlers for the application.
+
+ Args:
+ app: Flask application instance
+ """
+
+ @app.errorhandler(HTTPException)
+ def handle_http_exception(e: HTTPException):
+ """Return JSON instead of HTML for HTTP errors."""
+ log_exceptions(e, app.logger)
+ if isinstance(e, APIError):
+ return jsonify(e.to_dict()), e.code
+ else:
+ response = e.get_response()
+ response.data = jsonify(
+ ErrorResponse(error=e.description, name=e.name, code=e.code)
+ ).data
+ response.content_type = "application/json"
+ return response
+
+ @app.errorhandler(Exception)
+ def handle_uncaught_exception(e):
+ """Handler for uncaught exceptions.
+
+ Args:
+ e (Exception): Any uncaught exception
+ """
+ # pass through HTTP errors
+ if isinstance(e, HTTPException):
+ return handle_http_exception(e)
+
+ log_exceptions(e, app.logger)
+ return handle_http_exception(APIError())
diff --git a/unstract/core/src/unstract/core/flask/logging.py b/unstract/core/src/unstract/core/flask/logging.py
new file mode 100644
index 000000000..9fbf0a557
--- /dev/null
+++ b/unstract/core/src/unstract/core/flask/logging.py
@@ -0,0 +1,68 @@
+import logging
+
+from flask import g
+
+
+class RequestIDFilter(logging.Filter):
+ """Filter to inject request ID into log records."""
+
+ def filter(self, record):
+ record.request_id = getattr(g, "request_id", "N/A") if g else "N/A"
+ return True
+
+
+def setup_logging(log_level: str):
+ """Sets up logger for Flask based services
+ Args:
+ log_level (str): Log level to use. Can be one of
+ INFO, DEBUG, WARNING, ERROR
+ """
+ logging.config.dictConfig(
+ {
+ "version": 1,
+ "disable_existing_loggers": False,
+ "formatters": {
+ "default": {
+ "format": (
+ "%(levelname)s : [%(asctime)s]"
+ "{pid:%(process)d tid:%(thread)d request_id:%(request_id)s} "
+ "%(name)s:- %(message)s"
+ ),
+ },
+ },
+ "filters": {
+ "request_id": {
+ "()": RequestIDFilter,
+ }
+ },
+ "handlers": {
+ "wsgi": {
+ "class": "logging.StreamHandler",
+ "stream": "ext://flask.logging.wsgi_errors_stream",
+ "formatter": "default",
+ "filters": ["request_id"],
+ },
+ },
+ "loggers": {
+ "werkzeug": {
+ "level": log_level,
+ "handlers": ["wsgi"],
+ "propagate": False,
+ },
+ "gunicorn.access": {
+ "level": log_level,
+ "handlers": ["wsgi"],
+ "propagate": False,
+ },
+ "gunicorn.error": {
+ "level": log_level,
+ "handlers": ["wsgi"],
+ "propagate": False,
+ },
+ },
+ "root": {
+ "level": log_level,
+ "handlers": ["wsgi"],
+ },
+ }
+ )
diff --git a/unstract/core/src/unstract/core/flask/middleware.py b/unstract/core/src/unstract/core/flask/middleware.py
new file mode 100644
index 000000000..2f31fc0b3
--- /dev/null
+++ b/unstract/core/src/unstract/core/flask/middleware.py
@@ -0,0 +1,15 @@
+import uuid
+
+from flask import Flask, g, request
+
+
+def register_request_id_middleware(app: Flask):
+ """Adds request ID to each request
+
+ Obtains the ID from header or generates a new one and attaches
+ it to Flask's g object.
+ """
+
+ @app.before_request
+ def assign_request_id():
+ g.request_id = request.headers.get("X-Request-ID", str(uuid.uuid4()))
diff --git a/unstract/core/src/unstract/core/pubsub_helper.py b/unstract/core/src/unstract/core/pubsub_helper.py
index fdcf7ab78..7e6ca02bd 100644
--- a/unstract/core/src/unstract/core/pubsub_helper.py
+++ b/unstract/core/src/unstract/core/pubsub_helper.py
@@ -16,7 +16,7 @@ class LogPublisher:
kombu_conn = Connection(os.environ.get("CELERY_BROKER_URL"))
r = redis.Redis(
host=os.environ.get("REDIS_HOST"),
- port=os.environ.get("REDIS_PORT"),
+ port=os.environ.get("REDIS_PORT", 6379),
username=os.environ.get("REDIS_USER"),
password=os.environ.get("REDIS_PASSWORD"),
)