22import json
33import base64
44from typing import Any , Callable , Optional , TypeVar
5- from baml_py import BamlStream , Image
5+ from baml_py import BamlStream , Image , Pdf
66
77import httpx
88from fastapi import FastAPI , UploadFile , File , Form , HTTPException
1313from fastapi .middleware .cors import CORSMiddleware
1414from baml_client .types import Schema
1515from baml_py .errors import BamlError
16- from pdf2image import convert_from_bytes
17- from PIL import Image as PILImage
18- import io
1916
2017app = FastAPI ()
2118
@@ -90,7 +87,7 @@ async def execute_baml(
9087 url : str = Form (None ),
9188 baml_code : str = Form (...),
9289 return_type : str = Form (...),
93- ):
90+ ):
9491 final_content = await read_input_content (file , content , url )
9592 tb = TypeBuilder ()
9693 try :
@@ -130,16 +127,11 @@ async def stream_baml():
130127 yield json .dumps ({ "error" : str (e ) }) + "\n \n "
131128 return StreamingResponse (stream_baml (), media_type = "text/event-stream" )
132129
133- def convert_to_base64 (img : PILImage ):
134- buffered = io .BytesIO ()
135- img .save (buffered , format = "JPEG" )
136- return Image .from_base64 (base64 = base64 .b64encode (buffered .getvalue ()).decode ("utf-8" ), media_type = "image/jpeg" )
137-
138130async def read_input_content (
139131 file : Optional [UploadFile ] = None ,
140132 content : Optional [str ] = None ,
141133 url : Optional [str ] = None
142- ) -> str | Image | list [ Image ] :
134+ ) -> str | Image | Pdf :
143135 """
144136 Processes the input from one of the following:
145137 - file: an uploaded file (image, audio, PDF or text)
@@ -156,10 +148,9 @@ async def read_input_content(
156148 file_content = await file .read ()
157149 return file_content .decode ("utf-8" )
158150 elif file .content_type == "application/pdf" :
159- # Convert PDF to images
160151 file_content = await file .read ()
161- images = convert_from_bytes (file_content )
162- return [ convert_to_base64 ( img ) for img in images ]
152+ file_content_base64 = base64 . b64encode (file_content ). decode ( "utf-8" )
153+ return Pdf . from_base64 ( file_content_base64 )
163154 else :
164155 file_content = await file .read ()
165156 file_content_base64 = base64 .b64encode (file_content ).decode ("utf-8" )
0 commit comments