-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
41 lines (30 loc) · 964 Bytes
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
import os, io, base64
from PIL import Image
import pdf2image
import google.generativeai as genai
app = FastAPI()
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
contents = await file.read()
if contents is not None: # Change this line
images = pdf2image.convert_from_bytes(contents)
first_page = images[0]
# convert to bytes
img_byte_arr = io.BytesIO()
first_page.save(img_byte_arr, format="JPEG")
img_byte_arr = img_byte_arr.getvalue()
pdf_parts = [
{"mime_type": "image/jpeg", "data": base64.b64encode(img_byte_arr).decode()}
]
return pdf_parts
else:
return {"error": "No file uploaded!!"}