-
Notifications
You must be signed in to change notification settings - Fork 176
API refactor proposition #417
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
Open
hubert-rutkowski85
wants to merge
8
commits into
main
Choose a base branch
from
hubert/api-refactor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
994b580
refactor: move endpoints to separate file
hubert-rutkowski85 bc72b1c
refactor: improve router structure
hubert-rutkowski85 20cefe7
refactor: move out code from app.py
hubert-rutkowski85 e424123
refactor: move out code from general.py
hubert-rutkowski85 407fac4
Merge branch 'main' into hubert/api-refactor
hubert-rutkowski85 8ec67e4
fix: lint
hubert-rutkowski85 50efef5
fix: rename in makefile for versioning
hubert-rutkowski85 212333f
refactor: extract the response_generator and join_responses functions
hubert-rutkowski85 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import io | ||
| import json | ||
| import os | ||
| from typing import List, Sequence, Dict, Any, cast, Union | ||
|
|
||
| import pandas as pd | ||
| from fastapi import APIRouter, UploadFile, Depends, HTTPException | ||
| from starlette import status | ||
| from starlette.requests import Request | ||
| from starlette.responses import PlainTextResponse | ||
|
|
||
| from prepline_general.api.general import ( | ||
| ungz_file, | ||
| MultipartMixedResponse, | ||
| pipeline_api, | ||
| ) | ||
| from prepline_general.api.validation import _validate_chunking_strategy, get_validated_mimetype | ||
| from prepline_general.api.models.form_params import GeneralFormParams | ||
|
|
||
| router = APIRouter() | ||
|
|
||
|
|
||
| @router.post( | ||
| "/general/v0/general", | ||
| openapi_extra={"x-speakeasy-name-override": "partition"}, | ||
| tags=["general"], | ||
| summary="Summary", | ||
| description="Description", | ||
| operation_id="partition_parameters", | ||
| ) | ||
| @router.post("/general/v0.0.68/general", include_in_schema=False) | ||
| def general_partition( | ||
| request: Request, | ||
| # cannot use annotated type here because of a bug described here: | ||
| # https://github.com/tiangolo/fastapi/discussions/10280 | ||
| # The openapi metadata must be added separately in openapi.py file. | ||
| # TODO: Check if the bug is fixed and change the declaration to use Annoteted[List[UploadFile], File(...)] | ||
| # For new parameters - add them in models/form_params.py | ||
| files: List[UploadFile], | ||
| form_params: GeneralFormParams = Depends(GeneralFormParams.as_form), | ||
| ): | ||
| # -- must have a valid API key -- | ||
| if api_key_env := os.environ.get("UNSTRUCTURED_API_KEY"): | ||
| api_key = request.headers.get("unstructured-api-key") | ||
| if api_key != api_key_env: | ||
| raise HTTPException( | ||
| detail=f"API key {api_key} is invalid", status_code=status.HTTP_401_UNAUTHORIZED | ||
| ) | ||
|
|
||
| content_type = request.headers.get("Accept") | ||
|
|
||
| # -- detect response content-type conflict when multiple files are uploaded -- | ||
| if ( | ||
| len(files) > 1 | ||
| and content_type | ||
| and content_type | ||
| not in [ | ||
| "*/*", | ||
| "multipart/mixed", | ||
| "application/json", | ||
| "text/csv", | ||
| ] | ||
| ): | ||
| raise HTTPException( | ||
| detail=f"Conflict in media type {content_type} with response type 'multipart/mixed'.\n", | ||
| status_code=status.HTTP_406_NOT_ACCEPTABLE, | ||
| ) | ||
|
|
||
| # -- validate other arguments -- | ||
| chunking_strategy = _validate_chunking_strategy(form_params.chunking_strategy) | ||
|
|
||
| # -- unzip any uploaded files that need it -- | ||
| for idx, file in enumerate(files): | ||
| is_content_type_gz = file.content_type == "application/gzip" | ||
| is_extension_gz = file.filename and file.filename.endswith(".gz") | ||
| if is_content_type_gz or is_extension_gz: | ||
| files[idx] = ungz_file(file, form_params.gz_uncompressed_content_type) | ||
|
|
||
| def response_generator(is_multipart: bool): | ||
| for file in files: | ||
| file_content_type = get_validated_mimetype(file) | ||
|
|
||
| _file = file.file | ||
|
|
||
| response = pipeline_api( | ||
| _file, | ||
| request=request, | ||
| coordinates=form_params.coordinates, | ||
| encoding=form_params.encoding, | ||
| hi_res_model_name=form_params.hi_res_model_name, | ||
| include_page_breaks=form_params.include_page_breaks, | ||
| ocr_languages=form_params.ocr_languages, | ||
| pdf_infer_table_structure=form_params.pdf_infer_table_structure, | ||
| skip_infer_table_types=form_params.skip_infer_table_types, | ||
| strategy=form_params.strategy, | ||
| xml_keep_tags=form_params.xml_keep_tags, | ||
| response_type=form_params.output_format, | ||
| filename=str(file.filename), | ||
| file_content_type=file_content_type, | ||
| languages=form_params.languages, | ||
| extract_image_block_types=form_params.extract_image_block_types, | ||
| unique_element_ids=form_params.unique_element_ids, | ||
| # -- chunking options -- | ||
| chunking_strategy=chunking_strategy, | ||
| combine_under_n_chars=form_params.combine_under_n_chars, | ||
| max_characters=form_params.max_characters, | ||
| multipage_sections=form_params.multipage_sections, | ||
| new_after_n_chars=form_params.new_after_n_chars, | ||
| overlap=form_params.overlap, | ||
| overlap_all=form_params.overlap_all, | ||
| starting_page_number=form_params.starting_page_number, | ||
| ) | ||
|
|
||
| yield ( | ||
| json.dumps(response) | ||
| if is_multipart and type(response) not in [str, bytes] | ||
| else ( | ||
| PlainTextResponse(response) | ||
| if not is_multipart and form_params.output_format == "text/csv" | ||
| else response | ||
| ) | ||
| ) | ||
|
|
||
| def join_responses( | ||
| responses: Sequence[str | List[Dict[str, Any]] | PlainTextResponse] | ||
| ) -> List[str | List[Dict[str, Any]]] | PlainTextResponse: | ||
| """Consolidate partitionings from multiple documents into single response payload.""" | ||
| if form_params.output_format != "text/csv": | ||
| return cast(List[Union[str, List[Dict[str, Any]]]], responses) | ||
| responses = cast(List[PlainTextResponse], responses) | ||
| data = pd.read_csv( # pyright: ignore[reportUnknownMemberType] | ||
| io.BytesIO(responses[0].body) | ||
| ) | ||
| if len(responses) > 1: | ||
| for resp in responses[1:]: | ||
| resp_data = pd.read_csv( # pyright: ignore[reportUnknownMemberType] | ||
| io.BytesIO(resp.body) | ||
| ) | ||
| data = data.merge( # pyright: ignore[reportUnknownMemberType] | ||
| resp_data, how="outer" | ||
| ) | ||
| return PlainTextResponse(data.to_csv()) | ||
|
|
||
| return ( | ||
| MultipartMixedResponse( | ||
| response_generator(is_multipart=True), content_type=form_params.output_format | ||
| ) | ||
| if content_type == "multipart/mixed" | ||
| else ( | ||
| list(response_generator(is_multipart=False))[0] | ||
| if len(files) == 1 | ||
| else join_responses(list(response_generator(is_multipart=False))) | ||
| ) | ||
| ) | ||
|
|
||
|
|
||
| @router.get("/general/v0/general", include_in_schema=False) | ||
| @router.get("/general/v0.0.68/general", include_in_schema=False) | ||
| async def handle_invalid_get_request(): | ||
| raise HTTPException( | ||
| status_code=status.HTTP_405_METHOD_NOT_ALLOWED, detail="Only POST requests are supported." | ||
| ) | ||
|
|
||
|
|
||
| @router.get("/healthcheck", status_code=status.HTTP_200_OK, include_in_schema=False) | ||
| def healthcheck(request: Request): | ||
| return {"healthcheck": "HEALTHCHECK STATUS: EVERYTHING OK!"} | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.